_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
68675702f74c9bc942b89e99ca38eecd1f184993ace79697a37e79353bcda4d0
kfish/const-math-ghc-plugin
numrun011.hs
import Data.Ratio main = print (fromRational (1 % 85070591730234615865843651857942052864) :: Float)
null
https://raw.githubusercontent.com/kfish/const-math-ghc-plugin/c1d269e0ddc72a782c73cca233ec9488f69112a9/tests/ghc-7.4/numrun011.hs
haskell
import Data.Ratio main = print (fromRational (1 % 85070591730234615865843651857942052864) :: Float)
8dc81cfcba9cec7ab328a2359c17f73e80e83ab23acd7da569e742424c4d689f
INRIA/zelus
unsafe.ml
let sgn(x) = if x >= 0.0 then 1.0 else -1.0
null
https://raw.githubusercontent.com/INRIA/zelus/685428574b0f9100ad5a41bbaa416cd7a2506d5e/examples/misc/unsafe.ml
ocaml
let sgn(x) = if x >= 0.0 then 1.0 else -1.0
fc331d9b4b61949be46f0604c327a2a714f8a8d25314a1f54253ae917ce66cfa
takikawa/racket-ppa
info.rkt
(module info setup/infotab (#%module-begin (define collection (quote multi)) (define deps (quote ("rackunit-lib" "rackunit-doc" "rackunit-gui" "rackunit-plugin-lib"))) (define implies (quote ("rackunit-lib" "rackunit-doc" "rackunit-gui" "rackunit-plugin-lib"))) (define pkg-desc "RackUnit testing framework") (define pkg-authors (quote (ryanc noel))) (define license (quote (Apache-2.0 OR MIT)))))
null
https://raw.githubusercontent.com/takikawa/racket-ppa/26d6ae74a1b19258c9789b7c14c074d867a4b56b/share/pkgs/rackunit/info.rkt
racket
(module info setup/infotab (#%module-begin (define collection (quote multi)) (define deps (quote ("rackunit-lib" "rackunit-doc" "rackunit-gui" "rackunit-plugin-lib"))) (define implies (quote ("rackunit-lib" "rackunit-doc" "rackunit-gui" "rackunit-plugin-lib"))) (define pkg-desc "RackUnit testing framework") (define pkg-authors (quote (ryanc noel))) (define license (quote (Apache-2.0 OR MIT)))))
b60e23ccac0657ef0f3f21eea6e391b29f79f6cd1e3ba8d270fe654b127fc24d
lambdamikel/DLMAPS
dispatcher10.lisp
-*- Mode : Lisp ; Syntax : Ansi - Common - Lisp ; Package : THEMATIC - SUBSTRATE ; Base : 10 -*- (in-package :THEMATIC-SUBSTRATE) ;;; ;;; ;;; (defgeneric get-parser-class-for-substrate (substrate)) ;;; ;;; Interface: Substrate <-> Query ;;; #+:dlmaps (defmethod get-parser-class-for-substrate ((substrate substrate)) 'substrate-parser) #+:dlmaps (defmethod get-parser-class-for-substrate ((substrate racer-substrate)) 'racer-substrate-parser) #+:dlmaps (defmethod get-parser-class-for-substrate ((substrate racer-descriptions-substrate)) 'racer-descriptions-substrate-parser) (defmethod get-parser-class-for-substrate ((substrate racer-dummy-substrate)) 'nrql-abox-query-parser) (defmethod get-parser-class-for-substrate ((substrate racer-tbox-mirror-substrate)) 'nrql-tbox-query-parser) #+:midelora (defmethod get-parser-class-for-substrate ((substrate midelora-substrate)) 'midelora-abox-query-parser) #+:midelora (defmethod get-parser-class-for-substrate ((substrate midelora-tbox-mirror-substrate)) 'midelora-tbox-query-parser) ;;; Dispatcher - Methoden ;;; (defmethod make-dispatcher ((parser simple-parser) sym) " " alles , was get - expression - type ;;; zurueckliefert... (make-instance sym :dont-initialize-p t)) #+:dlmaps (defmethod make-dispatcher ((parser substrate-parser) sym) dieser simple - substrate and ;;; predicate-queries, sowie and/or -> homogeneous complex queries! (make-instance (case sym ((substrate-simple-and-node-query substrate-simple-or-node-query substrate-simple-and-edge-query substrate-simple-or-edge-query substrate-predicate-edge-query substrate-predicate-node-query same-as-query top-query bottom-query) sym) (and-query 'complex-substrate-and-query) (or-query 'complex-substrate-or-query) (otherwise (return-from make-dispatcher nil))) :dont-initialize-p t)) (defmethod make-dispatcher ((parser nrql-abox-query-parser) sym) dieser instance / edge - retrieval , und and/or (make-instance (case sym (and-query 'nrql-and-query) (or-query 'nrql-or-query) (instance-retrieval-query 'nrql-instance-retrieval-query) (edge-retrieval-query 'nrql-edge-retrieval-query) (has-known-successor-retrieval-query 'nrql-has-known-successor-retrieval-query) (cd-edge-retrieval-query 'nrql-cd-edge-retrieval-query) (top-query 'nrql-top-query) (bottom-query 'nrql-bottom-query) (same-as-query 'nrql-same-as-query) (true-query 'nrql-true-query) (false-query 'nrql-false-query) (otherwise (return-from make-dispatcher nil))) :dont-initialize-p t)) #+:midelora (defmethod make-dispatcher ((parser midelora-abox-query-parser) sym) (make-instance (case sym (and-query 'midelora-nrql-and-query) (or-query 'midelora-nrql-or-query) (instance-retrieval-query 'midelora-nrql-instance-retrieval-query) (edge-retrieval-query 'midelora-nrql-edge-retrieval-query) (has-known-successor-retrieval-query 'midelora-nrql-has-known-successor-retrieval-query) (top-query 'midelora-nrql-top-query) (bottom-query 'midelora-nrql-bottom-query) (same-as-query 'midelora-nrql-same-as-query) (true-query 'midelora-nrql-true-query) (false-query 'midelora-nrql-false-query) (otherwise (return-from make-dispatcher nil))) :dont-initialize-p t)) #+:dlmaps (defmethod make-dispatcher ((parser racer-substrate-parser) sym) das RACER - Substrate ist " hybrid " - > Substrate und ABox ;;; befragbar Knotenbeschreibungen i m Substrate ! z. B. simple - description , racer - description ! (make-instance (case sym (and-query 'hybrid-and-query) (or-query 'hybrid-or-query) (otherwise sym)) :dont-initialize-p t)) #+:dlmaps (defmethod make-dispatcher ((parser racer-descriptions-substrate-parser) sym) ;;; dieser Parser versteht nur RACER-Descriptions Annahme : ein racer - descriptions - substrate hat NUR RACER - descriptions ! ! ! - > simple - substrate - queries ! (make-instance (case sym ((substrate-racer-node-query substrate-racer-edge-query same-as-query top-query bottom-query) sym) (and-query 'complex-substrate-and-query) (or-query 'complex-substrate-or-query) (otherwise (return-from make-dispatcher nil))) :dont-initialize-p t))
null
https://raw.githubusercontent.com/lambdamikel/DLMAPS/7f8dbb9432069d41e6a7d9c13dc5b25602ad35dc/src/query/dispatcher10.lisp
lisp
Syntax : Ansi - Common - Lisp ; Package : THEMATIC - SUBSTRATE ; Base : 10 -*- Interface: Substrate <-> Query zurueckliefert... predicate-queries, sowie and/or -> homogeneous complex queries! befragbar dieser Parser versteht nur RACER-Descriptions
(in-package :THEMATIC-SUBSTRATE) (defgeneric get-parser-class-for-substrate (substrate)) #+:dlmaps (defmethod get-parser-class-for-substrate ((substrate substrate)) 'substrate-parser) #+:dlmaps (defmethod get-parser-class-for-substrate ((substrate racer-substrate)) 'racer-substrate-parser) #+:dlmaps (defmethod get-parser-class-for-substrate ((substrate racer-descriptions-substrate)) 'racer-descriptions-substrate-parser) (defmethod get-parser-class-for-substrate ((substrate racer-dummy-substrate)) 'nrql-abox-query-parser) (defmethod get-parser-class-for-substrate ((substrate racer-tbox-mirror-substrate)) 'nrql-tbox-query-parser) #+:midelora (defmethod get-parser-class-for-substrate ((substrate midelora-substrate)) 'midelora-abox-query-parser) #+:midelora (defmethod get-parser-class-for-substrate ((substrate midelora-tbox-mirror-substrate)) 'midelora-tbox-query-parser) Dispatcher - Methoden (defmethod make-dispatcher ((parser simple-parser) sym) " " alles , was get - expression - type (make-instance sym :dont-initialize-p t)) #+:dlmaps (defmethod make-dispatcher ((parser substrate-parser) sym) dieser simple - substrate and (make-instance (case sym ((substrate-simple-and-node-query substrate-simple-or-node-query substrate-simple-and-edge-query substrate-simple-or-edge-query substrate-predicate-edge-query substrate-predicate-node-query same-as-query top-query bottom-query) sym) (and-query 'complex-substrate-and-query) (or-query 'complex-substrate-or-query) (otherwise (return-from make-dispatcher nil))) :dont-initialize-p t)) (defmethod make-dispatcher ((parser nrql-abox-query-parser) sym) dieser instance / edge - retrieval , und and/or (make-instance (case sym (and-query 'nrql-and-query) (or-query 'nrql-or-query) (instance-retrieval-query 'nrql-instance-retrieval-query) (edge-retrieval-query 'nrql-edge-retrieval-query) (has-known-successor-retrieval-query 'nrql-has-known-successor-retrieval-query) (cd-edge-retrieval-query 'nrql-cd-edge-retrieval-query) (top-query 'nrql-top-query) (bottom-query 'nrql-bottom-query) (same-as-query 'nrql-same-as-query) (true-query 'nrql-true-query) (false-query 'nrql-false-query) (otherwise (return-from make-dispatcher nil))) :dont-initialize-p t)) #+:midelora (defmethod make-dispatcher ((parser midelora-abox-query-parser) sym) (make-instance (case sym (and-query 'midelora-nrql-and-query) (or-query 'midelora-nrql-or-query) (instance-retrieval-query 'midelora-nrql-instance-retrieval-query) (edge-retrieval-query 'midelora-nrql-edge-retrieval-query) (has-known-successor-retrieval-query 'midelora-nrql-has-known-successor-retrieval-query) (top-query 'midelora-nrql-top-query) (bottom-query 'midelora-nrql-bottom-query) (same-as-query 'midelora-nrql-same-as-query) (true-query 'midelora-nrql-true-query) (false-query 'midelora-nrql-false-query) (otherwise (return-from make-dispatcher nil))) :dont-initialize-p t)) #+:dlmaps (defmethod make-dispatcher ((parser racer-substrate-parser) sym) das RACER - Substrate ist " hybrid " - > Substrate und ABox Knotenbeschreibungen i m Substrate ! z. B. simple - description , racer - description ! (make-instance (case sym (and-query 'hybrid-and-query) (or-query 'hybrid-or-query) (otherwise sym)) :dont-initialize-p t)) #+:dlmaps (defmethod make-dispatcher ((parser racer-descriptions-substrate-parser) sym) Annahme : ein racer - descriptions - substrate hat NUR RACER - descriptions ! ! ! - > simple - substrate - queries ! (make-instance (case sym ((substrate-racer-node-query substrate-racer-edge-query same-as-query top-query bottom-query) sym) (and-query 'complex-substrate-and-query) (or-query 'complex-substrate-or-query) (otherwise (return-from make-dispatcher nil))) :dont-initialize-p t))
809cba7b961fceea76dd1c3321a626052262387f421b3a06d649cf17d7406363
SonyCSLParis/fcg-hybrids
constituent-structures.lisp
;; Copyright 2019-present Sony Computer Science Laboratories Paris ( ) Licensed under the Apache License , Version 2.0 ( the " License " ) ; ;; you may not use this file except in compliance with the License. ;; You may obtain a copy of the License at ;; -2.0 ;; Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , ;; WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ;; See the License for the specific language governing permissions and ;; limitations under the License. ;;========================================================================= (in-package :fcg) (export '(represent-constituent-structure)) ICA = Immediate Constituent Analysis ;; ;; Contents: ;; 1- Helper functions ;; ------------------------------------------------------------------------- (defun convert-ica-string-to-ica-list (string) "Converts a string representing a constituent analysis into a list representation." (loop for pair in '(("." "\\.") ("," "\\,") ("''" "PARENTH") ("``" "PARENTH") ("\"" "PARENTH")) do (setf string (string-replace string (first pair) (second pair)))) (read-from-string string)) ;; 2- Representing Constituent Structures ;; ------------------------------------------------------------------------- (defgeneric represent-constituent-structure (analysis transient-structure key cxn-inventory &optional language) (:documentation "Given a constituent structure analysis, expand the transient structure with units for phrases and constituency relations.")) For an example , check /languages / English / structures.lisp ;; Helper functions for dealing with bracketed representation of constituent structures ;; ------------------------------------------------------------------------------------ (defun terminal-node-p (node) "Is the node a terminal node in the constituent structure?" (if (loop for x in (rest node) when (listp x) return t) nil t)) ;; (terminal-node-p '(nnp luc steels)) ;; (terminal-node-p '(np (det the) (nn book))) (defun has-constituents-p (unit) "Check whether a unit has the constituents feature." (unit-feature-value unit 'constituents)) ;; (has-constituents-p '(np (constituents (det n)))) ;; (has-constituents-p '(n (lex-id test))) (defun make-unit-id (x) "Make a new unit name." (make-id (format nil "~a-unit" x))) ;; (make-unit-id 's)
null
https://raw.githubusercontent.com/SonyCSLParis/fcg-hybrids/7db632609a36dfa915bcc463b152c0b2bea962d9/structures/constituent-structures.lisp
lisp
Copyright 2019-present you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ========================================================================= Contents: 1- Helper functions ------------------------------------------------------------------------- 2- Representing Constituent Structures ------------------------------------------------------------------------- Helper functions for dealing with bracketed representation of constituent structures ------------------------------------------------------------------------------------ (terminal-node-p '(nnp luc steels)) (terminal-node-p '(np (det the) (nn book))) (has-constituents-p '(np (constituents (det n)))) (has-constituents-p '(n (lex-id test))) (make-unit-id 's)
Sony Computer Science Laboratories Paris ( ) distributed under the License is distributed on an " AS IS " BASIS , (in-package :fcg) (export '(represent-constituent-structure)) ICA = Immediate Constituent Analysis (defun convert-ica-string-to-ica-list (string) "Converts a string representing a constituent analysis into a list representation." (loop for pair in '(("." "\\.") ("," "\\,") ("''" "PARENTH") ("``" "PARENTH") ("\"" "PARENTH")) do (setf string (string-replace string (first pair) (second pair)))) (read-from-string string)) (defgeneric represent-constituent-structure (analysis transient-structure key cxn-inventory &optional language) (:documentation "Given a constituent structure analysis, expand the transient structure with units for phrases and constituency relations.")) For an example , check /languages / English / structures.lisp (defun terminal-node-p (node) "Is the node a terminal node in the constituent structure?" (if (loop for x in (rest node) when (listp x) return t) nil t)) (defun has-constituents-p (unit) "Check whether a unit has the constituents feature." (unit-feature-value unit 'constituents)) (defun make-unit-id (x) "Make a new unit name." (make-id (format nil "~a-unit" x)))
5c526b4f39bf898f12f5a0c318b7ba2a02530f19d6fc3a6025aa72d642b6d264
YellPika/constraint-rules
Rule.hs
{-# LANGUAGE ConstraintKinds #-} # LANGUAGE DataKinds # {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MonoLocalBinds #-} # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE RankNTypes #-} # LANGUAGE TemplateHaskell # # LANGUAGE UnicodeSyntax # module Data.Constraint.Rule ( RuleUsage (..), RuleArg (..), RuleName (..), RuleSpec (..), Use, Ignore, Intro, Deriv, Simpl, NoIntro, NoDeriv, NoSimpl, withIntro, withDeriv, withSimpl, ignoreIntro, ignoreDeriv, ignoreSimpl ) where import Data.Constraint.Rule.Plugin.Prelude import Data.Class.Closed.TH (close) import Data.Data (Data, Proxy) import GHC.TypeLits (Symbol) data RuleUsage = Intro | Deriv | Simpl deriving (Data, Eq, Ord, Show) instance Outputable RuleUsage where ppr = text . show data RuleArg = ∀a. RuleArg a data RuleName = RuleName Symbol Symbol data RuleSpec = RuleSpec RuleName [RuleArg] close [d| class Use (ruleUsage ∷ RuleUsage) (ruleSpec ∷ RuleSpec) instance Use (ruleUsage ∷ RuleUsage) (ruleSpec ∷ RuleSpec) class Ignore (ruleUsage ∷ RuleUsage) (ruleName ∷ RuleName) instance Ignore (ruleUsage ∷ RuleUsage) (ruleName ∷ RuleName) |] type Intro = Use 'Intro type Deriv = Use 'Deriv type Simpl = Use 'Simpl type NoIntro = Ignore 'Intro type NoDeriv = Ignore 'Deriv type NoSimpl = Ignore 'Simpl withIntro ∷ Proxy a → (Intro a ⇒ r) → r withIntro _ x = x withDeriv ∷ Proxy a → (Deriv a ⇒ r) → r withDeriv _ x = x withSimpl ∷ Proxy a → (Simpl a ⇒ r) → r withSimpl _ x = x ignoreIntro ∷ Proxy a → (NoIntro a ⇒ r) → r ignoreIntro _ x = x ignoreDeriv ∷ Proxy a → (NoDeriv a ⇒ r) → r ignoreDeriv _ x = x ignoreSimpl ∷ Proxy a → (NoSimpl a ⇒ r) → r ignoreSimpl _ x = x
null
https://raw.githubusercontent.com/YellPika/constraint-rules/b06dfae3fe01c45c1d78e5611c031ab6591d2e66/src/Data/Constraint/Rule.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DefaultSignatures # # LANGUAGE DeriveDataTypeable # # LANGUAGE KindSignatures # # LANGUAGE MonoLocalBinds # # LANGUAGE RankNTypes #
# LANGUAGE DataKinds # # LANGUAGE ExistentialQuantification # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE TemplateHaskell # # LANGUAGE UnicodeSyntax # module Data.Constraint.Rule ( RuleUsage (..), RuleArg (..), RuleName (..), RuleSpec (..), Use, Ignore, Intro, Deriv, Simpl, NoIntro, NoDeriv, NoSimpl, withIntro, withDeriv, withSimpl, ignoreIntro, ignoreDeriv, ignoreSimpl ) where import Data.Constraint.Rule.Plugin.Prelude import Data.Class.Closed.TH (close) import Data.Data (Data, Proxy) import GHC.TypeLits (Symbol) data RuleUsage = Intro | Deriv | Simpl deriving (Data, Eq, Ord, Show) instance Outputable RuleUsage where ppr = text . show data RuleArg = ∀a. RuleArg a data RuleName = RuleName Symbol Symbol data RuleSpec = RuleSpec RuleName [RuleArg] close [d| class Use (ruleUsage ∷ RuleUsage) (ruleSpec ∷ RuleSpec) instance Use (ruleUsage ∷ RuleUsage) (ruleSpec ∷ RuleSpec) class Ignore (ruleUsage ∷ RuleUsage) (ruleName ∷ RuleName) instance Ignore (ruleUsage ∷ RuleUsage) (ruleName ∷ RuleName) |] type Intro = Use 'Intro type Deriv = Use 'Deriv type Simpl = Use 'Simpl type NoIntro = Ignore 'Intro type NoDeriv = Ignore 'Deriv type NoSimpl = Ignore 'Simpl withIntro ∷ Proxy a → (Intro a ⇒ r) → r withIntro _ x = x withDeriv ∷ Proxy a → (Deriv a ⇒ r) → r withDeriv _ x = x withSimpl ∷ Proxy a → (Simpl a ⇒ r) → r withSimpl _ x = x ignoreIntro ∷ Proxy a → (NoIntro a ⇒ r) → r ignoreIntro _ x = x ignoreDeriv ∷ Proxy a → (NoDeriv a ⇒ r) → r ignoreDeriv _ x = x ignoreSimpl ∷ Proxy a → (NoSimpl a ⇒ r) → r ignoreSimpl _ x = x
6f013dc929a6f679d2433168a88f9638828607a81a44e8c7f3cb7dc57597cc46
S8A/htdp-exercises
ex159.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 ex159) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f))) ; Basic graphical constants (define BALLOON (circle 5 "solid" "red")) (define GRID-SQUARE (square 10 "outline" "black")) ; N Image -> Image ; produces a column of n copies of img (define (col n img) (cond [(zero? (sub1 n)) img] [(positive? (sub1 n)) (above img (col (sub1 n) img))])) (check-expect (col 3 GRID-SQUARE) (above GRID-SQUARE (above GRID-SQUARE GRID-SQUARE))) (check-expect (col 4 GRID-SQUARE) (above GRID-SQUARE (above GRID-SQUARE (above GRID-SQUARE GRID-SQUARE)))) ; N Image -> Image ; produces a row of n copies of img (define (row n img) (cond [(zero? (sub1 n)) img] [(positive? (sub1 n)) (beside img (row (sub1 n) img))])) (check-expect (row 3 GRID-SQUARE) (beside GRID-SQUARE (beside GRID-SQUARE GRID-SQUARE))) (check-expect (row 4 GRID-SQUARE) (beside GRID-SQUARE (beside GRID-SQUARE (beside GRID-SQUARE GRID-SQUARE)))) ; Computed graphical constants (define LECTURE-HALL-GRID (row 10 (col 20 GRID-SQUARE))) (define LECTURE-HALL (overlay LECTURE-HALL-GRID (rectangle (image-width LECTURE-HALL-GRID) (image-height LECTURE-HALL-GRID) "solid" "white"))) (define WIDTH (image-width LECTURE-HALL)) An N is one of : – 0 ; – (add1 N) ; interpretation represents the counting numbers ; A ListOfPosns is one of: ; - '() ; - (cons Posn ListOfPosns) (define lop1 (cons (make-posn 2 2.3) (cons (make-posn 7.6 3) '()))) (define lop2 (cons (make-posn 1 2) (cons (make-posn 2 4) (cons (make-posn 3 6) (cons (make-posn 4 8) (cons (make-posn 5 10) (cons (make-posn 6 12) (cons (make-posn 7 14) (cons (make-posn 8 16) (cons (make-posn 9 18) (cons (make-posn 10 20) '()))))))))))) (define-struct pair [balloon# lob]) ; A Pair is a structure (make-pair N List-of-posns) ; interpretation (make-pair n lob) means n balloons ; must yet be thrown and added to lob ; N -> List-of-posns Throws one balloon after the other to the lecture hall and produces ; the list of positions where the balloons hit. (define (riot n) (pair-lob (big-bang (make-pair n '()) [to-draw render] [on-tick tock]))) ; Pair -> Image ; Renders the current state of the lecture hall with the balloons thrown. (define (render p) (add-balloons (pair-lob p) LECTURE-HALL)) (check-expect (render (make-pair 7 lop1)) (add-balloons lop1 LECTURE-HALL)) (check-expect (render (make-pair 0 lop2)) (add-balloons lop2 LECTURE-HALL)) ; Pair -> Pair Makes the balloons fall one real pixel per tick , adding missing balloons one by one . (define (tock p) (make-pair (pair-balloon# p) (if (< (how-many (pair-lob p)) (pair-balloon# p)) (new-balloon (move-balloons (pair-lob p)) (pair-balloon# p)) (move-balloons (pair-lob p))))) (check-random (tock (make-pair 3 '())) (make-pair 3 (new-balloon (move-balloons '()) 3))) (check-expect (tock (make-pair 2 lop1)) (make-pair 2 (move-balloons lop1))) ; List-of-posns -> Image ; Adds the balloons to the image im at the positions specified by lop. (define (add-balloons lop im) (cond [(empty? lop) im] [(cons? lop) (add-balloon (first lop) (add-balloons (rest lop) im))])) (check-expect (add-balloons lop1 LECTURE-HALL) (place-image BALLOON 76 30 (place-image BALLOON 20 23 LECTURE-HALL))) ; Posn -> Image ; Adds ballon to the given image at the coordinates specified by p. Each unit in the coordinates maps to 10 pixels in the image . (define (add-balloon p im) (place-image BALLOON (* 10 (posn-x p)) (* 10 (posn-y p)) im)) (check-expect (add-balloon (make-posn 2 2.3) LECTURE-HALL) (place-image BALLOON 20 23 LECTURE-HALL)) ; List-of-posns -> List-of-posns Make all balloons fall one real pixel . (define (move-balloons lob) (cond [(empty? lob) '()] [(cons? lob) (cons (move-balloon (first lob)) (move-balloons (rest lob)))])) (check-expect (move-balloons '()) '()) (check-expect (move-balloons lop1) (cons (make-posn 2 2.4) (cons (make-posn 7.6 3.1) '()))) ; Posn -> Posn Move ballon down one real pixel ( 0.1 unit ) . (define (move-balloon b) (make-posn (posn-x b) (+ (posn-y b) 0.1))) (check-expect (move-balloon (make-posn 5 3.5)) (make-posn 5 3.6)) ; List-of-posns -> Number ; Counts how many positions are in the list. (define (how-many list) (cond [(empty? list) 0] [(cons? list) (+ 1 (how-many (rest list)))])) (check-expect (how-many lop1) 2) (check-expect (how-many lop2) 10) ; List-of-posns -> List-of-posns Adds one balloon at some point above the canvas . (define (new-balloon lob n) (cons (make-posn (/ (random WIDTH) 10) (* -2 (random n))) lob)) (check-random (new-balloon (cons (make-posn 3 5) '()) 3) (cons (make-posn (/ (random WIDTH) 10) (* -2 (random 3))) (cons (make-posn 3 5) '())))
null
https://raw.githubusercontent.com/S8A/htdp-exercises/578e49834a9513f29ef81b7589b28081c5e0b69f/ex159.rkt
racket
about the language level of this file in a form that our tools can easily process. Basic graphical constants N Image -> Image produces a column of n copies of img N Image -> Image produces a row of n copies of img Computed graphical constants – (add1 N) interpretation represents the counting numbers A ListOfPosns is one of: - '() - (cons Posn ListOfPosns) A Pair is a structure (make-pair N List-of-posns) interpretation (make-pair n lob) means n balloons must yet be thrown and added to lob N -> List-of-posns the list of positions where the balloons hit. Pair -> Image Renders the current state of the lecture hall with the balloons thrown. Pair -> Pair List-of-posns -> Image Adds the balloons to the image im at the positions specified by lop. Posn -> Image Adds ballon to the given image at the coordinates specified by p. List-of-posns -> List-of-posns Posn -> Posn List-of-posns -> Number Counts how many positions are in the list. List-of-posns -> List-of-posns
The first three lines of this file were inserted by . They record metadata #reader(lib "htdp-beginner-reader.ss" "lang")((modname ex159) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t constructor repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp") (lib "batch-io.rkt" "teachpack" "2htdp")) #f))) (define BALLOON (circle 5 "solid" "red")) (define GRID-SQUARE (square 10 "outline" "black")) (define (col n img) (cond [(zero? (sub1 n)) img] [(positive? (sub1 n)) (above img (col (sub1 n) img))])) (check-expect (col 3 GRID-SQUARE) (above GRID-SQUARE (above GRID-SQUARE GRID-SQUARE))) (check-expect (col 4 GRID-SQUARE) (above GRID-SQUARE (above GRID-SQUARE (above GRID-SQUARE GRID-SQUARE)))) (define (row n img) (cond [(zero? (sub1 n)) img] [(positive? (sub1 n)) (beside img (row (sub1 n) img))])) (check-expect (row 3 GRID-SQUARE) (beside GRID-SQUARE (beside GRID-SQUARE GRID-SQUARE))) (check-expect (row 4 GRID-SQUARE) (beside GRID-SQUARE (beside GRID-SQUARE (beside GRID-SQUARE GRID-SQUARE)))) (define LECTURE-HALL-GRID (row 10 (col 20 GRID-SQUARE))) (define LECTURE-HALL (overlay LECTURE-HALL-GRID (rectangle (image-width LECTURE-HALL-GRID) (image-height LECTURE-HALL-GRID) "solid" "white"))) (define WIDTH (image-width LECTURE-HALL)) An N is one of : – 0 (define lop1 (cons (make-posn 2 2.3) (cons (make-posn 7.6 3) '()))) (define lop2 (cons (make-posn 1 2) (cons (make-posn 2 4) (cons (make-posn 3 6) (cons (make-posn 4 8) (cons (make-posn 5 10) (cons (make-posn 6 12) (cons (make-posn 7 14) (cons (make-posn 8 16) (cons (make-posn 9 18) (cons (make-posn 10 20) '()))))))))))) (define-struct pair [balloon# lob]) Throws one balloon after the other to the lecture hall and produces (define (riot n) (pair-lob (big-bang (make-pair n '()) [to-draw render] [on-tick tock]))) (define (render p) (add-balloons (pair-lob p) LECTURE-HALL)) (check-expect (render (make-pair 7 lop1)) (add-balloons lop1 LECTURE-HALL)) (check-expect (render (make-pair 0 lop2)) (add-balloons lop2 LECTURE-HALL)) Makes the balloons fall one real pixel per tick , adding missing balloons one by one . (define (tock p) (make-pair (pair-balloon# p) (if (< (how-many (pair-lob p)) (pair-balloon# p)) (new-balloon (move-balloons (pair-lob p)) (pair-balloon# p)) (move-balloons (pair-lob p))))) (check-random (tock (make-pair 3 '())) (make-pair 3 (new-balloon (move-balloons '()) 3))) (check-expect (tock (make-pair 2 lop1)) (make-pair 2 (move-balloons lop1))) (define (add-balloons lop im) (cond [(empty? lop) im] [(cons? lop) (add-balloon (first lop) (add-balloons (rest lop) im))])) (check-expect (add-balloons lop1 LECTURE-HALL) (place-image BALLOON 76 30 (place-image BALLOON 20 23 LECTURE-HALL))) Each unit in the coordinates maps to 10 pixels in the image . (define (add-balloon p im) (place-image BALLOON (* 10 (posn-x p)) (* 10 (posn-y p)) im)) (check-expect (add-balloon (make-posn 2 2.3) LECTURE-HALL) (place-image BALLOON 20 23 LECTURE-HALL)) Make all balloons fall one real pixel . (define (move-balloons lob) (cond [(empty? lob) '()] [(cons? lob) (cons (move-balloon (first lob)) (move-balloons (rest lob)))])) (check-expect (move-balloons '()) '()) (check-expect (move-balloons lop1) (cons (make-posn 2 2.4) (cons (make-posn 7.6 3.1) '()))) Move ballon down one real pixel ( 0.1 unit ) . (define (move-balloon b) (make-posn (posn-x b) (+ (posn-y b) 0.1))) (check-expect (move-balloon (make-posn 5 3.5)) (make-posn 5 3.6)) (define (how-many list) (cond [(empty? list) 0] [(cons? list) (+ 1 (how-many (rest list)))])) (check-expect (how-many lop1) 2) (check-expect (how-many lop2) 10) Adds one balloon at some point above the canvas . (define (new-balloon lob n) (cons (make-posn (/ (random WIDTH) 10) (* -2 (random n))) lob)) (check-random (new-balloon (cons (make-posn 3 5) '()) 3) (cons (make-posn (/ (random WIDTH) 10) (* -2 (random 3))) (cons (make-posn 3 5) '())))
94207e56240a8f4307e71ea77c0f4d0a481e9bb656b515dc2711e21b54386252
mirage/ocaml-matrix
matrix_ctos.mli
open Json_encoding open Matrix_common module Account_data : sig module Put : sig module Query : Empty.QUERY module Request : sig type%accessor t = {data: Ezjsonm.value} val encoding : t encoding end module Response : Empty.JSON end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {data: Ezjsonm.value} val encoding : t encoding end end module Put_by_room : sig module Query : Empty.QUERY module Request : sig type%accessor t = {data: (string * string) list} val encoding : t encoding end module Response : Empty.JSON end module Get_by_room : sig module Query : Empty.QUERY module Response : sig type%accessor t = {data: (string * string) list} val encoding : t encoding end end end module Identifier : sig module User : sig type%accessor t = {user: string} val encoding : t encoding val pp : t Fmt.t end module Thirdparty : sig type%accessor t = {medium: string; address: string} val encoding : t encoding val pp : t Fmt.t end module Phone : sig type%accessor t = {country: string; phone: string} val encoding : t encoding val pp : t Fmt.t end type t = User of User.t | Thirdparty of Thirdparty.t | Phone of Phone.t val encoding : t encoding val pp : t Fmt.t end module Authentication : sig module Dummy : sig type t = unit val encoding : t encoding val pp : t Fmt.t end module Password : sig module V1 : sig type%accessor t = {user: string; password: string} val encoding : t encoding val pp : t Fmt.t end module V2 : sig type%accessor t = {identifier: Identifier.t; password: string} val encoding : t encoding val pp : t Fmt.t end type t = V1 of V1.t | V2 of V2.t val encoding : t encoding val pp : t Fmt.t end module Token : sig type%accessor t = {token: string; txn_id: string} val encoding : t encoding val pp : t Fmt.t end module Empty : Empty.JSON type t = | Dummy of Dummy.t | Password of Password.t | Token of Token.t | Empty of Empty.t val encoding : t encoding val pp : t Fmt.t end module Account : sig module Unbind_result : sig type t = Success | No_support val encoding : t encoding end module Password : sig module Post : sig module Query : Empty.QUERY module Request : sig type%accessor t = { auth: Authentication.Password.V1.t; new_password: string; } val encoding : t encoding end module Response : Empty.JSON end module Email_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; email: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = {sid: string; submit_url: string option} val encoding : t encoding end end module Msisdn_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; country: string; phone_number: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = {sid: string; submit_url: string option} val encoding : t encoding end end end module Deactivate : sig module Query : Empty.QUERY module Request : sig type%accessor t = { auth: Authentication.Password.V1.t; id_server: string option; } val encoding : t encoding end module Response : sig type%accessor t = {id_server_unbind_result: Unbind_result.t} val encoding : t encoding end end module Third_party_id : sig module Medium : sig type t = Email | Msisdn val encoding : t encoding end module Get : sig module Query : Empty.QUERY module Response : sig module Third_party_identifier : sig type%accessor t = { medium: Medium.t; address: string; validated_at: int; added_at: int; } val encoding : t encoding end type%accessor t = {threepids: Third_party_identifier.t list} val encoding : t encoding end end module Post : sig module Query : Empty.QUERY module Request : sig module Three_pid_creds : sig type%accessor t = { client_secret: string; id_server: string; sid: string; } val encoding : t encoding end type%accessor t = { three_pid_creds: Three_pid_creds.t; bind: bool option; } val encoding : t encoding end module Response : Empty.JSON end module Delete : sig module Query : Empty.QUERY module Request : sig type%accessor t = { id_server: string option; medium: Medium.t; address: string; } val encoding : t encoding end module Response : sig type%accessor t = {id_server_unbind_result: Unbind_result.t} val encoding : t encoding end end module Email_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; email: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = {sid: string; submit_url: string option} val encoding : t encoding end end module Msisdn_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; country: string; phone_number: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = {sid: string; submit_url: string option} val encoding : t encoding end end end module Whoami : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig type%accessor t = {user_id: string} val encoding : t encoding end end end module Audio_info : sig type%accessor t = { mimetype: string option; duration: int option; size: int option; } val encoding : t encoding end module Banning : sig module Ban : sig module Query : Empty.QUERY module Request : sig type%accessor t = {reason: string option; user_id: string} val encoding : t encoding end module Response : Empty.JSON end module Unban : sig module Query : Empty.QUERY module Request : sig type%accessor t = {user_id: string} val encoding : t encoding end module Response : Empty.JSON end end module Capabilities : sig module Capability : sig module Change_password : sig type%accessor t = {enabled: bool} val encoding : t encoding end module Room_versions : sig module Stability : sig type t = Stable | Unstable val encoding : t encoding end type%accessor t = { default: string; available: (string * Stability.t) list; } val encoding : t encoding end module Custom : sig type%accessor t = {name: string; content: Ezjsonm.value} val encoding : t encoding end type t = | Change_password of Change_password.t | Room_versions of Room_versions.t | Custom of Custom.t val encoding : t encoding end module Query : Empty.QUERY module Response : sig type%accessor t = {capabilities: Capability.t list} val encoding : t encoding end end module Device_lists : sig type%accessor t = {changed: string list option; left: string list option} val encoding : t encoding end module Devices : sig module Device : sig type%accessor t = { user_id: string option; (* Once again not advertised in the documentation *) device_id: string; display_name: string option; last_seen_ip: string option; last_seen_ts: int option; } val encoding : t encoding end module List : sig module Query : Empty.QUERY module Response : sig type%accessor t = {devices: Device.t list option} val encoding : t encoding end end module Get : sig module Query : Empty.QUERY module Response = Device end module Put : sig module Query : Empty.QUERY module Request : sig type%accessor t = {display_name: string option} val encoding : t encoding end module Response : Empty.JSON end module Delete : sig module Query : Empty.QUERY module Request : sig type%accessor t = {auth: Authentication.t option} val encoding : t encoding end module Response : Empty.JSON end module Delete_list : sig module Query : Empty.QUERY module Request : sig type%accessor t = {devices: string list; auth: Authentication.t option} val encoding : t encoding end module Response : Empty.JSON end end module Jwk : sig type%accessor t = { kty: string; key_ops: string list; alg: string; k: string; ext: bool; } val encoding : t encoding end module Encrypted_file : sig type%accessor t = { url: string; key: Jwk.t; iv: string; hashes: (string * string) list; v: string; } val encoding : t encoding end module Errors : sig module Error : sig type%accessor t = {errcode: string; error: string option} val encoding : t encoding val pp : t Fmt.t end module Rate_limited : sig type%accessor t = { errcode: string; error: string; retry_after_ms: int option; } val encoding : t encoding val pp : t Fmt.t end module Auth_error : sig module Flow : sig type%accessor t = {stages: string list} val encoding : t encoding val pp : t Fmt.t end type%accessor t = { errcode: string option; error: string option; completed: string list option; flows: Flow.t list; params: (string * (string * string) list) list option; session: string option; } val encoding : t encoding val pp : t Fmt.t end type t = | Error of Error.t | Auth_error of Auth_error.t | Rate_limited of Rate_limited.t val encoding : t encoding val pp : t Fmt.t end module Thumbnail_info : sig type%accessor t = { h: int option; w: int option; mimetype: string option; size: int option; } val encoding : t encoding end module Image_info : sig type%accessor t = { h: int option; w: int option; mimetype: string option; size: int option; thumbnail_url: string option; thumbnail_file: Encrypted_file.t option; thumbnail_info: Thumbnail_info.t option; } val encoding : t encoding end module File_info : sig type%accessor t = { mimetype: string option; size: int option; thumbnail_url: string option; thumbnail_file: Encrypted_file.t option; thumbnail_info: Thumbnail_info.t option; } val encoding : t encoding end module Location_info : sig type%accessor t = { thumbnail_url: string option; thumbnail_file: Encrypted_file.t option; thumbnail_info: Thumbnail_info.t option; } val encoding : t encoding end module Video_info : sig type%accessor t = { duration: int option; h: int option; w: int option; mimetype: string option; size: int option; thumbnail_url: string option; thumbnail_file: Encrypted_file.t option; thumbnail_info: Thumbnail_info.t option; } val encoding : t encoding end module Context : sig module Query : sig type%accessor t = {limit: int option} val args : t -> (string * string list) list end module Response : sig type%accessor t = { start: string option; end_: string option; events_before: Events.Room_event.t list option; event: Events.Room_event.t option; events_after: Events.Room_event.t list option; state: Events.State_event.t list option; } val encoding : t encoding end end module Filter : sig module Event_filter : sig type%accessor t = { limit: int option; not_senders: string list option; not_types: string list option; senders: string list option; types: string list option; } val encoding : t encoding end module State_filter : sig type%accessor t = { limit: int option; not_senders: string list option; not_types: string list option; senders: string list option; types: string list option; lazy_load_members: bool option; include_redundant_members: bool option; not_rooms: string list option; rooms: string list option; contains_url: bool option; } val encoding : t encoding end module Room_event_filter = State_filter module Room_filter : sig type%accessor t = { not_rooms: string list option; rooms: string list option; ephemeral: Room_event_filter.t option; include_leave: bool option; state: Room_event_filter.t option; timeline: Room_event_filter.t option; account_data: Room_event_filter.t option; } val encoding : t encoding end module Filter : sig module Event_format : sig type t = Client | Federation val encoding : t encoding end type%accessor t = { event_fields: string list option; event_format: Event_format.t option; presence: Event_filter.t option; account_data: Event_filter.t option; room: Room_filter.t option; } val encoding : t encoding end module Post : sig module Query : Empty.QUERY module Request = Filter module Response : sig type%accessor t = {filter_id: string} val encoding : t encoding end end module Get : sig module Query : Empty.QUERY module Response = Filter end end module Fully_read : sig module Query : Empty.QUERY module Request : sig type%accessor t = { fully_read: string option; (* see fully_read.ml *) read: string option; hidden: bool option; (* not in the documentation *) } val encoding : t encoding end module Response : Empty.JSON end module Joined : sig module Query : Empty.QUERY module Response : sig type%accessor t = {joined: string list} val encoding : t encoding end end module Joining : sig module Invite : sig module Query : Empty.QUERY module Request : sig type%accessor t = {user_id: string} val encoding : t encoding end module Response : Empty.JSON end module Invite_thirdparty : sig module Query : Empty.QUERY module Request : sig type%accessor t = {id_server: string; medium: string; address: string} val encoding : t encoding end module Response : Empty.JSON end module Join_with_id : sig module Query : Empty.QUERY module Request : sig type%accessor t = {third_party_signed: unit option} val encoding : t encoding end module Response : sig type%accessor t = {room_id: string} val encoding : t encoding end end module Join : sig module Query : sig type%accessor t = {server_name: string list option} val args : t -> (string * string list) list end module Request : sig type%accessor t = {third_party_signed: unit option} val encoding : t encoding end module Response : sig type%accessor t = {room_id: string} val encoding : t encoding end end end module Key_event : sig module Verification : sig module Request : sig type%accessor t = { from_device: string; transaction_id: string; methods: string list; timestamp: int; } val encoding : t encoding end module Start : sig type%accessor t = { from_device: string; transaction_id: string; verification_method: string; next_method: string; } val encoding : t encoding end module Cancel : sig type%accessor t = {transaction_id: string; reason: string; code: string} val encoding : t encoding end end module Sas_verification : sig module Sas : sig type t = Decimal | Emoji val encoding : t encoding end module Start : sig type%accessor t = { from_device: string; transaction_id: string; verification_method: string; key_agreement_protocols: string list; hashes: string list; message_authentication_codes: string list; short_authentication_string: Sas.t list; } val encoding : t encoding end module Accept : sig type%accessor t = { transaction_id: string; verification_method: string; key_agreement_protocol: string; hash: string; message_authentication_code: string; short_authentication_string: Sas.t list; commitment: string; } val encoding : t encoding end module Key : sig type%accessor t = {transaction_id: string; key: string} val encoding : t encoding end module Mac : sig type%accessor t = { transaction_id: string; mac: (string * string) list; keys: string; } val encoding : t encoding end end end module Keys : sig module Upload : sig module Query : Empty.QUERY module Request : sig module Device_keys : sig type%accessor t = { user_id: string; device_id: string; algorithms: string list; keys: (string * string) list; signatures: (string * (string * string) list) list; } val encoding : t encoding end module Keys_format : sig type t = Key of string | Object_key of Ezjsonm.value val encoding : t encoding end type%accessor t = { device_keys: Device_keys.t option; one_time_keys: (string * Keys_format.t) list option; } val encoding : t encoding end module Response : sig type%accessor t = {one_time_key_counts: (string * int) list} val encoding : t encoding end end module Query : sig module Query : Empty.QUERY module Request : sig type%accessor t = { timeout: int option; device_keys: (string * string list) list; token: string option; } val encoding : t encoding end module Response : sig module Device_keys : sig module Unsigned_device_info : sig type%accessor t = {device_display_name: string option} val encoding : t encoding end type%accessor t = { user_id: string; device_id: string; algorithms: string list; keys: (string * string) list; signatures: (string * (string * string) list) list; unsigned: Unsigned_device_info.t option; } val encoding : t encoding end type%accessor t = { failures: (string * Ezjsonm.value) list option; device_keys: (string * (string * Device_keys.t) list) list option; } val encoding : t encoding end end module Claim : sig module Query : Empty.QUERY module Request : sig type%accessor t = { timeout: int; one_time_keys: (string * (string * string) list) list; } val encoding : t encoding end module Response : sig type%accessor t = { failures: (string * Ezjsonm.value) list; one_time_keys: (string * (string * string) list) list; (* to correct *) } val encoding : t encoding end end module Changes : sig module Query : sig type%accessor t = {from: string; _to: string} val args : t -> (string * string list) list end module Response : sig type%accessor t = {changed: string list option; left: string list option} val encoding : t encoding end end end module Leaving : sig module Leave : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end module Forget : sig module Request : Empty.JSON module Response : Empty.JSON end module Kick : sig module Request : sig type%accessor t = {reason: string option; user_id: string} val encoding : t encoding end module Response : Empty.JSON end end module Well_known : sig module Query : Empty.QUERY module Response : sig type%accessor t = {homeserver: string; identity_server: string option} val encoding : t encoding val pp : Format.formatter -> t -> unit end end module Login : sig module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {types: string list option} val encoding : t encoding val pp : t Fmt.t end end module Post : sig module Query : Empty.QUERY module Request : sig type%accessor t = { auth: Authentication.t; device_id: string option; initial_device_display_name: string option; } val encoding : t encoding val pp : t Fmt.t end module Response : sig type%accessor t = { user_id: string option; access_token: string option; home_server: string option; device_id: string option; well_known: Well_known.Response.t option; } val encoding : t encoding val pp : t Fmt.t end end end module Logout : sig module Logout : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end module Logout_all : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end end module Media : sig val raw : Ezjsonm.value encoding module Upload : sig module Query : sig type%accessor t = {filename: string option} val args : t -> (string * string list) list module Header : sig type%accessor t = {content_type: string; content_length: int} val header : t -> (string * string) list end end module Request : sig type%accessor t = {file: string} val to_string : t -> string end module Response : sig type%accessor t = {content_uri: string} val encoding : t encoding end end module Download : sig module Query : sig type%accessor t = {allow_remote: bool option} val args : t -> (string * string list) list end module Response : sig type%accessor t = {file: string} val of_string : string -> t end end module Download_filename : sig module Response = Download.Response module Query = Download.Query end module Thumbnail : sig module Query : sig module Rezising : sig type t = Crop | Scale end type%accessor t = { width: int; height: int; rezising_method: Rezising.t option; allow_remote: bool option; } val args : t -> (string * string list) list end module Response : sig type%accessor t = {thumbnail: string} val of_string : string -> t end end module Preview : sig module Query : sig type%accessor t = {url: string; ts: int option} val args : t -> (string * string list) list end module Response : sig type%accessor t = {infos: (string * Ezjsonm.value) list} val encoding : t encoding end end module Config : sig module Query : Empty.QUERY module Response : sig type%accessor t = {upload_size: int option} val encoding : t encoding end end end module Notifications : sig module Query : sig type%accessor t = { from: string option; limit: int option; only: bool option; } val args : t -> (string * string list) list end module Response : sig module Notification : sig type%accessor t = { actions: Push_rule.Action.t; event: Events.Room_event.t; profile_tag: string option; read: bool; room_id: string; ts: int; } val encoding : t encoding end type%accessor t = { next_token: string option option; notifications: Notification.t list; } val encoding : t encoding end end module Open_id : sig module Query : Empty.QUERY module Response : sig type%accessor t = { access_token: string; token_type: string; matrix_server_name: string; expires_in: int; } val encoding : t encoding end end module Presence : sig module Put : sig module Query : Empty.QUERY module Request : sig type%accessor t = { presence: Events.Event_content.Presence.Presence.t; status_msg: string option; } val encoding : t encoding end module Response : Empty.JSON end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = { presence: Events.Event_content.Presence.Presence.t; last_active_ago: int option; status_msg: string option; currently_active: bool option; user_id: string option; } val encoding : t encoding end end end module Preview : sig module Query : sig type%accessor t = { from: string option; timeout: int option; room_id: string option; } val args : t -> (string * string list) list end module Response : sig type%accessor t = { start: string option; end_: string option; chunk: Events.Room_event.t list option; } val encoding : t encoding end end module Profile : sig module Display_name : sig module Set : sig module Query : Empty.QUERY module Request : sig type%accessor t = {displayname: string option} val encoding : t encoding end module Response : Empty.JSON end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {displayname: string option} val encoding : t encoding end end end module Avatar_url : sig module Set : sig module Query : Empty.QUERY module Request : sig type%accessor t = {avatar_url: string option} val encoding : t encoding end module Response : Empty.JSON end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {avatar_url: string option} val encoding : t encoding end end end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {displayname: string option; avatar_url: string option} val encoding : t encoding end end end module Push_rules : sig module Kind : sig type t = Override | Underride | Sender | Room | Content end module Get_all : sig module Query : Empty.QUERY module Response : sig type%accessor t = { content: Push_rule.t list option; override: Push_rule.t list option; room: Push_rule.t list option; sender: Push_rule.t list option; underride: Push_rule.t list option; } val encoding : t encoding end end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {push_rules: Push_rule.t} val encoding : t encoding end end module Delete : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end module Put : sig module Query : sig type%accessor t = {before: string option; after: string option} val args : t -> (string * string list) list end module Request : sig module Action : sig type t = Notify | Dont_notify | Coalesce | Set_weak val encoding : t encoding end type%accessor t = { actions: Action.t list; conditions: Push_rule.Push_condition.t list; pattern: string; } val encoding : t encoding end module Response : Empty.JSON end module Get_enabled : sig module Query : Empty.QUERY module Response : sig type%accessor t = {enabled: bool} val encoding : t encoding end end module Set_enabled : sig module Query : Empty.QUERY module Request : sig type%accessor t = {enabled: bool} val encoding : t encoding end module Response : Empty.JSON end module Get_actions : sig module Query : Empty.QUERY module Response : sig type%accessor t = {actions: string list} val encoding : t encoding end end module Set_actions : sig module Query : Empty.QUERY module Request : sig type%accessor t = {actions: string list} val encoding : t encoding end module Response : Empty.JSON end end module Pushers : sig module Pusher : sig module Pusher_data : sig type%accessor t = {url: string option; format: string option} val encoding : t encoding end type%accessor t = { pushkey: string; kind: string; app_id: string; app_display_name: string; device_display_name: string; profile_tag: string option; lang: string; data: Pusher_data.t; } val encoding : t encoding end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {pushers: Pusher.t list option} val encoding : t encoding end end module Set : sig module Query : Empty.QUERY module Request : sig type%accessor t = {pusher: Pusher.t; append: bool option} val encoding : t encoding end module Response : Empty.JSON end end module Receipt : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end module Register : sig module Register : sig module Query : sig module Kind : sig type t = User | Guest end type%accessor t = {kind: Kind.t option} val args : t -> (string * string list) list end module Request : sig type%accessor t = { auth: Authentication.t option; bind_email: bool option; bind_msisdn: bool option; username: string option; password: string option; device_id: string option; initial_device_display_name: string option; inhibit_login: bool option; } val encoding : t encoding end module Response : sig type%accessor t = { user_id: string; access_token: string option; home_server: string; device_id: string option; } val encoding : t encoding end end module Available : sig module Query : sig type%accessor t = {username: string} val args : t -> (string * string list) list end module Request : Empty.JSON module Response : sig type%accessor t = {available: bool} val encoding : t encoding end end module Email_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; email: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = { success: bool option; sid: string; submit_url: string option; } val encoding : t encoding end end module Msisdn_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; country: string; phone_number: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = { success: bool option; sid: string; submit_url: string option; msisdn: string option; intl_fmt: string option; } val encoding : t encoding end end end module Report : sig module Query : Empty.QUERY module Request : sig type%accessor t = {score: int; reason: string} val encoding : t encoding end module Response : Empty.JSON end module Room_event : sig module Get : sig module Event : sig module Query : Empty.QUERY module Request : Empty.JSON module Response = Events.Room_event end module State_key : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig type t = Ezjsonm.value val encoding : t encoding end end module State : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig type%accessor t = {events: Events.State_event.t list} val encoding : t encoding end end module Members : sig module Query : sig type%accessor t = { at: string option; membership: Events.Event_content.Membership.t option; not_membership: Events.Event_content.Membership.t option; } val args : t -> (string * string list) list end module Request : Empty.JSON module Response : sig type%accessor t = {chunk: Events.State_event.t list} val encoding : t encoding end end module Joined_members : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig module User : sig type%accessor t = { display_name: string option; avatar_url: string option; } val encoding : t encoding end type%accessor t = {joined: (string * User.t) list option} val encoding : t encoding end end end module Put : sig module State_event : sig module Query = Empty.Query module Request : sig type%accessor t = {event: Events.Event_content.t} val encoding : t encoding end module Response : sig type%accessor t = {event_id: string} val encoding : t encoding end end module Message_event : sig module Query = Empty.Query module Request : sig type%accessor t = {event: Events.Event_content.Message.t} val encoding : t encoding end module Response : sig type%accessor t = {event_id: string} val encoding : t encoding end end end end module Room : sig module Visibility : sig type t = Public | Private val encoding : t encoding end module Create : sig module Query : Empty.QUERY module Request : sig module Invite_3pid : sig type%accessor t = {id_server: string; medium: string; addresss: string} val encoding : t encoding end module Preset : sig type t = Public | Private | Trusted_private val encoding : t encoding end type%accessor t = { visibility: Visibility.t option; room_alias_name: string option; name: string option; topic: string option; invite: string list option; invite_3pid: Invite_3pid.t list option; room_version: string option; creation_content: Events.Event_content.Create.t option; initial_state: Events.State_event.t list option; preset: Preset.t option; is_direct: bool option; power_level_content_override: Events.Event_content.Power_levels.t option; } val encoding : t encoding end module Response : sig type%accessor t = {room_id: string} val encoding : t encoding end end module Create_alias : sig module Query : Empty.QUERY module Request : sig type%accessor t = {room_id: string} val encoding : t encoding end module Response : Empty.JSON end module Resolve_alias : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig type%accessor t = {room_id: string option; servers: string list option} val encoding : t encoding end end module Delete_alias : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end end module Room_listing : sig module Get_visibility : sig module Query : Empty.QUERY module Response : sig type%accessor t = {visibility: Room.Visibility.t} val encoding : t encoding end end module Set_visibility : sig module Query : Empty.QUERY module Request : sig type%accessor t = {visibility: Room.Visibility.t option} val encoding : t encoding end module Response : Empty.JSON end module Get_public_rooms : sig module Query : sig type%accessor t = { limit: int option; since: string option; server: string option; } val args : t -> (string * string list) list end module Response : sig module Public_rooms_chunk : sig type%accessor t = { aliases: string list option; canonical_alias: string option; name: string option; num_joined_members: int; room_id: string; topic: string option; world_readable: bool; guest_can_join: bool; avatar_url: string option; federate: bool option; } val encoding : t encoding end type%accessor t = { chunk: Public_rooms_chunk.t list; next_batch: string option; prev_batch: string option; total_room_count_estimate: int option; } val encoding : t encoding end end module Filter_public_rooms : sig module Query : sig type%accessor t = {server: string option} val args : t -> (string * string list) list end module Request : sig module Filter : sig type%accessor t = {generic_search_term: string option} val encoding : t encoding end type%accessor t = { limit: int option; since: string option; filter: Filter.t option; include_all_networks: bool option; third_party_instance_id: string option; } val encoding : t encoding end module Response = Get_public_rooms.Response end end module Rooms : sig module Room_summary : sig type%accessor t = { heroes: string list option; joined_member_count: int option; invited_member_count: int option; } val encoding : t encoding end module Timeline : sig type%accessor t = { events: Events.Room_event.t list option; limited: bool option; prev_batch: string option; } val encoding : t encoding end module Joined_room : sig module Unread_notifications : sig type%accessor t = { highlight_count: int option; notification_count: int option; } val encoding : t encoding end type%accessor t = { summary: Room_summary.t option; state: Events.State_event.t list option; timeline: Timeline.t option; ephemeral: Events.Event.t list option; account_data: Events.Event.t list option; unread_notifications: Unread_notifications.t option; } val encoding : t encoding end module Invited_room : sig type%accessor t = {invite_state: Events.State_event.t list option} val encoding : t encoding end module Left_room : sig type%accessor t = { state: Events.State_event.t list option; timeline: Timeline.t option; account_data: Events.Room_event.t list option; } val encoding : t encoding end type%accessor t = { join: (string * Joined_room.t) list; invite: (string * Invited_room.t) list; leave: (string * Left_room.t) list; } val encoding : t encoding end module Search : sig module Query : sig type%accessor t = {next_batch: string option} val args : t -> (string * string list) list end module Request : sig module Criteria : sig module Key : sig type t = Content_body | Content_name | Content_topic val encoding : t encoding end module Filter : sig type%accessor t = { limit: int option; not_senders: string list option; not_types: string list option; senders: string list option; types: string list option; lazy_load_members: bool option; include_redundant_members: bool option; not_rooms: string list option; rooms: string list option; contains_url: bool option; } val encoding : t encoding end module Order : sig type t = Recent | Rank val encoding : t encoding end module Include_event_context : sig type%accessor t = { before_limit: int option; after_limit: int option; include_profile: bool option; } val encoding : t encoding end module Groupings : sig module Group : sig type t = Room_id | Sender val encoding : t encoding end type%accessor t = {group_by: Group.t list option} val encoding : t encoding end type%accessor t = { search_term: string; keys: Key.t option; filter: Filter.t option; order_by: Order.t option; event_context: Include_event_context.t option; include_state: bool option; groupings: Groupings.t option; } val encoding : t encoding end type%accessor t = {criterias: Criteria.t option} val encoding : t encoding end module Response : sig module Results : sig module Result : sig module Event_context : sig module User_profile : sig type%accessor t = { displayname: string option; avatar_url: string option; } val encoding : t encoding end type%accessor t = { start: string option; end_: string option; profile_info: (string * User_profile.t) list option; events_before: Events.Room_event.t list option; events_after: Events.Room_event.t list option; } val encoding : t encoding end type%accessor t = { rank: int option; result: Events.Room_event.t option; context: Event_context.t option; } val encoding : t encoding end module Group_value : sig type%accessor t = { next_batch: string option; order: int option; results: string list option; } val encoding : t encoding end type%accessor t = { count: int option; highlights: string list option; results: Result.t list option; state: (string * Events.State_event.t) list option; groups: (string * (string * Group_value.t) list) list option; next_batch: string option; } val encoding : t encoding end type%accessor t = {results: Results.t option} val encoding : t encoding end end module Send_to_device : sig module Query : Empty.QUERY module Request : sig type%accessor t = { messages: (string * (string * Ezjsonm.value) list) list option; } val encoding : t encoding end module Response : Empty.JSON end module Session_data : sig type%accessor t = { algorithm: string; forwarding_curve25519_key_chain: string list; room_id: string; sender_key: string; sender_claimed_keys: (string * string) list; session_id: string; session_key: string; } val encoding : t encoding end module Sso : sig module Query : sig type%accessor t = {redirect_url: string} val args : t -> (string * string list) list end module Response : Empty.JSON end module Sync : sig module Query : sig module Presence : sig type t = Offline | Online | Unavailable val pp : Format.formatter -> t -> unit end type%accessor t = { filter: string option; since: string option; full_state: bool option; set_presence: Presence.t option; timeout: int option; } val args : t -> (string * string list) list val pp : t Fmt.t end module Response : sig type%accessor t = { next_batch: string; rooms: Rooms.t option; presence: Events.State_event.t list option; account_data: Events.State_event.t list option; to_device: Events.State_event.t list option; device_lists: Device_lists.t option; device_one_time_keys_count: (string * int) list option; groups: Ezjsonm.value option; (* Not on the documentation*) } val encoding : t encoding val pp : t Fmt.t end end module Tag : sig module Get : sig module Query : Empty.QUERY module Response : sig module Tag : sig type%accessor t = {order: float option} val encoding : t encoding end type%accessor t = {tags: (string * Tag.t) list} val encoding : t encoding end end module Put : sig module Query : Empty.QUERY module Request : sig type%accessor t = {order: float option} val encoding : t encoding end module Response : Empty.JSON end module Delete : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end end module Third_party_network : sig module Protocol : sig module Field_type : sig type%accessor t = {regexp: string; placeholder: string} val encoding : t encoding end module Instance : sig type%accessor t = { desc: string; icon: string option; fields: (string * string) list; network_id: string; } val encoding : t encoding end type%accessor t = { user_fields: string list; location_fields: string list; icon: string; field_types: (string * Field_type.t) list; instances: Instance.t list; } val encoding : t encoding end module Location : sig type%accessor t = { alias: string; protocol: string; fields: (string * string) list; } val encoding : t encoding end module User : sig type%accessor t = { user_id: string; protocol: string; fields: (string * string) list; } val encoding : t encoding end module Protocols : sig module Query : Empty.QUERY module Response : sig type%accessor t = {protocols: (string * Protocol.t) list} val encoding : t encoding end end module Get_protocol : sig module Query : Empty.QUERY module Response = Protocol end module Get_location : sig module Query : sig type%accessor t = {search_fields: string option} val args : t -> (string * string list) list end module Response : sig type%accessor t = {locations: Location.t list} val encoding : t encoding end end module Get_user : sig module Query : sig type%accessor t = {fields: (string * string list) list option} val args : t -> (string * string list) list end module Response : sig type%accessor t = {users: User.t list} val encoding : t encoding end end module Location_from_alias : sig module Query : sig type%accessor t = {alias: string} val args : t -> (string * string list) list end module Response : sig type%accessor t = {locations: Location.t list} val encoding : t encoding end end module User_from_user_id : sig module Query : sig type%accessor t = {user_id: string} val args : t -> (string * string list) list end module Response : sig type%accessor t = {users: User.t list} val encoding : t encoding end end end module Typing : sig module Query : Empty.QUERY module Request : sig type%accessor t = {typing: bool; timeout: int option} val encoding : t encoding end module Response : Empty.JSON end module Upgrade : sig module Query : Empty.QUERY module Request : sig type%accessor t = {new_version: string} val encoding : t encoding end module Response : sig type%accessor t = {replacement_room: string} val encoding : t encoding end end module User_directory : sig module Search : sig module Query : Empty.QUERY module Request : sig type%accessor t = {search_term: string; limited: int option} val encoding : t encoding end module Response : sig module User : sig type%accessor t = { user_id: string; display_name: string option; avatar_url: string option; } val encoding : t encoding end type%accessor t = {results: User.t list; limited: bool} val encoding : t encoding end end end module Versions : sig module Query : Empty.QUERY module Response : sig type%accessor t = { versions: string list; unstable_features: (string * bool) list option; } val encoding : t encoding end end module Voip : sig module Query : Empty.QUERY module Response : sig type%accessor t = { username: string option; password: string option; uris: string list option; ttl: int option; } val encoding : t encoding end end module Whois : sig module Query : Empty.QUERY module Response : sig module Device_info : sig module Session_info : sig module Connection_info : sig type%accessor t = { ip: string option; last_seen: int option; user_agent: string option; } val encoding : t encoding end type%accessor t = {connections: Connection_info.t list option} val encoding : t encoding end type%accessor t = {sessions: Session_info.t list option} val encoding : t encoding end type%accessor t = { user_id: string option; devices: (string * Device_info.t) list option; } val encoding : t encoding end end
null
https://raw.githubusercontent.com/mirage/ocaml-matrix/2a58d3d41c43404741f2dfdaf1d2d0f3757b2b69/lib/matrix-ctos/matrix_ctos.mli
ocaml
Once again not advertised in the documentation see fully_read.ml not in the documentation to correct Not on the documentation
open Json_encoding open Matrix_common module Account_data : sig module Put : sig module Query : Empty.QUERY module Request : sig type%accessor t = {data: Ezjsonm.value} val encoding : t encoding end module Response : Empty.JSON end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {data: Ezjsonm.value} val encoding : t encoding end end module Put_by_room : sig module Query : Empty.QUERY module Request : sig type%accessor t = {data: (string * string) list} val encoding : t encoding end module Response : Empty.JSON end module Get_by_room : sig module Query : Empty.QUERY module Response : sig type%accessor t = {data: (string * string) list} val encoding : t encoding end end end module Identifier : sig module User : sig type%accessor t = {user: string} val encoding : t encoding val pp : t Fmt.t end module Thirdparty : sig type%accessor t = {medium: string; address: string} val encoding : t encoding val pp : t Fmt.t end module Phone : sig type%accessor t = {country: string; phone: string} val encoding : t encoding val pp : t Fmt.t end type t = User of User.t | Thirdparty of Thirdparty.t | Phone of Phone.t val encoding : t encoding val pp : t Fmt.t end module Authentication : sig module Dummy : sig type t = unit val encoding : t encoding val pp : t Fmt.t end module Password : sig module V1 : sig type%accessor t = {user: string; password: string} val encoding : t encoding val pp : t Fmt.t end module V2 : sig type%accessor t = {identifier: Identifier.t; password: string} val encoding : t encoding val pp : t Fmt.t end type t = V1 of V1.t | V2 of V2.t val encoding : t encoding val pp : t Fmt.t end module Token : sig type%accessor t = {token: string; txn_id: string} val encoding : t encoding val pp : t Fmt.t end module Empty : Empty.JSON type t = | Dummy of Dummy.t | Password of Password.t | Token of Token.t | Empty of Empty.t val encoding : t encoding val pp : t Fmt.t end module Account : sig module Unbind_result : sig type t = Success | No_support val encoding : t encoding end module Password : sig module Post : sig module Query : Empty.QUERY module Request : sig type%accessor t = { auth: Authentication.Password.V1.t; new_password: string; } val encoding : t encoding end module Response : Empty.JSON end module Email_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; email: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = {sid: string; submit_url: string option} val encoding : t encoding end end module Msisdn_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; country: string; phone_number: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = {sid: string; submit_url: string option} val encoding : t encoding end end end module Deactivate : sig module Query : Empty.QUERY module Request : sig type%accessor t = { auth: Authentication.Password.V1.t; id_server: string option; } val encoding : t encoding end module Response : sig type%accessor t = {id_server_unbind_result: Unbind_result.t} val encoding : t encoding end end module Third_party_id : sig module Medium : sig type t = Email | Msisdn val encoding : t encoding end module Get : sig module Query : Empty.QUERY module Response : sig module Third_party_identifier : sig type%accessor t = { medium: Medium.t; address: string; validated_at: int; added_at: int; } val encoding : t encoding end type%accessor t = {threepids: Third_party_identifier.t list} val encoding : t encoding end end module Post : sig module Query : Empty.QUERY module Request : sig module Three_pid_creds : sig type%accessor t = { client_secret: string; id_server: string; sid: string; } val encoding : t encoding end type%accessor t = { three_pid_creds: Three_pid_creds.t; bind: bool option; } val encoding : t encoding end module Response : Empty.JSON end module Delete : sig module Query : Empty.QUERY module Request : sig type%accessor t = { id_server: string option; medium: Medium.t; address: string; } val encoding : t encoding end module Response : sig type%accessor t = {id_server_unbind_result: Unbind_result.t} val encoding : t encoding end end module Email_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; email: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = {sid: string; submit_url: string option} val encoding : t encoding end end module Msisdn_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; country: string; phone_number: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = {sid: string; submit_url: string option} val encoding : t encoding end end end module Whoami : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig type%accessor t = {user_id: string} val encoding : t encoding end end end module Audio_info : sig type%accessor t = { mimetype: string option; duration: int option; size: int option; } val encoding : t encoding end module Banning : sig module Ban : sig module Query : Empty.QUERY module Request : sig type%accessor t = {reason: string option; user_id: string} val encoding : t encoding end module Response : Empty.JSON end module Unban : sig module Query : Empty.QUERY module Request : sig type%accessor t = {user_id: string} val encoding : t encoding end module Response : Empty.JSON end end module Capabilities : sig module Capability : sig module Change_password : sig type%accessor t = {enabled: bool} val encoding : t encoding end module Room_versions : sig module Stability : sig type t = Stable | Unstable val encoding : t encoding end type%accessor t = { default: string; available: (string * Stability.t) list; } val encoding : t encoding end module Custom : sig type%accessor t = {name: string; content: Ezjsonm.value} val encoding : t encoding end type t = | Change_password of Change_password.t | Room_versions of Room_versions.t | Custom of Custom.t val encoding : t encoding end module Query : Empty.QUERY module Response : sig type%accessor t = {capabilities: Capability.t list} val encoding : t encoding end end module Device_lists : sig type%accessor t = {changed: string list option; left: string list option} val encoding : t encoding end module Devices : sig module Device : sig type%accessor t = { user_id: string option; device_id: string; display_name: string option; last_seen_ip: string option; last_seen_ts: int option; } val encoding : t encoding end module List : sig module Query : Empty.QUERY module Response : sig type%accessor t = {devices: Device.t list option} val encoding : t encoding end end module Get : sig module Query : Empty.QUERY module Response = Device end module Put : sig module Query : Empty.QUERY module Request : sig type%accessor t = {display_name: string option} val encoding : t encoding end module Response : Empty.JSON end module Delete : sig module Query : Empty.QUERY module Request : sig type%accessor t = {auth: Authentication.t option} val encoding : t encoding end module Response : Empty.JSON end module Delete_list : sig module Query : Empty.QUERY module Request : sig type%accessor t = {devices: string list; auth: Authentication.t option} val encoding : t encoding end module Response : Empty.JSON end end module Jwk : sig type%accessor t = { kty: string; key_ops: string list; alg: string; k: string; ext: bool; } val encoding : t encoding end module Encrypted_file : sig type%accessor t = { url: string; key: Jwk.t; iv: string; hashes: (string * string) list; v: string; } val encoding : t encoding end module Errors : sig module Error : sig type%accessor t = {errcode: string; error: string option} val encoding : t encoding val pp : t Fmt.t end module Rate_limited : sig type%accessor t = { errcode: string; error: string; retry_after_ms: int option; } val encoding : t encoding val pp : t Fmt.t end module Auth_error : sig module Flow : sig type%accessor t = {stages: string list} val encoding : t encoding val pp : t Fmt.t end type%accessor t = { errcode: string option; error: string option; completed: string list option; flows: Flow.t list; params: (string * (string * string) list) list option; session: string option; } val encoding : t encoding val pp : t Fmt.t end type t = | Error of Error.t | Auth_error of Auth_error.t | Rate_limited of Rate_limited.t val encoding : t encoding val pp : t Fmt.t end module Thumbnail_info : sig type%accessor t = { h: int option; w: int option; mimetype: string option; size: int option; } val encoding : t encoding end module Image_info : sig type%accessor t = { h: int option; w: int option; mimetype: string option; size: int option; thumbnail_url: string option; thumbnail_file: Encrypted_file.t option; thumbnail_info: Thumbnail_info.t option; } val encoding : t encoding end module File_info : sig type%accessor t = { mimetype: string option; size: int option; thumbnail_url: string option; thumbnail_file: Encrypted_file.t option; thumbnail_info: Thumbnail_info.t option; } val encoding : t encoding end module Location_info : sig type%accessor t = { thumbnail_url: string option; thumbnail_file: Encrypted_file.t option; thumbnail_info: Thumbnail_info.t option; } val encoding : t encoding end module Video_info : sig type%accessor t = { duration: int option; h: int option; w: int option; mimetype: string option; size: int option; thumbnail_url: string option; thumbnail_file: Encrypted_file.t option; thumbnail_info: Thumbnail_info.t option; } val encoding : t encoding end module Context : sig module Query : sig type%accessor t = {limit: int option} val args : t -> (string * string list) list end module Response : sig type%accessor t = { start: string option; end_: string option; events_before: Events.Room_event.t list option; event: Events.Room_event.t option; events_after: Events.Room_event.t list option; state: Events.State_event.t list option; } val encoding : t encoding end end module Filter : sig module Event_filter : sig type%accessor t = { limit: int option; not_senders: string list option; not_types: string list option; senders: string list option; types: string list option; } val encoding : t encoding end module State_filter : sig type%accessor t = { limit: int option; not_senders: string list option; not_types: string list option; senders: string list option; types: string list option; lazy_load_members: bool option; include_redundant_members: bool option; not_rooms: string list option; rooms: string list option; contains_url: bool option; } val encoding : t encoding end module Room_event_filter = State_filter module Room_filter : sig type%accessor t = { not_rooms: string list option; rooms: string list option; ephemeral: Room_event_filter.t option; include_leave: bool option; state: Room_event_filter.t option; timeline: Room_event_filter.t option; account_data: Room_event_filter.t option; } val encoding : t encoding end module Filter : sig module Event_format : sig type t = Client | Federation val encoding : t encoding end type%accessor t = { event_fields: string list option; event_format: Event_format.t option; presence: Event_filter.t option; account_data: Event_filter.t option; room: Room_filter.t option; } val encoding : t encoding end module Post : sig module Query : Empty.QUERY module Request = Filter module Response : sig type%accessor t = {filter_id: string} val encoding : t encoding end end module Get : sig module Query : Empty.QUERY module Response = Filter end end module Fully_read : sig module Query : Empty.QUERY module Request : sig type%accessor t = { fully_read: string option; read: string option; } val encoding : t encoding end module Response : Empty.JSON end module Joined : sig module Query : Empty.QUERY module Response : sig type%accessor t = {joined: string list} val encoding : t encoding end end module Joining : sig module Invite : sig module Query : Empty.QUERY module Request : sig type%accessor t = {user_id: string} val encoding : t encoding end module Response : Empty.JSON end module Invite_thirdparty : sig module Query : Empty.QUERY module Request : sig type%accessor t = {id_server: string; medium: string; address: string} val encoding : t encoding end module Response : Empty.JSON end module Join_with_id : sig module Query : Empty.QUERY module Request : sig type%accessor t = {third_party_signed: unit option} val encoding : t encoding end module Response : sig type%accessor t = {room_id: string} val encoding : t encoding end end module Join : sig module Query : sig type%accessor t = {server_name: string list option} val args : t -> (string * string list) list end module Request : sig type%accessor t = {third_party_signed: unit option} val encoding : t encoding end module Response : sig type%accessor t = {room_id: string} val encoding : t encoding end end end module Key_event : sig module Verification : sig module Request : sig type%accessor t = { from_device: string; transaction_id: string; methods: string list; timestamp: int; } val encoding : t encoding end module Start : sig type%accessor t = { from_device: string; transaction_id: string; verification_method: string; next_method: string; } val encoding : t encoding end module Cancel : sig type%accessor t = {transaction_id: string; reason: string; code: string} val encoding : t encoding end end module Sas_verification : sig module Sas : sig type t = Decimal | Emoji val encoding : t encoding end module Start : sig type%accessor t = { from_device: string; transaction_id: string; verification_method: string; key_agreement_protocols: string list; hashes: string list; message_authentication_codes: string list; short_authentication_string: Sas.t list; } val encoding : t encoding end module Accept : sig type%accessor t = { transaction_id: string; verification_method: string; key_agreement_protocol: string; hash: string; message_authentication_code: string; short_authentication_string: Sas.t list; commitment: string; } val encoding : t encoding end module Key : sig type%accessor t = {transaction_id: string; key: string} val encoding : t encoding end module Mac : sig type%accessor t = { transaction_id: string; mac: (string * string) list; keys: string; } val encoding : t encoding end end end module Keys : sig module Upload : sig module Query : Empty.QUERY module Request : sig module Device_keys : sig type%accessor t = { user_id: string; device_id: string; algorithms: string list; keys: (string * string) list; signatures: (string * (string * string) list) list; } val encoding : t encoding end module Keys_format : sig type t = Key of string | Object_key of Ezjsonm.value val encoding : t encoding end type%accessor t = { device_keys: Device_keys.t option; one_time_keys: (string * Keys_format.t) list option; } val encoding : t encoding end module Response : sig type%accessor t = {one_time_key_counts: (string * int) list} val encoding : t encoding end end module Query : sig module Query : Empty.QUERY module Request : sig type%accessor t = { timeout: int option; device_keys: (string * string list) list; token: string option; } val encoding : t encoding end module Response : sig module Device_keys : sig module Unsigned_device_info : sig type%accessor t = {device_display_name: string option} val encoding : t encoding end type%accessor t = { user_id: string; device_id: string; algorithms: string list; keys: (string * string) list; signatures: (string * (string * string) list) list; unsigned: Unsigned_device_info.t option; } val encoding : t encoding end type%accessor t = { failures: (string * Ezjsonm.value) list option; device_keys: (string * (string * Device_keys.t) list) list option; } val encoding : t encoding end end module Claim : sig module Query : Empty.QUERY module Request : sig type%accessor t = { timeout: int; one_time_keys: (string * (string * string) list) list; } val encoding : t encoding end module Response : sig type%accessor t = { failures: (string * Ezjsonm.value) list; } val encoding : t encoding end end module Changes : sig module Query : sig type%accessor t = {from: string; _to: string} val args : t -> (string * string list) list end module Response : sig type%accessor t = {changed: string list option; left: string list option} val encoding : t encoding end end end module Leaving : sig module Leave : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end module Forget : sig module Request : Empty.JSON module Response : Empty.JSON end module Kick : sig module Request : sig type%accessor t = {reason: string option; user_id: string} val encoding : t encoding end module Response : Empty.JSON end end module Well_known : sig module Query : Empty.QUERY module Response : sig type%accessor t = {homeserver: string; identity_server: string option} val encoding : t encoding val pp : Format.formatter -> t -> unit end end module Login : sig module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {types: string list option} val encoding : t encoding val pp : t Fmt.t end end module Post : sig module Query : Empty.QUERY module Request : sig type%accessor t = { auth: Authentication.t; device_id: string option; initial_device_display_name: string option; } val encoding : t encoding val pp : t Fmt.t end module Response : sig type%accessor t = { user_id: string option; access_token: string option; home_server: string option; device_id: string option; well_known: Well_known.Response.t option; } val encoding : t encoding val pp : t Fmt.t end end end module Logout : sig module Logout : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end module Logout_all : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end end module Media : sig val raw : Ezjsonm.value encoding module Upload : sig module Query : sig type%accessor t = {filename: string option} val args : t -> (string * string list) list module Header : sig type%accessor t = {content_type: string; content_length: int} val header : t -> (string * string) list end end module Request : sig type%accessor t = {file: string} val to_string : t -> string end module Response : sig type%accessor t = {content_uri: string} val encoding : t encoding end end module Download : sig module Query : sig type%accessor t = {allow_remote: bool option} val args : t -> (string * string list) list end module Response : sig type%accessor t = {file: string} val of_string : string -> t end end module Download_filename : sig module Response = Download.Response module Query = Download.Query end module Thumbnail : sig module Query : sig module Rezising : sig type t = Crop | Scale end type%accessor t = { width: int; height: int; rezising_method: Rezising.t option; allow_remote: bool option; } val args : t -> (string * string list) list end module Response : sig type%accessor t = {thumbnail: string} val of_string : string -> t end end module Preview : sig module Query : sig type%accessor t = {url: string; ts: int option} val args : t -> (string * string list) list end module Response : sig type%accessor t = {infos: (string * Ezjsonm.value) list} val encoding : t encoding end end module Config : sig module Query : Empty.QUERY module Response : sig type%accessor t = {upload_size: int option} val encoding : t encoding end end end module Notifications : sig module Query : sig type%accessor t = { from: string option; limit: int option; only: bool option; } val args : t -> (string * string list) list end module Response : sig module Notification : sig type%accessor t = { actions: Push_rule.Action.t; event: Events.Room_event.t; profile_tag: string option; read: bool; room_id: string; ts: int; } val encoding : t encoding end type%accessor t = { next_token: string option option; notifications: Notification.t list; } val encoding : t encoding end end module Open_id : sig module Query : Empty.QUERY module Response : sig type%accessor t = { access_token: string; token_type: string; matrix_server_name: string; expires_in: int; } val encoding : t encoding end end module Presence : sig module Put : sig module Query : Empty.QUERY module Request : sig type%accessor t = { presence: Events.Event_content.Presence.Presence.t; status_msg: string option; } val encoding : t encoding end module Response : Empty.JSON end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = { presence: Events.Event_content.Presence.Presence.t; last_active_ago: int option; status_msg: string option; currently_active: bool option; user_id: string option; } val encoding : t encoding end end end module Preview : sig module Query : sig type%accessor t = { from: string option; timeout: int option; room_id: string option; } val args : t -> (string * string list) list end module Response : sig type%accessor t = { start: string option; end_: string option; chunk: Events.Room_event.t list option; } val encoding : t encoding end end module Profile : sig module Display_name : sig module Set : sig module Query : Empty.QUERY module Request : sig type%accessor t = {displayname: string option} val encoding : t encoding end module Response : Empty.JSON end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {displayname: string option} val encoding : t encoding end end end module Avatar_url : sig module Set : sig module Query : Empty.QUERY module Request : sig type%accessor t = {avatar_url: string option} val encoding : t encoding end module Response : Empty.JSON end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {avatar_url: string option} val encoding : t encoding end end end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {displayname: string option; avatar_url: string option} val encoding : t encoding end end end module Push_rules : sig module Kind : sig type t = Override | Underride | Sender | Room | Content end module Get_all : sig module Query : Empty.QUERY module Response : sig type%accessor t = { content: Push_rule.t list option; override: Push_rule.t list option; room: Push_rule.t list option; sender: Push_rule.t list option; underride: Push_rule.t list option; } val encoding : t encoding end end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {push_rules: Push_rule.t} val encoding : t encoding end end module Delete : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end module Put : sig module Query : sig type%accessor t = {before: string option; after: string option} val args : t -> (string * string list) list end module Request : sig module Action : sig type t = Notify | Dont_notify | Coalesce | Set_weak val encoding : t encoding end type%accessor t = { actions: Action.t list; conditions: Push_rule.Push_condition.t list; pattern: string; } val encoding : t encoding end module Response : Empty.JSON end module Get_enabled : sig module Query : Empty.QUERY module Response : sig type%accessor t = {enabled: bool} val encoding : t encoding end end module Set_enabled : sig module Query : Empty.QUERY module Request : sig type%accessor t = {enabled: bool} val encoding : t encoding end module Response : Empty.JSON end module Get_actions : sig module Query : Empty.QUERY module Response : sig type%accessor t = {actions: string list} val encoding : t encoding end end module Set_actions : sig module Query : Empty.QUERY module Request : sig type%accessor t = {actions: string list} val encoding : t encoding end module Response : Empty.JSON end end module Pushers : sig module Pusher : sig module Pusher_data : sig type%accessor t = {url: string option; format: string option} val encoding : t encoding end type%accessor t = { pushkey: string; kind: string; app_id: string; app_display_name: string; device_display_name: string; profile_tag: string option; lang: string; data: Pusher_data.t; } val encoding : t encoding end module Get : sig module Query : Empty.QUERY module Response : sig type%accessor t = {pushers: Pusher.t list option} val encoding : t encoding end end module Set : sig module Query : Empty.QUERY module Request : sig type%accessor t = {pusher: Pusher.t; append: bool option} val encoding : t encoding end module Response : Empty.JSON end end module Receipt : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end module Register : sig module Register : sig module Query : sig module Kind : sig type t = User | Guest end type%accessor t = {kind: Kind.t option} val args : t -> (string * string list) list end module Request : sig type%accessor t = { auth: Authentication.t option; bind_email: bool option; bind_msisdn: bool option; username: string option; password: string option; device_id: string option; initial_device_display_name: string option; inhibit_login: bool option; } val encoding : t encoding end module Response : sig type%accessor t = { user_id: string; access_token: string option; home_server: string; device_id: string option; } val encoding : t encoding end end module Available : sig module Query : sig type%accessor t = {username: string} val args : t -> (string * string list) list end module Request : Empty.JSON module Response : sig type%accessor t = {available: bool} val encoding : t encoding end end module Email_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; email: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = { success: bool option; sid: string; submit_url: string option; } val encoding : t encoding end end module Msisdn_request_token : sig module Query : Empty.QUERY module Request : sig type%accessor t = { client_secret: string; country: string; phone_number: string; send_attempt: int; next_link: string option; id_server: string; } val encoding : t encoding end module Response : sig type%accessor t = { success: bool option; sid: string; submit_url: string option; msisdn: string option; intl_fmt: string option; } val encoding : t encoding end end end module Report : sig module Query : Empty.QUERY module Request : sig type%accessor t = {score: int; reason: string} val encoding : t encoding end module Response : Empty.JSON end module Room_event : sig module Get : sig module Event : sig module Query : Empty.QUERY module Request : Empty.JSON module Response = Events.Room_event end module State_key : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig type t = Ezjsonm.value val encoding : t encoding end end module State : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig type%accessor t = {events: Events.State_event.t list} val encoding : t encoding end end module Members : sig module Query : sig type%accessor t = { at: string option; membership: Events.Event_content.Membership.t option; not_membership: Events.Event_content.Membership.t option; } val args : t -> (string * string list) list end module Request : Empty.JSON module Response : sig type%accessor t = {chunk: Events.State_event.t list} val encoding : t encoding end end module Joined_members : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig module User : sig type%accessor t = { display_name: string option; avatar_url: string option; } val encoding : t encoding end type%accessor t = {joined: (string * User.t) list option} val encoding : t encoding end end end module Put : sig module State_event : sig module Query = Empty.Query module Request : sig type%accessor t = {event: Events.Event_content.t} val encoding : t encoding end module Response : sig type%accessor t = {event_id: string} val encoding : t encoding end end module Message_event : sig module Query = Empty.Query module Request : sig type%accessor t = {event: Events.Event_content.Message.t} val encoding : t encoding end module Response : sig type%accessor t = {event_id: string} val encoding : t encoding end end end end module Room : sig module Visibility : sig type t = Public | Private val encoding : t encoding end module Create : sig module Query : Empty.QUERY module Request : sig module Invite_3pid : sig type%accessor t = {id_server: string; medium: string; addresss: string} val encoding : t encoding end module Preset : sig type t = Public | Private | Trusted_private val encoding : t encoding end type%accessor t = { visibility: Visibility.t option; room_alias_name: string option; name: string option; topic: string option; invite: string list option; invite_3pid: Invite_3pid.t list option; room_version: string option; creation_content: Events.Event_content.Create.t option; initial_state: Events.State_event.t list option; preset: Preset.t option; is_direct: bool option; power_level_content_override: Events.Event_content.Power_levels.t option; } val encoding : t encoding end module Response : sig type%accessor t = {room_id: string} val encoding : t encoding end end module Create_alias : sig module Query : Empty.QUERY module Request : sig type%accessor t = {room_id: string} val encoding : t encoding end module Response : Empty.JSON end module Resolve_alias : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : sig type%accessor t = {room_id: string option; servers: string list option} val encoding : t encoding end end module Delete_alias : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end end module Room_listing : sig module Get_visibility : sig module Query : Empty.QUERY module Response : sig type%accessor t = {visibility: Room.Visibility.t} val encoding : t encoding end end module Set_visibility : sig module Query : Empty.QUERY module Request : sig type%accessor t = {visibility: Room.Visibility.t option} val encoding : t encoding end module Response : Empty.JSON end module Get_public_rooms : sig module Query : sig type%accessor t = { limit: int option; since: string option; server: string option; } val args : t -> (string * string list) list end module Response : sig module Public_rooms_chunk : sig type%accessor t = { aliases: string list option; canonical_alias: string option; name: string option; num_joined_members: int; room_id: string; topic: string option; world_readable: bool; guest_can_join: bool; avatar_url: string option; federate: bool option; } val encoding : t encoding end type%accessor t = { chunk: Public_rooms_chunk.t list; next_batch: string option; prev_batch: string option; total_room_count_estimate: int option; } val encoding : t encoding end end module Filter_public_rooms : sig module Query : sig type%accessor t = {server: string option} val args : t -> (string * string list) list end module Request : sig module Filter : sig type%accessor t = {generic_search_term: string option} val encoding : t encoding end type%accessor t = { limit: int option; since: string option; filter: Filter.t option; include_all_networks: bool option; third_party_instance_id: string option; } val encoding : t encoding end module Response = Get_public_rooms.Response end end module Rooms : sig module Room_summary : sig type%accessor t = { heroes: string list option; joined_member_count: int option; invited_member_count: int option; } val encoding : t encoding end module Timeline : sig type%accessor t = { events: Events.Room_event.t list option; limited: bool option; prev_batch: string option; } val encoding : t encoding end module Joined_room : sig module Unread_notifications : sig type%accessor t = { highlight_count: int option; notification_count: int option; } val encoding : t encoding end type%accessor t = { summary: Room_summary.t option; state: Events.State_event.t list option; timeline: Timeline.t option; ephemeral: Events.Event.t list option; account_data: Events.Event.t list option; unread_notifications: Unread_notifications.t option; } val encoding : t encoding end module Invited_room : sig type%accessor t = {invite_state: Events.State_event.t list option} val encoding : t encoding end module Left_room : sig type%accessor t = { state: Events.State_event.t list option; timeline: Timeline.t option; account_data: Events.Room_event.t list option; } val encoding : t encoding end type%accessor t = { join: (string * Joined_room.t) list; invite: (string * Invited_room.t) list; leave: (string * Left_room.t) list; } val encoding : t encoding end module Search : sig module Query : sig type%accessor t = {next_batch: string option} val args : t -> (string * string list) list end module Request : sig module Criteria : sig module Key : sig type t = Content_body | Content_name | Content_topic val encoding : t encoding end module Filter : sig type%accessor t = { limit: int option; not_senders: string list option; not_types: string list option; senders: string list option; types: string list option; lazy_load_members: bool option; include_redundant_members: bool option; not_rooms: string list option; rooms: string list option; contains_url: bool option; } val encoding : t encoding end module Order : sig type t = Recent | Rank val encoding : t encoding end module Include_event_context : sig type%accessor t = { before_limit: int option; after_limit: int option; include_profile: bool option; } val encoding : t encoding end module Groupings : sig module Group : sig type t = Room_id | Sender val encoding : t encoding end type%accessor t = {group_by: Group.t list option} val encoding : t encoding end type%accessor t = { search_term: string; keys: Key.t option; filter: Filter.t option; order_by: Order.t option; event_context: Include_event_context.t option; include_state: bool option; groupings: Groupings.t option; } val encoding : t encoding end type%accessor t = {criterias: Criteria.t option} val encoding : t encoding end module Response : sig module Results : sig module Result : sig module Event_context : sig module User_profile : sig type%accessor t = { displayname: string option; avatar_url: string option; } val encoding : t encoding end type%accessor t = { start: string option; end_: string option; profile_info: (string * User_profile.t) list option; events_before: Events.Room_event.t list option; events_after: Events.Room_event.t list option; } val encoding : t encoding end type%accessor t = { rank: int option; result: Events.Room_event.t option; context: Event_context.t option; } val encoding : t encoding end module Group_value : sig type%accessor t = { next_batch: string option; order: int option; results: string list option; } val encoding : t encoding end type%accessor t = { count: int option; highlights: string list option; results: Result.t list option; state: (string * Events.State_event.t) list option; groups: (string * (string * Group_value.t) list) list option; next_batch: string option; } val encoding : t encoding end type%accessor t = {results: Results.t option} val encoding : t encoding end end module Send_to_device : sig module Query : Empty.QUERY module Request : sig type%accessor t = { messages: (string * (string * Ezjsonm.value) list) list option; } val encoding : t encoding end module Response : Empty.JSON end module Session_data : sig type%accessor t = { algorithm: string; forwarding_curve25519_key_chain: string list; room_id: string; sender_key: string; sender_claimed_keys: (string * string) list; session_id: string; session_key: string; } val encoding : t encoding end module Sso : sig module Query : sig type%accessor t = {redirect_url: string} val args : t -> (string * string list) list end module Response : Empty.JSON end module Sync : sig module Query : sig module Presence : sig type t = Offline | Online | Unavailable val pp : Format.formatter -> t -> unit end type%accessor t = { filter: string option; since: string option; full_state: bool option; set_presence: Presence.t option; timeout: int option; } val args : t -> (string * string list) list val pp : t Fmt.t end module Response : sig type%accessor t = { next_batch: string; rooms: Rooms.t option; presence: Events.State_event.t list option; account_data: Events.State_event.t list option; to_device: Events.State_event.t list option; device_lists: Device_lists.t option; device_one_time_keys_count: (string * int) list option; } val encoding : t encoding val pp : t Fmt.t end end module Tag : sig module Get : sig module Query : Empty.QUERY module Response : sig module Tag : sig type%accessor t = {order: float option} val encoding : t encoding end type%accessor t = {tags: (string * Tag.t) list} val encoding : t encoding end end module Put : sig module Query : Empty.QUERY module Request : sig type%accessor t = {order: float option} val encoding : t encoding end module Response : Empty.JSON end module Delete : sig module Query : Empty.QUERY module Request : Empty.JSON module Response : Empty.JSON end end module Third_party_network : sig module Protocol : sig module Field_type : sig type%accessor t = {regexp: string; placeholder: string} val encoding : t encoding end module Instance : sig type%accessor t = { desc: string; icon: string option; fields: (string * string) list; network_id: string; } val encoding : t encoding end type%accessor t = { user_fields: string list; location_fields: string list; icon: string; field_types: (string * Field_type.t) list; instances: Instance.t list; } val encoding : t encoding end module Location : sig type%accessor t = { alias: string; protocol: string; fields: (string * string) list; } val encoding : t encoding end module User : sig type%accessor t = { user_id: string; protocol: string; fields: (string * string) list; } val encoding : t encoding end module Protocols : sig module Query : Empty.QUERY module Response : sig type%accessor t = {protocols: (string * Protocol.t) list} val encoding : t encoding end end module Get_protocol : sig module Query : Empty.QUERY module Response = Protocol end module Get_location : sig module Query : sig type%accessor t = {search_fields: string option} val args : t -> (string * string list) list end module Response : sig type%accessor t = {locations: Location.t list} val encoding : t encoding end end module Get_user : sig module Query : sig type%accessor t = {fields: (string * string list) list option} val args : t -> (string * string list) list end module Response : sig type%accessor t = {users: User.t list} val encoding : t encoding end end module Location_from_alias : sig module Query : sig type%accessor t = {alias: string} val args : t -> (string * string list) list end module Response : sig type%accessor t = {locations: Location.t list} val encoding : t encoding end end module User_from_user_id : sig module Query : sig type%accessor t = {user_id: string} val args : t -> (string * string list) list end module Response : sig type%accessor t = {users: User.t list} val encoding : t encoding end end end module Typing : sig module Query : Empty.QUERY module Request : sig type%accessor t = {typing: bool; timeout: int option} val encoding : t encoding end module Response : Empty.JSON end module Upgrade : sig module Query : Empty.QUERY module Request : sig type%accessor t = {new_version: string} val encoding : t encoding end module Response : sig type%accessor t = {replacement_room: string} val encoding : t encoding end end module User_directory : sig module Search : sig module Query : Empty.QUERY module Request : sig type%accessor t = {search_term: string; limited: int option} val encoding : t encoding end module Response : sig module User : sig type%accessor t = { user_id: string; display_name: string option; avatar_url: string option; } val encoding : t encoding end type%accessor t = {results: User.t list; limited: bool} val encoding : t encoding end end end module Versions : sig module Query : Empty.QUERY module Response : sig type%accessor t = { versions: string list; unstable_features: (string * bool) list option; } val encoding : t encoding end end module Voip : sig module Query : Empty.QUERY module Response : sig type%accessor t = { username: string option; password: string option; uris: string list option; ttl: int option; } val encoding : t encoding end end module Whois : sig module Query : Empty.QUERY module Response : sig module Device_info : sig module Session_info : sig module Connection_info : sig type%accessor t = { ip: string option; last_seen: int option; user_agent: string option; } val encoding : t encoding end type%accessor t = {connections: Connection_info.t list option} val encoding : t encoding end type%accessor t = {sessions: Session_info.t list option} val encoding : t encoding end type%accessor t = { user_id: string option; devices: (string * Device_info.t) list option; } val encoding : t encoding end end
d271cd64d4cc12231e70d1e521d04004d0ddf25ba65b39216dce7b06f0b078a4
ds-wizard/engine-backend
List_POST_FromTemplate.hs
module Wizard.Specs.API.Questionnaire.List_POST_FromTemplate ( list_post_fromTemplate, ) where import Data.Aeson (encode) import Network.HTTP.Types import Network.Wai (Application) import Test.Hspec import Test.Hspec.Wai hiding (shouldRespondWith) import Test.Hspec.Wai.Matcher import Shared.Api.Resource.Error.ErrorJM () import Shared.Localization.Messages.Public import Shared.Model.Error.Error import Wizard.Api.Resource.Questionnaire.QuestionnaireCreateFromTemplateDTO import Wizard.Api.Resource.Questionnaire.QuestionnaireCreateJM () import Wizard.Api.Resource.Questionnaire.QuestionnaireDTO import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO import qualified Wizard.Database.Migration.Development.DocumentTemplate.DocumentTemplateMigration as TML_Migration import Wizard.Database.Migration.Development.Questionnaire.Data.Questionnaires import qualified Wizard.Database.Migration.Development.Questionnaire.QuestionnaireMigration as QTN_Migration import qualified Wizard.Database.Migration.Development.User.UserMigration as U_Migration import Wizard.Localization.Messages.Public import Wizard.Model.Config.AppConfig hiding (request) import Wizard.Model.Context.AppContext import Wizard.Model.Questionnaire.Questionnaire import Wizard.Service.Config.App.AppConfigMapper import Wizard.Service.Config.App.AppConfigService import SharedTest.Specs.API.Common import Wizard.Specs.API.Common import Wizard.Specs.API.Questionnaire.Common import Wizard.Specs.Common -- ------------------------------------------------------------------------ -- POST /questionnaires?fromTemplate=true -- ------------------------------------------------------------------------ list_post_fromTemplate :: AppContext -> SpecWith ((), Application) list_post_fromTemplate appContext = describe "POST /questionnaires/from-template" $ do test_201 appContext test_400 appContext test_403 appContext -- ---------------------------------------------------- -- ---------------------------------------------------- -- ---------------------------------------------------- reqMethod = methodPost reqUrl = "/questionnaires/from-template" reqHeadersT authHeader = authHeader ++ [reqCtHeader] reqDtoT qtnTmlUuid name = QuestionnaireCreateFromTemplateDTO { name = name , questionnaireUuid = qtnTmlUuid } reqBodyT qtnTmlUuid name = encode (reqDtoT qtnTmlUuid name) -- ---------------------------------------------------- -- ---------------------------------------------------- -- ---------------------------------------------------- test_201 appContext = it "HTTP 200 OK" $ -- GIVEN: Prepare request do let reqHeaders = reqHeadersT [reqAuthHeader] let reqBody = reqBodyT questionnaire1.uuid questionnaire11.name -- AND: Prepare expectation let expStatus = 201 let expHeaders = resCtHeaderPlain : resCorsHeadersPlain let expDto = questionnaire11Dto let expBody = encode expDto -- AND: Run migrations runInContextIO U_Migration.runMigration appContext runInContextIO TML_Migration.runMigration appContext runInContextIO QTN_Migration.runMigration appContext -- WHEN: Call API response <- request reqMethod reqUrl reqHeaders reqBody -- THEN: Compare response with expectation let (status, headers, resBody) = destructResponse response :: (Int, ResponseHeaders, QuestionnaireDTO) assertResStatus status expStatus assertResHeaders headers expHeaders compareQuestionnaireCreateFromTemplateDtos resBody expDto -- AND: Find a result in DB assertCountInDB findQuestionnaires appContext 4 -- ---------------------------------------------------- -- ---------------------------------------------------- -- ---------------------------------------------------- test_400 appContext = it "HTTP 400 BAD REQUEST (questionnaireCreation: CustomQuestionnaireCreation)" $ -- GIVEN: Prepare request do let reqHeaders = reqHeadersT [reqAuthHeader] let reqBody = reqBodyT questionnaire2.uuid questionnaire11.name -- AND: Prepare expectation let expStatus = 400 let expHeaders = resCtHeader : resCorsHeaders let expDto = UserError . _ERROR_SERVICE_COMMON__FEATURE_IS_DISABLED $ "Questionnaire Template" let expBody = encode expDto -- AND: Change appConfig (Right appConfig) <- runInContextIO getAppConfig appContext let updatedAppConfig = appConfig {questionnaire = appConfig.questionnaire {questionnaireCreation = CustomQuestionnaireCreation}} runInContextIO (modifyAppConfigDto (toChangeDTO updatedAppConfig)) appContext -- AND: Run migrations runInContextIO U_Migration.runMigration appContext runInContextIO TML_Migration.runMigration appContext runInContextIO QTN_Migration.runMigration appContext -- WHEN: Call API response <- request reqMethod reqUrl reqHeaders reqBody -- THEN: Compare response with expectation let responseMatcher = ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody} response `shouldRespondWith` responseMatcher -- AND: Find a result in DB assertCountInDB findQuestionnaires appContext 3 -- ---------------------------------------------------- -- ---------------------------------------------------- -- ---------------------------------------------------- test_403 appContext = it "HTTP 403 FORBIDDEN (isTemplate: False)" $ -- GIVEN: Prepare request do let reqHeaders = reqHeadersT [reqAuthHeader] let reqBody = reqBodyT questionnaire2.uuid questionnaire11.name -- AND: Prepare expectation let expStatus = 403 let expHeaders = resCtHeader : resCorsHeaders let expDto = ForbiddenError $ _ERROR_VALIDATION__FORBIDDEN "Questionnaire Template" let expBody = encode expDto -- AND: Run migrations runInContextIO U_Migration.runMigration appContext runInContextIO TML_Migration.runMigration appContext runInContextIO QTN_Migration.runMigration appContext -- WHEN: Call API response <- request reqMethod reqUrl reqHeaders reqBody -- THEN: Compare response with expectation let responseMatcher = ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody} response `shouldRespondWith` responseMatcher -- AND: Find a result in DB assertCountInDB findQuestionnaires appContext 3
null
https://raw.githubusercontent.com/ds-wizard/engine-backend/d392b751192a646064305d3534c57becaa229f28/engine-wizard/test/Wizard/Specs/API/Questionnaire/List_POST_FromTemplate.hs
haskell
------------------------------------------------------------------------ POST /questionnaires?fromTemplate=true ------------------------------------------------------------------------ ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- GIVEN: Prepare request AND: Prepare expectation AND: Run migrations WHEN: Call API THEN: Compare response with expectation AND: Find a result in DB ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- GIVEN: Prepare request AND: Prepare expectation AND: Change appConfig AND: Run migrations WHEN: Call API THEN: Compare response with expectation AND: Find a result in DB ---------------------------------------------------- ---------------------------------------------------- ---------------------------------------------------- GIVEN: Prepare request AND: Prepare expectation AND: Run migrations WHEN: Call API THEN: Compare response with expectation AND: Find a result in DB
module Wizard.Specs.API.Questionnaire.List_POST_FromTemplate ( list_post_fromTemplate, ) where import Data.Aeson (encode) import Network.HTTP.Types import Network.Wai (Application) import Test.Hspec import Test.Hspec.Wai hiding (shouldRespondWith) import Test.Hspec.Wai.Matcher import Shared.Api.Resource.Error.ErrorJM () import Shared.Localization.Messages.Public import Shared.Model.Error.Error import Wizard.Api.Resource.Questionnaire.QuestionnaireCreateFromTemplateDTO import Wizard.Api.Resource.Questionnaire.QuestionnaireCreateJM () import Wizard.Api.Resource.Questionnaire.QuestionnaireDTO import Wizard.Database.DAO.Questionnaire.QuestionnaireDAO import qualified Wizard.Database.Migration.Development.DocumentTemplate.DocumentTemplateMigration as TML_Migration import Wizard.Database.Migration.Development.Questionnaire.Data.Questionnaires import qualified Wizard.Database.Migration.Development.Questionnaire.QuestionnaireMigration as QTN_Migration import qualified Wizard.Database.Migration.Development.User.UserMigration as U_Migration import Wizard.Localization.Messages.Public import Wizard.Model.Config.AppConfig hiding (request) import Wizard.Model.Context.AppContext import Wizard.Model.Questionnaire.Questionnaire import Wizard.Service.Config.App.AppConfigMapper import Wizard.Service.Config.App.AppConfigService import SharedTest.Specs.API.Common import Wizard.Specs.API.Common import Wizard.Specs.API.Questionnaire.Common import Wizard.Specs.Common list_post_fromTemplate :: AppContext -> SpecWith ((), Application) list_post_fromTemplate appContext = describe "POST /questionnaires/from-template" $ do test_201 appContext test_400 appContext test_403 appContext reqMethod = methodPost reqUrl = "/questionnaires/from-template" reqHeadersT authHeader = authHeader ++ [reqCtHeader] reqDtoT qtnTmlUuid name = QuestionnaireCreateFromTemplateDTO { name = name , questionnaireUuid = qtnTmlUuid } reqBodyT qtnTmlUuid name = encode (reqDtoT qtnTmlUuid name) test_201 appContext = it "HTTP 200 OK" $ do let reqHeaders = reqHeadersT [reqAuthHeader] let reqBody = reqBodyT questionnaire1.uuid questionnaire11.name let expStatus = 201 let expHeaders = resCtHeaderPlain : resCorsHeadersPlain let expDto = questionnaire11Dto let expBody = encode expDto runInContextIO U_Migration.runMigration appContext runInContextIO TML_Migration.runMigration appContext runInContextIO QTN_Migration.runMigration appContext response <- request reqMethod reqUrl reqHeaders reqBody let (status, headers, resBody) = destructResponse response :: (Int, ResponseHeaders, QuestionnaireDTO) assertResStatus status expStatus assertResHeaders headers expHeaders compareQuestionnaireCreateFromTemplateDtos resBody expDto assertCountInDB findQuestionnaires appContext 4 test_400 appContext = it "HTTP 400 BAD REQUEST (questionnaireCreation: CustomQuestionnaireCreation)" $ do let reqHeaders = reqHeadersT [reqAuthHeader] let reqBody = reqBodyT questionnaire2.uuid questionnaire11.name let expStatus = 400 let expHeaders = resCtHeader : resCorsHeaders let expDto = UserError . _ERROR_SERVICE_COMMON__FEATURE_IS_DISABLED $ "Questionnaire Template" let expBody = encode expDto (Right appConfig) <- runInContextIO getAppConfig appContext let updatedAppConfig = appConfig {questionnaire = appConfig.questionnaire {questionnaireCreation = CustomQuestionnaireCreation}} runInContextIO (modifyAppConfigDto (toChangeDTO updatedAppConfig)) appContext runInContextIO U_Migration.runMigration appContext runInContextIO TML_Migration.runMigration appContext runInContextIO QTN_Migration.runMigration appContext response <- request reqMethod reqUrl reqHeaders reqBody let responseMatcher = ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody} response `shouldRespondWith` responseMatcher assertCountInDB findQuestionnaires appContext 3 test_403 appContext = it "HTTP 403 FORBIDDEN (isTemplate: False)" $ do let reqHeaders = reqHeadersT [reqAuthHeader] let reqBody = reqBodyT questionnaire2.uuid questionnaire11.name let expStatus = 403 let expHeaders = resCtHeader : resCorsHeaders let expDto = ForbiddenError $ _ERROR_VALIDATION__FORBIDDEN "Questionnaire Template" let expBody = encode expDto runInContextIO U_Migration.runMigration appContext runInContextIO TML_Migration.runMigration appContext runInContextIO QTN_Migration.runMigration appContext response <- request reqMethod reqUrl reqHeaders reqBody let responseMatcher = ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody} response `shouldRespondWith` responseMatcher assertCountInDB findQuestionnaires appContext 3
e64922fa85ff87b905efae2590d06852cb6eb5b733b550f23f11465954940ff3
McParen/croatoan
legacy_coding.lisp
(in-package :croatoan) ;;; legacy coding ;;; -island.net/ncurses/man/legacy_coding.3x.html ;;; C prototypes ;; int use_legacy_coding(int level); ;;; Low-level C functions (defcfun ("use_legacy_coding" %use-legacy-coding) :int (level :int)) ;;; High-level Lisp wrappers Possible values : 0 ( default ) , 1 and 2 . (defun set-char-representation (level) "Set how char-to-string will represent a char." (%use-legacy-coding level)) ;;; NOTES This affects % unctrl / char - to - string . See util.lisp and the manpage . TODOs
null
https://raw.githubusercontent.com/McParen/croatoan/413e8855b78a2e408f90efc38e8485f880691684/src/legacy_coding.lisp
lisp
legacy coding -island.net/ncurses/man/legacy_coding.3x.html C prototypes int use_legacy_coding(int level); Low-level C functions High-level Lisp wrappers NOTES
(in-package :croatoan) (defcfun ("use_legacy_coding" %use-legacy-coding) :int (level :int)) Possible values : 0 ( default ) , 1 and 2 . (defun set-char-representation (level) "Set how char-to-string will represent a char." (%use-legacy-coding level)) This affects % unctrl / char - to - string . See util.lisp and the manpage . TODOs
1949ed1f479a3bb4d4326a774742dcebe62a1deb21b71041929625246deb7aa0
awslabs/s2n-bignum
bignum_mod_p256k1_4.ml
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) (* ========================================================================= *) (* Reduction modulo p_256k1, the field characteristic for secp256k1. *) (* ========================================================================= *) (**** print_literal_from_elf "arm/secp256k1/bignum_mod_p256k1_4.o";; ****) let bignum_mod_p256k1_4_mc = define_assert_from_elf "bignum_mod_p256k1_4_mc" "arm/secp256k1/bignum_mod_p256k1_4.o" [ arm_LDP X2 X3 X1 ( Immediate_Offset ( iword ( & 0 ) ) ) arm_LDP X4 X5 X1 ( Immediate_Offset ( iword ( & 16 ) ) ) arm_AND X6 X3 X4 arm_AND X6 X6 X5 arm_MOV X7 ( rvalue ( word 977 ) ) arm_ORR X7 X7 ( rvalue ( word 4294967296 ) ) arm_ADDS X7 X7 X2 arm_ADCS X6 X6 XZR arm_CSEL X2 X2 X7 Condition_CC arm_CSEL X3 X3 X6 Condition_CC arm_CSEL X4 X4 X6 Condition_CC arm_CSEL X5 X5 X6 Condition_CC arm_STP X2 ( Immediate_Offset ( iword ( & 0 ) ) ) arm_STP X4 X5 ( Immediate_Offset ( iword ( & 16 ) ) ) arm_RET X30 ];; let BIGNUM_MOD_P256K1_4_EXEC = ARM_MK_EXEC_RULE bignum_mod_p256k1_4_mc;; (* ------------------------------------------------------------------------- *) (* Proof. *) (* ------------------------------------------------------------------------- *) let p_256k1 = new_definition `p_256k1 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F`;; let P_256K1_AS_WORDLIST = prove (`p_256k1 = bignum_of_wordlist [word 0xfffffffefffffc2f; word_not(word 0);word_not(word 0);word_not(word 0)]`, REWRITE_TAC[p_256k1; bignum_of_wordlist] THEN CONV_TAC WORD_REDUCE_CONV THEN CONV_TAC NUM_REDUCE_CONV);; let BIGNUM_OF_WORDLIST_P256K1_LE = prove (`p_256k1 <= bignum_of_wordlist[n0;n1;n2;n3] <=> 0xfffffffefffffc2f <= val n0 /\ n1 = word_not(word 0) /\ n2 = word_not(word 0) /\ n3 = word_not(word 0)`, REWRITE_TAC[P_256K1_AS_WORDLIST] THEN ONCE_REWRITE_TAC[BIGNUM_OF_WORDLIST_LE] THEN SUBGOAL_THEN `bignum_of_wordlist[word_not(word 0);word_not(word 0);word_not(word 0)] = 2 EXP 192 - 1` SUBST1_TAC THENL [REWRITE_TAC[bignum_of_wordlist] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN REFL_TAC; ALL_TAC] THEN REWRITE_TAC[ARITH_RULE `2 EXP 192 - 1 < n <=> ~(n < 2 EXP (64 * 3))`] THEN CONV_TAC(LAND_CONV(ONCE_DEPTH_CONV SYM_CONV)) THEN SIMP_TAC[BIGNUM_OF_WORDLIST_EQ_MAX; BIGNUM_FROM_WORDLIST_BOUND_GEN; ALL; LENGTH; ARITH_MULT; ARITH_ADD; ARITH_SUC; ARITH_LE; ARITH_LT] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN REWRITE_TAC[CONJ_ACI]);; let BIGNUM_OF_WORDLIST_LT_P256K1 = prove (`bignum_of_wordlist[n0;n1;n2;n3] < p_256k1 <=> n1 = word_not(word 0) /\ n2 = word_not(word 0) /\ n3 = word_not(word 0) ==> val n0 < 0xfffffffefffffc2f`, REWRITE_TAC[GSYM NOT_LE; BIGNUM_OF_WORDLIST_P256K1_LE] THEN CONV_TAC TAUT);; let BIGNUM_OF_WORDLIST_LT_P256K1_CONDENSED = prove (`bignum_of_wordlist[n0;n1;n2;n3] < p_256k1 <=> bignum_of_wordlist[n0;word_and n1 (word_and n2 n3)] < 340282366920938463463374607427473243183`, TRANS_TAC EQ_TRANS `bignum_of_wordlist[n0;word_and n1 (word_and n2 n3)] < bignum_of_wordlist[word 0xfffffffefffffc2f; word 0xffffffffffffffff]` THEN CONJ_TAC THENL [REWRITE_TAC[BIGNUM_OF_WORDLIST_LT_P256K1] THEN REWRITE_TAC[BIGNUM_OF_WORDLIST_LT; LT_REFL; BIGNUM_OF_WORDLIST_SING] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN REWRITE_TAC[GSYM DIMINDEX_64; SYM(NUM_REDUCE_CONV `2 EXP 64 - 1`)] THEN SIMP_TAC[VAL_BOUND; ARITH_RULE `x < e ==> (x < e - 1 <=> ~(x = e - 1))`; VAL_WORD_AND_EQ_MAX] THEN REWRITE_TAC[GSYM VAL_EQ; DIMINDEX_64] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN CONV_TAC TAUT; AP_TERM_TAC THEN REWRITE_TAC[bignum_of_wordlist] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV)]);; let BIGNUM_MOD_P256K1_4_CORRECT = time prove (`!z x n pc. nonoverlapping (word pc,0x3c) (z,8 * 4) ==> ensures arm (\s. aligned_bytes_loaded s (word pc) bignum_mod_p256k1_4_mc /\ read PC s = word pc /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = n) (\s. read PC s = word (pc + 0x38) /\ bignum_from_memory (z,4) s = n MOD p_256k1) (MAYCHANGE [PC; X2; X3; X4; X5; X6; X7] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,4)])`, MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `n:num`; `pc:num`] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN BIGNUM_TERMRANGE_TAC `4` `n:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_LDIGITIZE_TAC "n_" `read (memory :> bytes (x,8 * 4)) s0` THEN ARM_ACCSTEPS_TAC BIGNUM_MOD_P256K1_4_EXEC [7;8] (1--14) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN DISCARD_STATE_TAC "s14" THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN MAP_EVERY EXISTS_TAC [`64 * 4`; `if n < p_256k1 then &n else &n - &p_256k1:real`] THEN REPEAT CONJ_TAC THENL [CONV_TAC NUM_REDUCE_CONV THEN BOUNDER_TAC[]; REWRITE_TAC[p_256k1] THEN ARITH_TAC; REWRITE_TAC[p_256k1] THEN ARITH_TAC; ALL_TAC; SIMP_TAC[REAL_OF_NUM_SUB; GSYM NOT_LT; GSYM COND_RAND] THEN AP_TERM_TAC THEN MATCH_MP_TAC MOD_CASES THEN UNDISCH_TAC `n < 2 EXP (64 * 4)` THEN REWRITE_TAC[p_256k1] THEN ARITH_TAC] THEN SUBGOAL_THEN `~carry_s8 <=> n < p_256k1` SUBST_ALL_TAC THENL [EXPAND_TAC "n" THEN REWRITE_TAC[BIGNUM_OF_WORDLIST_LT_P256K1_CONDENSED] THEN REWRITE_TAC[WORD_AND_ASSOC] THEN MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `128` THEN REWRITE_TAC[p_256k1; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN REWRITE_TAC[REAL_BITVAL_NOT] THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[]; ALL_TAC] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "n" THEN REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THENL [REAL_INTEGER_TAC; ALL_TAC] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [NOT_LT]) THEN EXPAND_TAC "n" THEN REWRITE_TAC[BIGNUM_OF_WORDLIST_P256K1_LE] THEN STRIP_TAC THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN ASM_REWRITE_TAC[] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN ASM_CASES_TAC `carry_s7:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THENL [DISCH_THEN(CONJUNCTS_THEN2 (fun th -> MP_TAC(end_itlist CONJ (DECARRY_RULE [th]))) (fun th -> MP_TAC(end_itlist CONJ (DESUM_RULE [th])))) THEN REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[p_256k1] THEN REAL_INTEGER_TAC; DISCH_THEN(MP_TAC o REWRITE_RULE[REAL_OF_NUM_CLAUSES] o CONJUNCT2) THEN MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN UNDISCH_TAC `18446744069414583343 <= val(n_0:int64)` THEN MP_TAC(SPEC `sum_s7:int64` VAL_BOUND_64) THEN ARITH_TAC]);; let BIGNUM_MOD_P256K1_4_SUBROUTINE_CORRECT = time prove (`!z x n pc returnaddress. nonoverlapping (word pc,0x3c) (z,8 * 4) ==> ensures arm (\s. aligned_bytes_loaded s (word pc) bignum_mod_p256k1_4_mc /\ read PC s = word pc /\ read X30 s = returnaddress /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = n) (\s. read PC s = returnaddress /\ bignum_from_memory (z,4) s = n MOD p_256k1) (MAYCHANGE [PC; X2; X3; X4; X5; X6; X7] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,4)])`, ARM_ADD_RETURN_NOSTACK_TAC BIGNUM_MOD_P256K1_4_EXEC BIGNUM_MOD_P256K1_4_CORRECT);;
null
https://raw.githubusercontent.com/awslabs/s2n-bignum/824c15f908d7a343af1b2f378cfedd36e880bdde/arm/proofs/bignum_mod_p256k1_4.ml
ocaml
========================================================================= Reduction modulo p_256k1, the field characteristic for secp256k1. ========================================================================= *** print_literal_from_elf "arm/secp256k1/bignum_mod_p256k1_4.o";; *** ------------------------------------------------------------------------- Proof. -------------------------------------------------------------------------
* Copyright Amazon.com , Inc. or its affiliates . All Rights Reserved . * SPDX - License - Identifier : Apache-2.0 OR ISC * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 OR ISC *) let bignum_mod_p256k1_4_mc = define_assert_from_elf "bignum_mod_p256k1_4_mc" "arm/secp256k1/bignum_mod_p256k1_4.o" [ arm_LDP X2 X3 X1 ( Immediate_Offset ( iword ( & 0 ) ) ) arm_LDP X4 X5 X1 ( Immediate_Offset ( iword ( & 16 ) ) ) arm_AND X6 X3 X4 arm_AND X6 X6 X5 arm_MOV X7 ( rvalue ( word 977 ) ) arm_ORR X7 X7 ( rvalue ( word 4294967296 ) ) arm_ADDS X7 X7 X2 arm_ADCS X6 X6 XZR arm_CSEL X2 X2 X7 Condition_CC arm_CSEL X3 X3 X6 Condition_CC arm_CSEL X4 X4 X6 Condition_CC arm_CSEL X5 X5 X6 Condition_CC arm_STP X2 ( Immediate_Offset ( iword ( & 0 ) ) ) arm_STP X4 X5 ( Immediate_Offset ( iword ( & 16 ) ) ) arm_RET X30 ];; let BIGNUM_MOD_P256K1_4_EXEC = ARM_MK_EXEC_RULE bignum_mod_p256k1_4_mc;; let p_256k1 = new_definition `p_256k1 = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F`;; let P_256K1_AS_WORDLIST = prove (`p_256k1 = bignum_of_wordlist [word 0xfffffffefffffc2f; word_not(word 0);word_not(word 0);word_not(word 0)]`, REWRITE_TAC[p_256k1; bignum_of_wordlist] THEN CONV_TAC WORD_REDUCE_CONV THEN CONV_TAC NUM_REDUCE_CONV);; let BIGNUM_OF_WORDLIST_P256K1_LE = prove (`p_256k1 <= bignum_of_wordlist[n0;n1;n2;n3] <=> 0xfffffffefffffc2f <= val n0 /\ n1 = word_not(word 0) /\ n2 = word_not(word 0) /\ n3 = word_not(word 0)`, REWRITE_TAC[P_256K1_AS_WORDLIST] THEN ONCE_REWRITE_TAC[BIGNUM_OF_WORDLIST_LE] THEN SUBGOAL_THEN `bignum_of_wordlist[word_not(word 0);word_not(word 0);word_not(word 0)] = 2 EXP 192 - 1` SUBST1_TAC THENL [REWRITE_TAC[bignum_of_wordlist] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN REFL_TAC; ALL_TAC] THEN REWRITE_TAC[ARITH_RULE `2 EXP 192 - 1 < n <=> ~(n < 2 EXP (64 * 3))`] THEN CONV_TAC(LAND_CONV(ONCE_DEPTH_CONV SYM_CONV)) THEN SIMP_TAC[BIGNUM_OF_WORDLIST_EQ_MAX; BIGNUM_FROM_WORDLIST_BOUND_GEN; ALL; LENGTH; ARITH_MULT; ARITH_ADD; ARITH_SUC; ARITH_LE; ARITH_LT] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN REWRITE_TAC[CONJ_ACI]);; let BIGNUM_OF_WORDLIST_LT_P256K1 = prove (`bignum_of_wordlist[n0;n1;n2;n3] < p_256k1 <=> n1 = word_not(word 0) /\ n2 = word_not(word 0) /\ n3 = word_not(word 0) ==> val n0 < 0xfffffffefffffc2f`, REWRITE_TAC[GSYM NOT_LE; BIGNUM_OF_WORDLIST_P256K1_LE] THEN CONV_TAC TAUT);; let BIGNUM_OF_WORDLIST_LT_P256K1_CONDENSED = prove (`bignum_of_wordlist[n0;n1;n2;n3] < p_256k1 <=> bignum_of_wordlist[n0;word_and n1 (word_and n2 n3)] < 340282366920938463463374607427473243183`, TRANS_TAC EQ_TRANS `bignum_of_wordlist[n0;word_and n1 (word_and n2 n3)] < bignum_of_wordlist[word 0xfffffffefffffc2f; word 0xffffffffffffffff]` THEN CONJ_TAC THENL [REWRITE_TAC[BIGNUM_OF_WORDLIST_LT_P256K1] THEN REWRITE_TAC[BIGNUM_OF_WORDLIST_LT; LT_REFL; BIGNUM_OF_WORDLIST_SING] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN REWRITE_TAC[GSYM DIMINDEX_64; SYM(NUM_REDUCE_CONV `2 EXP 64 - 1`)] THEN SIMP_TAC[VAL_BOUND; ARITH_RULE `x < e ==> (x < e - 1 <=> ~(x = e - 1))`; VAL_WORD_AND_EQ_MAX] THEN REWRITE_TAC[GSYM VAL_EQ; DIMINDEX_64] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN CONV_TAC TAUT; AP_TERM_TAC THEN REWRITE_TAC[bignum_of_wordlist] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV)]);; let BIGNUM_MOD_P256K1_4_CORRECT = time prove (`!z x n pc. nonoverlapping (word pc,0x3c) (z,8 * 4) ==> ensures arm (\s. aligned_bytes_loaded s (word pc) bignum_mod_p256k1_4_mc /\ read PC s = word pc /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = n) (\s. read PC s = word (pc + 0x38) /\ bignum_from_memory (z,4) s = n MOD p_256k1) (MAYCHANGE [PC; X2; X3; X4; X5; X6; X7] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,4)])`, MAP_EVERY X_GEN_TAC [`z:int64`; `x:int64`; `n:num`; `pc:num`] THEN REWRITE_TAC[C_ARGUMENTS; C_RETURN; SOME_FLAGS; NONOVERLAPPING_CLAUSES] THEN DISCH_THEN(REPEAT_TCL CONJUNCTS_THEN ASSUME_TAC) THEN BIGNUM_TERMRANGE_TAC `4` `n:num` THEN REWRITE_TAC[BIGNUM_FROM_MEMORY_BYTES] THEN ENSURES_INIT_TAC "s0" THEN BIGNUM_LDIGITIZE_TAC "n_" `read (memory :> bytes (x,8 * 4)) s0` THEN ARM_ACCSTEPS_TAC BIGNUM_MOD_P256K1_4_EXEC [7;8] (1--14) THEN ENSURES_FINAL_STATE_TAC THEN ASM_REWRITE_TAC[] THEN CONV_TAC(LAND_CONV BIGNUM_EXPAND_CONV) THEN ASM_REWRITE_TAC[] THEN DISCARD_STATE_TAC "s14" THEN CONV_TAC SYM_CONV THEN MATCH_MP_TAC EQUAL_FROM_CONGRUENT_MOD_MOD THEN MAP_EVERY EXISTS_TAC [`64 * 4`; `if n < p_256k1 then &n else &n - &p_256k1:real`] THEN REPEAT CONJ_TAC THENL [CONV_TAC NUM_REDUCE_CONV THEN BOUNDER_TAC[]; REWRITE_TAC[p_256k1] THEN ARITH_TAC; REWRITE_TAC[p_256k1] THEN ARITH_TAC; ALL_TAC; SIMP_TAC[REAL_OF_NUM_SUB; GSYM NOT_LT; GSYM COND_RAND] THEN AP_TERM_TAC THEN MATCH_MP_TAC MOD_CASES THEN UNDISCH_TAC `n < 2 EXP (64 * 4)` THEN REWRITE_TAC[p_256k1] THEN ARITH_TAC] THEN SUBGOAL_THEN `~carry_s8 <=> n < p_256k1` SUBST_ALL_TAC THENL [EXPAND_TAC "n" THEN REWRITE_TAC[BIGNUM_OF_WORDLIST_LT_P256K1_CONDENSED] THEN REWRITE_TAC[WORD_AND_ASSOC] THEN MATCH_MP_TAC FLAG_FROM_CARRY_LT THEN EXISTS_TAC `128` THEN REWRITE_TAC[p_256k1; bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THEN ACCUMULATOR_ASSUM_LIST(MP_TAC o end_itlist CONJ o DECARRY_RULE) THEN REWRITE_TAC[REAL_BITVAL_NOT] THEN DISCH_THEN(fun th -> REWRITE_TAC[th]) THEN BOUNDER_TAC[]; ALL_TAC] THEN COND_CASES_TAC THEN ASM_REWRITE_TAC[] THEN EXPAND_TAC "n" THEN REWRITE_TAC[bignum_of_wordlist; GSYM REAL_OF_NUM_CLAUSES] THENL [REAL_INTEGER_TAC; ALL_TAC] THEN FIRST_X_ASSUM(MP_TAC o GEN_REWRITE_RULE I [NOT_LT]) THEN EXPAND_TAC "n" THEN REWRITE_TAC[BIGNUM_OF_WORDLIST_P256K1_LE] THEN STRIP_TAC THEN ACCUMULATOR_POP_ASSUM_LIST(MP_TAC o end_itlist CONJ) THEN ASM_REWRITE_TAC[] THEN CONV_TAC(DEPTH_CONV WORD_NUM_RED_CONV) THEN ASM_CASES_TAC `carry_s7:bool` THEN ASM_REWRITE_TAC[BITVAL_CLAUSES] THENL [DISCH_THEN(CONJUNCTS_THEN2 (fun th -> MP_TAC(end_itlist CONJ (DECARRY_RULE [th]))) (fun th -> MP_TAC(end_itlist CONJ (DESUM_RULE [th])))) THEN REPEAT STRIP_TAC THEN ASM_REWRITE_TAC[p_256k1] THEN REAL_INTEGER_TAC; DISCH_THEN(MP_TAC o REWRITE_RULE[REAL_OF_NUM_CLAUSES] o CONJUNCT2) THEN MATCH_MP_TAC(TAUT `~p ==> p ==> q`) THEN UNDISCH_TAC `18446744069414583343 <= val(n_0:int64)` THEN MP_TAC(SPEC `sum_s7:int64` VAL_BOUND_64) THEN ARITH_TAC]);; let BIGNUM_MOD_P256K1_4_SUBROUTINE_CORRECT = time prove (`!z x n pc returnaddress. nonoverlapping (word pc,0x3c) (z,8 * 4) ==> ensures arm (\s. aligned_bytes_loaded s (word pc) bignum_mod_p256k1_4_mc /\ read PC s = word pc /\ read X30 s = returnaddress /\ C_ARGUMENTS [z; x] s /\ bignum_from_memory (x,4) s = n) (\s. read PC s = returnaddress /\ bignum_from_memory (z,4) s = n MOD p_256k1) (MAYCHANGE [PC; X2; X3; X4; X5; X6; X7] ,, MAYCHANGE SOME_FLAGS ,, MAYCHANGE [memory :> bignum(z,4)])`, ARM_ADD_RETURN_NOSTACK_TAC BIGNUM_MOD_P256K1_4_EXEC BIGNUM_MOD_P256K1_4_CORRECT);;
4cfefdd8638e3ca3dc4a85bb13b7bb29dcb2250dd12080a473f648628d5617b9
borkdude/aoc2017
day11.clj
(ns day11 (:require [clojure.string :as str] [util :refer [read-first]]) (:import [java.lang Math])) (defn data [] (as-> "day11.txt" $ (read-first $) (str/split $ #","))) (defn distance ^long [coords] (/ ^long (apply + (map #(Math/abs ^long %) coords)) 2)) (defn solve "See " [input] (reduce (fn [[[^long x ^long y ^long z] ^long max-dist] next-dir] (let [next-coords (case next-dir "n" [(inc x) (inc y) z] "s" [(dec x) (dec y) z] "ne" [(inc x) y (inc z)] "sw" [(dec x) y (dec z)] "nw" [x (inc y) (dec z)] "se" [x (dec y) (inc z)]) next-max (max max-dist (distance next-coords))] [next-coords next-max])) [[0 0 0] 0] input)) (defn part-1 [] (distance (first (solve (data))))) (defn part-2 [] (second (solve (data)))) ;;;; Scratch (comment (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) 794 1524 )
null
https://raw.githubusercontent.com/borkdude/aoc2017/0f5bce5e496d65d0e53a8983e71ea3462aa0569c/src/day11.clj
clojure
Scratch
(ns day11 (:require [clojure.string :as str] [util :refer [read-first]]) (:import [java.lang Math])) (defn data [] (as-> "day11.txt" $ (read-first $) (str/split $ #","))) (defn distance ^long [coords] (/ ^long (apply + (map #(Math/abs ^long %) coords)) 2)) (defn solve "See " [input] (reduce (fn [[[^long x ^long y ^long z] ^long max-dist] next-dir] (let [next-coords (case next-dir "n" [(inc x) (inc y) z] "s" [(dec x) (dec y) z] "ne" [(inc x) y (inc z)] "sw" [(dec x) y (dec z)] "nw" [x (inc y) (dec z)] "se" [x (dec y) (inc z)]) next-max (max max-dist (distance next-coords))] [next-coords next-max])) [[0 0 0] 0] input)) (defn part-1 [] (distance (first (solve (data))))) (defn part-2 [] (second (solve (data)))) (comment (set! *warn-on-reflection* true) (set! *unchecked-math* :warn-on-boxed) 794 1524 )
49fdbfe2c60146e360e00336b0dedcc60fa634a9e1ff9b28cc3d9ddc53260abd
ylgrgyq/resilience-for-clojure
ratelimiter_test.clj
(ns resilience.ratelimiter-test (:refer-clojure :exclude [name reset!]) (:require [clojure.test :refer :all] [resilience.ratelimiter :refer :all] [resilience.core :as resilience]) (:import (java.util.concurrent TimeUnit) (io.github.resilience4j.ratelimiter RequestNotPermitted))) (defn- duration-nanos [start-nanos] (- (System/nanoTime) start-nanos)) (defn- drain-permissions [testing-rate-limiter limiter-config] (let [c (volatile! 0) permissions-limit (:limit-for-period limiter-config)] (loop [] (when (< @c permissions-limit) (resilience/execute-with-rate-limiter testing-rate-limiter (vswap! c inc)) (recur))) @c)) (deftest test-rate-limiter (testing "do not need to wait when consume at most limit-for-period permissions continuously" (let [limiter-config {:timeout-millis 0 :limit-for-period 100 :limit-refresh-period-nanos (.toNanos TimeUnit/SECONDS 1)}] (defratelimiter testing-rate-limiter limiter-config) (is (= (drain-permissions testing-rate-limiter limiter-config) (:limit-for-period limiter-config))))) (testing "when no permissions left next request must wait at least limit-refresh-period-millis for more permissions" (let [limiter-config {:timeout-millis 200 :limit-for-period 1 :limit-refresh-period-nanos (.toNanos TimeUnit/MILLISECONDS 200)} c (volatile! 0) on-successfule-acquire-times (atom 0) on-successfule-acquire-fn (fn [] (swap! on-successfule-acquire-times inc))] (defratelimiter testing-rate-limiter limiter-config) (set-on-successful-acquire-event-consumer! testing-rate-limiter on-successfule-acquire-fn) (set-on-all-event-consumer! testing-rate-limiter {:on-successful-acquire on-successfule-acquire-fn}) (is (= (drain-permissions testing-rate-limiter limiter-config) (:limit-for-period limiter-config))) ;; due to implementation to acquire the next permission after all permissions ;; were acquired is not need to wait whole period configured by :limit-for-period (let [start (System/nanoTime)] (resilience/execute-with-rate-limiter testing-rate-limiter (vswap! c inc)) (let [d (duration-nanos start)] (is (<= d (:limit-refresh-period-nanos limiter-config))))) (doseq [_ (range 10)] (let [start (System/nanoTime)] (resilience/execute-with-rate-limiter testing-rate-limiter (vswap! c inc)) (is (< (/ (Math/abs (long (- (duration-nanos start) (:limit-refresh-period-nanos limiter-config)))) (:limit-refresh-period-nanos limiter-config)) 0.05)))) (Thread/sleep 300) (is (= {:number-of-waiting-threads 0, :available-permissions 1} (metrics testing-rate-limiter))) ;; we registered every kind of events twice, so statistic should be double (is (= @on-successfule-acquire-times (* 2 (inc @c)))))) (testing "failed to acquire permission" (let [limiter-config {:timeout-millis 50 :limit-for-period 1 :limit-refresh-period-nanos (.toNanos TimeUnit/SECONDS 1)} c (volatile! 0) on-failed-acquire-times (atom 0) on-failed-acquire-fn (fn [] (swap! on-failed-acquire-times inc))] (defratelimiter testing-rate-limiter limiter-config) (set-on-failed-acquire-event-consumer! testing-rate-limiter on-failed-acquire-fn) (set-on-all-event-consumer! testing-rate-limiter {:on-failed-acquire on-failed-acquire-fn}) (is (= (drain-permissions testing-rate-limiter limiter-config) (:limit-for-period limiter-config))) (is (thrown? RequestNotPermitted (resilience/execute-with-rate-limiter testing-rate-limiter (vswap! c inc)))) (is (= @on-failed-acquire-times (* 2 (inc @c))))))) (deftest test-registry (testing "do not need to wait when consume at most limit-for-period permissions continuously" (let [limiter-config {:timeout-millis 0 :limit-for-period 100 :limit-refresh-period-nanos (.toNanos TimeUnit/SECONDS 1)}] (defregistry testing-registry limiter-config) (defratelimiter testing-rate-limiter {:registry testing-registry}) (is (= (drain-permissions testing-rate-limiter limiter-config) (:limit-for-period limiter-config))) (is (= [testing-rate-limiter] (get-all-rate-limiters testing-registry))))))
null
https://raw.githubusercontent.com/ylgrgyq/resilience-for-clojure/7b0532d1c72d416020402c15eb5699143be4b7bf/test/resilience/ratelimiter_test.clj
clojure
due to implementation to acquire the next permission after all permissions were acquired is not need to wait whole period configured by :limit-for-period we registered every kind of events twice, so statistic should be double
(ns resilience.ratelimiter-test (:refer-clojure :exclude [name reset!]) (:require [clojure.test :refer :all] [resilience.ratelimiter :refer :all] [resilience.core :as resilience]) (:import (java.util.concurrent TimeUnit) (io.github.resilience4j.ratelimiter RequestNotPermitted))) (defn- duration-nanos [start-nanos] (- (System/nanoTime) start-nanos)) (defn- drain-permissions [testing-rate-limiter limiter-config] (let [c (volatile! 0) permissions-limit (:limit-for-period limiter-config)] (loop [] (when (< @c permissions-limit) (resilience/execute-with-rate-limiter testing-rate-limiter (vswap! c inc)) (recur))) @c)) (deftest test-rate-limiter (testing "do not need to wait when consume at most limit-for-period permissions continuously" (let [limiter-config {:timeout-millis 0 :limit-for-period 100 :limit-refresh-period-nanos (.toNanos TimeUnit/SECONDS 1)}] (defratelimiter testing-rate-limiter limiter-config) (is (= (drain-permissions testing-rate-limiter limiter-config) (:limit-for-period limiter-config))))) (testing "when no permissions left next request must wait at least limit-refresh-period-millis for more permissions" (let [limiter-config {:timeout-millis 200 :limit-for-period 1 :limit-refresh-period-nanos (.toNanos TimeUnit/MILLISECONDS 200)} c (volatile! 0) on-successfule-acquire-times (atom 0) on-successfule-acquire-fn (fn [] (swap! on-successfule-acquire-times inc))] (defratelimiter testing-rate-limiter limiter-config) (set-on-successful-acquire-event-consumer! testing-rate-limiter on-successfule-acquire-fn) (set-on-all-event-consumer! testing-rate-limiter {:on-successful-acquire on-successfule-acquire-fn}) (is (= (drain-permissions testing-rate-limiter limiter-config) (:limit-for-period limiter-config))) (let [start (System/nanoTime)] (resilience/execute-with-rate-limiter testing-rate-limiter (vswap! c inc)) (let [d (duration-nanos start)] (is (<= d (:limit-refresh-period-nanos limiter-config))))) (doseq [_ (range 10)] (let [start (System/nanoTime)] (resilience/execute-with-rate-limiter testing-rate-limiter (vswap! c inc)) (is (< (/ (Math/abs (long (- (duration-nanos start) (:limit-refresh-period-nanos limiter-config)))) (:limit-refresh-period-nanos limiter-config)) 0.05)))) (Thread/sleep 300) (is (= {:number-of-waiting-threads 0, :available-permissions 1} (metrics testing-rate-limiter))) (is (= @on-successfule-acquire-times (* 2 (inc @c)))))) (testing "failed to acquire permission" (let [limiter-config {:timeout-millis 50 :limit-for-period 1 :limit-refresh-period-nanos (.toNanos TimeUnit/SECONDS 1)} c (volatile! 0) on-failed-acquire-times (atom 0) on-failed-acquire-fn (fn [] (swap! on-failed-acquire-times inc))] (defratelimiter testing-rate-limiter limiter-config) (set-on-failed-acquire-event-consumer! testing-rate-limiter on-failed-acquire-fn) (set-on-all-event-consumer! testing-rate-limiter {:on-failed-acquire on-failed-acquire-fn}) (is (= (drain-permissions testing-rate-limiter limiter-config) (:limit-for-period limiter-config))) (is (thrown? RequestNotPermitted (resilience/execute-with-rate-limiter testing-rate-limiter (vswap! c inc)))) (is (= @on-failed-acquire-times (* 2 (inc @c))))))) (deftest test-registry (testing "do not need to wait when consume at most limit-for-period permissions continuously" (let [limiter-config {:timeout-millis 0 :limit-for-period 100 :limit-refresh-period-nanos (.toNanos TimeUnit/SECONDS 1)}] (defregistry testing-registry limiter-config) (defratelimiter testing-rate-limiter {:registry testing-registry}) (is (= (drain-permissions testing-rate-limiter limiter-config) (:limit-for-period limiter-config))) (is (= [testing-rate-limiter] (get-all-rate-limiters testing-registry))))))
34503f8bde01ab8c047f35248c93ae67099f3edf7995d0d6758a041bda9fd634
Incubaid/baardskeerder
index_test.ml
* This file is part of Baardskeerder . * * Copyright ( C ) 2011 Incubaid BVBA * * Baardskeerder is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * Baardskeerder 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 Baardskeerder . If not , see < / > . * This file is part of Baardskeerder. * * Copyright (C) 2011 Incubaid BVBA * * Baardskeerder is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Baardskeerder 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 Baardskeerder. If not, see </>. *) open Index open Indexz open OUnit open Base let t_neighbours () = let z = (out 0 7, [("j", out 0 15); ("d", out 0 14)], []) in let nb = Indexz.neighbours z in OUnit.assert_equal (NL (out 0 14)) nb let t_neighbours2 () = let z = (out 0 37,["g", out 0 21],["m", out 0 31; "t", out 0 32]) in let nb = Indexz.neighbours z in OUnit.assert_equal (N2(out 0 37, out 0 31)) nb let t_neighbours3 () = let z = (out 0 0,["m", out 0 1; "g", out 0 2],["t", out 0 3]) in let nb = Indexz.neighbours z in OUnit.assert_equal (N2(out 0 2,out 0 3)) nb let t_suppress () = let z = (out 0 7, [("j", out 0 15); ("d", out 0 14)], []) in let nb = Indexz.neighbours z in match nb with | NL pos -> begin match pos with | Outer (0, 14) -> let z2 = Indexz.suppress L (out 0 17) None z in Printf.printf "z2= %s\n" (iz2s z2) | Outer _ -> failwith "should be Outer(0,14)" | Inner _ -> failwith "should be Outer _" end | NR _ | N2 _ -> failwith "should be NL 14" let t_suppress2 () = let z = (out 0 7,["d", out 0 8],[]) in let nb = Indexz.neighbours z in match nb with | NL pos -> begin match pos with |Outer (0, 7) -> let z2 = Indexz.suppress L (out 0 17) None z in Printf.printf "index = %s\n" (iz2s z2) | Outer _ -> failwith "should be Outer(0,7)" | Inner _ -> failwith "should be Outer _" end | NR _ | N2 _ -> failwith "should be NL 7" let t_suppress3 () = let z = (out 0 0,["m", out 0 1; "g", out 0 2],["t", out 0 3]) in let r = Indexz.suppress L (out 0 4) (Some "q") z in let () = Printf.printf "r = %s\n" (iz2s r) in let e = (out 0 0,["g", out 0 4],["q", out 0 3]) in OUnit.assert_equal ~printer:iz2s e r; () let t_suppress4() = let z = (out 0 78, [("key_12", out 0 79)], [("key_16", out 0 95)]) in let r = Indexz.suppress L (out 0 98) (Some "key_15") z in let e = make_indexz (out 0 98, ["key_15", out 0 95]) in OUnit.assert_equal ~printer:iz2s e r let t_split () = let d = 2 and lpos = out 0 21 and sep = "q" and rpos = out 0 22 and z = (out 0 7, [("j", out 0 18); ("d", out 0 14)], []) in let left, _ , _ = Indexz.split d lpos sep rpos z in OUnit.assert_equal ~printer:index2s (out 0 7, ["d",out 0 14]) left let t_split2() = let d = 2 and lpos = out 0 21 and sep = "j" and rpos = out 0 22 and z = (out 0 7, [("d", out 0 18)], [("q", out 0 15)]) in let left,_,right = Indexz.split d lpos sep rpos z in let printer = index2s in OUnit.assert_equal ~printer (out 0 7,["d", out 0 21]) left; OUnit.assert_equal ~printer (out 0 22,["q",out 0 15]) right let t_replace () = let z = (out 0 7, [("d", out 0 14)], [("m", out 0 15)]) in let index = Indexz.replace (out 0 18) z in OUnit.assert_equal ~printer:index2s index (out 0 7,("d",out 0 18) :: ("m",out 0 15)::[]) let t_replace_with_sep ( ) = let sep = " key_12 " in let start = 107 in let z = ( ( 76 , [ ( " key_10 " , 103 ) ] ) , [ ( " key_13 " , 93 ) ] ) in let r , _ = Index.indexz_replace_with_sep sep start z in let expected = 76 , [ " key_10 " , 107 ; " key_12 " , 93 ] in OUnit.assert_equal ~printer : index2s expected r let t_replace_with_sep () = let sep = "key_12" in let start = 107 in let z = Loc ((76, [("key_10", 103)]), [("key_13", 93)]) in let r,_ = Index.indexz_replace_with_sep sep start z in let expected = 76, ["key_10", 107; "key_12", 93] in OUnit.assert_equal ~printer:index2s expected r *) let t_merge () = let index = out 0 110, ["key_3", out 0 93] in let sep = "key_3" in let right = out 0 94, ["key_5", out 0 64 ; "key_7", out 0 54] in let m = "can't merge:(Outer (0, 110), [\"key_3\", Outer (0, 93)]) "^ "\"key_3\" (Outer (0, 94), [\"key_5\", Outer (0, 64); \"key_7\", "^ "Outer (0, 54)])" in OUnit.assert_raises (Failure m) (fun () -> index_merge index sep right) let suite = "Index" >:::[ "neighbours" >:: t_neighbours; "neighbours2" >:: t_neighbours2; "neighbours3" >:: t_neighbours3; "suppress" >:: t_suppress; "suppress2" >:: t_suppress2; "suppress3" >:: t_suppress3; "suppress4" >:: t_suppress4; "split" >:: t_split; "split2" >:: t_split2; "replace" >:: t_replace; " replace_with_sep " > : : t_replace_with_sep ; "merge" >:: t_merge; ]
null
https://raw.githubusercontent.com/Incubaid/baardskeerder/3975cb7f0e92e1f35eeab17beeb906344e43dae0/src/index_test.ml
ocaml
* This file is part of Baardskeerder . * * Copyright ( C ) 2011 Incubaid BVBA * * Baardskeerder is free software : you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , either version 3 of the License , or * ( at your option ) any later version . * * Baardskeerder 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 Baardskeerder . If not , see < / > . * This file is part of Baardskeerder. * * Copyright (C) 2011 Incubaid BVBA * * Baardskeerder is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Baardskeerder 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 Baardskeerder. If not, see </>. *) open Index open Indexz open OUnit open Base let t_neighbours () = let z = (out 0 7, [("j", out 0 15); ("d", out 0 14)], []) in let nb = Indexz.neighbours z in OUnit.assert_equal (NL (out 0 14)) nb let t_neighbours2 () = let z = (out 0 37,["g", out 0 21],["m", out 0 31; "t", out 0 32]) in let nb = Indexz.neighbours z in OUnit.assert_equal (N2(out 0 37, out 0 31)) nb let t_neighbours3 () = let z = (out 0 0,["m", out 0 1; "g", out 0 2],["t", out 0 3]) in let nb = Indexz.neighbours z in OUnit.assert_equal (N2(out 0 2,out 0 3)) nb let t_suppress () = let z = (out 0 7, [("j", out 0 15); ("d", out 0 14)], []) in let nb = Indexz.neighbours z in match nb with | NL pos -> begin match pos with | Outer (0, 14) -> let z2 = Indexz.suppress L (out 0 17) None z in Printf.printf "z2= %s\n" (iz2s z2) | Outer _ -> failwith "should be Outer(0,14)" | Inner _ -> failwith "should be Outer _" end | NR _ | N2 _ -> failwith "should be NL 14" let t_suppress2 () = let z = (out 0 7,["d", out 0 8],[]) in let nb = Indexz.neighbours z in match nb with | NL pos -> begin match pos with |Outer (0, 7) -> let z2 = Indexz.suppress L (out 0 17) None z in Printf.printf "index = %s\n" (iz2s z2) | Outer _ -> failwith "should be Outer(0,7)" | Inner _ -> failwith "should be Outer _" end | NR _ | N2 _ -> failwith "should be NL 7" let t_suppress3 () = let z = (out 0 0,["m", out 0 1; "g", out 0 2],["t", out 0 3]) in let r = Indexz.suppress L (out 0 4) (Some "q") z in let () = Printf.printf "r = %s\n" (iz2s r) in let e = (out 0 0,["g", out 0 4],["q", out 0 3]) in OUnit.assert_equal ~printer:iz2s e r; () let t_suppress4() = let z = (out 0 78, [("key_12", out 0 79)], [("key_16", out 0 95)]) in let r = Indexz.suppress L (out 0 98) (Some "key_15") z in let e = make_indexz (out 0 98, ["key_15", out 0 95]) in OUnit.assert_equal ~printer:iz2s e r let t_split () = let d = 2 and lpos = out 0 21 and sep = "q" and rpos = out 0 22 and z = (out 0 7, [("j", out 0 18); ("d", out 0 14)], []) in let left, _ , _ = Indexz.split d lpos sep rpos z in OUnit.assert_equal ~printer:index2s (out 0 7, ["d",out 0 14]) left let t_split2() = let d = 2 and lpos = out 0 21 and sep = "j" and rpos = out 0 22 and z = (out 0 7, [("d", out 0 18)], [("q", out 0 15)]) in let left,_,right = Indexz.split d lpos sep rpos z in let printer = index2s in OUnit.assert_equal ~printer (out 0 7,["d", out 0 21]) left; OUnit.assert_equal ~printer (out 0 22,["q",out 0 15]) right let t_replace () = let z = (out 0 7, [("d", out 0 14)], [("m", out 0 15)]) in let index = Indexz.replace (out 0 18) z in OUnit.assert_equal ~printer:index2s index (out 0 7,("d",out 0 18) :: ("m",out 0 15)::[]) let t_replace_with_sep ( ) = let sep = " key_12 " in let start = 107 in let z = ( ( 76 , [ ( " key_10 " , 103 ) ] ) , [ ( " key_13 " , 93 ) ] ) in let r , _ = Index.indexz_replace_with_sep sep start z in let expected = 76 , [ " key_10 " , 107 ; " key_12 " , 93 ] in OUnit.assert_equal ~printer : index2s expected r let t_replace_with_sep () = let sep = "key_12" in let start = 107 in let z = Loc ((76, [("key_10", 103)]), [("key_13", 93)]) in let r,_ = Index.indexz_replace_with_sep sep start z in let expected = 76, ["key_10", 107; "key_12", 93] in OUnit.assert_equal ~printer:index2s expected r *) let t_merge () = let index = out 0 110, ["key_3", out 0 93] in let sep = "key_3" in let right = out 0 94, ["key_5", out 0 64 ; "key_7", out 0 54] in let m = "can't merge:(Outer (0, 110), [\"key_3\", Outer (0, 93)]) "^ "\"key_3\" (Outer (0, 94), [\"key_5\", Outer (0, 64); \"key_7\", "^ "Outer (0, 54)])" in OUnit.assert_raises (Failure m) (fun () -> index_merge index sep right) let suite = "Index" >:::[ "neighbours" >:: t_neighbours; "neighbours2" >:: t_neighbours2; "neighbours3" >:: t_neighbours3; "suppress" >:: t_suppress; "suppress2" >:: t_suppress2; "suppress3" >:: t_suppress3; "suppress4" >:: t_suppress4; "split" >:: t_split; "split2" >:: t_split2; "replace" >:: t_replace; " replace_with_sep " > : : t_replace_with_sep ; "merge" >:: t_merge; ]
233368031650ea9f7b569639c6249d2157021ac7f51401dc2e1aa87918d2beb7
mbj/mhs
TH.hs
module LHT.TH (readFile) where import Instances.TH.Lift () import LHT.Prelude import Language.Haskell.TH.Syntax import qualified Data.Text.IO as Text import qualified System.Path as Path readFile :: Path.AbsRelFile -> Q (TExp Text) readFile path = do qAddDependentFile filepath TExp <$> (lift =<< runIO (Text.readFile filepath)) where filepath = Path.toString path
null
https://raw.githubusercontent.com/mbj/mhs/391fe59fa77ac9a8b197fafe710870e426093460/lht/src/LHT/TH.hs
haskell
module LHT.TH (readFile) where import Instances.TH.Lift () import LHT.Prelude import Language.Haskell.TH.Syntax import qualified Data.Text.IO as Text import qualified System.Path as Path readFile :: Path.AbsRelFile -> Q (TExp Text) readFile path = do qAddDependentFile filepath TExp <$> (lift =<< runIO (Text.readFile filepath)) where filepath = Path.toString path
7de0d02326179b023f320f4966fec168b171cfe89390299b7dd3f14a24135e30
cyverse-archive/DiscoveryEnvironmentBackend
json_body.clj
(ns jex.json-body (:use [clojure.java.io :only [reader]] [clojure-commons.error-codes] [slingshot.slingshot :only [try+ throw+]]) (:require [cheshire.core :as cheshire] [clojure.tools.logging :as log])) (defn- json-body? [request] (let [content-type (:content-type request)] (not (empty? (re-find #"^application/json" content-type))))) (defn get-json [request] (try (cheshire/decode-stream (reader (:body request)) true) (catch Exception e (throw+ {:error_code ERR_INVALID_JSON})))) (defn- valid-method? [request] (cond (= (:request-method request) "post") true (= (:request-method request) :post) true (= (:request-method request) "put") true (= (:request-method request) :put) true :else false)) (defn parse-json-body [handler] (fn [request] (cond (not (valid-method? request)) (handler request) (not (contains? request :body)) (handler request) (not (json-body? request)) (handler request) :else (try+ (let [body-map (get-json request) new-req (assoc request :body body-map)] (handler new-req)) (catch error? err (log/error (format-exception (:throwable &throw-context))) (err-resp "parse-json" (:object &throw-context))) (catch java.lang.Exception e (log/error (format-exception (:throwable &throw-context))) (err-resp "parse-json" (unchecked &throw-context)))))))
null
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/JEX/src/jex/json_body.clj
clojure
(ns jex.json-body (:use [clojure.java.io :only [reader]] [clojure-commons.error-codes] [slingshot.slingshot :only [try+ throw+]]) (:require [cheshire.core :as cheshire] [clojure.tools.logging :as log])) (defn- json-body? [request] (let [content-type (:content-type request)] (not (empty? (re-find #"^application/json" content-type))))) (defn get-json [request] (try (cheshire/decode-stream (reader (:body request)) true) (catch Exception e (throw+ {:error_code ERR_INVALID_JSON})))) (defn- valid-method? [request] (cond (= (:request-method request) "post") true (= (:request-method request) :post) true (= (:request-method request) "put") true (= (:request-method request) :put) true :else false)) (defn parse-json-body [handler] (fn [request] (cond (not (valid-method? request)) (handler request) (not (contains? request :body)) (handler request) (not (json-body? request)) (handler request) :else (try+ (let [body-map (get-json request) new-req (assoc request :body body-map)] (handler new-req)) (catch error? err (log/error (format-exception (:throwable &throw-context))) (err-resp "parse-json" (:object &throw-context))) (catch java.lang.Exception e (log/error (format-exception (:throwable &throw-context))) (err-resp "parse-json" (unchecked &throw-context)))))))
fe4fe65ad20a32b4c3efff9c484ee3570d4d9b7049f9f5e5566dc6a87b2f8b29
Bike/hominy
core.lisp
(in-package #:hominy/baselib) ;;; Define a "core" environment. This contains definitions for parts of the standard library ;;; that are pretty intrinsic to the semantics of the language, versus modules, which while ;;; critical (e.g. numbers) are in a sense optional. ;;; Pretty vague criterion, admittedly. But basically it means stuff relating to the types ;;; used in the core evaluation algorithm: combiners, environments, symbols, lists. ;;; By which definition boolean stuff like $cond doesn't belong, actually... (defvar *empty* (i:make-fixed-environment #() #())) (defun binds? (symbol environment) "Returns (Lisp) true iff symbol is bound in environment, directly or indirectly." (labels ((aux (environment) (if (nth-value 1 (i:local-cell symbol environment)) (return-from binds? t) (i:map-parents #'aux environment)))) (aux environment) nil)) (defenv (*core* *corec*) (*ground*) (defapp list (&rest elems) ignore ignore elems) (defapp list* (&rest elems) ignore ignore (apply #'list* elems)) (let ((wrap (i:lookup 'syms::wrap *ground*)) ($vau (i:lookup 'syms::$vau *ground*))) (defmac $lambda (ptree &rest body) ignore ignore (list wrap (list* $vau ptree i:ignore body)))) (macrolet ((defc (name) `(defapp ,name (list) ignore ignore (,name list))) (defcs (&rest names) `(progn ,@(loop for name in names collect `(defc ,name))))) (defcs caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr)) (defapp apply (applicative list) ignore frame (i:combine (i:unwrap applicative) list *empty* frame)) (defapp eapply (applicative list) env frame (i:combine (i:unwrap applicative) list env frame)) (let (($if (i:lookup 'syms::$if *ground*)) ($sequence (i:lookup 'syms::$sequence *ground*))) (defmac $cond (&rest clauses) ignore ignore (labels ((aux (comb) (if (null comb) i:inert (destructuring-bind ((test . body) . clauses) comb (list $if test (list* $sequence body) (aux clauses)))))) (aux clauses)))) (defapp map (app &rest lists) dynenv ignore ;; FIXME: Frames for the map combinations (when (null lists) (error 'type-error :datum lists :expected-type 'cons)) (loop with comb = (i:unwrap app) for sublists = lists then (mapcar #'cdr sublists) for items = (mapcar #'car sublists) FIXME : says error if the lists do n't have the same length , ;; which is probably better. until (some #'null sublists) collect (i:combine comb items dynenv))) (defapp not? (bool) ignore ignore (cond ((eq bool i:true) i:false) ((eq bool i:false) i:true) (t (error 'type-error :datum bool :expected-type 'i:boolean)))) (defapp and? (&rest bools) ignore ignore (boolify (every (lambda (b) (unless (typep b 'boolean) (error 'type-error :datum b :expected-type 'i:boolean)) (eq b i:true)) bools))) (defapp or? (&rest bools) ignore ignore (boolify (some (lambda (b) (unless (typep b 'boolean) (error 'type-error :datum b :expected-type 'i:boolean)) (eq b i:true)) bools))) for recursive definitions . (let* (($and? (make-instance 'macro)) ($if (i:lookup 'syms::$if *ground*)) (body (lambda (dynenv frame bools) (declare (cl:ignore dynenv frame)) (cond ((null bools) i:true) ((null (cdr bools)) (first bools)) ; tail context (t (list $if (first bools) (list* $and? (rest bools)) i:false))))) (op (i:make-builtin-operative body 'syms::$and?))) (setf (%expander $and?) op) (i:define $and? 'syms::$and? *defining-environment*)) (let* (($or? (make-instance 'macro)) ($if (i:lookup 'syms::$if *ground*)) (body (lambda (dynenv frame bools) (declare (cl:ignore dynenv frame)) (cond ((null bools) i:false) ((null (cdr bools)) (first bools)) ; tail context (t (list $if (first bools) i:true (list* $or? (rest bools))))))) (op (i:make-builtin-operative body 'syms::$or?))) (setf (%expander $or?) op) (i:define $or? 'syms::$or? *defining-environment*)) (defapp combiner? (object) ignore ignore (boolify (typep object 'i:combiner))) (defapp append (&rest lists) ignore ignore (reduce #'append lists)) (defapp filter (app list) ignore ignore (let ((under (i:unwrap app))) (remove-if-not (lambda (elem) (i:combine under (list elem) *empty*)) list))) (defapp reduce (list binop id) dynenv frame ;; FIXME: Frames for combinations (if (null list) id (let ((under (i:unwrap binop))) (reduce (lambda (o1 o2) (i:combine under (list o1 o2) dynenv frame)) list)))) (defapp append! (&rest lists) ignore ignore (reduce #'nconc lists)) (defapp assq (object list) ignore ignore (assoc object list)) (defapp memq? (object list) ignore ignore (boolify (member object list))) (defop $binds? (env sym) dynenv ignore (boolify (binds? sym (i:eval env dynenv)))) (defapp get-current-environment () env ignore env) (let (($lambda (i:lookup 'syms::$lambda *defining-environment*))) (defmac $let (bindings &rest body) ignore ignore (list* (list* $lambda (mapcar #'first bindings) body) (mapcar #'second bindings)))) (let (($let (i:lookup 'syms::$let *defining-environment*))) (defmac $let* (bindings &rest body) ignore ignore (labels ((aux (bindings) (if (null bindings) (list* $let () body) (list $let (list (first bindings)) (aux (rest bindings)))))) (aux bindings)))) This has slightly different behavior from with respect to forms that immediately evaluate the newly bound names . In , doing such will ;; get you the outside binding value if there is one, or else error with an ;; unbound variable. (This is not stated outright but is the behavior of the ;; given derivation.) This here binds everything to #inert. I think the ideal ;; would be to signal an error. To do that, either there needs to be a special ;; "unbound" marker to put in temporarily, or something like symbol macros. (let (($let (i:lookup 'syms::$let *defining-environment*)) ($set! (i:lookup 'syms::$set! *ground*)) (list (i:lookup 'syms::list *defining-environment*))) (defmac $letrec (bindings &rest body) ignore ignore (list* $let (mapcar (lambda (bind) (list (first bind) i:inert)) bindings) (list $set! (mapcar #'first bindings) (list* list (mapcar #'second bindings))) body))) (let (($letrec (i:lookup 'syms::$letrec *defining-environment*))) (defmac $letrec* (bindings &rest body) ignore ignore (labels ((aux (bindings) (if (null bindings) (list* $letrec () body) (list $letrec (list (first bindings)) (aux (rest bindings)))))) (aux bindings)))) (defapp for-each (app &rest lists) dynenv frame ;; FIXME: Frames (when (null lists) (error 'type-error :datum lists :expected-type 'cons)) (loop with comb = (i:unwrap app) for sublists = lists then (mapcar #'cdr lists) for items = (mapcar #'car sublists) do (i:combine comb items dynenv frame) FIXME : says error if the lists do n't have the same length , ;; which is probably better. until (some #'null sublists)) i:inert) Establish a lexically bound escape , like cl : block . ;; You still use just THROW to get to it, though. ;; FIXME: Might be better to give these an encapsulated type, ;; but on the other hand that would make using them with dconts awkward. ;; FIXME: In the final version ought to use static keys, not a gensym. (let (($catch (i:lookup 'syms::$catch *continuation*)) ($make-catch-tag (i:lookup 'syms::$make-catch-tag *continuation*)) ($let (i:lookup 'syms::$let *defining-environment*))) (defmac $let/ec (block-name &rest body) ignore ignore (let ((csym (gensym "CATCH"))) #+(or) `($let (((,csym ,block-name) ($make-catch-tag ,block-name))) ($catch ,csym ,@body)) (list $let (list (list (list csym block-name) (list $make-catch-tag block-name))) (list* $catch csym body))))))
null
https://raw.githubusercontent.com/Bike/hominy/ee8bb886d26f9c04eadf978ddbf4141c687b0c74/baselib/core.lisp
lisp
Define a "core" environment. This contains definitions for parts of the standard library that are pretty intrinsic to the semantics of the language, versus modules, which while critical (e.g. numbers) are in a sense optional. Pretty vague criterion, admittedly. But basically it means stuff relating to the types used in the core evaluation algorithm: combiners, environments, symbols, lists. By which definition boolean stuff like $cond doesn't belong, actually... FIXME: Frames for the map combinations which is probably better. tail context tail context FIXME: Frames for combinations get you the outside binding value if there is one, or else error with an unbound variable. (This is not stated outright but is the behavior of the given derivation.) This here binds everything to #inert. I think the ideal would be to signal an error. To do that, either there needs to be a special "unbound" marker to put in temporarily, or something like symbol macros. FIXME: Frames which is probably better. You still use just THROW to get to it, though. FIXME: Might be better to give these an encapsulated type, but on the other hand that would make using them with dconts awkward. FIXME: In the final version ought to use static keys, not a gensym.
(in-package #:hominy/baselib) (defvar *empty* (i:make-fixed-environment #() #())) (defun binds? (symbol environment) "Returns (Lisp) true iff symbol is bound in environment, directly or indirectly." (labels ((aux (environment) (if (nth-value 1 (i:local-cell symbol environment)) (return-from binds? t) (i:map-parents #'aux environment)))) (aux environment) nil)) (defenv (*core* *corec*) (*ground*) (defapp list (&rest elems) ignore ignore elems) (defapp list* (&rest elems) ignore ignore (apply #'list* elems)) (let ((wrap (i:lookup 'syms::wrap *ground*)) ($vau (i:lookup 'syms::$vau *ground*))) (defmac $lambda (ptree &rest body) ignore ignore (list wrap (list* $vau ptree i:ignore body)))) (macrolet ((defc (name) `(defapp ,name (list) ignore ignore (,name list))) (defcs (&rest names) `(progn ,@(loop for name in names collect `(defc ,name))))) (defcs caar cadr cdar cddr caaar caadr cadar caddr cdaar cdadr cddar cdddr caaaar caaadr caadar caaddr cadaar cadadr caddar cadddr cdaaar cdaadr cdadar cdaddr cddaar cddadr cdddar cddddr)) (defapp apply (applicative list) ignore frame (i:combine (i:unwrap applicative) list *empty* frame)) (defapp eapply (applicative list) env frame (i:combine (i:unwrap applicative) list env frame)) (let (($if (i:lookup 'syms::$if *ground*)) ($sequence (i:lookup 'syms::$sequence *ground*))) (defmac $cond (&rest clauses) ignore ignore (labels ((aux (comb) (if (null comb) i:inert (destructuring-bind ((test . body) . clauses) comb (list $if test (list* $sequence body) (aux clauses)))))) (aux clauses)))) (defapp map (app &rest lists) dynenv ignore (when (null lists) (error 'type-error :datum lists :expected-type 'cons)) (loop with comb = (i:unwrap app) for sublists = lists then (mapcar #'cdr sublists) for items = (mapcar #'car sublists) FIXME : says error if the lists do n't have the same length , until (some #'null sublists) collect (i:combine comb items dynenv))) (defapp not? (bool) ignore ignore (cond ((eq bool i:true) i:false) ((eq bool i:false) i:true) (t (error 'type-error :datum bool :expected-type 'i:boolean)))) (defapp and? (&rest bools) ignore ignore (boolify (every (lambda (b) (unless (typep b 'boolean) (error 'type-error :datum b :expected-type 'i:boolean)) (eq b i:true)) bools))) (defapp or? (&rest bools) ignore ignore (boolify (some (lambda (b) (unless (typep b 'boolean) (error 'type-error :datum b :expected-type 'i:boolean)) (eq b i:true)) bools))) for recursive definitions . (let* (($and? (make-instance 'macro)) ($if (i:lookup 'syms::$if *ground*)) (body (lambda (dynenv frame bools) (declare (cl:ignore dynenv frame)) (cond ((null bools) i:true) (t (list $if (first bools) (list* $and? (rest bools)) i:false))))) (op (i:make-builtin-operative body 'syms::$and?))) (setf (%expander $and?) op) (i:define $and? 'syms::$and? *defining-environment*)) (let* (($or? (make-instance 'macro)) ($if (i:lookup 'syms::$if *ground*)) (body (lambda (dynenv frame bools) (declare (cl:ignore dynenv frame)) (cond ((null bools) i:false) (t (list $if (first bools) i:true (list* $or? (rest bools))))))) (op (i:make-builtin-operative body 'syms::$or?))) (setf (%expander $or?) op) (i:define $or? 'syms::$or? *defining-environment*)) (defapp combiner? (object) ignore ignore (boolify (typep object 'i:combiner))) (defapp append (&rest lists) ignore ignore (reduce #'append lists)) (defapp filter (app list) ignore ignore (let ((under (i:unwrap app))) (remove-if-not (lambda (elem) (i:combine under (list elem) *empty*)) list))) (defapp reduce (list binop id) dynenv frame (if (null list) id (let ((under (i:unwrap binop))) (reduce (lambda (o1 o2) (i:combine under (list o1 o2) dynenv frame)) list)))) (defapp append! (&rest lists) ignore ignore (reduce #'nconc lists)) (defapp assq (object list) ignore ignore (assoc object list)) (defapp memq? (object list) ignore ignore (boolify (member object list))) (defop $binds? (env sym) dynenv ignore (boolify (binds? sym (i:eval env dynenv)))) (defapp get-current-environment () env ignore env) (let (($lambda (i:lookup 'syms::$lambda *defining-environment*))) (defmac $let (bindings &rest body) ignore ignore (list* (list* $lambda (mapcar #'first bindings) body) (mapcar #'second bindings)))) (let (($let (i:lookup 'syms::$let *defining-environment*))) (defmac $let* (bindings &rest body) ignore ignore (labels ((aux (bindings) (if (null bindings) (list* $let () body) (list $let (list (first bindings)) (aux (rest bindings)))))) (aux bindings)))) This has slightly different behavior from with respect to forms that immediately evaluate the newly bound names . In , doing such will (let (($let (i:lookup 'syms::$let *defining-environment*)) ($set! (i:lookup 'syms::$set! *ground*)) (list (i:lookup 'syms::list *defining-environment*))) (defmac $letrec (bindings &rest body) ignore ignore (list* $let (mapcar (lambda (bind) (list (first bind) i:inert)) bindings) (list $set! (mapcar #'first bindings) (list* list (mapcar #'second bindings))) body))) (let (($letrec (i:lookup 'syms::$letrec *defining-environment*))) (defmac $letrec* (bindings &rest body) ignore ignore (labels ((aux (bindings) (if (null bindings) (list* $letrec () body) (list $letrec (list (first bindings)) (aux (rest bindings)))))) (aux bindings)))) (defapp for-each (app &rest lists) dynenv frame (when (null lists) (error 'type-error :datum lists :expected-type 'cons)) (loop with comb = (i:unwrap app) for sublists = lists then (mapcar #'cdr lists) for items = (mapcar #'car sublists) do (i:combine comb items dynenv frame) FIXME : says error if the lists do n't have the same length , until (some #'null sublists)) i:inert) Establish a lexically bound escape , like cl : block . (let (($catch (i:lookup 'syms::$catch *continuation*)) ($make-catch-tag (i:lookup 'syms::$make-catch-tag *continuation*)) ($let (i:lookup 'syms::$let *defining-environment*))) (defmac $let/ec (block-name &rest body) ignore ignore (let ((csym (gensym "CATCH"))) #+(or) `($let (((,csym ,block-name) ($make-catch-tag ,block-name))) ($catch ,csym ,@body)) (list $let (list (list (list csym block-name) (list $make-catch-tag block-name))) (list* $catch csym body))))))
9ec4820ed598ddb99eac0715ad876c16c73b0624f2818d02f125476aac714fea
aantron/luv
once.mli
This file is part of Luv , released under the MIT license . See LICENSE.md for details , or visit . details, or visit . *) * Once - only initialization . See { { : #once-only-initialization } { i Once - only initialization } } in libuv . See {{:#once-only-initialization} {i Once-only initialization}} in libuv. *) type t (** Binds {{:#c.uv_once_t} [uv_once_t]}. *) val init : unit -> (t, Error.t) result * Allocates and initializes a once - only barrier . Binds { { : #once-only-initialization } [ UV_ONCE_INIT ] } . See { { : -pages/man3/pthread_once.3p.html } [ ) ] } . Binds {{:#once-only-initialization} [UV_ONCE_INIT]}. See {{:-pages/man3/pthread_once.3p.html} [pthread_once(3p)]}. *) val once : t -> (unit -> unit) -> unit * Guards the given callback to be called only once . Binds { { : #c.uv_once } [ uv_once ] } . See { { : -pages/man3/pthread_once.3p.html } [ ) ] } . Binds {{:#c.uv_once} [uv_once]}. See {{:-pages/man3/pthread_once.3p.html} [pthread_once(3p)]}. *) val once_c : t -> nativeint -> unit (** Like {!Luv.Once.once}, but takes a pointer to a C function. *)
null
https://raw.githubusercontent.com/aantron/luv/4b49d3edad2179c76d685500edf1b44f61ec4be8/src/once.mli
ocaml
* Binds {{:#c.uv_once_t} [uv_once_t]}. * Like {!Luv.Once.once}, but takes a pointer to a C function.
This file is part of Luv , released under the MIT license . See LICENSE.md for details , or visit . details, or visit . *) * Once - only initialization . See { { : #once-only-initialization } { i Once - only initialization } } in libuv . See {{:#once-only-initialization} {i Once-only initialization}} in libuv. *) type t val init : unit -> (t, Error.t) result * Allocates and initializes a once - only barrier . Binds { { : #once-only-initialization } [ UV_ONCE_INIT ] } . See { { : -pages/man3/pthread_once.3p.html } [ ) ] } . Binds {{:#once-only-initialization} [UV_ONCE_INIT]}. See {{:-pages/man3/pthread_once.3p.html} [pthread_once(3p)]}. *) val once : t -> (unit -> unit) -> unit * Guards the given callback to be called only once . Binds { { : #c.uv_once } [ uv_once ] } . See { { : -pages/man3/pthread_once.3p.html } [ ) ] } . Binds {{:#c.uv_once} [uv_once]}. See {{:-pages/man3/pthread_once.3p.html} [pthread_once(3p)]}. *) val once_c : t -> nativeint -> unit
fb73c46e5d35663a43d1e5955fe34c5cd4afd253bb159546a163c3c217fd4e3b
CryptoKami/cryptokami-core
Swagger.hs
-- | Wallet swagger implementation # OPTIONS_GHC -F -pgmF autoexporter #
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/wallet/src/Pos/Wallet/Web/Swagger.hs
haskell
| Wallet swagger implementation
# OPTIONS_GHC -F -pgmF autoexporter #
c7052a41d13d0faa1465c9ce9ec1eb69b444076f4c5d2431728c812366a5cd2f
mpickering/apply-refact
Bracket1.hs
no = f (x x)
null
https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Bracket1.hs
haskell
no = f (x x)
9eb8e9ae34ef1cb99aba33f4867fa0cbffb8c23cc307d2ffac3078116b368e67
semperos/rankle
util_test.clj
(ns com.semperos.rankle.util-test (:require [clojure.test :refer :all] [com.semperos.rankle.util :as util])) (def ^:dynamic *processed*) (def ^:dynamic *iteration*) (deftest test-cond-table (testing "Default cond-table `and`" (let [success? (fn [] (= *processed* ::success)) failure? (fn [] (= *processed* ::failure)) final? (fn [] (= *iteration* ::final)) intermediate? (fn [] (= *iteration* ::retry)) ok (constantly ::ok) log (constantly ::log) test (fn [[p i] expected] (binding [*processed* p *iteration* i] (is (= expected (util/cond-table :| __________ (final?) (intermediate?) :| (success?) (ok) ::not-bad :| (failure?) -1 (log))) (str "If processed is " p " and iteration is " i " then the result should be " expected))))] (test [::failure ::retry] ::log) (test [::failure ::final] -1) (test [::success ::retry] ::not-bad) (test [::success ::final] ::ok))) (testing "Custom op, xor function table" (let [xor (fn [x y] (let [x⊻y (fn [& args] (= [x y] args))] (util/cond-table :| x⊻y 0 1 :| 0 0 1 :| 1 1 0))) test (fn [[x y] expected] (let [xor-result (xor x y) bit-xor-result (bit-xor x y)] (is (= expected xor-result bit-xor-result) (str "Expected " expected " but xor gave " xor-result " and bit-xor gave " bit-xor-result))))] (test [0 0] 0) (test [1 1] 0) (test [0 1] 1) (test [1 0] 1)))) (deftest test-validate-cond-table (is (thrown-with-msg? IllegalArgumentException #"Each row in cond-table must begin with the keyword :\|" (util/validate-cond-table [ :a :b :| :c :d :e]))) (is (thrown-with-msg? IllegalArgumentException #"Every row after the first in cond-table must start with a predicate and include an expression for each cell in the table." (util/validate-cond-table [:| :a :b :| :c :d :e :| :g :h]))) (is (thrown-with-msg? IllegalArgumentException #"Every row after the first in cond-table must start with a predicate and include an expression for each cell in the table." (util/validate-cond-table [:| :a :b :| :c :e :| :f :g :h]))))
null
https://raw.githubusercontent.com/semperos/rankle/d898c144e33056d743848620f17564d88d87e874/test/com/semperos/rankle/util_test.clj
clojure
(ns com.semperos.rankle.util-test (:require [clojure.test :refer :all] [com.semperos.rankle.util :as util])) (def ^:dynamic *processed*) (def ^:dynamic *iteration*) (deftest test-cond-table (testing "Default cond-table `and`" (let [success? (fn [] (= *processed* ::success)) failure? (fn [] (= *processed* ::failure)) final? (fn [] (= *iteration* ::final)) intermediate? (fn [] (= *iteration* ::retry)) ok (constantly ::ok) log (constantly ::log) test (fn [[p i] expected] (binding [*processed* p *iteration* i] (is (= expected (util/cond-table :| __________ (final?) (intermediate?) :| (success?) (ok) ::not-bad :| (failure?) -1 (log))) (str "If processed is " p " and iteration is " i " then the result should be " expected))))] (test [::failure ::retry] ::log) (test [::failure ::final] -1) (test [::success ::retry] ::not-bad) (test [::success ::final] ::ok))) (testing "Custom op, xor function table" (let [xor (fn [x y] (let [x⊻y (fn [& args] (= [x y] args))] (util/cond-table :| x⊻y 0 1 :| 0 0 1 :| 1 1 0))) test (fn [[x y] expected] (let [xor-result (xor x y) bit-xor-result (bit-xor x y)] (is (= expected xor-result bit-xor-result) (str "Expected " expected " but xor gave " xor-result " and bit-xor gave " bit-xor-result))))] (test [0 0] 0) (test [1 1] 0) (test [0 1] 1) (test [1 0] 1)))) (deftest test-validate-cond-table (is (thrown-with-msg? IllegalArgumentException #"Each row in cond-table must begin with the keyword :\|" (util/validate-cond-table [ :a :b :| :c :d :e]))) (is (thrown-with-msg? IllegalArgumentException #"Every row after the first in cond-table must start with a predicate and include an expression for each cell in the table." (util/validate-cond-table [:| :a :b :| :c :d :e :| :g :h]))) (is (thrown-with-msg? IllegalArgumentException #"Every row after the first in cond-table must start with a predicate and include an expression for each cell in the table." (util/validate-cond-table [:| :a :b :| :c :e :| :f :g :h]))))
1aa9bf5e81c9dde84c63e2b739c819ddcb2ad7cba71ebec39ab0f29982456df9
haskell-lisp/yale-haskell
parser-macros.scm
Macro definitions for the parser & lexer . ;;; This macro allows debugging of the lexer. Before releasing, this can ;;; be replaced by (begin ,@body) for faster code. (define-syntax (trace-parser tag . body) ; `(begin ; (let* ((k (tracing-parse/entry ',tag)) ; (res (begin ,@body))) ; (tracing-parse/exit ',tag k res) ; res)) (declare (ignore tag)) `(begin ,@body) ) Macros used by the lexer . ;;; The lexer used a macro, char-case, to dispatch on the syntactic catagory of ;;; a character. These catagories (processed at compile time) are defined ;;; here. Note that some of these definitions use the char-code ;;; directly and would need updating for different character sets. (define *lex-definitions* '((vtab 11) ; define by ascii code to avoid relying of the reader (formfeed 12) (whitechar #\newline #\space #\tab formfeed vtab) (small #\a - #\z) (large #\A - #\Z) (digit #\0 - #\9) (symbol #\! #\# #\$ #\% #\& #\* #\+ #\. #\/ #\< #\= #\> #\? #\@ #\\ #\^ #\|) (presymbol #\- #\~) (exponent #\e #\E) (graphic large small digit #\! #\" #\# #\$ #\% #\& #\' #\( #\) #\* #\+ # \ < # \= # \ > # \ ? # \@ #\[ #\\ #\] #\^ #\_ #\` #\{ #\| #\} #\~) (charesc #\a #\b #\f #\n #\r #\t #\v #\\ #\" #\' #\&) (cntrl large #\@ #\[ #\\ #\] #\^ #\_))) ;;; The char-case macro is similar to case using characters to select. ;;; The following capabilities are added by char-case: ;;; pre-defined constants are denoted by symbols (defined above) ;;; ranges of characters are represented using -. For example, ( # \a - # \z # \A - # \Z ) denotes all alphabetics . ;;; numbers refer to the char code of a character. ;;; The generated code is optimized somewhat to take advantage of ;;; consecutive character ranges. With a little work, this could be ;;; implemented using jump tables someday. (define-syntax (char-case exp . alts) (expand-char-case exp alts)) (define (expand-char-case exp alts) (let ((temp (gensym))) `(let ((,temp ,exp)) ,(expand-char-case1 temp alts)))) (define (expand-char-case1 temp alts) (if (null? alts) '() (let* ((alt (car alts)) (test (car alt)) (body (cons 'begin (cdr alt))) (rest (expand-char-case1 temp (cdr alts)))) (cond ((eq? test 'else) body) (else `(if (or ,@(gen-char-tests temp (if (pair? test) test (list test)))) ,body ,rest)))))) (define (gen-char-tests temp tests) (gen-char-tests-1 temp (sort-list (gather-char-tests tests) (function char<?)))) (define (gen-char-tests-1 temp chars) (cond ((null? chars) '()) ((long-enough-run? chars 3) (gen-range-check temp (car chars) (car chars) (cdr chars))) (else `((char=? ,temp ',(car chars)) ,@(gen-char-tests-1 temp (cdr chars)))))) (define (gen-range-check temp first current chars) (if (and (pair? chars) (consec-chars? current (car chars))) (gen-range-check temp first (car chars) (cdr chars)) `((and (char>=? ,temp ',first) (char<=? ,temp ',current)) ,@(gen-char-tests-1 temp chars)))) (define (consec-chars? c1 c2) (eqv? (+ 1 (char->integer c1)) (char->integer c2))) (define (long-enough-run? l n) (or (eqv? n 1) (and (pair? (cdr l)) (consec-chars? (car l) (cadr l)) (long-enough-run? (cdr l) (1- n))))) (define (gather-char-tests tests) (cond ((null? tests) '()) ((symbol? (car tests)) (let ((new-test (assq (car tests) *lex-definitions*))) (if new-test (gather-char-tests (append (cdr new-test) (cdr tests))) (error "Unknown character class: ~A~%" (car tests))))) ((integer? (car tests)) (cons (integer->char (car tests)) (gather-char-tests (cdr tests)))) ((and (pair? (cdr tests)) (eq? '- (cadr tests))) (letrec ((fn (lambda (a z) (if (char>? a z) (gather-char-tests (cdddr tests)) (cons a (funcall fn (integer->char (+ 1 (char->integer a))) z)))))) (funcall fn (car tests) (caddr tests)))) ((char? (car tests)) (cons (car tests) (gather-char-tests (cdr tests)))) (else (error "Invalid selector in char-case: ~A~%" (car tests))))) ;;; This macro scans a list of characters on a given syntaxtic catagory. ;;; The current character is always included in the resulting list. (define-syntax (scan-list-of char-type) `(letrec ((test-next (lambda () (char-case *char* (,char-type (let ((c *char*)) (advance-char) (cons c (funcall test-next)))) (else '()))))) (let ((c *char*)) (advance-char) (cons c (funcall test-next))))) ;;; This macro tests for string equality in which the strings are ;;; represented by lists of characters. The comparisons are expanded ;;; inline (really just a little partial evaluation going on here!) for ;;; fast execution. The tok argument evaluate to a list of chars. The string ;;; argument must be a string constant, which is converted to characters ;;; as the macro expands. (define-syntax (string=/list? tok string) (let ((temp (gensym))) `(let ((,temp ,tok)) ,(expand-string=/list? temp (string->list string))))) (define (expand-string=/list? var chars) (if (null? chars) `(null? ,var) (let ((new-temp (gensym))) `(and (pair? ,var) (char=? (car ,var) ',(car chars)) (let ((,new-temp (cdr ,var))) ,(expand-string=/list? new-temp (cdr chars))))))) ;;; This macro extends the string equality defined above to search a ;;; list of reserved words quickly for keywords. It does this by a case dispatch on the first character of the string and then processing the remaining characters string=/list . This would go a little ;;; faster with recursive char-case statements, but I'm a little too ;;; lazy at for this at the moment. If a keyword is found is emitted ;;; as a symbol. If not, the token string is emitted with the token ;;; type indicated. Assume the string being scanned is a list of chars assigned to a var . ( Yeah - I know - I should add a ;;; var for this argument!!). (define-syntax (parse-reserved var token-type . reserved-words) (let ((sorted-rws (sort-list reserved-words (function string<?)))) `(let ((thunk (lambda () (emit-token/string ',token-type ,var)))) (char-case (car ,var) ,@(expand-parse-reserved var (group-by-first-char (list (car sorted-rws)) (cdr sorted-rws))) (else (funcall thunk)))))) (define (group-by-first-char group rest) (cond ((null? rest) (list group)) ((char=? (string-ref (car group) 0) (string-ref (car rest) 0)) (group-by-first-char (append group (list (car rest))) (cdr rest))) (else (cons group (group-by-first-char (list (car rest)) (cdr rest)))))) (define (expand-parse-reserved var groups) (if (null? groups) '() `((,(string-ref (caar groups) 0) (cond ,@(expand-parse-reserved/group var (car groups)) (else (funcall thunk)))) ,@(expand-parse-reserved var (cdr groups))))) (define (expand-parse-reserved/group var group) (if (null? group) '() `(((string=/list? (cdr ,var) ,(substring (car group) 1 (string-length (car group)))) (emit-token ',(string->symbol (car group)))) ,@(expand-parse-reserved/group var (cdr group))))) ;;; The following macros are used by the parser. ;;; The primary macro used by the parser is token-case, which dispatches ;;; on the type of the current token (this is always *token* - unlike the ;;; lexer, no lookahead is provided; however, some of these dispatches are ;;; procedures that do a limited lookahead. The problem with lookahead is that ;;; the layout rule adds tokens which are not visible looking into the ;;; token stream directly. ;;; Unlike char-case, the token is normally advanced unless the selector ;;; includes `no-advance'. The final else also avoids advancing the token. ;;; In addition to raw token types, more complex types can be used. These ;;; are defined here. The construct `satisfies fn' calls the indicated ;;; function to determine whether the current token matches. ;;; If the token type to be matched is not a constant, the construct ;;; `unquote var' matches the current token against the type in the var. (define *predefined-syntactic-catagories* '( (+ satisfies at-varsym/+?) (- satisfies at-varsym/-?) (tycon no-advance conid) (tyvar no-advance varid) (var no-advance varid satisfies at-varsym/paren?) (con no-advance conid satisfies at-consym/paren?) (name no-advance var con) (consym/paren no-advance satisfies at-consym/paren?) (varsym? no-advance varsym) (consym? no-advance consym) (varid? no-advance varid) (conid? no-advance conid) (op no-advance varsym consym \`) (varop no-advance varsym satisfies at-varid/quoted?) (conop no-advance consym satisfies at-conid/quoted?) (modid no-advance conid) (literal no-advance integer float char string) (numeric no-advance integer float) (k no-advance integer) (+k no-advance satisfies at-+k?) (-n no-advance satisfies at--n?) (apat-start no-advance varid conid literal _ \( \[ \~) (pat-start no-advance - apat-start) (atype-start no-advance tycon tyvar \( \[) (aexp-start no-advance varid conid \( \[ literal) )) ;;; The format of token-case is ;;; (token-case ( sel1 . e1 ) ( sel2 . e2 ) ... [ ( else . en ) ] ) ;;; If the sel is a symbol it is the same as a singleton list: (@ x) = ((@) x) ;;; Warning: this generates rather poor code! Should be fixed up someday. (define-syntax (token-case . alts) `(cond ,@(map (function gen-token-case-alt) alts))) (define (gen-token-case-alt alt) (let ((test (car alt)) (code (cdr alt))) (cond ((eq? test 'else) `(else ,@code)) ((symbol? test) (gen-token-case-alt-1 (expand-catagories (list test)) code)) (else (gen-token-case-alt-1 (expand-catagories test) code))))) (define (expand-catagories terms) (if (null? terms) terms (let ((a (assq (car terms) *predefined-syntactic-catagories*)) (r (expand-catagories (cdr terms)))) (if (null? a) (cons (car terms) r) (expand-catagories (append (cdr a) r)))))) (define (gen-token-case-alt-1 test code) `((or ,@(gen-token-test test)) ,@(if (memq 'no-advance test) '() '((advance-token))) ,@code)) (define (gen-token-test test) (cond ((null? test) '()) ((eq? (car test) 'no-advance) (gen-token-test (cdr test))) ((eq? (car test) 'unquote) (cons `(eq? *token* ,(cadr test)) (gen-token-test (cddr test)))) ((eq? (car test) 'satisfies) (cons (list (cadr test)) (gen-token-test (cddr test)))) (else (cons `(eq? *token* ',(car test)) (gen-token-test (cdr test)))))) ;;; require-tok requires a specific token to be at the scanner. If it ;;; is found, the token is advanced over. Otherwise, the error ;;; routine is called. (define-syntax (require-token tok error-handler) `(token-case (,tok '()) (else ,error-handler))) ;;; The save-parser-context macro captures the current line & file and ;;; attaches it to the ast node generated. (define-syntax (save-parser-context . body) (let ((temp1 (gensym)) (temp2 (gensym))) `(let ((,temp1 (capture-current-line)) (,temp2 (begin ,@body))) (setf (ast-node-line-number ,temp2) ,temp1) ,temp2))) (define (capture-current-line) (make source-pointer (line *current-line*) (file *current-file*))) (define-syntax (push-decl-list decl place) `(setf ,place (nconc ,place (list ,decl))))
null
https://raw.githubusercontent.com/haskell-lisp/yale-haskell/4e987026148fe65c323afbc93cd560c07bf06b3f/parser/parser-macros.scm
scheme
This macro allows debugging of the lexer. Before releasing, this can be replaced by (begin ,@body) for faster code. `(begin (let* ((k (tracing-parse/entry ',tag)) (res (begin ,@body))) (tracing-parse/exit ',tag k res) res)) The lexer used a macro, char-case, to dispatch on the syntactic catagory of a character. These catagories (processed at compile time) are defined here. Note that some of these definitions use the char-code directly and would need updating for different character sets. define by ascii code to avoid relying of the reader The char-case macro is similar to case using characters to select. The following capabilities are added by char-case: pre-defined constants are denoted by symbols (defined above) ranges of characters are represented using -. For example, numbers refer to the char code of a character. The generated code is optimized somewhat to take advantage of consecutive character ranges. With a little work, this could be implemented using jump tables someday. This macro scans a list of characters on a given syntaxtic catagory. The current character is always included in the resulting list. This macro tests for string equality in which the strings are represented by lists of characters. The comparisons are expanded inline (really just a little partial evaluation going on here!) for fast execution. The tok argument evaluate to a list of chars. The string argument must be a string constant, which is converted to characters as the macro expands. This macro extends the string equality defined above to search a list of reserved words quickly for keywords. It does this by a case faster with recursive char-case statements, but I'm a little too lazy at for this at the moment. If a keyword is found is emitted as a symbol. If not, the token string is emitted with the token type indicated. Assume the string being scanned is a list of var for this argument!!). The following macros are used by the parser. The primary macro used by the parser is token-case, which dispatches on the type of the current token (this is always *token* - unlike the lexer, no lookahead is provided; however, some of these dispatches are procedures that do a limited lookahead. The problem with lookahead is that the layout rule adds tokens which are not visible looking into the token stream directly. Unlike char-case, the token is normally advanced unless the selector includes `no-advance'. The final else also avoids advancing the token. In addition to raw token types, more complex types can be used. These are defined here. The construct `satisfies fn' calls the indicated function to determine whether the current token matches. If the token type to be matched is not a constant, the construct `unquote var' matches the current token against the type in the var. The format of token-case is (token-case If the sel is a symbol it is the same as a singleton list: (@ x) = ((@) x) Warning: this generates rather poor code! Should be fixed up someday. require-tok requires a specific token to be at the scanner. If it is found, the token is advanced over. Otherwise, the error routine is called. The save-parser-context macro captures the current line & file and attaches it to the ast node generated.
Macro definitions for the parser & lexer . (define-syntax (trace-parser tag . body) (declare (ignore tag)) `(begin ,@body) ) Macros used by the lexer . (define *lex-definitions* (formfeed 12) (whitechar #\newline #\space #\tab formfeed vtab) (small #\a - #\z) (large #\A - #\Z) (digit #\0 - #\9) (symbol #\! #\# #\$ #\% #\& #\* #\+ #\. #\/ #\< #\= #\> #\? #\@ #\\ #\^ #\|) (presymbol #\- #\~) (exponent #\e #\E) (graphic large small digit #\! #\" #\# #\$ #\% #\& #\' #\( #\) #\* #\+ # \ < # \= # \ > # \ ? # \@ #\[ #\\ #\] #\^ #\_ #\` #\{ #\| #\} #\~) (charesc #\a #\b #\f #\n #\r #\t #\v #\\ #\" #\' #\&) (cntrl large #\@ #\[ #\\ #\] #\^ #\_))) ( # \a - # \z # \A - # \Z ) denotes all alphabetics . (define-syntax (char-case exp . alts) (expand-char-case exp alts)) (define (expand-char-case exp alts) (let ((temp (gensym))) `(let ((,temp ,exp)) ,(expand-char-case1 temp alts)))) (define (expand-char-case1 temp alts) (if (null? alts) '() (let* ((alt (car alts)) (test (car alt)) (body (cons 'begin (cdr alt))) (rest (expand-char-case1 temp (cdr alts)))) (cond ((eq? test 'else) body) (else `(if (or ,@(gen-char-tests temp (if (pair? test) test (list test)))) ,body ,rest)))))) (define (gen-char-tests temp tests) (gen-char-tests-1 temp (sort-list (gather-char-tests tests) (function char<?)))) (define (gen-char-tests-1 temp chars) (cond ((null? chars) '()) ((long-enough-run? chars 3) (gen-range-check temp (car chars) (car chars) (cdr chars))) (else `((char=? ,temp ',(car chars)) ,@(gen-char-tests-1 temp (cdr chars)))))) (define (gen-range-check temp first current chars) (if (and (pair? chars) (consec-chars? current (car chars))) (gen-range-check temp first (car chars) (cdr chars)) `((and (char>=? ,temp ',first) (char<=? ,temp ',current)) ,@(gen-char-tests-1 temp chars)))) (define (consec-chars? c1 c2) (eqv? (+ 1 (char->integer c1)) (char->integer c2))) (define (long-enough-run? l n) (or (eqv? n 1) (and (pair? (cdr l)) (consec-chars? (car l) (cadr l)) (long-enough-run? (cdr l) (1- n))))) (define (gather-char-tests tests) (cond ((null? tests) '()) ((symbol? (car tests)) (let ((new-test (assq (car tests) *lex-definitions*))) (if new-test (gather-char-tests (append (cdr new-test) (cdr tests))) (error "Unknown character class: ~A~%" (car tests))))) ((integer? (car tests)) (cons (integer->char (car tests)) (gather-char-tests (cdr tests)))) ((and (pair? (cdr tests)) (eq? '- (cadr tests))) (letrec ((fn (lambda (a z) (if (char>? a z) (gather-char-tests (cdddr tests)) (cons a (funcall fn (integer->char (+ 1 (char->integer a))) z)))))) (funcall fn (car tests) (caddr tests)))) ((char? (car tests)) (cons (car tests) (gather-char-tests (cdr tests)))) (else (error "Invalid selector in char-case: ~A~%" (car tests))))) (define-syntax (scan-list-of char-type) `(letrec ((test-next (lambda () (char-case *char* (,char-type (let ((c *char*)) (advance-char) (cons c (funcall test-next)))) (else '()))))) (let ((c *char*)) (advance-char) (cons c (funcall test-next))))) (define-syntax (string=/list? tok string) (let ((temp (gensym))) `(let ((,temp ,tok)) ,(expand-string=/list? temp (string->list string))))) (define (expand-string=/list? var chars) (if (null? chars) `(null? ,var) (let ((new-temp (gensym))) `(and (pair? ,var) (char=? (car ,var) ',(car chars)) (let ((,new-temp (cdr ,var))) ,(expand-string=/list? new-temp (cdr chars))))))) dispatch on the first character of the string and then processing the remaining characters string=/list . This would go a little chars assigned to a var . ( Yeah - I know - I should add a (define-syntax (parse-reserved var token-type . reserved-words) (let ((sorted-rws (sort-list reserved-words (function string<?)))) `(let ((thunk (lambda () (emit-token/string ',token-type ,var)))) (char-case (car ,var) ,@(expand-parse-reserved var (group-by-first-char (list (car sorted-rws)) (cdr sorted-rws))) (else (funcall thunk)))))) (define (group-by-first-char group rest) (cond ((null? rest) (list group)) ((char=? (string-ref (car group) 0) (string-ref (car rest) 0)) (group-by-first-char (append group (list (car rest))) (cdr rest))) (else (cons group (group-by-first-char (list (car rest)) (cdr rest)))))) (define (expand-parse-reserved var groups) (if (null? groups) '() `((,(string-ref (caar groups) 0) (cond ,@(expand-parse-reserved/group var (car groups)) (else (funcall thunk)))) ,@(expand-parse-reserved var (cdr groups))))) (define (expand-parse-reserved/group var group) (if (null? group) '() `(((string=/list? (cdr ,var) ,(substring (car group) 1 (string-length (car group)))) (emit-token ',(string->symbol (car group)))) ,@(expand-parse-reserved/group var (cdr group))))) (define *predefined-syntactic-catagories* '( (+ satisfies at-varsym/+?) (- satisfies at-varsym/-?) (tycon no-advance conid) (tyvar no-advance varid) (var no-advance varid satisfies at-varsym/paren?) (con no-advance conid satisfies at-consym/paren?) (name no-advance var con) (consym/paren no-advance satisfies at-consym/paren?) (varsym? no-advance varsym) (consym? no-advance consym) (varid? no-advance varid) (conid? no-advance conid) (op no-advance varsym consym \`) (varop no-advance varsym satisfies at-varid/quoted?) (conop no-advance consym satisfies at-conid/quoted?) (modid no-advance conid) (literal no-advance integer float char string) (numeric no-advance integer float) (k no-advance integer) (+k no-advance satisfies at-+k?) (-n no-advance satisfies at--n?) (apat-start no-advance varid conid literal _ \( \[ \~) (pat-start no-advance - apat-start) (atype-start no-advance tycon tyvar \( \[) (aexp-start no-advance varid conid \( \[ literal) )) ( sel1 . e1 ) ( sel2 . e2 ) ... [ ( else . en ) ] ) (define-syntax (token-case . alts) `(cond ,@(map (function gen-token-case-alt) alts))) (define (gen-token-case-alt alt) (let ((test (car alt)) (code (cdr alt))) (cond ((eq? test 'else) `(else ,@code)) ((symbol? test) (gen-token-case-alt-1 (expand-catagories (list test)) code)) (else (gen-token-case-alt-1 (expand-catagories test) code))))) (define (expand-catagories terms) (if (null? terms) terms (let ((a (assq (car terms) *predefined-syntactic-catagories*)) (r (expand-catagories (cdr terms)))) (if (null? a) (cons (car terms) r) (expand-catagories (append (cdr a) r)))))) (define (gen-token-case-alt-1 test code) `((or ,@(gen-token-test test)) ,@(if (memq 'no-advance test) '() '((advance-token))) ,@code)) (define (gen-token-test test) (cond ((null? test) '()) ((eq? (car test) 'no-advance) (gen-token-test (cdr test))) ((eq? (car test) 'unquote) (cons `(eq? *token* ,(cadr test)) (gen-token-test (cddr test)))) ((eq? (car test) 'satisfies) (cons (list (cadr test)) (gen-token-test (cddr test)))) (else (cons `(eq? *token* ',(car test)) (gen-token-test (cdr test)))))) (define-syntax (require-token tok error-handler) `(token-case (,tok '()) (else ,error-handler))) (define-syntax (save-parser-context . body) (let ((temp1 (gensym)) (temp2 (gensym))) `(let ((,temp1 (capture-current-line)) (,temp2 (begin ,@body))) (setf (ast-node-line-number ,temp2) ,temp1) ,temp2))) (define (capture-current-line) (make source-pointer (line *current-line*) (file *current-file*))) (define-syntax (push-decl-list decl place) `(setf ,place (nconc ,place (list ,decl))))
0189dbe85d2834412d8afb5d18096324d751d4d56d8ede5364e8f16cea823076
aryx/lfs
atom.ml
(** The classic atoms found in most logics (propositional logic, predicate logic, etc.). *) open Logic module type PARAM = sig val names : string -> bool (** The predicate for admissible names for atoms. *) end module Make (Param : PARAM) : Logic.T = struct include Default let props () = {(no_props "Atom") with df = isok; st' = isok; sg' = isok; po_entails = isok; cs_entails = isok; cp_entails = isok; cp'_entails = isok; cp_top = isok; cs_bot = isok; defst_conj = isok; cs_conj = isok; cp_conj = isok; cs_disj = isok; cp_disj = isok; reduced_right = isok; reduced_bot = isok; reduced_bot' = isok; } type t = Attr of string | Term of string let isvalue f = true let parse = parser | [<'Token.Term n when Param.names n & not (List.mem n Syntax.keywords)>] -> Term n | [<'Token.Ident a when Param.names a & not (List.mem a Syntax.keywords)>] -> Attr a let parse_compact = parser | [<'Token.String s>] -> let res = ref [] in let l = String.length s in for i = l - 1 downto 0 do match s.[i] with | 'a' .. 'z' -> res := Token.Ident (String.sub s i 1) :: !res | 'A' .. 'Z' -> res := Token.Term (String.sub s i 1) :: !res | ' ' | '\t' | '\n' -> res := Token.Term "_" :: !res | _ -> () done; !res let print = function | Attr a -> [Token.Ident a] | Term name -> [Token.Term name] let rec entails a b = a=b let conj a b = if a=b then a else raise Not_found let disj a b = if a=b then [a] else [a; b] let features a = LSet.singleton (true,a) let rec gen y d gs = if y=d & not (List.exists (fun x -> x = y) gs) then LSet.singleton y else LSet.empty () end
null
https://raw.githubusercontent.com/aryx/lfs/b931530c7132b77dfaf3c99d452dc044fce37589/logfun/src/atom.ml
ocaml
* The classic atoms found in most logics (propositional logic, predicate logic, etc.). * The predicate for admissible names for atoms.
open Logic module type PARAM = sig end module Make (Param : PARAM) : Logic.T = struct include Default let props () = {(no_props "Atom") with df = isok; st' = isok; sg' = isok; po_entails = isok; cs_entails = isok; cp_entails = isok; cp'_entails = isok; cp_top = isok; cs_bot = isok; defst_conj = isok; cs_conj = isok; cp_conj = isok; cs_disj = isok; cp_disj = isok; reduced_right = isok; reduced_bot = isok; reduced_bot' = isok; } type t = Attr of string | Term of string let isvalue f = true let parse = parser | [<'Token.Term n when Param.names n & not (List.mem n Syntax.keywords)>] -> Term n | [<'Token.Ident a when Param.names a & not (List.mem a Syntax.keywords)>] -> Attr a let parse_compact = parser | [<'Token.String s>] -> let res = ref [] in let l = String.length s in for i = l - 1 downto 0 do match s.[i] with | 'a' .. 'z' -> res := Token.Ident (String.sub s i 1) :: !res | 'A' .. 'Z' -> res := Token.Term (String.sub s i 1) :: !res | ' ' | '\t' | '\n' -> res := Token.Term "_" :: !res | _ -> () done; !res let print = function | Attr a -> [Token.Ident a] | Term name -> [Token.Term name] let rec entails a b = a=b let conj a b = if a=b then a else raise Not_found let disj a b = if a=b then [a] else [a; b] let features a = LSet.singleton (true,a) let rec gen y d gs = if y=d & not (List.exists (fun x -> x = y) gs) then LSet.singleton y else LSet.empty () end
4a19155e2d13d6855b4c1c17bfbb45966b2dfe3fc546ec6739eb37c54db16ab8
alaisi/postgres.async
project.clj
(defproject alaisi/postgres.async "0.9.0-SNAPSHOT" :description "Asynchronous PostgreSQL Clojure client" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :scm {:name "git" :url ""} :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/core.async "0.2.374"] [com.github.alaisi.pgasync/postgres-async-driver "0.9"] [cheshire "5.6.1" :scope "provided"]] :lein-release {:deploy-via :clojars} :global-vars {*warn-on-reflection* true} :target-path "target/%s" :profiles {:dev {:source-paths ["dev"] :dependencies [[org.clojure/tools.namespace "0.2.11"] [org.clojure/java.classpath "0.2.3"]]}})
null
https://raw.githubusercontent.com/alaisi/postgres.async/fd27ecc504f29c033da3cb12bd8e8a61539026b7/project.clj
clojure
(defproject alaisi/postgres.async "0.9.0-SNAPSHOT" :description "Asynchronous PostgreSQL Clojure client" :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :scm {:name "git" :url ""} :dependencies [[org.clojure/clojure "1.8.0"] [org.clojure/core.async "0.2.374"] [com.github.alaisi.pgasync/postgres-async-driver "0.9"] [cheshire "5.6.1" :scope "provided"]] :lein-release {:deploy-via :clojars} :global-vars {*warn-on-reflection* true} :target-path "target/%s" :profiles {:dev {:source-paths ["dev"] :dependencies [[org.clojure/tools.namespace "0.2.11"] [org.clojure/java.classpath "0.2.3"]]}})
d2f0282166a1661475c4d5f81bdc10eeedd2429d5b43224e98cd0f2312306c91
igrishaev/remus
project.clj
(defproject remus "0.2.5-SNAPSHOT" :description "Attentive RSS/Atom feed parser" :deploy-repositories {"releases" {:url "" :creds :gpg}} :release-tasks [["vcs" "assert-committed"] ["test"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag" "--no-sign"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]] :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[com.rometools/rome "1.18.0"] [clj-http "3.12.3"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.1"] [log4j/log4j "1.2.17"]] :global-vars {*warn-on-reflection* true *assert* true}}})
null
https://raw.githubusercontent.com/igrishaev/remus/97807daf3c05f247915d728e3509fe4588fee145/project.clj
clojure
(defproject remus "0.2.5-SNAPSHOT" :description "Attentive RSS/Atom feed parser" :deploy-repositories {"releases" {:url "" :creds :gpg}} :release-tasks [["vcs" "assert-committed"] ["test"] ["change" "version" "leiningen.release/bump-version" "release"] ["vcs" "commit"] ["vcs" "tag" "--no-sign"] ["deploy"] ["change" "version" "leiningen.release/bump-version"] ["vcs" "commit"] ["vcs" "push"]] :url "" :license {:name "Eclipse Public License" :url "-v10.html"} :dependencies [[com.rometools/rome "1.18.0"] [clj-http "3.12.3"]] :profiles {:dev {:dependencies [[org.clojure/clojure "1.10.1"] [log4j/log4j "1.2.17"]] :global-vars {*warn-on-reflection* true *assert* true}}})
f379412cc1da0e1ea24a06fff230fcc69631e9a6ecd13264f728b2a49ffd0386
8thlight/hyperion
project.clj
(defproject hyperion/hyperion-sqlite "3.7.1" :description "SQLite Datastore for Hyperion" :dependencies [[org.clojure/clojure "1.5.1"] [hyperion/hyperion-api "3.7.1"] [hyperion/hyperion-sql "3.7.1"] [org.xerial/sqlite-jdbc "3.7.2"] [chee "1.1.0"]] :profiles {:dev {:dependencies [[speclj "2.7.5"]]}} :test-paths ["spec/"] :plugins [[speclj "2.7.5"]])
null
https://raw.githubusercontent.com/8thlight/hyperion/b1b8f60a5ef013da854e98319220b97920727865/sqlite/project.clj
clojure
(defproject hyperion/hyperion-sqlite "3.7.1" :description "SQLite Datastore for Hyperion" :dependencies [[org.clojure/clojure "1.5.1"] [hyperion/hyperion-api "3.7.1"] [hyperion/hyperion-sql "3.7.1"] [org.xerial/sqlite-jdbc "3.7.2"] [chee "1.1.0"]] :profiles {:dev {:dependencies [[speclj "2.7.5"]]}} :test-paths ["spec/"] :plugins [[speclj "2.7.5"]])
b244456a6832cd7a94da1f8cbe4ea142bfa14fb3c4c2681f1061884b85a0fffa
JHU-PL-Lab/jaylang
Fibonacci00.ml
let rec bot _ = bot () let fail _ = assert false let rec fib_without_checking_1060 set_flag_fib_1052 s_fib_n_1049 n_1031 = let set_flag_fib_1052 = true in let s_fib_n_1049 = n_1031 in if n_1031 < 2 then 1 else fib_without_checking_1060 set_flag_fib_1052 s_fib_n_1049 (n_1031 - 1) + fib_without_checking_1060 set_flag_fib_1052 s_fib_n_1049 (n_1031 - 2) let rec fib_1030 prev_set_flag_fib_1051 s_prev_fib_n_1050 n_1031 = let u =if prev_set_flag_fib_1051 then let u_1078 = fail () in bot() else () in fib_without_checking_1060 prev_set_flag_fib_1051 s_prev_fib_n_1050 n_1031 let main_1032 r = let set_flag_fib_1052 = false in let s_fib_n_1049 = 0 in fib_1030 set_flag_fib_1052 s_fib_n_1049 r
null
https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/484b3876986a515fb57b11768a1b3b50418cde0c/benchmark/cases/mochi_origin/termination/Fibonacci00.ml
ocaml
let rec bot _ = bot () let fail _ = assert false let rec fib_without_checking_1060 set_flag_fib_1052 s_fib_n_1049 n_1031 = let set_flag_fib_1052 = true in let s_fib_n_1049 = n_1031 in if n_1031 < 2 then 1 else fib_without_checking_1060 set_flag_fib_1052 s_fib_n_1049 (n_1031 - 1) + fib_without_checking_1060 set_flag_fib_1052 s_fib_n_1049 (n_1031 - 2) let rec fib_1030 prev_set_flag_fib_1051 s_prev_fib_n_1050 n_1031 = let u =if prev_set_flag_fib_1051 then let u_1078 = fail () in bot() else () in fib_without_checking_1060 prev_set_flag_fib_1051 s_prev_fib_n_1050 n_1031 let main_1032 r = let set_flag_fib_1052 = false in let s_fib_n_1049 = 0 in fib_1030 set_flag_fib_1052 s_fib_n_1049 r
d8ca0cb47e5b01e16eb1d64e1f0a796a5a8f8d81f65c4602adf77180b08f5ffb
Octachron/olivine
funptr.ml
module Aliases= struct module L = Info.Linguistic module Ty = Lib.Ty module C = Common end open Aliases open Item open Utils let mkty ctx args ret = let ret = Type.converter ctx ~degraded:true ret in let fn = C.listr (fun l r -> [%expr[%e l] @-> [%e r] ]) (Type.converter ctx ~degraded:true) args [%expr returning [%e ret]] in [%expr let open Ctypes in [%e fn] ] let expand = function | [] -> [Ty.Name (L.simple ["void"])] | l -> l let view = L.(~:"ctype") let make ctx (_tyname, (fn:Ty.fn)) = let ty = pty view and tyo = pty L.(view//"opt")in match List.map snd @@ Ty.flatten_fn_fields fn.args with | [] -> let typ = [%type: unit Ctypes.ptr] in decltype ~manifest:typ "t" ^:: item [[%stri let [%p ty] = Ctypes.(ptr void)]] [val' view [%type: [%t typ] Ctypes.typ] ] | args -> let t = Type.fn2 ~decay_array:All ~mono:true ctx fn in decltype ~manifest:t "t" ^:: item [[%stri let [%p ty], [%p tyo] = let ty = [%e mkty ctx args fn.return] in Foreign.funptr ty, Foreign.funptr_opt ty ]] [ val' view [%type: t Ctypes.typ]; val' L.(view//"opt") [%type: t option Ctypes.typ]; ]
null
https://raw.githubusercontent.com/Octachron/olivine/e93df595ad1e8bad5a8af689bac7d150753ab9fb/aster/funptr.ml
ocaml
module Aliases= struct module L = Info.Linguistic module Ty = Lib.Ty module C = Common end open Aliases open Item open Utils let mkty ctx args ret = let ret = Type.converter ctx ~degraded:true ret in let fn = C.listr (fun l r -> [%expr[%e l] @-> [%e r] ]) (Type.converter ctx ~degraded:true) args [%expr returning [%e ret]] in [%expr let open Ctypes in [%e fn] ] let expand = function | [] -> [Ty.Name (L.simple ["void"])] | l -> l let view = L.(~:"ctype") let make ctx (_tyname, (fn:Ty.fn)) = let ty = pty view and tyo = pty L.(view//"opt")in match List.map snd @@ Ty.flatten_fn_fields fn.args with | [] -> let typ = [%type: unit Ctypes.ptr] in decltype ~manifest:typ "t" ^:: item [[%stri let [%p ty] = Ctypes.(ptr void)]] [val' view [%type: [%t typ] Ctypes.typ] ] | args -> let t = Type.fn2 ~decay_array:All ~mono:true ctx fn in decltype ~manifest:t "t" ^:: item [[%stri let [%p ty], [%p tyo] = let ty = [%e mkty ctx args fn.return] in Foreign.funptr ty, Foreign.funptr_opt ty ]] [ val' view [%type: t Ctypes.typ]; val' L.(view//"opt") [%type: t option Ctypes.typ]; ]
237779bdb56daf654a451f2a33a6636d08e769da1ef76e1895ebca37289f615f
codedownio/aeson-typescript
LegalNameSpec.hs
module LegalNameSpec where import Data.Aeson.TypeScript.LegalName import Data.List.NonEmpty (NonEmpty (..)) import Test.Hspec tests :: Spec tests = describe "Data.Aeson.TypeScript.LegalName" $ do describe "checkIllegalNameChars" $ do describe "legal Haskell names" $ do it "allows an uppercase letter" $ do checkIllegalNameChars ('A' :| []) `shouldBe` Nothing it "allows an underscore" $ do checkIllegalNameChars ('_' :| "asdf") `shouldBe` Nothing it "reports that ' is illegal" $ do checkIllegalNameChars ('F' :| "oo'") `shouldBe` Just ('\'' :| []) describe "illegal Haskell names" $ do it "allows a $" $ do checkIllegalNameChars ('$' :| "asdf") `shouldBe` Nothing
null
https://raw.githubusercontent.com/codedownio/aeson-typescript/d6a3addf220d51dcc1199744869beda2b8bb2aa1/test/LegalNameSpec.hs
haskell
module LegalNameSpec where import Data.Aeson.TypeScript.LegalName import Data.List.NonEmpty (NonEmpty (..)) import Test.Hspec tests :: Spec tests = describe "Data.Aeson.TypeScript.LegalName" $ do describe "checkIllegalNameChars" $ do describe "legal Haskell names" $ do it "allows an uppercase letter" $ do checkIllegalNameChars ('A' :| []) `shouldBe` Nothing it "allows an underscore" $ do checkIllegalNameChars ('_' :| "asdf") `shouldBe` Nothing it "reports that ' is illegal" $ do checkIllegalNameChars ('F' :| "oo'") `shouldBe` Just ('\'' :| []) describe "illegal Haskell names" $ do it "allows a $" $ do checkIllegalNameChars ('$' :| "asdf") `shouldBe` Nothing
f880c5ba4565b3dbdd1bcc13e7c6ae9d9af87310936643c3bc69e87b3b367744
emqx/hocon
hocon_schema_html_tests.erl
%%-------------------------------------------------------------------- Copyright ( c ) 2021 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %%-------------------------------------------------------------------- -module(hocon_schema_html_tests). -include_lib("eunit/include/eunit.hrl"). no_crash_test_() -> [ {"demo_schema", gen(demo_schema, "./test/data/demo_schema_doc.conf")}, {"demo_schema2", gen(demo_schema2)}, {"emqx_schema", gen(emqx_schema)}, {"arbitrary1", gen(#{ namespace => dummy, roots => [foo], fields => #{foo => [{"f1", hoconsc:enum([bar])}]} })}, {"arbitrary2", gen(#{ namespace => dummy, roots => [foo], fields => #{foo => [{"f1", hoconsc:mk(hoconsc:ref(emqx_schema, "zone"))}]} })} ]. gen(Schema) -> fun() -> hocon_schema_html:gen(Schema, "test", undefined) end. gen(Schema, DescFile) -> fun() -> hocon_schema_html:gen(Schema, "test", DescFile) end.
null
https://raw.githubusercontent.com/emqx/hocon/04206f910caae871568dd1035b05003d1dcce555/test/hocon_schema_html_tests.erl
erlang
-------------------------------------------------------------------- you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------
Copyright ( c ) 2021 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(hocon_schema_html_tests). -include_lib("eunit/include/eunit.hrl"). no_crash_test_() -> [ {"demo_schema", gen(demo_schema, "./test/data/demo_schema_doc.conf")}, {"demo_schema2", gen(demo_schema2)}, {"emqx_schema", gen(emqx_schema)}, {"arbitrary1", gen(#{ namespace => dummy, roots => [foo], fields => #{foo => [{"f1", hoconsc:enum([bar])}]} })}, {"arbitrary2", gen(#{ namespace => dummy, roots => [foo], fields => #{foo => [{"f1", hoconsc:mk(hoconsc:ref(emqx_schema, "zone"))}]} })} ]. gen(Schema) -> fun() -> hocon_schema_html:gen(Schema, "test", undefined) end. gen(Schema, DescFile) -> fun() -> hocon_schema_html:gen(Schema, "test", DescFile) end.
45cb12a6c73798c95e8a4a167bd5817a1f149c3d798a7c078f4c85c9c9e46956
rtoy/cmucl
package.lisp
;;; -*- Log: code.log; Package: Lisp -*- ;;; ;;; ********************************************************************** This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . ;;; (ext:file-comment "$Header: src/code/package.lisp $") ;;; ;;; ********************************************************************** ;;; ;;; Package stuff and stuff like that. ;;; Re - Written by . Earlier version written by . Apropos & iteration macros courtesy of Skef Wholey . Defpackage by . With - Package - Iterator by . Defpackage and do - mumble - symbols macros re - written by . ;;; (in-package "LISP") (intl:textdomain "cmucl") (export '(package packagep *package* make-package in-package find-package package-name package-nicknames rename-package delete-package package-use-list package-used-by-list package-shadowing-symbols list-all-packages intern find-symbol unintern export unexport import shadowing-import shadow use-package unuse-package find-all-symbols do-symbols with-package-iterator do-external-symbols do-all-symbols apropos apropos-list defpackage)) (in-package "EXTENSIONS") (export '(*keyword-package* *lisp-package* *default-package-use-list* map-apropos package-children package-parent package-lock package-definition-lock without-package-locks unlock-all-packages)) (in-package "KERNEL") (export '(%in-package old-in-package %defpackage)) (in-package "LISP") #+relative-package-names (sys:register-lisp-feature :relative-package-names) (defvar *default-package-use-list* '("COMMON-LISP") "The list of packages to use by default of no :USE argument is supplied to MAKE-PACKAGE or other package creation forms.") ;;; INTERNAL conditions (define-condition simple-package-error (simple-condition package-error) ()) (defstruct (package (:constructor internal-make-package) (:predicate packagep) (:print-function %print-package) (:make-load-form-fun (lambda (package) (values `(package-or-lose ',(package-name package)) nil)))) "Standard structure for the description of a package. Consists of a list of all hash tables, the name of the package, the nicknames of the package, the use-list for the package, the used-by- list, hash- tables for the internal and external symbols, and a list of the shadowing symbols." (tables (list nil)) ; A list of all the hashtables for inherited symbols. ;; ;; The string name of the package. (%name nil :type (or simple-string null)) ;; ;; List of nickname strings. (%nicknames () :type list) ;; ;; List of packages we use. (%use-list () :type list) ;; ;; List of packages that use this package. (%used-by-list () :type list) ;; ;; Hashtables of internal & external symbols. (internal-symbols (required-argument) :type package-hashtable) (external-symbols (required-argument) :type package-hashtable) ;; ;; List of shadowing symbols. (%shadowing-symbols () :type list) ;; ;; Locks for this package. The PACKAGE-LOCK is a lock on the ;; structure of the package, and controls modifications to its list ;; of symbols and its export list. The PACKAGE-DEFINITION-LOCK ;; protects all symbols in the package from being redefined. These ;; are initially disabled, and are enabled by the function ;; PACKAGE-LOCKS-INIT during after-save-initializations. (lock nil :type boolean) (definition-lock nil :type boolean) ;; Documentation string for this package (doc-string nil :type (or simple-string null))) (defun %print-package (s stream d) (declare (ignore d) (stream stream)) (if (package-%name s) (cond (*print-escape* (multiple-value-bind (iu it) (internal-symbol-count s) (multiple-value-bind (eu et) (external-symbol-count s) (print-unreadable-object (s stream) (format stream (intl:gettext "The ~A package, ~D/~D internal, ~D/~D external") (package-%name s) iu it eu et))))) (t (print-unreadable-object (s stream) (format stream (intl:gettext "The ~A package") (package-%name s))))) (print-unreadable-object (s stream :identity t) (format stream (intl:gettext "deleted package"))))) ;;; Can get the name (NIL) of a deleted package. ;;; (defun package-name (x) (package-%name (if (packagep x) x (package-or-lose x)))) (macrolet ((frob (ext real) `(defun ,ext (x) (,real (package-or-lose x))))) (frob package-nicknames package-%nicknames) (frob package-use-list package-%use-list) (frob package-used-by-list package-%used-by-list) (frob package-shadowing-symbols package-%shadowing-symbols)) (defvar *package* () "The current package.") ;;; An equal hashtable from package names to packages. ;;; (defvar *package-names* (make-hash-table :test #'equal)) ;;; Lots of people want the keyword package and Lisp package without a lot ;;; of fuss, so we give them their own variables. ;;; (defvar *lisp-package*) (defvar *keyword-package*) (defvar *enable-package-locked-errors* nil) (define-condition package-locked-error (simple-package-error) () (:report (lambda (condition stream) (format stream (intl:gettext "~&~@<Attempt to modify the locked package ~A, by ~3i~:_~?~:>") (package-name (package-error-package condition)) (simple-condition-format-control condition) (simple-condition-format-arguments condition))))) (defun package-locks-init () (let ((package-names '("COMMON-LISP" "LISP" "PCL" "CLOS-MOP" "EVAL" "NEW-ASSEM" "DISASSEM" "LOOP" "ANSI-LOOP" "INSPECT" "C" "PROFILE" "WIRE" "BIGNUM" "VM" "FORMAT" "DFIXNUM" "PRETTY-PRINT" "C-CALL" "ALIEN" "ALIEN-INTERNALS" "UNIX" "CONDITIONS" "DEBUG" "DEBUG-INTERNALS" "SYSTEM" "KERNEL" "EXTENSIONS" #+mp "MULTIPROCESSING" "WALKER" "XREF" "STREAM" "INTL"))) (dolist (p package-names) (let ((p (find-package p))) (when p (setf (package-definition-lock p) t) (setf (package-lock p) t)))) (setf *enable-package-locked-errors* t) (push 'redefining-function ext:*setf-fdefinition-hook*)) (values)) (pushnew 'package-locks-init ext:*after-save-initializations*) (defun unlock-all-packages () (dolist (p (list-all-packages)) (setf (package-definition-lock p) nil) (setf (package-lock p) nil))) (defmacro without-package-locks (&body body) `(eval-when (:compile-toplevel :load-toplevel :execute) (let ((*enable-package-locked-errors* nil)) ;; Tell the compiler about disabled locks too. This is a ;; workaround for the case of defmacro of a symbol in a locked ;; package. (ext:compiler-let ((*enable-package-locked-errors* nil)) ,@body)))) ;; trap attempts to redefine a function in a locked package, and ;; signal a continuable error. (defun redefining-function (function replacement) (declare (ignore replacement)) (when *enable-package-locked-errors* (multiple-value-bind (valid block-name) (ext:valid-function-name-p function) (declare (ignore valid)) (let ((package (symbol-package block-name))) (when package (when (package-definition-lock package) (when (and (consp function) (member (first function) '(pcl::slot-accessor pcl::method pcl::fast-method pcl::effective-method pcl::ctor))) (return-from redefining-function nil)) (restart-case (error 'package-locked-error :package package :format-control (intl:gettext "redefining function ~A") :format-arguments (list function)) (continue () :report (lambda (stream) (write-string (intl:gettext "Ignore the lock and continue") stream))) (unlock-package () :report (lambda (stream) (write-string (intl:gettext "Disable package's definition-lock, then continue") stream)) (setf (ext:package-definition-lock package) nil)) (unlock-all () :report (lambda (stream) (write-string (intl:gettext "Disable all package locks, then continue") stream)) (unlock-all-packages))))))))) ;;; This magical variable is T during initialization so Use-Package's of packages ;;; that don't yet exist quietly win. Such packages are thrown onto the list ;;; *Deferred-Use-Packages* so that this can be fixed up later. (defvar *in-package-init* nil) (defvar *deferred-use-packages* nil) (defun stringify-name (name kind) (typecase name (string (string-to-nfc name)) (symbol (symbol-name name)) (base-char (let ((res (make-string 1))) (setf (schar res 0) name) res)) (t (error (intl:gettext "Bogus ~A name: ~S") kind name)))) (defun stringify-names (names kind) (mapcar #'(lambda (name) (stringify-name name kind)) names)) package - namify -- Internal ;;; ;;; Make a package name into a simple-string. ;;; (defun package-namify (n) (stringify-name n "package")) package - namestring -- Internal ;;; ;;; Take a package-or-string-or-symbol and return a package name. ;;; (defun package-namestring (thing) (if (packagep thing) (let ((name (package-%name thing))) (or name (error (intl:gettext "Can't do anything to a deleted package: ~S") thing))) (package-namify thing))) package - name - to - package -- Internal ;;; ;;; Given a package name, a simple-string, do a package name lookup. ;;; (defun package-name-to-package (name) (declare (simple-string name)) (values (gethash name *package-names*))) package - parent -- Internal . ;;; ;;; Because this function is called via the reader, we want it to be as ;;; fast as possible. ;;; #+relative-package-names (defun package-parent (package-specifier) "Given PACKAGE-SPECIFIER, a package, symbol or string, return the parent package. If there is not a parent, signal an error." (declare (optimize (speed 3))) (flet ((find-last-dot (name) (do* ((len (1- (length name))) (i len (1- i))) ((= i -1) nil) (declare (fixnum len i)) (when (char= #\. (schar name i)) (return i))))) (let* ((child (package-namestring package-specifier)) (dot-position (find-last-dot child))) (cond (dot-position (let ((parent (subseq child 0 dot-position))) (or (package-name-to-package parent) (error 'simple-package-error :name child :format-control (intl:gettext "The parent of ~a does not exist.") :format-arguments (list child))))) (t (error 'simple-package-error :name child :format-control (intl:gettext "There is no parent of ~a.") :format-arguments (list child))))))) package - children -- Internal . ;;; ;;; While this function is not called via the reader, we do want it to be ;;; fast. ;;; #+relative-package-names (defun package-children (package-specifier &key (recurse t)) "Given PACKAGE-SPECIFIER, a package, symbol or string, return all the packages which are in the hierarchy 'under' the given package. If :recurse is nil, then only return the immediate children of the package." (declare (optimize (speed 3))) (let ((res ()) (parent (package-namestring package-specifier))) (labels ((string-prefix-p (prefix string) (declare (simple-string prefix string)) ;; Return length of `prefix' if `string' starts with `prefix'. ;; We don't use `search' because it does much more than we need and this version is about 10x faster than calling ` search ' . (let ((prefix-len (length prefix)) (seq-len (length string))) (declare (type index prefix-len seq-len)) (when (>= prefix-len seq-len) (return-from string-prefix-p nil)) (do ((i 0 (1+ i))) ((= i prefix-len) prefix-len) (declare (type index i)) (unless (char= (schar prefix i) (schar string i)) (return nil))))) (test-package (package-name package) (declare (simple-string package-name) (type package package)) (let ((prefix (string-prefix-p (concatenate 'simple-string parent ".") package-name))) (cond (recurse (when prefix (pushnew package res))) (t (when (and prefix (not (find #\. package-name :start prefix))) (pushnew package res))))))) (maphash #'test-package *package-names*) res))) relative - package - name - to - package -- Internal ;;; ;;; Given a package name, a simple-string, do a relative package name lookup. ;;; It is intended that this function will be called from find-package. ;;; #+relative-package-names (defun relative-package-name-to-package (name) (declare (simple-string name) (optimize (speed 3))) (flet ((relative-to (package name) (declare (type package package) (simple-string name)) (if (string= "" name) package (let ((parent-name (package-%name package))) (unless parent-name (error (intl:gettext "Can't do anything to a deleted package: ~S") package)) (package-name-to-package (concatenate 'simple-string parent-name "." name))))) (find-non-dot (name) (do* ((len (length name)) (i 0 (1+ i))) ((= i len) nil) (declare (type index len i)) (when (char/= #\. (schar name i)) (return i))))) (when (and (plusp (length name)) (char= #\. (schar name 0))) (let* ((last-dot-position (or (find-non-dot name) (length name))) (n-dots last-dot-position) (name (subseq name last-dot-position))) (cond ((= 1 n-dots) ;; relative to current package (relative-to *package* name)) (t relative to our ( - n - dots 1)'th parent (let ((package *package*) (tmp nil)) (dotimes (i (1- n-dots)) (declare (fixnum i)) (setq tmp (package-parent package)) (unless tmp (error 'simple-package-error :name (string package) :format-control (intl:gettext "The parent of ~a does not exist.") :format-arguments (list package))) (setq package tmp)) (relative-to package name)))))))) ;;; find-package -- Public ;;; ;;; (defun find-package (name) "Find the package having the specified name." (if (packagep name) name (let ((name (package-namify name))) (or (package-name-to-package name) #+relative-package-names (relative-package-name-to-package name))))) package - or - lose -- Internal ;;; ;;; Take a package-or-string-or-symbol and return a package. ;;; (defun package-or-lose (thing) (cond ((packagep thing) (unless (package-%name thing) (error (intl:gettext "Can't do anything to a deleted package: ~S") thing)) thing) (t (let ((thing (package-namify thing))) (cond ((package-name-to-package thing)) (t ANSI spec 's type - error where this is called . But , ;; but the resulting message is somewhat unclear. May need a new condition type ? (with-simple-restart (continue (intl:gettext "Make this package.")) (error 'type-error :datum thing :expected-type 'package)) (make-package thing))))))) package - listify -- Internal ;;; ;;; Return a list of packages given a package-or-string-or-symbol or ;;; list thereof, or die trying. ;;; (defun package-listify (thing) (let ((res ())) (dolist (thing (if (listp thing) thing (list thing)) res) (push (package-or-lose thing) res)))) Package - Hashtables ;;; ;;; Packages are implemented using a special kind of hashtable. It is an open hashtable with a parallel 8 - bit I - vector of hash - codes . The ;;; primary purpose of the hash for each entry is to reduce paging by ;;; allowing collisions and misses to be detected without paging in the ;;; symbol and pname for an entry. If the hash for an entry doesn't ;;; match that for the symbol that we are looking for, then we can ;;; go on without touching the symbol, pname, or even hashtable vector. ;;; It turns out that, contrary to my expectations, paging is a very ;;; important consideration the design of the package representation. Using a similar scheme without the entry hash , the fasloader was spending more than half its time paging in INTERN . The hash code also indicates the status of an entry . If it zero , ;;; the entry is unused. If it is one, then it is deleted. ;;; Double-hashing is used for collision resolution. (deftype hash-vector () '(simple-array (unsigned-byte 8) (*))) (defstruct (package-hashtable (:constructor internal-make-package-hashtable ()) (:copier nil) (:print-function (lambda (table stream d) (declare (ignore d) (stream stream)) (format stream (intl:gettext "#<Package-Hashtable: Size = ~D, Free = ~D, Deleted = ~D>") (package-hashtable-size table) (package-hashtable-free table) (package-hashtable-deleted table))))) ;; ;; The g-vector of symbols. (table nil :type (or simple-vector null)) ;; ;; The i-vector of pname hash values. (hash nil :type (or hash-vector null)) ;; ;; The maximum number of entries allowed. (size 0 :type index) ;; ;; The entries that can be made before we have to rehash. (free 0 :type index) ;; ;; The number of deleted entries. (deleted 0 :type index)) ;;; The maximum density we allow in a package hashtable. ;;; (defparameter package-rehash-threshold 3/4) Entry - Hash -- Internal ;;; ;;; Compute a number from the sxhash of the pname and the length which must be between 2 and 255 . ;;; (defmacro entry-hash (length sxhash) `(the fixnum (+ (the fixnum (rem (the fixnum (logxor ,length ,sxhash (the fixnum (ash ,sxhash -8)) (the fixnum (ash ,sxhash -16)) (the fixnum (ash ,sxhash -19)))) 254)) 2))) Make - Package - Hashtable -- Internal ;;; ;;; Make a package hashtable having a prime number of entries at least as great as ( / size package - rehash - threshold ) . If Res is supplied , ;;; then it is destructively modified to produce the result. This is ;;; useful when changing the size, since there are many pointers to ;;; the hashtable. ;;; (defun make-package-hashtable (size &optional (res (internal-make-package-hashtable))) (do ((n (logior (truncate size package-rehash-threshold) 1) (+ n 2))) ((primep n) (setf (package-hashtable-table res) (make-array n)) (setf (package-hashtable-hash res) (make-array n :element-type '(unsigned-byte 8) :initial-element 0)) (let ((size (truncate (* n package-rehash-threshold)))) (setf (package-hashtable-size res) size) (setf (package-hashtable-free res) size)) (setf (package-hashtable-deleted res) 0) res) (declare (fixnum n)))) Internal - Symbol - Count , External - Symbols - Count -- Internal ;;; Return internal and external symbols . Used by Genesis and stuff . ;;; (flet ((stuff (table) (let ((size (the fixnum (- (the fixnum (package-hashtable-size table)) (the fixnum (package-hashtable-deleted table)))))) (declare (fixnum size)) (values (the fixnum (- size (the fixnum (package-hashtable-free table)))) size)))) (defun internal-symbol-count (package) (stuff (package-internal-symbols package))) (defun external-symbol-count (package) (stuff (package-external-symbols package)))) Add - Symbol -- Internal ;;; ;;; Add a symbol to a package hashtable. The symbol is assumed ;;; not to be present. ;;; (defun add-symbol (table symbol) (let* ((vec (package-hashtable-table table)) (hash (package-hashtable-hash table)) (len (length vec)) (sxhash (%sxhash-simple-string (symbol-name symbol))) (h2 (the fixnum (1+ (the fixnum (rem sxhash (the fixnum (- len 2)))))))) (declare (simple-vector vec) (type (simple-array (unsigned-byte 8)) hash) (fixnum len sxhash h2)) (cond ((zerop (the fixnum (package-hashtable-free table))) (make-package-hashtable (the fixnum (* (the fixnum (package-hashtable-size table)) 2)) table) (add-symbol table symbol) (dotimes (i len) (declare (fixnum i)) (when (> (the fixnum (aref hash i)) 1) (add-symbol table (svref vec i))))) (t (do ((i (rem sxhash len) (rem (+ i h2) len))) ((< (the fixnum (aref hash i)) 2) (if (zerop (the fixnum (aref hash i))) (decf (the fixnum (package-hashtable-free table))) (decf (the fixnum (package-hashtable-deleted table)))) (setf (svref vec i) symbol) (setf (aref hash i) (entry-hash (length (the simple-string (symbol-name symbol))) sxhash))) (declare (fixnum i))))))) With - Symbol -- Internal ;;; Find where the symbol named is stored in Table . Index - Var is bound to the index , or NIL if it is not present . is bound to the symbol . Length and are the length and sxhash of . Entry - Hash is the entry - hash of the string and length . ;;; (defmacro with-symbol ((index-var symbol-var table string length sxhash entry-hash) &body forms) (let ((vec (gensym)) (hash (gensym)) (len (gensym)) (h2 (gensym)) (name (gensym)) (name-len (gensym)) (ehash (gensym))) `(let* ((,vec (package-hashtable-table ,table)) (,hash (package-hashtable-hash ,table)) (,len (length ,vec)) (,h2 (1+ (the index (rem (the index ,sxhash) (the index (- ,len 2))))))) (declare (type (simple-array (unsigned-byte 8) (*)) ,hash) (simple-vector ,vec) (type index ,len ,h2)) (prog ((,index-var (rem (the index ,sxhash) ,len)) ,symbol-var ,ehash) (declare (type (or index null) ,index-var)) LOOP (setq ,ehash (aref ,hash ,index-var)) (cond ((eql ,ehash ,entry-hash) (setq ,symbol-var (svref ,vec ,index-var)) (let* ((,name (symbol-name ,symbol-var)) (,name-len (length ,name))) (declare (simple-string ,name) (type index ,name-len)) (when (and (= ,name-len ,length) (string= ,string ,name :end1 ,length :end2 ,name-len)) (go DOIT)))) ((zerop ,ehash) (setq ,index-var nil) (go DOIT))) (setq ,index-var (+ ,index-var ,h2)) (when (>= ,index-var ,len) (setq ,index-var (- ,index-var ,len))) (go LOOP) DOIT (return (progn ,@forms)))))) Nuke - Symbol -- Internal ;;; Delete the entry for String in Table . The entry must exist . ;;; (defun nuke-symbol (table string) (declare (simple-string string)) (let* ((length (length string)) (hash (%sxhash-simple-string string)) (ehash (entry-hash length hash))) (declare (type index length hash)) (with-symbol (index symbol table string length hash ehash) (setf (aref (package-hashtable-hash table) index) 1) (setf (aref (package-hashtable-table table) index) nil) (incf (package-hashtable-deleted table))))) ;;;; Iteration macros. (defmacro do-symbols ((var &optional (package '*package*) result-form) &parse-body (body decls)) "DO-SYMBOLS (VAR [PACKAGE [RESULT-FORM]]) {DECLARATION}* {TAG | FORM}* Executes the FORMs at least once for each symbol accessible in the given PACKAGE with VAR bound to the current symbol." (let ((flet-name (gensym "DO-SYMBOLS-"))) `(block nil (flet ((,flet-name (,var) ,@decls (tagbody ,@body))) (let* ((package (package-or-lose ,package)) (shadows (package-%shadowing-symbols package))) (flet ((iterate-over-hash-table (table ignore) (let ((hash-vec (package-hashtable-hash table)) (sym-vec (package-hashtable-table table))) (declare (type (simple-array (unsigned-byte 8) (*)) hash-vec) (type simple-vector sym-vec)) (dotimes (i (length sym-vec)) (when (>= (aref hash-vec i) 2) (let ((sym (aref sym-vec i))) (declare (inline member)) (unless (member sym ignore :test #'string=) (,flet-name sym)))))))) (iterate-over-hash-table (package-internal-symbols package) nil) (iterate-over-hash-table (package-external-symbols package) nil) (dolist (use (package-%use-list package)) (iterate-over-hash-table (package-external-symbols use) shadows))))) (let ((,var nil)) (declare (ignorable ,var)) ,@decls ,result-form)))) (defmacro do-external-symbols ((var &optional (package '*package*) result-form) &parse-body (body decls)) "DO-EXTERNAL-SYMBOLS (VAR [PACKAGE [RESULT-FORM]]) {DECL}* {TAG | FORM}* Executes the FORMs once for each external symbol in the given PACKAGE with VAR bound to the current symbol." (let ((flet-name (gensym "DO-SYMBOLS-"))) `(block nil (flet ((,flet-name (,var) ,@decls (tagbody ,@body))) (let* ((package (package-or-lose ,package)) (table (package-external-symbols package)) (hash-vec (package-hashtable-hash table)) (sym-vec (package-hashtable-table table))) (declare (type (simple-array (unsigned-byte 8) (*)) hash-vec) (type simple-vector sym-vec)) (dotimes (i (length sym-vec)) (when (>= (aref hash-vec i) 2) (,flet-name (aref sym-vec i)))))) (let ((,var nil)) (declare (ignorable ,var)) ,@decls ,result-form)))) (defmacro do-all-symbols ((var &optional result-form) &parse-body (body decls)) "DO-ALL-SYMBOLS (VAR [RESULT-FORM]) {DECLARATION}* {TAG | FORM}* Executes the FORMs once for each symbol in every package with VAR bound to the current symbol." (let ((flet-name (gensym "DO-SYMBOLS-"))) `(block nil (flet ((,flet-name (,var) ,@decls (tagbody ,@body))) (dolist (package (list-all-packages)) (flet ((iterate-over-hash-table (table) (let ((hash-vec (package-hashtable-hash table)) (sym-vec (package-hashtable-table table))) (declare (type (simple-array (unsigned-byte 8) (*)) hash-vec) (type simple-vector sym-vec)) (dotimes (i (length sym-vec)) (when (>= (aref hash-vec i) 2) (,flet-name (aref sym-vec i))))))) (iterate-over-hash-table (package-internal-symbols package)) (iterate-over-hash-table (package-external-symbols package))))) (let ((,var nil)) (declare (ignorable ,var)) ,@decls ,result-form)))) ;;;; WITH-PACKAGE-ITERATOR (defmacro with-package-iterator ((mname package-list &rest symbol-types) &body body) "Within the lexical scope of the body forms, MNAME is defined via macrolet such that successive invocations of (mname) will return the symbols, one by one, from the packages in PACKAGE-LIST. SYMBOL-TYPES may be any of :inherited :external :internal." (let* ((packages (gensym)) (these-packages (gensym)) (ordered-types (let ((res nil)) (dolist (kind '(:inherited :external :internal) res) (when (member kind symbol-types) (push kind res))))) ; Order symbol-types. (counter (gensym)) (kind (gensym)) (hash-vector (gensym)) (vector (gensym)) (package-use-list (gensym)) (init-macro (gensym)) (end-test-macro (gensym)) (real-symbol-p (gensym)) (inherited-symbol-p (gensym)) (BLOCK (gensym))) `(let* ((,these-packages ,package-list) (,packages `,(mapcar #'(lambda (package) (if (packagep package) package (or (find-package package) (error 'simple-package-error :name (string package) :format-control (intl:gettext "~@<~S does not name a package ~:>") :format-arguments (list package))))) (if (consp ,these-packages) ,these-packages (list ,these-packages)))) (,counter nil) (,kind (car ,packages)) (,hash-vector nil) (,vector nil) (,package-use-list nil)) ,(if (member :inherited ordered-types) `(setf ,package-use-list (package-%use-list (car ,packages))) `(declare (ignore ,package-use-list))) (macrolet ((,init-macro (next-kind) (let ((symbols (gensym))) `(progn (setf ,',kind ,next-kind) (setf ,',counter nil) ,(case next-kind (:internal `(let ((,symbols (package-internal-symbols (car ,',packages)))) (when ,symbols (setf ,',vector (package-hashtable-table ,symbols)) (setf ,',hash-vector (package-hashtable-hash ,symbols))))) (:external `(let ((,symbols (package-external-symbols (car ,',packages)))) (when ,symbols (setf ,',vector (package-hashtable-table ,symbols)) (setf ,',hash-vector (package-hashtable-hash ,symbols))))) (:inherited `(let ((,symbols (and ,',package-use-list (package-external-symbols (car ,',package-use-list))))) (when ,symbols (setf ,',vector (package-hashtable-table ,symbols)) (setf ,',hash-vector (package-hashtable-hash ,symbols))))))))) (,end-test-macro (this-kind) `,(let ((next-kind (cadr (member this-kind ',ordered-types)))) (if next-kind `(,',init-macro ,next-kind) `(if (endp (setf ,',packages (cdr ,',packages))) (return-from ,',BLOCK) (,',init-macro ,(car ',ordered-types))))))) (when ,packages ,(when (null symbol-types) (simple-program-error (intl:gettext "Must supply at least one of :internal, ~ :external, or :inherited."))) ,(dolist (symbol symbol-types) (unless (member symbol '(:internal :external :inherited)) (simple-program-error (intl:gettext "~S is not one of :internal, :external, ~ or :inherited.") symbol))) (,init-macro ,(car ordered-types)) (flet ((,real-symbol-p (number) (> number 1))) (macrolet ((,mname () `(block ,',BLOCK (loop (case ,',kind ,@(when (member :internal ',ordered-types) `((:internal (setf ,',counter (position-if #',',real-symbol-p ,',hash-vector :start (if ,',counter (1+ ,',counter) 0))) (if ,',counter (return-from ,',BLOCK (values t (svref ,',vector ,',counter) ,',kind (car ,',packages))) (,',end-test-macro :internal))))) ,@(when (member :external ',ordered-types) `((:external (setf ,',counter (position-if #',',real-symbol-p ,',hash-vector :start (if ,',counter (1+ ,',counter) 0))) (if ,',counter (return-from ,',BLOCK (values t (svref ,',vector ,',counter) ,',kind (car ,',packages))) (,',end-test-macro :external))))) ,@(when (member :inherited ',ordered-types) `((:inherited (flet ((,',inherited-symbol-p (number) (when (,',real-symbol-p number) (let* ((p (position number ,',hash-vector :start (if ,',counter (1+ ,',counter) 0))) (s (svref ,',vector p))) (eql (nth-value 1 (find-symbol (symbol-name s) (car ,',packages))) :inherited))))) (setf ,',counter (position-if #',',inherited-symbol-p ,',hash-vector :start (if ,',counter (1+ ,',counter) 0)))) (cond (,',counter (return-from ,',BLOCK (values t (svref ,',vector ,',counter) ,',kind (car ,',packages)) )) (t (setf ,',package-use-list (cdr ,',package-use-list)) (cond ((endp ,',package-use-list) (setf ,',packages (cdr ,',packages)) (when (endp ,',packages) (return-from ,',BLOCK)) (setf ,',package-use-list (package-%use-list (car ,',packages))) (,',init-macro ,(car ',ordered-types))) (t (,',init-macro :inherited) (setf ,',counter nil))))))))))))) ,@body))))))) ;;;; DEFPACKAGE: (defmacro defpackage (package &rest options) "Defines a new package called PACKAGE. Each of OPTIONS should be one of the following: (:NICKNAMES {package-name}*) (:SIZE <integer>) (:SHADOW {symbol-name}*) (:SHADOWING-IMPORT-FROM <package-name> {symbol-name}*) (:USE {package-name}*) (:IMPORT-FROM <package-name> {symbol-name}*) (:INTERN {symbol-name}*) (:EXPORT {symbol-name}*) (:DOCUMENTATION doc-string) All options except :SIZE and :DOCUMENTATION can be used multiple times." (let ((nicknames nil) (size nil) (shadows nil) (shadowing-imports nil) (use nil) (use-p nil) (imports nil) (interns nil) (exports nil) (doc nil)) (dolist (option options) (unless (consp option) (simple-program-error (intl:gettext "Bogus DEFPACKAGE option: ~S") option)) (case (car option) (:nicknames (setf nicknames (stringify-names (cdr option) "package"))) (:size (cond (size (simple-program-error (intl:gettext "Can't specify :SIZE twice."))) ((and (consp (cdr option)) (typep (second option) 'unsigned-byte)) (setf size (second option))) (t (simple-program-error (intl:gettext "Bogus :SIZE, must be a positive integer: ~S") (second option))))) (:shadow (let ((new (stringify-names (cdr option) "symbol"))) (setf shadows (append shadows new)))) (:shadowing-import-from (let ((package-name (stringify-name (second option) "package")) (names (stringify-names (cddr option) "symbol"))) (let ((assoc (assoc package-name shadowing-imports :test #'string=))) (if assoc (setf (cdr assoc) (append (cdr assoc) names)) (setf shadowing-imports (acons package-name names shadowing-imports)))))) (:use (let ((new (stringify-names (cdr option) "package"))) (setf use (delete-duplicates (nconc use new) :test #'string=)) (setf use-p t))) (:import-from (let ((package-name (stringify-name (second option) "package")) (names (stringify-names (cddr option) "symbol"))) (let ((assoc (assoc package-name imports :test #'string=))) (if assoc (setf (cdr assoc) (append (cdr assoc) names)) (setf imports (acons package-name names imports)))))) (:intern (let ((new (stringify-names (cdr option) "symbol"))) (setf interns (append interns new)))) (:export (let ((new (stringify-names (cdr option) "symbol"))) (setf exports (append exports new)))) (:documentation (when doc (simple-program-error (intl:gettext "Can't specify :DOCUMENTATION twice."))) (setf doc (coerce (second option) 'simple-string))) (t (simple-program-error (intl:gettext "Bogus DEFPACKAGE option: ~S") option)))) (check-disjoint `(:intern ,@interns) `(:export ,@exports)) (check-disjoint `(:intern ,@interns) `(:import-from ,@(apply #'append (mapcar #'rest imports))) `(:shadow ,@shadows) `(:shadowing-import-from ,@(apply #'append (mapcar #'rest shadowing-imports)))) `(eval-when (compile load eval) (%defpackage ,(stringify-name package "package") ',nicknames ',size ',shadows ',shadowing-imports ',(if use-p use :default) ',imports ',interns ',exports ',doc)))) (defun check-disjoint (&rest args) ;; Check whether all given arguments specify disjoint sets of symbols. ;; Each argument is of the form (:key . set). (loop for (current-arg . rest-args) on args do (loop with (key1 . set1) = current-arg for (key2 . set2) in rest-args for common = (delete-duplicates (intersection set1 set2 :test #'string=)) unless (null common) do (simple-program-error (intl:gettext "Parameters ~S and ~S must be disjoint ~ but have common elements ~% ~S") key1 key2 common)))) (defun %defpackage (name nicknames size shadows shadowing-imports use imports interns exports doc-string) (declare (type simple-base-string name) (type list nicknames shadows shadowing-imports imports interns exports) (type (or list (member :default)) use) (type (or simple-base-string null) doc-string)) (let ((package (or (find-package name) (progn (when (eq use :default) (setf use *default-package-use-list*)) (make-package name :use nil :internal-symbols (or size 10) :external-symbols (length exports)))))) (unless (string= (the string (package-name package)) name) (error 'simple-package-error :package name :format-control (intl:gettext "~A is a nick-name for the package ~A") :format-arguments (list name (package-name name)))) (enter-new-nicknames package nicknames) Shadows and Shadowing - imports . (let ((old-shadows (package-%shadowing-symbols package))) (shadow shadows package) (dolist (sym-name shadows) (setf old-shadows (remove (find-symbol sym-name package) old-shadows))) (dolist (simports-from shadowing-imports) (let ((other-package (package-or-lose (car simports-from)))) (dolist (sym-name (cdr simports-from)) (let ((sym (find-or-make-symbol sym-name other-package))) (shadowing-import sym package) (setf old-shadows (remove sym old-shadows)))))) (when old-shadows (warn (intl:gettext "~A also shadows the following symbols:~% ~S") name old-shadows))) ;; Use (unless (eq use :default) (let ((old-use-list (package-use-list package)) (new-use-list (mapcar #'package-or-lose use))) (use-package (set-difference new-use-list old-use-list) package) (let ((laterize (set-difference old-use-list new-use-list))) (when laterize (unuse-package laterize package) (warn (intl:gettext "~A previously used the following packages:~% ~S") name laterize))))) Import and Intern . (dolist (sym-name interns) (intern sym-name package)) (dolist (imports-from imports) (let ((other-package (package-or-lose (car imports-from)))) (dolist (sym-name (cdr imports-from)) (import (list (find-or-make-symbol sym-name other-package)) package)))) ;; Exports. (let ((old-exports nil) (exports (mapcar #'(lambda (sym-name) (intern sym-name package)) exports))) (do-external-symbols (sym package) (push sym old-exports)) (export exports package) (let ((diff (set-difference old-exports exports))) (when diff (warn (intl:gettext "~A also exports the following symbols:~% ~S") name diff)))) ;; Documentation (setf (package-doc-string package) doc-string) package)) (defun find-or-make-symbol (name package) (multiple-value-bind (symbol how) (find-symbol name package) (cond (how symbol) (t (with-simple-restart (continue "INTERN it.") (error 'simple-package-error :package package :format-control (intl:gettext "~A does not contain a symbol ~A") :format-arguments (list (package-name package) name))) (intern name package))))) Enter - New - Nicknames -- Internal ;;; Enter any new Nicknames for Package into * package - names * . ;;; If there is a conflict then give the user a chance to do ;;; something about it. ;;; (defun enter-new-nicknames (package nicknames) (check-type nicknames list) (dolist (n nicknames) (let* ((n (package-namify n)) (found (package-name-to-package n))) (cond ((not found) (setf (gethash n *package-names*) package) (push n (package-%nicknames package))) ((eq found package)) ((string= (the string (package-%name found)) n) (with-simple-restart (continue (intl:gettext "Ignore this nickname.")) (error 'simple-package-error :package package :format-control (intl:gettext "~S is a package name, so it cannot be a nickname for ~S.") :format-arguments (list n (package-%name package))))) (t (with-simple-restart (continue (intl:gettext "Redefine this nickname.")) (error 'simple-package-error :package package :format-control (intl:gettext "~S is already a nickname for ~S.") :format-arguments (list n (package-%name found)))) (setf (gethash n *package-names*) package) (push n (package-%nicknames package))))))) ;;; Make-Package -- Public ;;; ;;; Check for package name conflicts in name and nicknames, then ;;; make the package. Do a use-package for each thing in the use list ;;; so that checking for conflicting exports among used packages is done. ;;; (defun make-package (name &key (use *default-package-use-list*) nicknames (internal-symbols 10) (external-symbols 10)) "Makes a new package having the specified Name and Nicknames. The package will inherit all external symbols from each package in the use list. :Internal-Symbols and :External-Symbols are estimates for the number of internal and external symbols which will ultimately be present in the package." (when (find-package name) (cerror (intl:gettext "Leave existing package alone.") (intl:gettext "A package named ~S already exists") name)) (let* ((name (package-namify name)) (package (internal-make-package :%name name :internal-symbols (make-package-hashtable internal-symbols) :external-symbols (make-package-hashtable external-symbols)))) (if *in-package-init* (push (list use package) *deferred-use-packages*) (use-package use package)) (enter-new-nicknames package nicknames) (setf (gethash name *package-names*) package))) Old - In - Package -- Sorta Public . ;;; Like Make - Package , only different . Should go away someday . ;;; (defun old-in-package (name &rest keys &key nicknames use) "Sets *PACKAGE* to package with given NAME, creating the package if it does not exist. If the package already exists then it is modified to agree with the :USE and :NICKNAMES arguments. Any new nicknames are added without removing any old ones not specified. If any package in the :Use list is not currently used, then it is added to the use list." (let ((package (find-package name))) (cond (package (if *in-package-init* (push (list use package) *deferred-use-packages*) (use-package use package)) (enter-new-nicknames package nicknames) (setq *package* package)) (t (setq *package* (apply #'make-package name keys)))))) ;;; IN-PACKAGE -- public. ;;; (defmacro in-package (package &rest noise) (cond ((or noise (not (or (stringp package) (symbolp package)))) (warn (intl:gettext "Old-style IN-PACKAGE.")) `(old-in-package ,package ,@noise)) (t `(%in-package ',(stringify-name package "package"))))) ;;; (defun %in-package (name) (let ((package (find-package name))) (unless package (with-simple-restart (continue (intl:gettext "Make this package.")) (error 'simple-package-error :package name :format-control (intl:gettext "The package named ~S doesn't exist.") :format-arguments (list name))) (setq package (make-package name))) (setf *package* package))) ;;; Rename-Package -- Public ;;; ;;; Change the name if we can, blast any old nicknames and then ;;; add in any new ones. ;;; (defun rename-package (package new-name &optional (new-nicknames ())) "Replaces the name and nicknames of Package. The old name and all of the old nicknames of Package are eliminated and are replaced by New-Name and New-Nicknames." (let* ((package (package-or-lose package)) (new-name (string new-name)) (found (find-package new-name))) (unless (or (not found) (eq found package)) (error 'simple-package-error :package new-name :format-control (intl:gettext "A package named ~S already exists.") :format-arguments (list new-name))) (remhash (package-%name package) *package-names*) (dolist (n (package-%nicknames package)) (remhash n *package-names*)) (setf (package-%name package) new-name) (setf (gethash new-name *package-names*) package) (setf (package-%nicknames package) ()) (enter-new-nicknames package new-nicknames) package)) ;;; Delete-Package -- Public ;;; (defun delete-package (package-or-name) "Delete the PACKAGE-OR-NAME from the package system data structures." (let ((package (if (packagep package-or-name) package-or-name (find-package package-or-name)))) (cond ((not package) (with-simple-restart (continue (intl:gettext "Return NIL")) (error 'simple-package-error :package package-or-name :format-control (intl:gettext "No package of name ~S.") :format-arguments (list package-or-name))) nil) ((not (package-name package)) nil) (t (let ((use-list (package-used-by-list package))) (when use-list (with-simple-restart (continue (intl:gettext "Remove dependency in other packages.")) (error 'simple-package-error :package package :format-control "Package ~S is used by package(s):~% ~S" :format-arguments (list (package-name package) (mapcar #'package-name use-list)))) (dolist (p use-list) (unuse-package package p)))) (dolist (used (package-use-list package)) (unuse-package used package)) (do-symbols (sym package) (unintern sym package)) (remhash (package-name package) *package-names*) (dolist (nick (package-nicknames package)) (remhash nick *package-names*)) (setf (package-%name package) nil) t)))) ;;; List-All-Packages -- Public ;;; ;;; (defun list-all-packages () "Returns a list of all existing packages." (let ((res ())) (maphash #'(lambda (k v) (declare (ignore k)) (pushnew v res)) *package-names*) res)) Intern -- Public ;;; ;;; Simple-stringify the name and call intern*. ;;; (defun intern (name &optional package) "Returns a symbol having the specified name, creating it if necessary." (let ((name (string-to-nfc name)) (package (if package (package-or-lose package) *package*))) (declare (type simple-string name)) (intern* name (length name) package))) ;;; Find-Symbol -- Public ;;; ;;; Ditto. ;;; (defun find-symbol (name &optional package) "Returns the symbol NAME in PACKAGE. If such a symbol is found then the second value is :internal, :external or :inherited to indicate how the symbol is accessible. If no symbol is found then both values are NIL." (let ((name (string-to-nfc name))) (declare (simple-string name)) (find-symbol* name (length name) (if package (package-or-lose package) *package*)))) Intern * -- Internal ;;; ;;; If the symbol doesn't exist then create it, special-casing ;;; the keyword package. ;;; (defun intern* (name length package) (declare (simple-string name)) (multiple-value-bind (symbol where) (find-symbol* name length package) (if where (values symbol where) (progn #+(or) (when *enable-package-locked-errors* (when (ext:package-lock package) (restart-case (error 'package-locked-error :package package :format-control (intl:gettext "interning symbol ~A") :format-arguments (list (subseq name 0 length))) (continue () :report "Ignore the lock and continue") (unlock-package () :report "Unlock package, then continue" (setf (ext:package-lock package) nil)) (unlock-all () :report "Unlock all packages, then continue" (unlock-all-packages))))) (let ((symbol (make-symbol (subseq name 0 length)))) (%set-symbol-package symbol package) (cond ((eq package *keyword-package*) (add-symbol (package-external-symbols package) symbol) (%set-symbol-value symbol symbol)) (t (add-symbol (package-internal-symbols package) symbol))) (values symbol nil)))))) find - symbol * -- Internal ;;; ;;; Check internal and external symbols, then scan down the list ;;; of hashtables for inherited symbols. When an inherited symbol ;;; is found pull that table to the beginning of the list. ;;; (defun find-symbol* (string length package) (declare (simple-string string) (type index length)) (let* ((hash (%sxhash-simple-substring string length)) (ehash (entry-hash length hash))) (declare (type index hash ehash)) (with-symbol (found symbol (package-internal-symbols package) string length hash ehash) (when found (return-from find-symbol* (values symbol :internal)))) (with-symbol (found symbol (package-external-symbols package) string length hash ehash) (when found (return-from find-symbol* (values symbol :external)))) (let ((head (package-tables package))) (do ((prev head table) (table (cdr head) (cdr table))) ((null table) (values nil nil)) (with-symbol (found symbol (car table) string length hash ehash) (when found (unless (eq prev head) (shiftf (cdr prev) (cdr table) (cdr head) table)) (return-from find-symbol* (values symbol :inherited)))))))) find - external - symbol -- Internal ;;; ;;; Similar to find-symbol, but only looks for an external symbol. ;;; This is used for fast name-conflict checking in this file and symbol ;;; printing in the printer. ;;; (defun find-external-symbol (string package) (declare (simple-string string)) (let* ((length (length string)) (hash (%sxhash-simple-string string)) (ehash (entry-hash length hash))) (declare (type index length hash)) (with-symbol (found symbol (package-external-symbols package) string length hash ehash) (values symbol found)))) ;;; unintern -- Public ;;; ;;; If we are uninterning a shadowing symbol, then a name conflict can ;;; result, otherwise just nuke the symbol. ;;; (defun unintern (symbol &optional (package *package*)) "Makes SYMBOL no longer present in PACKAGE. If SYMBOL was present then T is returned, otherwise NIL. If PACKAGE is SYMBOL's home package, then it is made uninterned." (let* ((package (package-or-lose package)) (name (symbol-name symbol)) (shadowing-symbols (package-%shadowing-symbols package))) (declare (list shadowing-symbols) (simple-string name)) (when *enable-package-locked-errors* (when (ext:package-lock package) (restart-case (error 'package-locked-error :package package :format-control (intl:gettext "uninterning symbol ~A") :format-arguments (list name)) (continue () :report (lambda (stream) (write-string (intl:gettext "Ignore the lock and continue") stream))) (unlock-package () :report (lambda (stream) (write-string (intl:gettext "Disable package's lock then continue") stream)) (setf (ext:package-lock package) nil)) (unlock-all () :report (lambda (stream) (write-string (intl:gettext "Unlock all packages, then continue") stream)) (unlock-all-packages))))) ;; ;; If a name conflict is revealed, give use a chance to shadowing-import ;; one of the accessible symbols. (when (member symbol shadowing-symbols) (let ((cset ())) (dolist (p (package-%use-list package)) (multiple-value-bind (s w) (find-external-symbol name p) (when w (pushnew s cset)))) (when (cdr cset) (loop (cerror (intl:gettext "prompt for a symbol to shadowing-import.") 'simple-package-error :package package :format-control (intl:gettext "Uninterning symbol ~S causes name conflict among these symbols:~%~S") :format-arguments (list symbol cset)) (write-string (intl:gettext "Symbol to shadowing-import: ") *query-io*) (let ((sym (read *query-io*))) (cond ((not (symbolp sym)) (format *query-io* (intl:gettext "~S is not a symbol.") sym)) ((not (member sym cset)) (format *query-io* (intl:gettext "~S is not one of the conflicting symbols.") sym)) (t (shadowing-import sym package) (return-from unintern t))))))) (setf (package-%shadowing-symbols package) (remove symbol shadowing-symbols))) (multiple-value-bind (s w) (find-symbol name package) (cond ((not (eq symbol s)) nil) ((or (eq w :internal) (eq w :external)) (nuke-symbol (if (eq w :internal) (package-internal-symbols package) (package-external-symbols package)) name) (if (eq (symbol-package symbol) package) (%set-symbol-package symbol nil)) t) (t nil))))) Symbol - Listify -- Internal ;;; ;;; Take a symbol-or-list-of-symbols and return a list, checking types. ;;; (defun symbol-listify (thing) (cond ((listp thing) (dolist (s thing) (unless (symbolp s) (error (intl:gettext "~S is not a symbol.") s))) thing) ((symbolp thing) (list thing)) (t (error (intl:gettext "~S is neither a symbol nor a list of symbols.") thing)))) Moby - Unintern -- Internal ;;; ;;; Like Unintern, but if symbol is inherited chases down the ;;; package it is inherited from and uninterns it there. Used ;;; for name-conflict resolution. Shadowing symbols are not ;;; uninterned since they do not cause conflicts. ;;; (defun moby-unintern (symbol package) (unless (member symbol (package-%shadowing-symbols package)) (or (unintern symbol package) (let ((name (symbol-name symbol))) (multiple-value-bind (s w) (find-symbol name package) (declare (ignore s)) (when (eq w :inherited) (dolist (q (package-%use-list package)) (multiple-value-bind (u x) (find-external-symbol name q) (declare (ignore u)) (when x (unintern symbol q) (return t)))))))))) ;;; Export -- Public ;;; ;;; Do more stuff. ;;; (defun export (symbols &optional (package *package*)) "Exports SYMBOLS from PACKAGE, checking that no name conflicts result." (let ((package (package-or-lose package)) (syms ())) ;; ;; Punt any symbols that are already external. (dolist (sym (symbol-listify symbols)) (multiple-value-bind (s w) (find-external-symbol (symbol-name sym) package) (declare (ignore s)) (unless (or w (member sym syms)) (push sym syms)))) ;; ;; Find symbols and packages with conflicts. (let ((used-by (package-%used-by-list package)) (cpackages ()) (cset ())) (dolist (sym syms) (let ((name (symbol-name sym))) (dolist (p used-by) (multiple-value-bind (s w) (find-symbol name p) (when (and w (not (eq s sym)) (not (member s (package-%shadowing-symbols p)))) (pushnew sym cset) (pushnew p cpackages)))))) (when cset (restart-case (error 'simple-package-error :package package :format-control (intl:gettext "Exporting these symbols from the ~A package:~%~S~%~ results in name conflicts with these packages:~%~{~A ~}") :format-arguments (list (package-%name package) cset (mapcar #'package-%name cpackages))) (unintern-conflicting-symbols () :report (lambda (stream) (write-string (intl:gettext "Unintern conflicting symbols.") stream)) (dolist (p cpackages) (dolist (sym cset) (moby-unintern sym p)))) (skip-exporting-these-symbols () :report (lambda (stream) (write-string (intl:gettext "Skip exporting conflicting symbols.") stream)) (setq syms (nset-difference syms cset)))))) ;; ;; Check that all symbols are accessible. If not, ask to import them. (let ((missing ()) (imports ())) (dolist (sym syms) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (cond ((not (and w (eq s sym))) (push sym missing)) ((eq w :inherited) (push sym imports))))) (when missing (with-simple-restart (continue (intl:gettext "Import these symbols into the ~A package.") (package-%name package)) (error 'simple-package-error :package package :format-control (intl:gettext "These symbols are not accessible in the ~A package:~%~S") :format-arguments (list (package-%name package) missing))) (import missing package)) (import imports package)) ;; And now , three pages later , we export the suckers . (let ((internal (package-internal-symbols package)) (external (package-external-symbols package))) (dolist (sym syms) (nuke-symbol internal (symbol-name sym)) (add-symbol external sym))) t)) ;;; Unexport -- Public ;;; ;;; Check that all symbols are accessible, then move from external to ;;; internal. ;;; (defun unexport (symbols &optional (package *package*)) "Makes SYMBOLS no longer exported from PACKAGE." (let ((package (package-or-lose package)) (syms ())) (when *enable-package-locked-errors* (when (ext:package-lock package) (restart-case (error 'package-locked-error :package package :format-control (intl:gettext "unexporting symbols ~A") :format-arguments (list symbols)) (continue () :report (lambda (stream) (write-string (intl:gettext "Ignore the lock and continue") stream))) (unlock-package () :report (lambda (stream) (write-string (intl:gettext "Disable package's lock then continue") stream)) (setf (ext:package-lock package) nil)) (unlock-all () :report (lambda (stream) (write-string (intl:gettext "Unlock all packages, then continue") stream)) (unlock-all-packages))))) (dolist (sym (symbol-listify symbols)) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (cond ((or (not w) (not (eq s sym))) (error 'simple-package-error :package package :format-control (intl:gettext "~S is not accessible in the ~A package.") :format-arguments (list sym (package-%name package)))) ((eq w :external) (pushnew sym syms))))) (let ((internal (package-internal-symbols package)) (external (package-external-symbols package))) (dolist (sym syms) (add-symbol internal sym) (nuke-symbol external (symbol-name sym)))) t)) ;;; Import -- Public ;;; Check for name conflic caused by the import and let the user ;;; shadowing-import if there is. ;;; (defun import (symbols &optional (package *package*)) "Make SYMBOLS accessible as internal symbols in PACKAGE. If a symbol is already accessible then it has no effect. If a name conflict would result from the importation, then a correctable error is signalled." (let ((package (package-or-lose package)) (symbols (symbol-listify symbols)) (syms ()) (cset ())) (dolist (sym symbols) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (cond ((not w) (let ((found (member sym syms :test #'string=))) (if found (when (not (eq (car found) sym)) (push sym cset)) (push sym syms)))) ((not (eq s sym)) (push sym cset)) ((eq w :inherited) (push sym syms))))) (when cset (with-simple-restart (continue (intl:gettext "Import these symbols with Shadowing-Import.")) (error 'simple-package-error :package package :format-control (intl:gettext "Importing these symbols into the ~A package ~ causes a name conflict:~%~S") :format-arguments (list (package-%name package) cset)))) ;; ;; Add the new symbols to the internal hashtable. (let ((internal (package-internal-symbols package))) (dolist (sym syms) (add-symbol internal sym))) ;; If any of the symbols are uninterned , make them be owned by Package . (dolist (sym symbols) (unless (symbol-package sym) (%set-symbol-package sym package))) (shadowing-import cset package))) Shadowing - Import -- Public ;;; ;;; If a conflicting symbol is present, unintern it, otherwise just ;;; stick the symbol in. ;;; (defun shadowing-import (symbols &optional (package *package*)) "Import SYMBOLS into PACKAGE, disregarding any name conflict. If a symbol of the same name is present, then it is uninterned. The symbols are added to the Package-Shadowing-Symbols." (let* ((package (package-or-lose package)) (internal (package-internal-symbols package))) (dolist (sym (symbol-listify symbols)) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (unless (and w (not (eq w :inherited)) (eq s sym)) (when (or (eq w :internal) (eq w :external)) ;; ;; If it was shadowed, we don't want Unintern to flame out... (setf (package-%shadowing-symbols package) (remove s (the list (package-%shadowing-symbols package)))) (unintern s package)) (add-symbol internal sym)) (pushnew sym (package-%shadowing-symbols package))))) t) Shadow -- Public ;;; ;;; (defun shadow (symbols &optional (package *package*)) "Make an internal symbol in PACKAGE with the same name as each of the specified SYMBOLS, adding the new symbols to the Package-Shadowing-Symbols. If a symbol with the given name is already present in PACKAGE, then the existing symbol is placed in the shadowing symbols list if it is not already present." (let* ((package (package-or-lose package)) (internal (package-internal-symbols package))) (dolist (name (mapcar #'string (if (listp symbols) symbols (list symbols)))) (multiple-value-bind (s w) (find-symbol name package) (when (or (not w) (eq w :inherited)) (setq s (make-symbol name)) (%set-symbol-package s package) (add-symbol internal s)) (pushnew s (package-%shadowing-symbols package))))) t) ;;; Use-Package -- Public ;;; ;;; Do stuff to use a package, with all kinds of fun name-conflict ;;; checking. ;;; (defun use-package (packages-to-use &optional (package *package*)) "Add all the PACKAGES-TO-USE to the use list for PACKAGE so that the external symbols of the used packages are accessible as internal symbols in PACKAGE." (let ((packages (package-listify packages-to-use)) (package (package-or-lose package))) ;; ;; Loop over each package, use'ing one at a time... (dolist (pkg packages) (unless (member pkg (package-%use-list package)) (let ((cset ()) (shadowing-symbols (package-%shadowing-symbols package)) (use-list (package-%use-list package))) ;; ;; If the number of symbols already accessible is less than the ;; number to be inherited then it is faster to run the test the ;; other way. This is particularly valuable in the case of ;; a new package use'ing Lisp. (cond ((< (+ (internal-symbol-count package) (external-symbol-count package) (let ((res 0)) (dolist (p use-list res) (incf res (external-symbol-count p))))) (external-symbol-count pkg)) (do-symbols (sym package) (multiple-value-bind (s w) (find-external-symbol (symbol-name sym) pkg) (when (and w (not (eq s sym)) (not (member sym shadowing-symbols))) (push sym cset)))) (dolist (p use-list) (do-external-symbols (sym p) (multiple-value-bind (s w) (find-external-symbol (symbol-name sym) pkg) (when (and w (not (eq s sym)) (not (member (find-symbol (symbol-name sym) package) shadowing-symbols))) (push sym cset)))))) (t (do-external-symbols (sym pkg) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (when (and w (not (eq s sym)) (not (member s shadowing-symbols))) (push s cset)))))) (when cset (cerror (intl:gettext "Unintern the conflicting symbols in the ~2*~A package.") (intl:gettext "Use'ing package ~A results in name conflicts for these symbols:~%~S") (package-%name pkg) cset (package-%name package)) (dolist (s cset) (moby-unintern s package)))) (push pkg (package-%use-list package)) (push (package-external-symbols pkg) (cdr (package-tables package))) (push package (package-%used-by-list pkg))))) t) Unuse - Package -- Public ;;; ;;; (defun unuse-package (packages-to-unuse &optional (package *package*)) "Remove PACKAGES-TO-UNUSE from the use list for PACKAGE." (let ((package (package-or-lose package))) (dolist (p (package-listify packages-to-unuse)) (setf (package-%use-list package) (remove p (the list (package-%use-list package)))) (setf (package-tables package) (delete (package-external-symbols p) (the list (package-tables package)))) (setf (package-%used-by-list p) (remove package (the list (package-%used-by-list p))))) t)) ;;; Find-All-Symbols -- Public ;;; ;;; (defun find-all-symbols (string-or-symbol) "Return a list of all symbols in the system having the specified name." (let ((string (string string-or-symbol)) (res ())) (maphash #'(lambda (k v) (declare (ignore k)) (multiple-value-bind (s w) (find-symbol string v) (when w (pushnew s res)))) *package-names*) res)) Apropos and Apropos - List . (defun briefly-describe-symbol (symbol) (let ((prefix-length nil)) (flet ((print-symbol (&optional kind) (fresh-line) (if prefix-length (dotimes (i prefix-length) (write-char #\Space)) (let ((symbol-string (prin1-to-string symbol))) (write-string symbol-string) (setq prefix-length (length symbol-string)))) (when kind (write-string " [") (write-string kind) (write-string "] ")))) ;; Variable namespace (multiple-value-bind (kind recorded-p) (info variable kind symbol) (when (or (boundp symbol) recorded-p) (print-symbol (ecase kind (:special (intl:gettext "special variable")) (:constant (intl:gettext "constant")) (:global (intl:gettext "undefined variable")) (:macro (intl:gettext "symbol macro")) (:alien (intl:gettext "alien variable")))) (when (boundp symbol) (write-string (intl:gettext "value: ")) (let ((*print-length* (or ext:*describe-print-length* *print-length*)) (*print-level* (or ext:*describe-print-level* *print-level*))) (prin1 (symbol-value symbol)))))) ;; Function namespace (when (fboundp symbol) (cond ((macro-function symbol) (print-symbol (intl:gettext "macro")) (let ((arglist (kernel:%function-arglist (macro-function symbol)))) (when (stringp arglist) (write-string arglist)))) ((special-operator-p symbol) (print-symbol (intl:gettext "special operator")) (let ((arglist (kernel:%function-arglist (symbol-function symbol)))) (when (stringp arglist) (write-string arglist)))) (t (print-symbol (intl:gettext "function")) ;; could do better than this with (kernel:type-specifier ;; (info function type symbol)) when it's a byte-compiled function (let ((arglist (kernel:%function-arglist (symbol-function symbol)))) (when (stringp arglist) (write-string arglist)))))) ;; Class and Type Namespace(s) (cond ((kernel::find-class symbol nil) (print-symbol (intl:gettext "class"))) ((info type kind symbol) (print-symbol (intl:gettext "type")))) ;; Make sure we at least print the symbol itself if we don't know ;; anything else about it: (when (null prefix-length) (print-symbol))))) (defun apropos-search (symbol string) (declare (simple-string string)) (do* ((index 0 (1+ index)) (name (symbol-name symbol)) (length (length string)) (terminus (- (length name) length))) ((> index terminus) nil) (declare (simple-string name) (type index index length) (fixnum terminus)) (if (do ((jndex 0 (1+ jndex)) (kndex index (1+ kndex))) ((= jndex length) t) (declare (fixnum jndex kndex)) (let ((char (schar name kndex))) (unless (char= (schar string jndex) (char-upcase char)) (return nil)))) (return t)))) ;;; MAP-APROPOS -- public (extension). ;;; (defun map-apropos (fun string &optional package external-only) "Call FUN with each symbol that contains STRING. If PACKAGE is supplied then only use symbols present in that package. If EXTERNAL-ONLY is true then only use symbols exported from the specified package." (let ((string (nstring-upcase (string-to-nfc (string string))))) (declare (simple-string string)) (flet ((apropos-in-package (package) (if external-only (do-external-symbols (symbol package) (if (and (eq (symbol-package symbol) package) (apropos-search symbol string)) (funcall fun symbol))) (do-symbols (symbol package) (if (and (eq (symbol-package symbol) package) (apropos-search symbol string)) (funcall fun symbol)))))) (if (null package) (mapc #'apropos-in-package (list-all-packages)) (apropos-in-package (package-or-lose package)))) nil)) ;;; APROPOS -- public. ;;; (defun apropos (string &optional package) "Briefly describe all symbols which contain the specified STRING. If PACKAGE is supplied then only describe symbols present in that package. If EXTERNAL-ONLY is non-NIL then only describe external symbols in the specified package." (map-apropos #'briefly-describe-symbol string package) (values)) ;;; APROPOS-LIST -- public. ;;; (defun apropos-list (string &optional package) "Identical to APROPOS, except that it returns a list of the symbols found instead of describing them." (collect ((result)) (map-apropos #'(lambda (symbol) (result symbol)) string package) (result))) ;;; Initialization. The cold loader ( Genesis ) makes the data structure in * initial - symbols * . ;;; We grovel over it, making the specified packages and interning the ;;; symbols. For a description of the format of *initial-symbols* see the Genesis source . (defvar *initial-symbols*) (defun package-init () (let ((*in-package-init* t)) (dolist (spec *initial-symbols*) (let* ((pkg (apply #'make-package (first spec))) (internal (package-internal-symbols pkg)) (external (package-external-symbols pkg))) ;; ;; Put internal symbols in the internal hashtable and set package. (dolist (symbol (second spec)) (add-symbol internal symbol) (%set-symbol-package symbol pkg)) ;; ;; External symbols same, only go in external table. (dolist (symbol (third spec)) (add-symbol external symbol) (%set-symbol-package symbol pkg)) ;; ;; Don't set package for Imported symbols. (dolist (symbol (fourth spec)) (add-symbol internal symbol)) (dolist (symbol (fifth spec)) (add-symbol external symbol)) ;; ;; Put shadowing symbols in the shadowing symbols list. (setf (package-%shadowing-symbols pkg) (sixth spec)))) (makunbound '*initial-symbols*) ; So it gets GC'ed. ;; Make some other packages that should be around in the cold load: (make-package "COMMON-LISP-USER" :nicknames '("CL-USER")) ;; Now do the *deferred-use-packages*: (dolist (args *deferred-use-packages*) (apply #'use-package args)) (makunbound '*deferred-use-packages*) (setq *lisp-package* (find-package "LISP")) (setq *keyword-package* (find-package "KEYWORD")) ;; For the kernel core image wizards, set the package to *Lisp-Package*. (setq *package* *lisp-package*)))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/code/package.lisp
lisp
-*- Log: code.log; Package: Lisp -*- ********************************************************************** ********************************************************************** Package stuff and stuff like that. INTERNAL conditions A list of all the hashtables for inherited symbols. The string name of the package. List of nickname strings. List of packages we use. List of packages that use this package. Hashtables of internal & external symbols. List of shadowing symbols. Locks for this package. The PACKAGE-LOCK is a lock on the structure of the package, and controls modifications to its list of symbols and its export list. The PACKAGE-DEFINITION-LOCK protects all symbols in the package from being redefined. These are initially disabled, and are enabled by the function PACKAGE-LOCKS-INIT during after-save-initializations. Documentation string for this package Can get the name (NIL) of a deleted package. An equal hashtable from package names to packages. Lots of people want the keyword package and Lisp package without a lot of fuss, so we give them their own variables. Tell the compiler about disabled locks too. This is a workaround for the case of defmacro of a symbol in a locked package. trap attempts to redefine a function in a locked package, and signal a continuable error. This magical variable is T during initialization so Use-Package's of packages that don't yet exist quietly win. Such packages are thrown onto the list *Deferred-Use-Packages* so that this can be fixed up later. Make a package name into a simple-string. Take a package-or-string-or-symbol and return a package name. Given a package name, a simple-string, do a package name lookup. Because this function is called via the reader, we want it to be as fast as possible. While this function is not called via the reader, we do want it to be fast. Return length of `prefix' if `string' starts with `prefix'. We don't use `search' because it does much more than we need Given a package name, a simple-string, do a relative package name lookup. It is intended that this function will be called from find-package. relative to current package find-package -- Public Take a package-or-string-or-symbol and return a package. but the resulting message is somewhat unclear. Return a list of packages given a package-or-string-or-symbol or list thereof, or die trying. Packages are implemented using a special kind of hashtable. It is primary purpose of the hash for each entry is to reduce paging by allowing collisions and misses to be detected without paging in the symbol and pname for an entry. If the hash for an entry doesn't match that for the symbol that we are looking for, then we can go on without touching the symbol, pname, or even hashtable vector. It turns out that, contrary to my expectations, paging is a very important consideration the design of the package representation. the entry is unused. If it is one, then it is deleted. Double-hashing is used for collision resolution. The g-vector of symbols. The i-vector of pname hash values. The maximum number of entries allowed. The entries that can be made before we have to rehash. The number of deleted entries. The maximum density we allow in a package hashtable. Compute a number from the sxhash of the pname and the length which Make a package hashtable having a prime number of entries at least then it is destructively modified to produce the result. This is useful when changing the size, since there are many pointers to the hashtable. Add a symbol to a package hashtable. The symbol is assumed not to be present. Iteration macros. WITH-PACKAGE-ITERATOR Order symbol-types. DEFPACKAGE: Check whether all given arguments specify disjoint sets of symbols. Each argument is of the form (:key . set). Use Exports. Documentation If there is a conflict then give the user a chance to do something about it. Make-Package -- Public Check for package name conflicts in name and nicknames, then make the package. Do a use-package for each thing in the use list so that checking for conflicting exports among used packages is done. IN-PACKAGE -- public. Rename-Package -- Public Change the name if we can, blast any old nicknames and then add in any new ones. Delete-Package -- Public List-All-Packages -- Public Simple-stringify the name and call intern*. Find-Symbol -- Public Ditto. If the symbol doesn't exist then create it, special-casing the keyword package. Check internal and external symbols, then scan down the list of hashtables for inherited symbols. When an inherited symbol is found pull that table to the beginning of the list. Similar to find-symbol, but only looks for an external symbol. This is used for fast name-conflict checking in this file and symbol printing in the printer. unintern -- Public If we are uninterning a shadowing symbol, then a name conflict can result, otherwise just nuke the symbol. If a name conflict is revealed, give use a chance to shadowing-import one of the accessible symbols. Take a symbol-or-list-of-symbols and return a list, checking types. Like Unintern, but if symbol is inherited chases down the package it is inherited from and uninterns it there. Used for name-conflict resolution. Shadowing symbols are not uninterned since they do not cause conflicts. Export -- Public Do more stuff. Punt any symbols that are already external. Find symbols and packages with conflicts. Check that all symbols are accessible. If not, ask to import them. Unexport -- Public Check that all symbols are accessible, then move from external to internal. Import -- Public shadowing-import if there is. Add the new symbols to the internal hashtable. If a conflicting symbol is present, unintern it, otherwise just stick the symbol in. If it was shadowed, we don't want Unintern to flame out... Use-Package -- Public Do stuff to use a package, with all kinds of fun name-conflict checking. Loop over each package, use'ing one at a time... If the number of symbols already accessible is less than the number to be inherited then it is faster to run the test the other way. This is particularly valuable in the case of a new package use'ing Lisp. Find-All-Symbols -- Public Variable namespace Function namespace could do better than this with (kernel:type-specifier (info function type symbol)) when it's a byte-compiled function Class and Type Namespace(s) Make sure we at least print the symbol itself if we don't know anything else about it: MAP-APROPOS -- public (extension). APROPOS -- public. APROPOS-LIST -- public. Initialization. We grovel over it, making the specified packages and interning the symbols. For a description of the format of *initial-symbols* see Put internal symbols in the internal hashtable and set package. External symbols same, only go in external table. Don't set package for Imported symbols. Put shadowing symbols in the shadowing symbols list. So it gets GC'ed. Make some other packages that should be around in the cold load: Now do the *deferred-use-packages*: For the kernel core image wizards, set the package to *Lisp-Package*.
This code was written as part of the CMU Common Lisp project at Carnegie Mellon University , and has been placed in the public domain . (ext:file-comment "$Header: src/code/package.lisp $") Re - Written by . Earlier version written by . Apropos & iteration macros courtesy of Skef Wholey . Defpackage by . With - Package - Iterator by . Defpackage and do - mumble - symbols macros re - written by . (in-package "LISP") (intl:textdomain "cmucl") (export '(package packagep *package* make-package in-package find-package package-name package-nicknames rename-package delete-package package-use-list package-used-by-list package-shadowing-symbols list-all-packages intern find-symbol unintern export unexport import shadowing-import shadow use-package unuse-package find-all-symbols do-symbols with-package-iterator do-external-symbols do-all-symbols apropos apropos-list defpackage)) (in-package "EXTENSIONS") (export '(*keyword-package* *lisp-package* *default-package-use-list* map-apropos package-children package-parent package-lock package-definition-lock without-package-locks unlock-all-packages)) (in-package "KERNEL") (export '(%in-package old-in-package %defpackage)) (in-package "LISP") #+relative-package-names (sys:register-lisp-feature :relative-package-names) (defvar *default-package-use-list* '("COMMON-LISP") "The list of packages to use by default of no :USE argument is supplied to MAKE-PACKAGE or other package creation forms.") (define-condition simple-package-error (simple-condition package-error) ()) (defstruct (package (:constructor internal-make-package) (:predicate packagep) (:print-function %print-package) (:make-load-form-fun (lambda (package) (values `(package-or-lose ',(package-name package)) nil)))) "Standard structure for the description of a package. Consists of a list of all hash tables, the name of the package, the nicknames of the package, the use-list for the package, the used-by- list, hash- tables for the internal and external symbols, and a list of the shadowing symbols." (%name nil :type (or simple-string null)) (%nicknames () :type list) (%use-list () :type list) (%used-by-list () :type list) (internal-symbols (required-argument) :type package-hashtable) (external-symbols (required-argument) :type package-hashtable) (%shadowing-symbols () :type list) (lock nil :type boolean) (definition-lock nil :type boolean) (doc-string nil :type (or simple-string null))) (defun %print-package (s stream d) (declare (ignore d) (stream stream)) (if (package-%name s) (cond (*print-escape* (multiple-value-bind (iu it) (internal-symbol-count s) (multiple-value-bind (eu et) (external-symbol-count s) (print-unreadable-object (s stream) (format stream (intl:gettext "The ~A package, ~D/~D internal, ~D/~D external") (package-%name s) iu it eu et))))) (t (print-unreadable-object (s stream) (format stream (intl:gettext "The ~A package") (package-%name s))))) (print-unreadable-object (s stream :identity t) (format stream (intl:gettext "deleted package"))))) (defun package-name (x) (package-%name (if (packagep x) x (package-or-lose x)))) (macrolet ((frob (ext real) `(defun ,ext (x) (,real (package-or-lose x))))) (frob package-nicknames package-%nicknames) (frob package-use-list package-%use-list) (frob package-used-by-list package-%used-by-list) (frob package-shadowing-symbols package-%shadowing-symbols)) (defvar *package* () "The current package.") (defvar *package-names* (make-hash-table :test #'equal)) (defvar *lisp-package*) (defvar *keyword-package*) (defvar *enable-package-locked-errors* nil) (define-condition package-locked-error (simple-package-error) () (:report (lambda (condition stream) (format stream (intl:gettext "~&~@<Attempt to modify the locked package ~A, by ~3i~:_~?~:>") (package-name (package-error-package condition)) (simple-condition-format-control condition) (simple-condition-format-arguments condition))))) (defun package-locks-init () (let ((package-names '("COMMON-LISP" "LISP" "PCL" "CLOS-MOP" "EVAL" "NEW-ASSEM" "DISASSEM" "LOOP" "ANSI-LOOP" "INSPECT" "C" "PROFILE" "WIRE" "BIGNUM" "VM" "FORMAT" "DFIXNUM" "PRETTY-PRINT" "C-CALL" "ALIEN" "ALIEN-INTERNALS" "UNIX" "CONDITIONS" "DEBUG" "DEBUG-INTERNALS" "SYSTEM" "KERNEL" "EXTENSIONS" #+mp "MULTIPROCESSING" "WALKER" "XREF" "STREAM" "INTL"))) (dolist (p package-names) (let ((p (find-package p))) (when p (setf (package-definition-lock p) t) (setf (package-lock p) t)))) (setf *enable-package-locked-errors* t) (push 'redefining-function ext:*setf-fdefinition-hook*)) (values)) (pushnew 'package-locks-init ext:*after-save-initializations*) (defun unlock-all-packages () (dolist (p (list-all-packages)) (setf (package-definition-lock p) nil) (setf (package-lock p) nil))) (defmacro without-package-locks (&body body) `(eval-when (:compile-toplevel :load-toplevel :execute) (let ((*enable-package-locked-errors* nil)) (ext:compiler-let ((*enable-package-locked-errors* nil)) ,@body)))) (defun redefining-function (function replacement) (declare (ignore replacement)) (when *enable-package-locked-errors* (multiple-value-bind (valid block-name) (ext:valid-function-name-p function) (declare (ignore valid)) (let ((package (symbol-package block-name))) (when package (when (package-definition-lock package) (when (and (consp function) (member (first function) '(pcl::slot-accessor pcl::method pcl::fast-method pcl::effective-method pcl::ctor))) (return-from redefining-function nil)) (restart-case (error 'package-locked-error :package package :format-control (intl:gettext "redefining function ~A") :format-arguments (list function)) (continue () :report (lambda (stream) (write-string (intl:gettext "Ignore the lock and continue") stream))) (unlock-package () :report (lambda (stream) (write-string (intl:gettext "Disable package's definition-lock, then continue") stream)) (setf (ext:package-definition-lock package) nil)) (unlock-all () :report (lambda (stream) (write-string (intl:gettext "Disable all package locks, then continue") stream)) (unlock-all-packages))))))))) (defvar *in-package-init* nil) (defvar *deferred-use-packages* nil) (defun stringify-name (name kind) (typecase name (string (string-to-nfc name)) (symbol (symbol-name name)) (base-char (let ((res (make-string 1))) (setf (schar res 0) name) res)) (t (error (intl:gettext "Bogus ~A name: ~S") kind name)))) (defun stringify-names (names kind) (mapcar #'(lambda (name) (stringify-name name kind)) names)) package - namify -- Internal (defun package-namify (n) (stringify-name n "package")) package - namestring -- Internal (defun package-namestring (thing) (if (packagep thing) (let ((name (package-%name thing))) (or name (error (intl:gettext "Can't do anything to a deleted package: ~S") thing))) (package-namify thing))) package - name - to - package -- Internal (defun package-name-to-package (name) (declare (simple-string name)) (values (gethash name *package-names*))) package - parent -- Internal . #+relative-package-names (defun package-parent (package-specifier) "Given PACKAGE-SPECIFIER, a package, symbol or string, return the parent package. If there is not a parent, signal an error." (declare (optimize (speed 3))) (flet ((find-last-dot (name) (do* ((len (1- (length name))) (i len (1- i))) ((= i -1) nil) (declare (fixnum len i)) (when (char= #\. (schar name i)) (return i))))) (let* ((child (package-namestring package-specifier)) (dot-position (find-last-dot child))) (cond (dot-position (let ((parent (subseq child 0 dot-position))) (or (package-name-to-package parent) (error 'simple-package-error :name child :format-control (intl:gettext "The parent of ~a does not exist.") :format-arguments (list child))))) (t (error 'simple-package-error :name child :format-control (intl:gettext "There is no parent of ~a.") :format-arguments (list child))))))) package - children -- Internal . #+relative-package-names (defun package-children (package-specifier &key (recurse t)) "Given PACKAGE-SPECIFIER, a package, symbol or string, return all the packages which are in the hierarchy 'under' the given package. If :recurse is nil, then only return the immediate children of the package." (declare (optimize (speed 3))) (let ((res ()) (parent (package-namestring package-specifier))) (labels ((string-prefix-p (prefix string) (declare (simple-string prefix string)) and this version is about 10x faster than calling ` search ' . (let ((prefix-len (length prefix)) (seq-len (length string))) (declare (type index prefix-len seq-len)) (when (>= prefix-len seq-len) (return-from string-prefix-p nil)) (do ((i 0 (1+ i))) ((= i prefix-len) prefix-len) (declare (type index i)) (unless (char= (schar prefix i) (schar string i)) (return nil))))) (test-package (package-name package) (declare (simple-string package-name) (type package package)) (let ((prefix (string-prefix-p (concatenate 'simple-string parent ".") package-name))) (cond (recurse (when prefix (pushnew package res))) (t (when (and prefix (not (find #\. package-name :start prefix))) (pushnew package res))))))) (maphash #'test-package *package-names*) res))) relative - package - name - to - package -- Internal #+relative-package-names (defun relative-package-name-to-package (name) (declare (simple-string name) (optimize (speed 3))) (flet ((relative-to (package name) (declare (type package package) (simple-string name)) (if (string= "" name) package (let ((parent-name (package-%name package))) (unless parent-name (error (intl:gettext "Can't do anything to a deleted package: ~S") package)) (package-name-to-package (concatenate 'simple-string parent-name "." name))))) (find-non-dot (name) (do* ((len (length name)) (i 0 (1+ i))) ((= i len) nil) (declare (type index len i)) (when (char/= #\. (schar name i)) (return i))))) (when (and (plusp (length name)) (char= #\. (schar name 0))) (let* ((last-dot-position (or (find-non-dot name) (length name))) (n-dots last-dot-position) (name (subseq name last-dot-position))) (cond ((= 1 n-dots) (relative-to *package* name)) (t relative to our ( - n - dots 1)'th parent (let ((package *package*) (tmp nil)) (dotimes (i (1- n-dots)) (declare (fixnum i)) (setq tmp (package-parent package)) (unless tmp (error 'simple-package-error :name (string package) :format-control (intl:gettext "The parent of ~a does not exist.") :format-arguments (list package))) (setq package tmp)) (relative-to package name)))))))) (defun find-package (name) "Find the package having the specified name." (if (packagep name) name (let ((name (package-namify name))) (or (package-name-to-package name) #+relative-package-names (relative-package-name-to-package name))))) package - or - lose -- Internal (defun package-or-lose (thing) (cond ((packagep thing) (unless (package-%name thing) (error (intl:gettext "Can't do anything to a deleted package: ~S") thing)) thing) (t (let ((thing (package-namify thing))) (cond ((package-name-to-package thing)) (t ANSI spec 's type - error where this is called . But , May need a new condition type ? (with-simple-restart (continue (intl:gettext "Make this package.")) (error 'type-error :datum thing :expected-type 'package)) (make-package thing))))))) package - listify -- Internal (defun package-listify (thing) (let ((res ())) (dolist (thing (if (listp thing) thing (list thing)) res) (push (package-or-lose thing) res)))) Package - Hashtables an open hashtable with a parallel 8 - bit I - vector of hash - codes . The Using a similar scheme without the entry hash , the fasloader was spending more than half its time paging in INTERN . The hash code also indicates the status of an entry . If it zero , (deftype hash-vector () '(simple-array (unsigned-byte 8) (*))) (defstruct (package-hashtable (:constructor internal-make-package-hashtable ()) (:copier nil) (:print-function (lambda (table stream d) (declare (ignore d) (stream stream)) (format stream (intl:gettext "#<Package-Hashtable: Size = ~D, Free = ~D, Deleted = ~D>") (package-hashtable-size table) (package-hashtable-free table) (package-hashtable-deleted table))))) (table nil :type (or simple-vector null)) (hash nil :type (or hash-vector null)) (size 0 :type index) (free 0 :type index) (deleted 0 :type index)) (defparameter package-rehash-threshold 3/4) Entry - Hash -- Internal must be between 2 and 255 . (defmacro entry-hash (length sxhash) `(the fixnum (+ (the fixnum (rem (the fixnum (logxor ,length ,sxhash (the fixnum (ash ,sxhash -8)) (the fixnum (ash ,sxhash -16)) (the fixnum (ash ,sxhash -19)))) 254)) 2))) Make - Package - Hashtable -- Internal as great as ( / size package - rehash - threshold ) . If Res is supplied , (defun make-package-hashtable (size &optional (res (internal-make-package-hashtable))) (do ((n (logior (truncate size package-rehash-threshold) 1) (+ n 2))) ((primep n) (setf (package-hashtable-table res) (make-array n)) (setf (package-hashtable-hash res) (make-array n :element-type '(unsigned-byte 8) :initial-element 0)) (let ((size (truncate (* n package-rehash-threshold)))) (setf (package-hashtable-size res) size) (setf (package-hashtable-free res) size)) (setf (package-hashtable-deleted res) 0) res) (declare (fixnum n)))) Internal - Symbol - Count , External - Symbols - Count -- Internal Return internal and external symbols . Used by Genesis and stuff . (flet ((stuff (table) (let ((size (the fixnum (- (the fixnum (package-hashtable-size table)) (the fixnum (package-hashtable-deleted table)))))) (declare (fixnum size)) (values (the fixnum (- size (the fixnum (package-hashtable-free table)))) size)))) (defun internal-symbol-count (package) (stuff (package-internal-symbols package))) (defun external-symbol-count (package) (stuff (package-external-symbols package)))) Add - Symbol -- Internal (defun add-symbol (table symbol) (let* ((vec (package-hashtable-table table)) (hash (package-hashtable-hash table)) (len (length vec)) (sxhash (%sxhash-simple-string (symbol-name symbol))) (h2 (the fixnum (1+ (the fixnum (rem sxhash (the fixnum (- len 2)))))))) (declare (simple-vector vec) (type (simple-array (unsigned-byte 8)) hash) (fixnum len sxhash h2)) (cond ((zerop (the fixnum (package-hashtable-free table))) (make-package-hashtable (the fixnum (* (the fixnum (package-hashtable-size table)) 2)) table) (add-symbol table symbol) (dotimes (i len) (declare (fixnum i)) (when (> (the fixnum (aref hash i)) 1) (add-symbol table (svref vec i))))) (t (do ((i (rem sxhash len) (rem (+ i h2) len))) ((< (the fixnum (aref hash i)) 2) (if (zerop (the fixnum (aref hash i))) (decf (the fixnum (package-hashtable-free table))) (decf (the fixnum (package-hashtable-deleted table)))) (setf (svref vec i) symbol) (setf (aref hash i) (entry-hash (length (the simple-string (symbol-name symbol))) sxhash))) (declare (fixnum i))))))) With - Symbol -- Internal Find where the symbol named is stored in Table . Index - Var is bound to the index , or NIL if it is not present . is bound to the symbol . Length and are the length and sxhash of . Entry - Hash is the entry - hash of the string and length . (defmacro with-symbol ((index-var symbol-var table string length sxhash entry-hash) &body forms) (let ((vec (gensym)) (hash (gensym)) (len (gensym)) (h2 (gensym)) (name (gensym)) (name-len (gensym)) (ehash (gensym))) `(let* ((,vec (package-hashtable-table ,table)) (,hash (package-hashtable-hash ,table)) (,len (length ,vec)) (,h2 (1+ (the index (rem (the index ,sxhash) (the index (- ,len 2))))))) (declare (type (simple-array (unsigned-byte 8) (*)) ,hash) (simple-vector ,vec) (type index ,len ,h2)) (prog ((,index-var (rem (the index ,sxhash) ,len)) ,symbol-var ,ehash) (declare (type (or index null) ,index-var)) LOOP (setq ,ehash (aref ,hash ,index-var)) (cond ((eql ,ehash ,entry-hash) (setq ,symbol-var (svref ,vec ,index-var)) (let* ((,name (symbol-name ,symbol-var)) (,name-len (length ,name))) (declare (simple-string ,name) (type index ,name-len)) (when (and (= ,name-len ,length) (string= ,string ,name :end1 ,length :end2 ,name-len)) (go DOIT)))) ((zerop ,ehash) (setq ,index-var nil) (go DOIT))) (setq ,index-var (+ ,index-var ,h2)) (when (>= ,index-var ,len) (setq ,index-var (- ,index-var ,len))) (go LOOP) DOIT (return (progn ,@forms)))))) Nuke - Symbol -- Internal Delete the entry for String in Table . The entry must exist . (defun nuke-symbol (table string) (declare (simple-string string)) (let* ((length (length string)) (hash (%sxhash-simple-string string)) (ehash (entry-hash length hash))) (declare (type index length hash)) (with-symbol (index symbol table string length hash ehash) (setf (aref (package-hashtable-hash table) index) 1) (setf (aref (package-hashtable-table table) index) nil) (incf (package-hashtable-deleted table))))) (defmacro do-symbols ((var &optional (package '*package*) result-form) &parse-body (body decls)) "DO-SYMBOLS (VAR [PACKAGE [RESULT-FORM]]) {DECLARATION}* {TAG | FORM}* Executes the FORMs at least once for each symbol accessible in the given PACKAGE with VAR bound to the current symbol." (let ((flet-name (gensym "DO-SYMBOLS-"))) `(block nil (flet ((,flet-name (,var) ,@decls (tagbody ,@body))) (let* ((package (package-or-lose ,package)) (shadows (package-%shadowing-symbols package))) (flet ((iterate-over-hash-table (table ignore) (let ((hash-vec (package-hashtable-hash table)) (sym-vec (package-hashtable-table table))) (declare (type (simple-array (unsigned-byte 8) (*)) hash-vec) (type simple-vector sym-vec)) (dotimes (i (length sym-vec)) (when (>= (aref hash-vec i) 2) (let ((sym (aref sym-vec i))) (declare (inline member)) (unless (member sym ignore :test #'string=) (,flet-name sym)))))))) (iterate-over-hash-table (package-internal-symbols package) nil) (iterate-over-hash-table (package-external-symbols package) nil) (dolist (use (package-%use-list package)) (iterate-over-hash-table (package-external-symbols use) shadows))))) (let ((,var nil)) (declare (ignorable ,var)) ,@decls ,result-form)))) (defmacro do-external-symbols ((var &optional (package '*package*) result-form) &parse-body (body decls)) "DO-EXTERNAL-SYMBOLS (VAR [PACKAGE [RESULT-FORM]]) {DECL}* {TAG | FORM}* Executes the FORMs once for each external symbol in the given PACKAGE with VAR bound to the current symbol." (let ((flet-name (gensym "DO-SYMBOLS-"))) `(block nil (flet ((,flet-name (,var) ,@decls (tagbody ,@body))) (let* ((package (package-or-lose ,package)) (table (package-external-symbols package)) (hash-vec (package-hashtable-hash table)) (sym-vec (package-hashtable-table table))) (declare (type (simple-array (unsigned-byte 8) (*)) hash-vec) (type simple-vector sym-vec)) (dotimes (i (length sym-vec)) (when (>= (aref hash-vec i) 2) (,flet-name (aref sym-vec i)))))) (let ((,var nil)) (declare (ignorable ,var)) ,@decls ,result-form)))) (defmacro do-all-symbols ((var &optional result-form) &parse-body (body decls)) "DO-ALL-SYMBOLS (VAR [RESULT-FORM]) {DECLARATION}* {TAG | FORM}* Executes the FORMs once for each symbol in every package with VAR bound to the current symbol." (let ((flet-name (gensym "DO-SYMBOLS-"))) `(block nil (flet ((,flet-name (,var) ,@decls (tagbody ,@body))) (dolist (package (list-all-packages)) (flet ((iterate-over-hash-table (table) (let ((hash-vec (package-hashtable-hash table)) (sym-vec (package-hashtable-table table))) (declare (type (simple-array (unsigned-byte 8) (*)) hash-vec) (type simple-vector sym-vec)) (dotimes (i (length sym-vec)) (when (>= (aref hash-vec i) 2) (,flet-name (aref sym-vec i))))))) (iterate-over-hash-table (package-internal-symbols package)) (iterate-over-hash-table (package-external-symbols package))))) (let ((,var nil)) (declare (ignorable ,var)) ,@decls ,result-form)))) (defmacro with-package-iterator ((mname package-list &rest symbol-types) &body body) "Within the lexical scope of the body forms, MNAME is defined via macrolet such that successive invocations of (mname) will return the symbols, one by one, from the packages in PACKAGE-LIST. SYMBOL-TYPES may be any of :inherited :external :internal." (let* ((packages (gensym)) (these-packages (gensym)) (ordered-types (let ((res nil)) (dolist (kind '(:inherited :external :internal) res) (when (member kind symbol-types) (counter (gensym)) (kind (gensym)) (hash-vector (gensym)) (vector (gensym)) (package-use-list (gensym)) (init-macro (gensym)) (end-test-macro (gensym)) (real-symbol-p (gensym)) (inherited-symbol-p (gensym)) (BLOCK (gensym))) `(let* ((,these-packages ,package-list) (,packages `,(mapcar #'(lambda (package) (if (packagep package) package (or (find-package package) (error 'simple-package-error :name (string package) :format-control (intl:gettext "~@<~S does not name a package ~:>") :format-arguments (list package))))) (if (consp ,these-packages) ,these-packages (list ,these-packages)))) (,counter nil) (,kind (car ,packages)) (,hash-vector nil) (,vector nil) (,package-use-list nil)) ,(if (member :inherited ordered-types) `(setf ,package-use-list (package-%use-list (car ,packages))) `(declare (ignore ,package-use-list))) (macrolet ((,init-macro (next-kind) (let ((symbols (gensym))) `(progn (setf ,',kind ,next-kind) (setf ,',counter nil) ,(case next-kind (:internal `(let ((,symbols (package-internal-symbols (car ,',packages)))) (when ,symbols (setf ,',vector (package-hashtable-table ,symbols)) (setf ,',hash-vector (package-hashtable-hash ,symbols))))) (:external `(let ((,symbols (package-external-symbols (car ,',packages)))) (when ,symbols (setf ,',vector (package-hashtable-table ,symbols)) (setf ,',hash-vector (package-hashtable-hash ,symbols))))) (:inherited `(let ((,symbols (and ,',package-use-list (package-external-symbols (car ,',package-use-list))))) (when ,symbols (setf ,',vector (package-hashtable-table ,symbols)) (setf ,',hash-vector (package-hashtable-hash ,symbols))))))))) (,end-test-macro (this-kind) `,(let ((next-kind (cadr (member this-kind ',ordered-types)))) (if next-kind `(,',init-macro ,next-kind) `(if (endp (setf ,',packages (cdr ,',packages))) (return-from ,',BLOCK) (,',init-macro ,(car ',ordered-types))))))) (when ,packages ,(when (null symbol-types) (simple-program-error (intl:gettext "Must supply at least one of :internal, ~ :external, or :inherited."))) ,(dolist (symbol symbol-types) (unless (member symbol '(:internal :external :inherited)) (simple-program-error (intl:gettext "~S is not one of :internal, :external, ~ or :inherited.") symbol))) (,init-macro ,(car ordered-types)) (flet ((,real-symbol-p (number) (> number 1))) (macrolet ((,mname () `(block ,',BLOCK (loop (case ,',kind ,@(when (member :internal ',ordered-types) `((:internal (setf ,',counter (position-if #',',real-symbol-p ,',hash-vector :start (if ,',counter (1+ ,',counter) 0))) (if ,',counter (return-from ,',BLOCK (values t (svref ,',vector ,',counter) ,',kind (car ,',packages))) (,',end-test-macro :internal))))) ,@(when (member :external ',ordered-types) `((:external (setf ,',counter (position-if #',',real-symbol-p ,',hash-vector :start (if ,',counter (1+ ,',counter) 0))) (if ,',counter (return-from ,',BLOCK (values t (svref ,',vector ,',counter) ,',kind (car ,',packages))) (,',end-test-macro :external))))) ,@(when (member :inherited ',ordered-types) `((:inherited (flet ((,',inherited-symbol-p (number) (when (,',real-symbol-p number) (let* ((p (position number ,',hash-vector :start (if ,',counter (1+ ,',counter) 0))) (s (svref ,',vector p))) (eql (nth-value 1 (find-symbol (symbol-name s) (car ,',packages))) :inherited))))) (setf ,',counter (position-if #',',inherited-symbol-p ,',hash-vector :start (if ,',counter (1+ ,',counter) 0)))) (cond (,',counter (return-from ,',BLOCK (values t (svref ,',vector ,',counter) ,',kind (car ,',packages)) )) (t (setf ,',package-use-list (cdr ,',package-use-list)) (cond ((endp ,',package-use-list) (setf ,',packages (cdr ,',packages)) (when (endp ,',packages) (return-from ,',BLOCK)) (setf ,',package-use-list (package-%use-list (car ,',packages))) (,',init-macro ,(car ',ordered-types))) (t (,',init-macro :inherited) (setf ,',counter nil))))))))))))) ,@body))))))) (defmacro defpackage (package &rest options) "Defines a new package called PACKAGE. Each of OPTIONS should be one of the following: (:NICKNAMES {package-name}*) (:SIZE <integer>) (:SHADOW {symbol-name}*) (:SHADOWING-IMPORT-FROM <package-name> {symbol-name}*) (:USE {package-name}*) (:IMPORT-FROM <package-name> {symbol-name}*) (:INTERN {symbol-name}*) (:EXPORT {symbol-name}*) (:DOCUMENTATION doc-string) All options except :SIZE and :DOCUMENTATION can be used multiple times." (let ((nicknames nil) (size nil) (shadows nil) (shadowing-imports nil) (use nil) (use-p nil) (imports nil) (interns nil) (exports nil) (doc nil)) (dolist (option options) (unless (consp option) (simple-program-error (intl:gettext "Bogus DEFPACKAGE option: ~S") option)) (case (car option) (:nicknames (setf nicknames (stringify-names (cdr option) "package"))) (:size (cond (size (simple-program-error (intl:gettext "Can't specify :SIZE twice."))) ((and (consp (cdr option)) (typep (second option) 'unsigned-byte)) (setf size (second option))) (t (simple-program-error (intl:gettext "Bogus :SIZE, must be a positive integer: ~S") (second option))))) (:shadow (let ((new (stringify-names (cdr option) "symbol"))) (setf shadows (append shadows new)))) (:shadowing-import-from (let ((package-name (stringify-name (second option) "package")) (names (stringify-names (cddr option) "symbol"))) (let ((assoc (assoc package-name shadowing-imports :test #'string=))) (if assoc (setf (cdr assoc) (append (cdr assoc) names)) (setf shadowing-imports (acons package-name names shadowing-imports)))))) (:use (let ((new (stringify-names (cdr option) "package"))) (setf use (delete-duplicates (nconc use new) :test #'string=)) (setf use-p t))) (:import-from (let ((package-name (stringify-name (second option) "package")) (names (stringify-names (cddr option) "symbol"))) (let ((assoc (assoc package-name imports :test #'string=))) (if assoc (setf (cdr assoc) (append (cdr assoc) names)) (setf imports (acons package-name names imports)))))) (:intern (let ((new (stringify-names (cdr option) "symbol"))) (setf interns (append interns new)))) (:export (let ((new (stringify-names (cdr option) "symbol"))) (setf exports (append exports new)))) (:documentation (when doc (simple-program-error (intl:gettext "Can't specify :DOCUMENTATION twice."))) (setf doc (coerce (second option) 'simple-string))) (t (simple-program-error (intl:gettext "Bogus DEFPACKAGE option: ~S") option)))) (check-disjoint `(:intern ,@interns) `(:export ,@exports)) (check-disjoint `(:intern ,@interns) `(:import-from ,@(apply #'append (mapcar #'rest imports))) `(:shadow ,@shadows) `(:shadowing-import-from ,@(apply #'append (mapcar #'rest shadowing-imports)))) `(eval-when (compile load eval) (%defpackage ,(stringify-name package "package") ',nicknames ',size ',shadows ',shadowing-imports ',(if use-p use :default) ',imports ',interns ',exports ',doc)))) (defun check-disjoint (&rest args) (loop for (current-arg . rest-args) on args do (loop with (key1 . set1) = current-arg for (key2 . set2) in rest-args for common = (delete-duplicates (intersection set1 set2 :test #'string=)) unless (null common) do (simple-program-error (intl:gettext "Parameters ~S and ~S must be disjoint ~ but have common elements ~% ~S") key1 key2 common)))) (defun %defpackage (name nicknames size shadows shadowing-imports use imports interns exports doc-string) (declare (type simple-base-string name) (type list nicknames shadows shadowing-imports imports interns exports) (type (or list (member :default)) use) (type (or simple-base-string null) doc-string)) (let ((package (or (find-package name) (progn (when (eq use :default) (setf use *default-package-use-list*)) (make-package name :use nil :internal-symbols (or size 10) :external-symbols (length exports)))))) (unless (string= (the string (package-name package)) name) (error 'simple-package-error :package name :format-control (intl:gettext "~A is a nick-name for the package ~A") :format-arguments (list name (package-name name)))) (enter-new-nicknames package nicknames) Shadows and Shadowing - imports . (let ((old-shadows (package-%shadowing-symbols package))) (shadow shadows package) (dolist (sym-name shadows) (setf old-shadows (remove (find-symbol sym-name package) old-shadows))) (dolist (simports-from shadowing-imports) (let ((other-package (package-or-lose (car simports-from)))) (dolist (sym-name (cdr simports-from)) (let ((sym (find-or-make-symbol sym-name other-package))) (shadowing-import sym package) (setf old-shadows (remove sym old-shadows)))))) (when old-shadows (warn (intl:gettext "~A also shadows the following symbols:~% ~S") name old-shadows))) (unless (eq use :default) (let ((old-use-list (package-use-list package)) (new-use-list (mapcar #'package-or-lose use))) (use-package (set-difference new-use-list old-use-list) package) (let ((laterize (set-difference old-use-list new-use-list))) (when laterize (unuse-package laterize package) (warn (intl:gettext "~A previously used the following packages:~% ~S") name laterize))))) Import and Intern . (dolist (sym-name interns) (intern sym-name package)) (dolist (imports-from imports) (let ((other-package (package-or-lose (car imports-from)))) (dolist (sym-name (cdr imports-from)) (import (list (find-or-make-symbol sym-name other-package)) package)))) (let ((old-exports nil) (exports (mapcar #'(lambda (sym-name) (intern sym-name package)) exports))) (do-external-symbols (sym package) (push sym old-exports)) (export exports package) (let ((diff (set-difference old-exports exports))) (when diff (warn (intl:gettext "~A also exports the following symbols:~% ~S") name diff)))) (setf (package-doc-string package) doc-string) package)) (defun find-or-make-symbol (name package) (multiple-value-bind (symbol how) (find-symbol name package) (cond (how symbol) (t (with-simple-restart (continue "INTERN it.") (error 'simple-package-error :package package :format-control (intl:gettext "~A does not contain a symbol ~A") :format-arguments (list (package-name package) name))) (intern name package))))) Enter - New - Nicknames -- Internal Enter any new Nicknames for Package into * package - names * . (defun enter-new-nicknames (package nicknames) (check-type nicknames list) (dolist (n nicknames) (let* ((n (package-namify n)) (found (package-name-to-package n))) (cond ((not found) (setf (gethash n *package-names*) package) (push n (package-%nicknames package))) ((eq found package)) ((string= (the string (package-%name found)) n) (with-simple-restart (continue (intl:gettext "Ignore this nickname.")) (error 'simple-package-error :package package :format-control (intl:gettext "~S is a package name, so it cannot be a nickname for ~S.") :format-arguments (list n (package-%name package))))) (t (with-simple-restart (continue (intl:gettext "Redefine this nickname.")) (error 'simple-package-error :package package :format-control (intl:gettext "~S is already a nickname for ~S.") :format-arguments (list n (package-%name found)))) (setf (gethash n *package-names*) package) (push n (package-%nicknames package))))))) (defun make-package (name &key (use *default-package-use-list*) nicknames (internal-symbols 10) (external-symbols 10)) "Makes a new package having the specified Name and Nicknames. The package will inherit all external symbols from each package in the use list. :Internal-Symbols and :External-Symbols are estimates for the number of internal and external symbols which will ultimately be present in the package." (when (find-package name) (cerror (intl:gettext "Leave existing package alone.") (intl:gettext "A package named ~S already exists") name)) (let* ((name (package-namify name)) (package (internal-make-package :%name name :internal-symbols (make-package-hashtable internal-symbols) :external-symbols (make-package-hashtable external-symbols)))) (if *in-package-init* (push (list use package) *deferred-use-packages*) (use-package use package)) (enter-new-nicknames package nicknames) (setf (gethash name *package-names*) package))) Old - In - Package -- Sorta Public . Like Make - Package , only different . Should go away someday . (defun old-in-package (name &rest keys &key nicknames use) "Sets *PACKAGE* to package with given NAME, creating the package if it does not exist. If the package already exists then it is modified to agree with the :USE and :NICKNAMES arguments. Any new nicknames are added without removing any old ones not specified. If any package in the :Use list is not currently used, then it is added to the use list." (let ((package (find-package name))) (cond (package (if *in-package-init* (push (list use package) *deferred-use-packages*) (use-package use package)) (enter-new-nicknames package nicknames) (setq *package* package)) (t (setq *package* (apply #'make-package name keys)))))) (defmacro in-package (package &rest noise) (cond ((or noise (not (or (stringp package) (symbolp package)))) (warn (intl:gettext "Old-style IN-PACKAGE.")) `(old-in-package ,package ,@noise)) (t `(%in-package ',(stringify-name package "package"))))) (defun %in-package (name) (let ((package (find-package name))) (unless package (with-simple-restart (continue (intl:gettext "Make this package.")) (error 'simple-package-error :package name :format-control (intl:gettext "The package named ~S doesn't exist.") :format-arguments (list name))) (setq package (make-package name))) (setf *package* package))) (defun rename-package (package new-name &optional (new-nicknames ())) "Replaces the name and nicknames of Package. The old name and all of the old nicknames of Package are eliminated and are replaced by New-Name and New-Nicknames." (let* ((package (package-or-lose package)) (new-name (string new-name)) (found (find-package new-name))) (unless (or (not found) (eq found package)) (error 'simple-package-error :package new-name :format-control (intl:gettext "A package named ~S already exists.") :format-arguments (list new-name))) (remhash (package-%name package) *package-names*) (dolist (n (package-%nicknames package)) (remhash n *package-names*)) (setf (package-%name package) new-name) (setf (gethash new-name *package-names*) package) (setf (package-%nicknames package) ()) (enter-new-nicknames package new-nicknames) package)) (defun delete-package (package-or-name) "Delete the PACKAGE-OR-NAME from the package system data structures." (let ((package (if (packagep package-or-name) package-or-name (find-package package-or-name)))) (cond ((not package) (with-simple-restart (continue (intl:gettext "Return NIL")) (error 'simple-package-error :package package-or-name :format-control (intl:gettext "No package of name ~S.") :format-arguments (list package-or-name))) nil) ((not (package-name package)) nil) (t (let ((use-list (package-used-by-list package))) (when use-list (with-simple-restart (continue (intl:gettext "Remove dependency in other packages.")) (error 'simple-package-error :package package :format-control "Package ~S is used by package(s):~% ~S" :format-arguments (list (package-name package) (mapcar #'package-name use-list)))) (dolist (p use-list) (unuse-package package p)))) (dolist (used (package-use-list package)) (unuse-package used package)) (do-symbols (sym package) (unintern sym package)) (remhash (package-name package) *package-names*) (dolist (nick (package-nicknames package)) (remhash nick *package-names*)) (setf (package-%name package) nil) t)))) (defun list-all-packages () "Returns a list of all existing packages." (let ((res ())) (maphash #'(lambda (k v) (declare (ignore k)) (pushnew v res)) *package-names*) res)) Intern -- Public (defun intern (name &optional package) "Returns a symbol having the specified name, creating it if necessary." (let ((name (string-to-nfc name)) (package (if package (package-or-lose package) *package*))) (declare (type simple-string name)) (intern* name (length name) package))) (defun find-symbol (name &optional package) "Returns the symbol NAME in PACKAGE. If such a symbol is found then the second value is :internal, :external or :inherited to indicate how the symbol is accessible. If no symbol is found then both values are NIL." (let ((name (string-to-nfc name))) (declare (simple-string name)) (find-symbol* name (length name) (if package (package-or-lose package) *package*)))) Intern * -- Internal (defun intern* (name length package) (declare (simple-string name)) (multiple-value-bind (symbol where) (find-symbol* name length package) (if where (values symbol where) (progn #+(or) (when *enable-package-locked-errors* (when (ext:package-lock package) (restart-case (error 'package-locked-error :package package :format-control (intl:gettext "interning symbol ~A") :format-arguments (list (subseq name 0 length))) (continue () :report "Ignore the lock and continue") (unlock-package () :report "Unlock package, then continue" (setf (ext:package-lock package) nil)) (unlock-all () :report "Unlock all packages, then continue" (unlock-all-packages))))) (let ((symbol (make-symbol (subseq name 0 length)))) (%set-symbol-package symbol package) (cond ((eq package *keyword-package*) (add-symbol (package-external-symbols package) symbol) (%set-symbol-value symbol symbol)) (t (add-symbol (package-internal-symbols package) symbol))) (values symbol nil)))))) find - symbol * -- Internal (defun find-symbol* (string length package) (declare (simple-string string) (type index length)) (let* ((hash (%sxhash-simple-substring string length)) (ehash (entry-hash length hash))) (declare (type index hash ehash)) (with-symbol (found symbol (package-internal-symbols package) string length hash ehash) (when found (return-from find-symbol* (values symbol :internal)))) (with-symbol (found symbol (package-external-symbols package) string length hash ehash) (when found (return-from find-symbol* (values symbol :external)))) (let ((head (package-tables package))) (do ((prev head table) (table (cdr head) (cdr table))) ((null table) (values nil nil)) (with-symbol (found symbol (car table) string length hash ehash) (when found (unless (eq prev head) (shiftf (cdr prev) (cdr table) (cdr head) table)) (return-from find-symbol* (values symbol :inherited)))))))) find - external - symbol -- Internal (defun find-external-symbol (string package) (declare (simple-string string)) (let* ((length (length string)) (hash (%sxhash-simple-string string)) (ehash (entry-hash length hash))) (declare (type index length hash)) (with-symbol (found symbol (package-external-symbols package) string length hash ehash) (values symbol found)))) (defun unintern (symbol &optional (package *package*)) "Makes SYMBOL no longer present in PACKAGE. If SYMBOL was present then T is returned, otherwise NIL. If PACKAGE is SYMBOL's home package, then it is made uninterned." (let* ((package (package-or-lose package)) (name (symbol-name symbol)) (shadowing-symbols (package-%shadowing-symbols package))) (declare (list shadowing-symbols) (simple-string name)) (when *enable-package-locked-errors* (when (ext:package-lock package) (restart-case (error 'package-locked-error :package package :format-control (intl:gettext "uninterning symbol ~A") :format-arguments (list name)) (continue () :report (lambda (stream) (write-string (intl:gettext "Ignore the lock and continue") stream))) (unlock-package () :report (lambda (stream) (write-string (intl:gettext "Disable package's lock then continue") stream)) (setf (ext:package-lock package) nil)) (unlock-all () :report (lambda (stream) (write-string (intl:gettext "Unlock all packages, then continue") stream)) (unlock-all-packages))))) (when (member symbol shadowing-symbols) (let ((cset ())) (dolist (p (package-%use-list package)) (multiple-value-bind (s w) (find-external-symbol name p) (when w (pushnew s cset)))) (when (cdr cset) (loop (cerror (intl:gettext "prompt for a symbol to shadowing-import.") 'simple-package-error :package package :format-control (intl:gettext "Uninterning symbol ~S causes name conflict among these symbols:~%~S") :format-arguments (list symbol cset)) (write-string (intl:gettext "Symbol to shadowing-import: ") *query-io*) (let ((sym (read *query-io*))) (cond ((not (symbolp sym)) (format *query-io* (intl:gettext "~S is not a symbol.") sym)) ((not (member sym cset)) (format *query-io* (intl:gettext "~S is not one of the conflicting symbols.") sym)) (t (shadowing-import sym package) (return-from unintern t))))))) (setf (package-%shadowing-symbols package) (remove symbol shadowing-symbols))) (multiple-value-bind (s w) (find-symbol name package) (cond ((not (eq symbol s)) nil) ((or (eq w :internal) (eq w :external)) (nuke-symbol (if (eq w :internal) (package-internal-symbols package) (package-external-symbols package)) name) (if (eq (symbol-package symbol) package) (%set-symbol-package symbol nil)) t) (t nil))))) Symbol - Listify -- Internal (defun symbol-listify (thing) (cond ((listp thing) (dolist (s thing) (unless (symbolp s) (error (intl:gettext "~S is not a symbol.") s))) thing) ((symbolp thing) (list thing)) (t (error (intl:gettext "~S is neither a symbol nor a list of symbols.") thing)))) Moby - Unintern -- Internal (defun moby-unintern (symbol package) (unless (member symbol (package-%shadowing-symbols package)) (or (unintern symbol package) (let ((name (symbol-name symbol))) (multiple-value-bind (s w) (find-symbol name package) (declare (ignore s)) (when (eq w :inherited) (dolist (q (package-%use-list package)) (multiple-value-bind (u x) (find-external-symbol name q) (declare (ignore u)) (when x (unintern symbol q) (return t)))))))))) (defun export (symbols &optional (package *package*)) "Exports SYMBOLS from PACKAGE, checking that no name conflicts result." (let ((package (package-or-lose package)) (syms ())) (dolist (sym (symbol-listify symbols)) (multiple-value-bind (s w) (find-external-symbol (symbol-name sym) package) (declare (ignore s)) (unless (or w (member sym syms)) (push sym syms)))) (let ((used-by (package-%used-by-list package)) (cpackages ()) (cset ())) (dolist (sym syms) (let ((name (symbol-name sym))) (dolist (p used-by) (multiple-value-bind (s w) (find-symbol name p) (when (and w (not (eq s sym)) (not (member s (package-%shadowing-symbols p)))) (pushnew sym cset) (pushnew p cpackages)))))) (when cset (restart-case (error 'simple-package-error :package package :format-control (intl:gettext "Exporting these symbols from the ~A package:~%~S~%~ results in name conflicts with these packages:~%~{~A ~}") :format-arguments (list (package-%name package) cset (mapcar #'package-%name cpackages))) (unintern-conflicting-symbols () :report (lambda (stream) (write-string (intl:gettext "Unintern conflicting symbols.") stream)) (dolist (p cpackages) (dolist (sym cset) (moby-unintern sym p)))) (skip-exporting-these-symbols () :report (lambda (stream) (write-string (intl:gettext "Skip exporting conflicting symbols.") stream)) (setq syms (nset-difference syms cset)))))) (let ((missing ()) (imports ())) (dolist (sym syms) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (cond ((not (and w (eq s sym))) (push sym missing)) ((eq w :inherited) (push sym imports))))) (when missing (with-simple-restart (continue (intl:gettext "Import these symbols into the ~A package.") (package-%name package)) (error 'simple-package-error :package package :format-control (intl:gettext "These symbols are not accessible in the ~A package:~%~S") :format-arguments (list (package-%name package) missing))) (import missing package)) (import imports package)) And now , three pages later , we export the suckers . (let ((internal (package-internal-symbols package)) (external (package-external-symbols package))) (dolist (sym syms) (nuke-symbol internal (symbol-name sym)) (add-symbol external sym))) t)) (defun unexport (symbols &optional (package *package*)) "Makes SYMBOLS no longer exported from PACKAGE." (let ((package (package-or-lose package)) (syms ())) (when *enable-package-locked-errors* (when (ext:package-lock package) (restart-case (error 'package-locked-error :package package :format-control (intl:gettext "unexporting symbols ~A") :format-arguments (list symbols)) (continue () :report (lambda (stream) (write-string (intl:gettext "Ignore the lock and continue") stream))) (unlock-package () :report (lambda (stream) (write-string (intl:gettext "Disable package's lock then continue") stream)) (setf (ext:package-lock package) nil)) (unlock-all () :report (lambda (stream) (write-string (intl:gettext "Unlock all packages, then continue") stream)) (unlock-all-packages))))) (dolist (sym (symbol-listify symbols)) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (cond ((or (not w) (not (eq s sym))) (error 'simple-package-error :package package :format-control (intl:gettext "~S is not accessible in the ~A package.") :format-arguments (list sym (package-%name package)))) ((eq w :external) (pushnew sym syms))))) (let ((internal (package-internal-symbols package)) (external (package-external-symbols package))) (dolist (sym syms) (add-symbol internal sym) (nuke-symbol external (symbol-name sym)))) t)) Check for name conflic caused by the import and let the user (defun import (symbols &optional (package *package*)) "Make SYMBOLS accessible as internal symbols in PACKAGE. If a symbol is already accessible then it has no effect. If a name conflict would result from the importation, then a correctable error is signalled." (let ((package (package-or-lose package)) (symbols (symbol-listify symbols)) (syms ()) (cset ())) (dolist (sym symbols) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (cond ((not w) (let ((found (member sym syms :test #'string=))) (if found (when (not (eq (car found) sym)) (push sym cset)) (push sym syms)))) ((not (eq s sym)) (push sym cset)) ((eq w :inherited) (push sym syms))))) (when cset (with-simple-restart (continue (intl:gettext "Import these symbols with Shadowing-Import.")) (error 'simple-package-error :package package :format-control (intl:gettext "Importing these symbols into the ~A package ~ causes a name conflict:~%~S") :format-arguments (list (package-%name package) cset)))) (let ((internal (package-internal-symbols package))) (dolist (sym syms) (add-symbol internal sym))) If any of the symbols are uninterned , make them be owned by Package . (dolist (sym symbols) (unless (symbol-package sym) (%set-symbol-package sym package))) (shadowing-import cset package))) Shadowing - Import -- Public (defun shadowing-import (symbols &optional (package *package*)) "Import SYMBOLS into PACKAGE, disregarding any name conflict. If a symbol of the same name is present, then it is uninterned. The symbols are added to the Package-Shadowing-Symbols." (let* ((package (package-or-lose package)) (internal (package-internal-symbols package))) (dolist (sym (symbol-listify symbols)) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (unless (and w (not (eq w :inherited)) (eq s sym)) (when (or (eq w :internal) (eq w :external)) (setf (package-%shadowing-symbols package) (remove s (the list (package-%shadowing-symbols package)))) (unintern s package)) (add-symbol internal sym)) (pushnew sym (package-%shadowing-symbols package))))) t) Shadow -- Public (defun shadow (symbols &optional (package *package*)) "Make an internal symbol in PACKAGE with the same name as each of the specified SYMBOLS, adding the new symbols to the Package-Shadowing-Symbols. If a symbol with the given name is already present in PACKAGE, then the existing symbol is placed in the shadowing symbols list if it is not already present." (let* ((package (package-or-lose package)) (internal (package-internal-symbols package))) (dolist (name (mapcar #'string (if (listp symbols) symbols (list symbols)))) (multiple-value-bind (s w) (find-symbol name package) (when (or (not w) (eq w :inherited)) (setq s (make-symbol name)) (%set-symbol-package s package) (add-symbol internal s)) (pushnew s (package-%shadowing-symbols package))))) t) (defun use-package (packages-to-use &optional (package *package*)) "Add all the PACKAGES-TO-USE to the use list for PACKAGE so that the external symbols of the used packages are accessible as internal symbols in PACKAGE." (let ((packages (package-listify packages-to-use)) (package (package-or-lose package))) (dolist (pkg packages) (unless (member pkg (package-%use-list package)) (let ((cset ()) (shadowing-symbols (package-%shadowing-symbols package)) (use-list (package-%use-list package))) (cond ((< (+ (internal-symbol-count package) (external-symbol-count package) (let ((res 0)) (dolist (p use-list res) (incf res (external-symbol-count p))))) (external-symbol-count pkg)) (do-symbols (sym package) (multiple-value-bind (s w) (find-external-symbol (symbol-name sym) pkg) (when (and w (not (eq s sym)) (not (member sym shadowing-symbols))) (push sym cset)))) (dolist (p use-list) (do-external-symbols (sym p) (multiple-value-bind (s w) (find-external-symbol (symbol-name sym) pkg) (when (and w (not (eq s sym)) (not (member (find-symbol (symbol-name sym) package) shadowing-symbols))) (push sym cset)))))) (t (do-external-symbols (sym pkg) (multiple-value-bind (s w) (find-symbol (symbol-name sym) package) (when (and w (not (eq s sym)) (not (member s shadowing-symbols))) (push s cset)))))) (when cset (cerror (intl:gettext "Unintern the conflicting symbols in the ~2*~A package.") (intl:gettext "Use'ing package ~A results in name conflicts for these symbols:~%~S") (package-%name pkg) cset (package-%name package)) (dolist (s cset) (moby-unintern s package)))) (push pkg (package-%use-list package)) (push (package-external-symbols pkg) (cdr (package-tables package))) (push package (package-%used-by-list pkg))))) t) Unuse - Package -- Public (defun unuse-package (packages-to-unuse &optional (package *package*)) "Remove PACKAGES-TO-UNUSE from the use list for PACKAGE." (let ((package (package-or-lose package))) (dolist (p (package-listify packages-to-unuse)) (setf (package-%use-list package) (remove p (the list (package-%use-list package)))) (setf (package-tables package) (delete (package-external-symbols p) (the list (package-tables package)))) (setf (package-%used-by-list p) (remove package (the list (package-%used-by-list p))))) t)) (defun find-all-symbols (string-or-symbol) "Return a list of all symbols in the system having the specified name." (let ((string (string string-or-symbol)) (res ())) (maphash #'(lambda (k v) (declare (ignore k)) (multiple-value-bind (s w) (find-symbol string v) (when w (pushnew s res)))) *package-names*) res)) Apropos and Apropos - List . (defun briefly-describe-symbol (symbol) (let ((prefix-length nil)) (flet ((print-symbol (&optional kind) (fresh-line) (if prefix-length (dotimes (i prefix-length) (write-char #\Space)) (let ((symbol-string (prin1-to-string symbol))) (write-string symbol-string) (setq prefix-length (length symbol-string)))) (when kind (write-string " [") (write-string kind) (write-string "] ")))) (multiple-value-bind (kind recorded-p) (info variable kind symbol) (when (or (boundp symbol) recorded-p) (print-symbol (ecase kind (:special (intl:gettext "special variable")) (:constant (intl:gettext "constant")) (:global (intl:gettext "undefined variable")) (:macro (intl:gettext "symbol macro")) (:alien (intl:gettext "alien variable")))) (when (boundp symbol) (write-string (intl:gettext "value: ")) (let ((*print-length* (or ext:*describe-print-length* *print-length*)) (*print-level* (or ext:*describe-print-level* *print-level*))) (prin1 (symbol-value symbol)))))) (when (fboundp symbol) (cond ((macro-function symbol) (print-symbol (intl:gettext "macro")) (let ((arglist (kernel:%function-arglist (macro-function symbol)))) (when (stringp arglist) (write-string arglist)))) ((special-operator-p symbol) (print-symbol (intl:gettext "special operator")) (let ((arglist (kernel:%function-arglist (symbol-function symbol)))) (when (stringp arglist) (write-string arglist)))) (t (print-symbol (intl:gettext "function")) (let ((arglist (kernel:%function-arglist (symbol-function symbol)))) (when (stringp arglist) (write-string arglist)))))) (cond ((kernel::find-class symbol nil) (print-symbol (intl:gettext "class"))) ((info type kind symbol) (print-symbol (intl:gettext "type")))) (when (null prefix-length) (print-symbol))))) (defun apropos-search (symbol string) (declare (simple-string string)) (do* ((index 0 (1+ index)) (name (symbol-name symbol)) (length (length string)) (terminus (- (length name) length))) ((> index terminus) nil) (declare (simple-string name) (type index index length) (fixnum terminus)) (if (do ((jndex 0 (1+ jndex)) (kndex index (1+ kndex))) ((= jndex length) t) (declare (fixnum jndex kndex)) (let ((char (schar name kndex))) (unless (char= (schar string jndex) (char-upcase char)) (return nil)))) (return t)))) (defun map-apropos (fun string &optional package external-only) "Call FUN with each symbol that contains STRING. If PACKAGE is supplied then only use symbols present in that package. If EXTERNAL-ONLY is true then only use symbols exported from the specified package." (let ((string (nstring-upcase (string-to-nfc (string string))))) (declare (simple-string string)) (flet ((apropos-in-package (package) (if external-only (do-external-symbols (symbol package) (if (and (eq (symbol-package symbol) package) (apropos-search symbol string)) (funcall fun symbol))) (do-symbols (symbol package) (if (and (eq (symbol-package symbol) package) (apropos-search symbol string)) (funcall fun symbol)))))) (if (null package) (mapc #'apropos-in-package (list-all-packages)) (apropos-in-package (package-or-lose package)))) nil)) (defun apropos (string &optional package) "Briefly describe all symbols which contain the specified STRING. If PACKAGE is supplied then only describe symbols present in that package. If EXTERNAL-ONLY is non-NIL then only describe external symbols in the specified package." (map-apropos #'briefly-describe-symbol string package) (values)) (defun apropos-list (string &optional package) "Identical to APROPOS, except that it returns a list of the symbols found instead of describing them." (collect ((result)) (map-apropos #'(lambda (symbol) (result symbol)) string package) (result))) The cold loader ( Genesis ) makes the data structure in * initial - symbols * . the Genesis source . (defvar *initial-symbols*) (defun package-init () (let ((*in-package-init* t)) (dolist (spec *initial-symbols*) (let* ((pkg (apply #'make-package (first spec))) (internal (package-internal-symbols pkg)) (external (package-external-symbols pkg))) (dolist (symbol (second spec)) (add-symbol internal symbol) (%set-symbol-package symbol pkg)) (dolist (symbol (third spec)) (add-symbol external symbol) (%set-symbol-package symbol pkg)) (dolist (symbol (fourth spec)) (add-symbol internal symbol)) (dolist (symbol (fifth spec)) (add-symbol external symbol)) (setf (package-%shadowing-symbols pkg) (sixth spec)))) (make-package "COMMON-LISP-USER" :nicknames '("CL-USER")) (dolist (args *deferred-use-packages*) (apply #'use-package args)) (makunbound '*deferred-use-packages*) (setq *lisp-package* (find-package "LISP")) (setq *keyword-package* (find-package "KEYWORD")) (setq *package* *lisp-package*)))
143e2bd7ad59e5b9de1e4311ee554a412e28707a7fbcc6b3ebf46b8631d3abd4
dmitryvk/sbcl-win32-threads
properties.impure.lisp
;;;; miscellaneous tests of symbol properties This software is part of the SBCL system . See the README file for ;;;; more information. ;;;; While most of SBCL is derived from the CMU CL system , the test ;;;; files (like this one) were written from scratch after the fork from CMU CL . ;;;; ;;;; This software is in the public domain and is provided with ;;;; absolutely no warranty. See the COPYING and CREDITS files for ;;;; more information. (in-package "CL-USER") (defun test-symbol (symbol) (setf (symbol-plist symbol) nil) (setf (get symbol 'foo) '(my list)) (setf (get symbol 'bar) 10) (setf (get symbol 'baz) t) (assert (eql (get symbol 'bar) 10)) (assert (= (length (symbol-plist symbol)) 6)) (remprop symbol 'foo) (assert (not (get symbol 'foo)))) (mapc #'test-symbol '(foo :keyword || t nil)) In early 0.7 versions on non - x86 ports , setting the property list ;;; of 'NIL would trash (CDR NIL), due to a screwup in the low-level ;;; layout of SYMBOL. (There are several low-level punnish tricks used ;;; to make NIL work both as a cons and as a symbol without requiring ;;; a lot of conditional branching at runtime.) (defparameter *nil-that-the-compiler-cannot-constant-fold* nil) (assert (not (car *nil-that-the-compiler-cannot-constant-fold*))) (assert (not (cdr *nil-that-the-compiler-cannot-constant-fold*))) ;;; success
null
https://raw.githubusercontent.com/dmitryvk/sbcl-win32-threads/5abfd64b00a0937ba2df2919f177697d1d91bde4/tests/properties.impure.lisp
lisp
miscellaneous tests of symbol properties more information. files (like this one) were written from scratch after the fork This software is in the public domain and is provided with absolutely no warranty. See the COPYING and CREDITS files for more information. of 'NIL would trash (CDR NIL), due to a screwup in the low-level layout of SYMBOL. (There are several low-level punnish tricks used to make NIL work both as a cons and as a symbol without requiring a lot of conditional branching at runtime.) success
This software is part of the SBCL system . See the README file for While most of SBCL is derived from the CMU CL system , the test from CMU CL . (in-package "CL-USER") (defun test-symbol (symbol) (setf (symbol-plist symbol) nil) (setf (get symbol 'foo) '(my list)) (setf (get symbol 'bar) 10) (setf (get symbol 'baz) t) (assert (eql (get symbol 'bar) 10)) (assert (= (length (symbol-plist symbol)) 6)) (remprop symbol 'foo) (assert (not (get symbol 'foo)))) (mapc #'test-symbol '(foo :keyword || t nil)) In early 0.7 versions on non - x86 ports , setting the property list (defparameter *nil-that-the-compiler-cannot-constant-fold* nil) (assert (not (car *nil-that-the-compiler-cannot-constant-fold*))) (assert (not (cdr *nil-that-the-compiler-cannot-constant-fold*)))
339e4c1b8f791230b4a95d31d5bcbac023c943ca2e721700d5ba3a9c4c85710e
fujita-y/ypsilon
programs.scm
#!nobacktrace (library (rnrs programs (6)) (export command-line exit) (import (core primitives)))
null
https://raw.githubusercontent.com/fujita-y/ypsilon/f742470e2810aabb7a7c898fd6c07227c14a725f/sitelib/rnrs/programs.scm
scheme
#!nobacktrace (library (rnrs programs (6)) (export command-line exit) (import (core primitives)))
b3ae583852afdb74623bf4f1191b6bcce3f5f71295814b2bc2e39fae8ca633b8
froydnj/ironclad
pkcs1.lisp
;;;; -*- mode: lisp; indent-tabs-mode: nil -*- pkcs1.lisp -- implementation of OAEP and PSS schemes (in-package :crypto) ;;; Mask generation function (defun mgf (digest-name seed num-bytes) "Expand the SEED to a NUM-BYTES bytes vector using the DIGEST-NAME digest." (loop with result = #() with digest-len = (digest-length digest-name) for digest = (make-digest digest-name) then (reinitialize-instance digest) for counter from 0 to (floor num-bytes digest-len) for counter-bytes = (integer-to-octets counter :n-bits 32) for tmp = (digest-sequence digest (concatenate '(vector (unsigned-byte 8)) seed counter-bytes)) do (setf result (concatenate '(vector (unsigned-byte 8)) result tmp)) finally (return (subseq result 0 num-bytes)))) (defun oaep-encode (digest-name message num-bytes &optional label) "Return a NUM-BYTES bytes vector containing the OAEP encoding of the MESSAGE using the DIGEST-NAME digest (and the optional LABEL octet vector)." (let ((digest-len (digest-length digest-name))) (assert (<= (length message) (- num-bytes (* 2 digest-len) 2))) (let* ((digest (make-digest digest-name)) (prng (or *prng* (make-prng :fortuna :seed :random))) (label (or label (coerce #() '(vector (unsigned-byte 8))))) (padding-len (- num-bytes (length message) (* 2 digest-len) 2)) (padding (make-array padding-len :element-type '(unsigned-byte 8) :initial-element 0)) (l-hash (digest-sequence digest label)) (db (concatenate '(vector (unsigned-byte 8)) l-hash padding #(1) message)) (seed (random-data digest-len prng)) (db-mask (mgf digest-name seed (- num-bytes digest-len 1))) (masked-db (map '(vector (unsigned-byte 8)) #'logxor db db-mask)) (seed-mask (mgf digest-name masked-db digest-len)) (masked-seed (map '(vector (unsigned-byte 8)) #'logxor seed seed-mask))) (concatenate '(vector (unsigned-byte 8)) #(0) masked-seed masked-db)))) (defun oaep-decode (digest-name message &optional label) "Return an octet vector containing the data that was encoded in the MESSAGE with OAEP using the DIGEST-NAME digest (and the optional LABEL octet vector)." (let ((digest-len (digest-length digest-name))) (assert (>= (length message) (+ (* 2 digest-len) 2))) (let* ((digest (make-digest digest-name)) (label (or label (coerce #() '(vector (unsigned-byte 8))))) (zero-byte (elt message 0)) (masked-seed (subseq message 1 (1+ digest-len))) (masked-db (subseq message (1+ digest-len))) (seed-mask (mgf digest-name masked-db digest-len)) (seed (map '(vector (unsigned-byte 8)) #'logxor masked-seed seed-mask)) (db-mask (mgf digest-name seed (- (length message) digest-len 1))) (db (map '(vector (unsigned-byte 8)) #'logxor masked-db db-mask)) (l-hash1 (digest-sequence digest label)) (l-hash2 (subseq db 0 digest-len)) (padding-len (loop for i from digest-len below (length db) while (zerop (elt db i)) finally (return (- i digest-len)))) (one-byte (elt db (+ digest-len padding-len)))) (unless (and (zerop zero-byte) (= 1 one-byte) (equalp l-hash1 l-hash2)) ;; FIXME: "real" ironclad error needed here (error "OAEP decoding error")) (subseq db (+ digest-len padding-len 1))))) (defun pss-encode (digest-name message num-bytes) (let ((digest-len (digest-length digest-name))) (assert (>= num-bytes (+ (* 2 digest-len) 2))) (let* ((prng (or *prng* (make-prng :fortuna :seed :random))) (m-hash (digest-sequence digest-name message)) (salt (random-data digest-len prng)) (m1 (concatenate '(vector (unsigned-byte 8)) #(0 0 0 0 0 0 0 0) m-hash salt)) (h (digest-sequence digest-name m1)) (ps (make-array (- num-bytes (* 2 digest-len) 2) :element-type '(unsigned-byte 8) :initial-element 0)) (db (concatenate '(vector (unsigned-byte 8)) ps #(1) salt)) (db-mask (mgf digest-name h (- num-bytes digest-len 1))) (masked-db (map '(vector (unsigned-byte 8)) #'logxor db db-mask))) (setf (ldb (byte 1 7) (elt masked-db 0)) 0) (concatenate '(vector (unsigned-byte 8)) masked-db h #(188))))) (defun pss-verify (digest-name message encoded-message) (let ((digest-len (digest-length digest-name)) (em-len (length encoded-message))) (assert (>= em-len (+ (* 2 digest-len) 2))) (assert (= (elt encoded-message (- em-len 1)) 188)) (let* ((m-hash (digest-sequence digest-name message)) (masked-db (subseq encoded-message 0 (- em-len digest-len 1))) (h (subseq encoded-message (- em-len digest-len 1) (- em-len 1))) (db-mask (mgf digest-name h (- em-len digest-len 1))) (db (map '(vector (unsigned-byte 8)) #'logxor masked-db db-mask))) (setf (ldb (byte 1 7) (elt db 0)) 0) (let* ((ps (subseq db 0 (- em-len (* 2 digest-len) 2))) (one-byte (elt db (- em-len (* 2 digest-len) 2))) (salt (subseq db (- (length db) digest-len))) (m1 (concatenate '(vector (unsigned-byte 8)) #(0 0 0 0 0 0 0 0) m-hash salt)) (h1 (digest-sequence digest-name m1))) (and (= 1 one-byte) (loop for i across ps always (zerop i)) (equalp h h1))))))
null
https://raw.githubusercontent.com/froydnj/ironclad/fe88483bba68eac4db3b48bb4a5a40035965fc84/src/public-key/pkcs1.lisp
lisp
-*- mode: lisp; indent-tabs-mode: nil -*- Mask generation function FIXME: "real" ironclad error needed here
pkcs1.lisp -- implementation of OAEP and PSS schemes (in-package :crypto) (defun mgf (digest-name seed num-bytes) "Expand the SEED to a NUM-BYTES bytes vector using the DIGEST-NAME digest." (loop with result = #() with digest-len = (digest-length digest-name) for digest = (make-digest digest-name) then (reinitialize-instance digest) for counter from 0 to (floor num-bytes digest-len) for counter-bytes = (integer-to-octets counter :n-bits 32) for tmp = (digest-sequence digest (concatenate '(vector (unsigned-byte 8)) seed counter-bytes)) do (setf result (concatenate '(vector (unsigned-byte 8)) result tmp)) finally (return (subseq result 0 num-bytes)))) (defun oaep-encode (digest-name message num-bytes &optional label) "Return a NUM-BYTES bytes vector containing the OAEP encoding of the MESSAGE using the DIGEST-NAME digest (and the optional LABEL octet vector)." (let ((digest-len (digest-length digest-name))) (assert (<= (length message) (- num-bytes (* 2 digest-len) 2))) (let* ((digest (make-digest digest-name)) (prng (or *prng* (make-prng :fortuna :seed :random))) (label (or label (coerce #() '(vector (unsigned-byte 8))))) (padding-len (- num-bytes (length message) (* 2 digest-len) 2)) (padding (make-array padding-len :element-type '(unsigned-byte 8) :initial-element 0)) (l-hash (digest-sequence digest label)) (db (concatenate '(vector (unsigned-byte 8)) l-hash padding #(1) message)) (seed (random-data digest-len prng)) (db-mask (mgf digest-name seed (- num-bytes digest-len 1))) (masked-db (map '(vector (unsigned-byte 8)) #'logxor db db-mask)) (seed-mask (mgf digest-name masked-db digest-len)) (masked-seed (map '(vector (unsigned-byte 8)) #'logxor seed seed-mask))) (concatenate '(vector (unsigned-byte 8)) #(0) masked-seed masked-db)))) (defun oaep-decode (digest-name message &optional label) "Return an octet vector containing the data that was encoded in the MESSAGE with OAEP using the DIGEST-NAME digest (and the optional LABEL octet vector)." (let ((digest-len (digest-length digest-name))) (assert (>= (length message) (+ (* 2 digest-len) 2))) (let* ((digest (make-digest digest-name)) (label (or label (coerce #() '(vector (unsigned-byte 8))))) (zero-byte (elt message 0)) (masked-seed (subseq message 1 (1+ digest-len))) (masked-db (subseq message (1+ digest-len))) (seed-mask (mgf digest-name masked-db digest-len)) (seed (map '(vector (unsigned-byte 8)) #'logxor masked-seed seed-mask)) (db-mask (mgf digest-name seed (- (length message) digest-len 1))) (db (map '(vector (unsigned-byte 8)) #'logxor masked-db db-mask)) (l-hash1 (digest-sequence digest label)) (l-hash2 (subseq db 0 digest-len)) (padding-len (loop for i from digest-len below (length db) while (zerop (elt db i)) finally (return (- i digest-len)))) (one-byte (elt db (+ digest-len padding-len)))) (unless (and (zerop zero-byte) (= 1 one-byte) (equalp l-hash1 l-hash2)) (error "OAEP decoding error")) (subseq db (+ digest-len padding-len 1))))) (defun pss-encode (digest-name message num-bytes) (let ((digest-len (digest-length digest-name))) (assert (>= num-bytes (+ (* 2 digest-len) 2))) (let* ((prng (or *prng* (make-prng :fortuna :seed :random))) (m-hash (digest-sequence digest-name message)) (salt (random-data digest-len prng)) (m1 (concatenate '(vector (unsigned-byte 8)) #(0 0 0 0 0 0 0 0) m-hash salt)) (h (digest-sequence digest-name m1)) (ps (make-array (- num-bytes (* 2 digest-len) 2) :element-type '(unsigned-byte 8) :initial-element 0)) (db (concatenate '(vector (unsigned-byte 8)) ps #(1) salt)) (db-mask (mgf digest-name h (- num-bytes digest-len 1))) (masked-db (map '(vector (unsigned-byte 8)) #'logxor db db-mask))) (setf (ldb (byte 1 7) (elt masked-db 0)) 0) (concatenate '(vector (unsigned-byte 8)) masked-db h #(188))))) (defun pss-verify (digest-name message encoded-message) (let ((digest-len (digest-length digest-name)) (em-len (length encoded-message))) (assert (>= em-len (+ (* 2 digest-len) 2))) (assert (= (elt encoded-message (- em-len 1)) 188)) (let* ((m-hash (digest-sequence digest-name message)) (masked-db (subseq encoded-message 0 (- em-len digest-len 1))) (h (subseq encoded-message (- em-len digest-len 1) (- em-len 1))) (db-mask (mgf digest-name h (- em-len digest-len 1))) (db (map '(vector (unsigned-byte 8)) #'logxor masked-db db-mask))) (setf (ldb (byte 1 7) (elt db 0)) 0) (let* ((ps (subseq db 0 (- em-len (* 2 digest-len) 2))) (one-byte (elt db (- em-len (* 2 digest-len) 2))) (salt (subseq db (- (length db) digest-len))) (m1 (concatenate '(vector (unsigned-byte 8)) #(0 0 0 0 0 0 0 0) m-hash salt)) (h1 (digest-sequence digest-name m1))) (and (= 1 one-byte) (loop for i across ps always (zerop i)) (equalp h h1))))))
9d94c8bcca37bf7a41b64ac01141c69743e8225de850ea88410387f1d29db31b
pveber/bistro
bistro_script.ml
open Base open Ppxlib module B = struct include Ast_builder.Make(struct let loc = Location.none end) let econstr s args = let args = match args with | [] -> None | [x] -> Some x | l -> Some (pexp_tuple l) in pexp_construct (Located.lident s) args let enil () = econstr "[]" [] let econs hd tl = econstr "::" [hd; tl] let elist l = List.fold_right ~f:econs l ~init:(enil ()) end module Position = struct type t = { cnum : int ; bol : int ; lnum : int ; } [@@deriving sexp] let zero = { cnum = 0 ; bol = 0 ; lnum = 0 } let shift p n = { p with cnum = p.cnum + n } let newline p = { cnum = p.cnum + 1 ; bol = p.cnum + 1 ; lnum = p.lnum + 1 } let translate_lexing_position (q : Lexing.position) ~by:p = { q with pos_lnum = p.lnum + q.pos_lnum ; pos_bol = if p.lnum = 0 then q.pos_bol - 2 else q.pos_cnum + p.bol ; pos_cnum = p.cnum + q.pos_cnum } let move_lexing_pos (p : t) (lp : Lexing.position) = { lp with pos_cnum = p.cnum ; pos_bol = p.bol ; pos_lnum = p.lnum } let move_loc (loc : Location.t) p q = { loc with loc_start = move_lexing_pos p loc.loc_start ; loc_end = move_lexing_pos q loc.loc_end } end type token = [ | `Text of Position.t * Position.t | `Antiquotation of Position.t * Position.t ] [@@deriving sexp] type lexing_error = [ | `Unmatched_opening_bracket of Position.t | `Unmatched_closing_bracket of Position.t ] [@@deriving sexp] type lexing_result = (token list, lexing_error) Result.t [@@deriving sexp] let lexer s : lexing_result = let n = String.length s in let opening i = i < n - 2 && Char.(s.[i] = '<' && s.[i + 1] = '<' && s.[i + 2] = '<') and closing i = i < n - 2 && Char.(s.[i] = '>' && s.[i + 1] = '>' && s.[i + 2] = '>') in let classify_current_pos { Position.cnum = i ; _ } = if i = n then `EOI else if Char.(s.[i] = '\n') then `Newline else if opening i then `Opening_bracket else if closing i then `Closing_bracket else `Text in let add_text_item acc start stop = if Position.(start.cnum < stop.cnum) then `Text (start, stop) :: acc else acc in let rec loop pos state acc = match classify_current_pos pos, state with | `EOI, `Quotation p -> Ok (List.rev (add_text_item acc p pos)) | `EOI, `Antiquotation (bracket_pos, _) -> Error (`Unmatched_opening_bracket bracket_pos) | `Opening_bracket, `Quotation p -> let newpos = Position.shift pos 3 in loop newpos (`Antiquotation (pos, newpos)) (add_text_item acc p pos) | `Opening_bracket, `Antiquotation (bracket_pos, _) -> Error (`Unmatched_opening_bracket bracket_pos) | `Closing_bracket, `Quotation _ -> Error (`Unmatched_closing_bracket pos) | `Closing_bracket, `Antiquotation (_, p) -> let newpos = Position.shift pos 3 in loop newpos (`Quotation newpos) (`Antiquotation (p, pos) :: acc) | `Newline, _ -> loop (Position.newline pos) state acc | `Text, _ -> loop (Position.shift pos 1) state acc in loop Position.zero (`Quotation Position.zero) [] let print_lexing_result r = r |> sexp_of_lexing_result |> Sexp.to_string_hum |> Stdio.print_string let%expect_test "text only" = print_lexing_result @@ lexer "rien" ; [%expect {| (Ok ((Text (((cnum 0) (bol 0) (lnum 0)) ((cnum 4) (bol 0) (lnum 0)))))) |}] let%expect_test "text + antiquot 1" = print_lexing_result @@ lexer "ad<<<a>>> <<<e>>>b" ; [%expect {| (Ok ((Text (((cnum 0) (bol 0) (lnum 0)) ((cnum 2) (bol 0) (lnum 0)))) (Antiquotation (((cnum 5) (bol 0) (lnum 0)) ((cnum 6) (bol 0) (lnum 0)))) (Text (((cnum 9) (bol 0) (lnum 0)) ((cnum 10) (bol 0) (lnum 0)))) (Antiquotation (((cnum 13) (bol 0) (lnum 0)) ((cnum 14) (bol 0) (lnum 0)))) (Text (((cnum 17) (bol 0) (lnum 0)) ((cnum 18) (bol 0) (lnum 0)))))) |}] let%expect_test "text + antiquot 2" = print_lexing_result @@ lexer "ri<<<en>>><<<>>>"; [%expect {| (Ok ((Text (((cnum 0) (bol 0) (lnum 0)) ((cnum 2) (bol 0) (lnum 0)))) (Antiquotation (((cnum 5) (bol 0) (lnum 0)) ((cnum 7) (bol 0) (lnum 0)))) (Antiquotation (((cnum 13) (bol 0) (lnum 0)) ((cnum 13) (bol 0) (lnum 0)))))) |}] let%expect_test "text + antiquot + eol" = print_lexing_result @@ lexer "ri<<<en>>>\n<<<du \n tout>>>"; [%expect {| (Ok ((Text (((cnum 0) (bol 0) (lnum 0)) ((cnum 2) (bol 0) (lnum 0)))) (Antiquotation (((cnum 5) (bol 0) (lnum 0)) ((cnum 7) (bol 0) (lnum 0)))) (Text (((cnum 10) (bol 0) (lnum 0)) ((cnum 11) (bol 11) (lnum 1)))) (Antiquotation (((cnum 14) (bol 11) (lnum 1)) ((cnum 23) (bol 18) (lnum 2)))))) |}] let translate_position (p : Lexing.position) ~from:(q : Lexing.position) = { q with pos_lnum = p.pos_lnum + q.pos_lnum - 1 ; pos_bol = if p.pos_lnum = 1 then q.pos_bol else q.pos_cnum + p.pos_bol ; pos_cnum = p.pos_cnum + q.pos_cnum } class ast_loc_transform = object inherit Ast.map method bool x = x method char c = c method int x = x method list f x = List.map x ~f method option f x = Option.map x ~f method string x = x end class ast_translation pos = object inherit ast_loc_transform method! location loc = { loc with loc_start = translate_position loc.loc_start ~from:pos ; loc_end = translate_position loc.loc_end ~from:pos } end let rewrite str loc = let module Location = Ocaml_common.Location in match lexer str with | Error (`Unmatched_closing_bracket p) -> let msg = "Unmatched closing bracket" in let loc = Position.move_loc loc p (Position.shift p 2) in let err = Location.error ~loc msg in raise (Location.Error err) | Error (`Unmatched_opening_bracket p) -> let msg = "Unmatched opening bracket" in let loc = Position.move_loc loc p (Position.shift p 2) in let err = Location.error ~loc msg in raise (Location.Error err) | Ok fragments -> List.map fragments ~f:(function | `Text (i, j) -> let i = i.Position.cnum in let j = j.Position.cnum in let e = B.estring (String.sub str ~pos:i ~len:(j - i)) in [%expr Bistro.Shell_dsl.string [%e e]] | `Antiquotation (i, j) -> let cnum_i = i.Position.cnum in let cnum_j = j.Position.cnum in let txt = String.sub str ~pos:cnum_i ~len:(cnum_j - cnum_i) in let e = Parse.expression (Lexing.from_string txt) in let i' = Position.translate_lexing_position ~by:i loc.loc_start in let j' = Position.translate_lexing_position ~by:j loc.loc_start in let loc' = Location.{ loc with loc_start = i' ; loc_end = j' } in (new ast_translation loc'.loc_start)#expression e ) |> B.elist |> (fun e -> [%expr Bistro.Shell_dsl.seq ~sep:"" [%e e]]) let rewriter ~loc:_ ~path:_ { txt = str ; loc } = rewrite str loc let loc_start file_name = { Lexing.pos_fname = file_name ; pos_lnum = 1 ; pos_bol = 0 ; pos_cnum = 0 ; } let loc_end ~file_name ~file_contents = let pos_fname = file_name in let last_line_number = Base.String.count file_contents ~f:Char.(( = ) '\n') in let last_line_length = match Base.String.rindex file_contents '\n' with | None -> String.length file_contents | Some i -> String.length file_contents - i in let pos_bol = last_line_length - 1 in let pos_cnum = String.length file_contents in let pos_lnum = last_line_number in { Lexing.pos_fname ; pos_lnum ; pos_bol ; pos_cnum } let includee_loc ~file_name ~file_contents = let loc_start = loc_start file_name in let loc_end = loc_end ~file_name ~file_contents in { Location.loc_start ; loc_end ; loc_ghost = false } let include_rewriter ~loc:_ ~path:_ { txt = fn ; loc } = match Stdio.In_channel.read_all fn with | contents -> let loc = includee_loc ~file_name:fn ~file_contents:contents in rewrite contents loc | exception _ -> let module Location = Ocaml_common.Location in let msg = Printf.sprintf "Cannot read %s from %s, have you forgot to add it in a preprocessor_deps field of your dune file?" (Stdlib.Sys.getcwd ()) fn in let err = Location.error ~loc msg in raise (Location.Error err)
null
https://raw.githubusercontent.com/pveber/bistro/d363bd2d8257babbcb6db15bd83fd6465df7c268/ppx/bistro_script.ml
ocaml
open Base open Ppxlib module B = struct include Ast_builder.Make(struct let loc = Location.none end) let econstr s args = let args = match args with | [] -> None | [x] -> Some x | l -> Some (pexp_tuple l) in pexp_construct (Located.lident s) args let enil () = econstr "[]" [] let econs hd tl = econstr "::" [hd; tl] let elist l = List.fold_right ~f:econs l ~init:(enil ()) end module Position = struct type t = { cnum : int ; bol : int ; lnum : int ; } [@@deriving sexp] let zero = { cnum = 0 ; bol = 0 ; lnum = 0 } let shift p n = { p with cnum = p.cnum + n } let newline p = { cnum = p.cnum + 1 ; bol = p.cnum + 1 ; lnum = p.lnum + 1 } let translate_lexing_position (q : Lexing.position) ~by:p = { q with pos_lnum = p.lnum + q.pos_lnum ; pos_bol = if p.lnum = 0 then q.pos_bol - 2 else q.pos_cnum + p.bol ; pos_cnum = p.cnum + q.pos_cnum } let move_lexing_pos (p : t) (lp : Lexing.position) = { lp with pos_cnum = p.cnum ; pos_bol = p.bol ; pos_lnum = p.lnum } let move_loc (loc : Location.t) p q = { loc with loc_start = move_lexing_pos p loc.loc_start ; loc_end = move_lexing_pos q loc.loc_end } end type token = [ | `Text of Position.t * Position.t | `Antiquotation of Position.t * Position.t ] [@@deriving sexp] type lexing_error = [ | `Unmatched_opening_bracket of Position.t | `Unmatched_closing_bracket of Position.t ] [@@deriving sexp] type lexing_result = (token list, lexing_error) Result.t [@@deriving sexp] let lexer s : lexing_result = let n = String.length s in let opening i = i < n - 2 && Char.(s.[i] = '<' && s.[i + 1] = '<' && s.[i + 2] = '<') and closing i = i < n - 2 && Char.(s.[i] = '>' && s.[i + 1] = '>' && s.[i + 2] = '>') in let classify_current_pos { Position.cnum = i ; _ } = if i = n then `EOI else if Char.(s.[i] = '\n') then `Newline else if opening i then `Opening_bracket else if closing i then `Closing_bracket else `Text in let add_text_item acc start stop = if Position.(start.cnum < stop.cnum) then `Text (start, stop) :: acc else acc in let rec loop pos state acc = match classify_current_pos pos, state with | `EOI, `Quotation p -> Ok (List.rev (add_text_item acc p pos)) | `EOI, `Antiquotation (bracket_pos, _) -> Error (`Unmatched_opening_bracket bracket_pos) | `Opening_bracket, `Quotation p -> let newpos = Position.shift pos 3 in loop newpos (`Antiquotation (pos, newpos)) (add_text_item acc p pos) | `Opening_bracket, `Antiquotation (bracket_pos, _) -> Error (`Unmatched_opening_bracket bracket_pos) | `Closing_bracket, `Quotation _ -> Error (`Unmatched_closing_bracket pos) | `Closing_bracket, `Antiquotation (_, p) -> let newpos = Position.shift pos 3 in loop newpos (`Quotation newpos) (`Antiquotation (p, pos) :: acc) | `Newline, _ -> loop (Position.newline pos) state acc | `Text, _ -> loop (Position.shift pos 1) state acc in loop Position.zero (`Quotation Position.zero) [] let print_lexing_result r = r |> sexp_of_lexing_result |> Sexp.to_string_hum |> Stdio.print_string let%expect_test "text only" = print_lexing_result @@ lexer "rien" ; [%expect {| (Ok ((Text (((cnum 0) (bol 0) (lnum 0)) ((cnum 4) (bol 0) (lnum 0)))))) |}] let%expect_test "text + antiquot 1" = print_lexing_result @@ lexer "ad<<<a>>> <<<e>>>b" ; [%expect {| (Ok ((Text (((cnum 0) (bol 0) (lnum 0)) ((cnum 2) (bol 0) (lnum 0)))) (Antiquotation (((cnum 5) (bol 0) (lnum 0)) ((cnum 6) (bol 0) (lnum 0)))) (Text (((cnum 9) (bol 0) (lnum 0)) ((cnum 10) (bol 0) (lnum 0)))) (Antiquotation (((cnum 13) (bol 0) (lnum 0)) ((cnum 14) (bol 0) (lnum 0)))) (Text (((cnum 17) (bol 0) (lnum 0)) ((cnum 18) (bol 0) (lnum 0)))))) |}] let%expect_test "text + antiquot 2" = print_lexing_result @@ lexer "ri<<<en>>><<<>>>"; [%expect {| (Ok ((Text (((cnum 0) (bol 0) (lnum 0)) ((cnum 2) (bol 0) (lnum 0)))) (Antiquotation (((cnum 5) (bol 0) (lnum 0)) ((cnum 7) (bol 0) (lnum 0)))) (Antiquotation (((cnum 13) (bol 0) (lnum 0)) ((cnum 13) (bol 0) (lnum 0)))))) |}] let%expect_test "text + antiquot + eol" = print_lexing_result @@ lexer "ri<<<en>>>\n<<<du \n tout>>>"; [%expect {| (Ok ((Text (((cnum 0) (bol 0) (lnum 0)) ((cnum 2) (bol 0) (lnum 0)))) (Antiquotation (((cnum 5) (bol 0) (lnum 0)) ((cnum 7) (bol 0) (lnum 0)))) (Text (((cnum 10) (bol 0) (lnum 0)) ((cnum 11) (bol 11) (lnum 1)))) (Antiquotation (((cnum 14) (bol 11) (lnum 1)) ((cnum 23) (bol 18) (lnum 2)))))) |}] let translate_position (p : Lexing.position) ~from:(q : Lexing.position) = { q with pos_lnum = p.pos_lnum + q.pos_lnum - 1 ; pos_bol = if p.pos_lnum = 1 then q.pos_bol else q.pos_cnum + p.pos_bol ; pos_cnum = p.pos_cnum + q.pos_cnum } class ast_loc_transform = object inherit Ast.map method bool x = x method char c = c method int x = x method list f x = List.map x ~f method option f x = Option.map x ~f method string x = x end class ast_translation pos = object inherit ast_loc_transform method! location loc = { loc with loc_start = translate_position loc.loc_start ~from:pos ; loc_end = translate_position loc.loc_end ~from:pos } end let rewrite str loc = let module Location = Ocaml_common.Location in match lexer str with | Error (`Unmatched_closing_bracket p) -> let msg = "Unmatched closing bracket" in let loc = Position.move_loc loc p (Position.shift p 2) in let err = Location.error ~loc msg in raise (Location.Error err) | Error (`Unmatched_opening_bracket p) -> let msg = "Unmatched opening bracket" in let loc = Position.move_loc loc p (Position.shift p 2) in let err = Location.error ~loc msg in raise (Location.Error err) | Ok fragments -> List.map fragments ~f:(function | `Text (i, j) -> let i = i.Position.cnum in let j = j.Position.cnum in let e = B.estring (String.sub str ~pos:i ~len:(j - i)) in [%expr Bistro.Shell_dsl.string [%e e]] | `Antiquotation (i, j) -> let cnum_i = i.Position.cnum in let cnum_j = j.Position.cnum in let txt = String.sub str ~pos:cnum_i ~len:(cnum_j - cnum_i) in let e = Parse.expression (Lexing.from_string txt) in let i' = Position.translate_lexing_position ~by:i loc.loc_start in let j' = Position.translate_lexing_position ~by:j loc.loc_start in let loc' = Location.{ loc with loc_start = i' ; loc_end = j' } in (new ast_translation loc'.loc_start)#expression e ) |> B.elist |> (fun e -> [%expr Bistro.Shell_dsl.seq ~sep:"" [%e e]]) let rewriter ~loc:_ ~path:_ { txt = str ; loc } = rewrite str loc let loc_start file_name = { Lexing.pos_fname = file_name ; pos_lnum = 1 ; pos_bol = 0 ; pos_cnum = 0 ; } let loc_end ~file_name ~file_contents = let pos_fname = file_name in let last_line_number = Base.String.count file_contents ~f:Char.(( = ) '\n') in let last_line_length = match Base.String.rindex file_contents '\n' with | None -> String.length file_contents | Some i -> String.length file_contents - i in let pos_bol = last_line_length - 1 in let pos_cnum = String.length file_contents in let pos_lnum = last_line_number in { Lexing.pos_fname ; pos_lnum ; pos_bol ; pos_cnum } let includee_loc ~file_name ~file_contents = let loc_start = loc_start file_name in let loc_end = loc_end ~file_name ~file_contents in { Location.loc_start ; loc_end ; loc_ghost = false } let include_rewriter ~loc:_ ~path:_ { txt = fn ; loc } = match Stdio.In_channel.read_all fn with | contents -> let loc = includee_loc ~file_name:fn ~file_contents:contents in rewrite contents loc | exception _ -> let module Location = Ocaml_common.Location in let msg = Printf.sprintf "Cannot read %s from %s, have you forgot to add it in a preprocessor_deps field of your dune file?" (Stdlib.Sys.getcwd ()) fn in let err = Location.error ~loc msg in raise (Location.Error err)
15f8b49d80b01e7c1bd72fe9613c5342c73830b0303a432af8453c290be81c26
sylane/erod
erod.erl
%%% ========================================================================== Copyright ( c ) 2014 < > %%% %%% This file is part of erod. %%% %%% Erod 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 </>. %%% ========================================================================== 2014 < > @author < > %%% @doc TODO: Document module erod. %%% @end %%% ========================================================================== -module(erod). -author('Sebastien Merle'). %%% ========================================================================== %%% Includes %%% ========================================================================== -include("erod_document.hrl"). -include("erod_policy.hrl"). %%% ========================================================================== %%% Exports %%% ========================================================================== %%% API functions -export([start_document/3]). %%% ========================================================================== %%% Types %%% ========================================================================== -type key() :: erodlib:erod_key(). -type version() :: erodlib:erod_version(). -type patch_path_part() :: erodlib:erod_patch_path_part(). -type patch_entry() :: erodlib:erod_patch_entry(). -type patch() :: erodlib:erod_patch(). -type view_id() :: atom(). -type page_id() :: pos_integer(). -type user_id() :: pos_integer(). -type session_id() :: pos_integer(). -type session_token() :: binary(). -type content_type() :: entity | patch. -type entity() :: tuple(). -type entity_item() :: {key(), entity()}. -type entity_items() :: list(entity_item()) | []. -type view_spec() :: {ViewId :: atom(), PageSize :: pos_integer(), OrderFun :: function()}. -type view_specs() :: list(view_spec()) | []. -type content() :: #erod_content{}. -type page() :: #erod_page{}. -type policy() :: #erod_policy{}. -type action_id() :: atom(). -type action_args() :: [term()] | []. -type action() :: {action_id(), action_args()}. -type actions() :: [action()] | []. -type document() :: erod_document:document(). -type context() :: erod_context:context(). -type proxy() :: erod_proxy:proxy(). -export_type([key/0, version/0, view_id/0, page_id/0, user_id/0, session_id/0, session_token/0, content_type/0, view_spec/0, view_specs/0, entity/0, entity_item/0, entity_items/0, patch_path_part/0, patch_entry/0, patch/0, content/0, page/0, policy/0, action_id/0, action_args/0, action/0, actions/0, document/0, context/0, proxy/0]). %%% ========================================================================== %%% API Functions %%% ========================================================================== %% ----------------------------------------------------------------- @doc Starts a document process for the gien document factory and options . %% @end %% ----------------------------------------------------------------- -spec start_document(DocKey, FactMod, Opts) -> {ok, Pid} | {error, Reason} when DocKey :: erod:key(), FactMod :: module(), Opts :: term(), Pid :: pid(), Reason :: term(). %% ----------------------------------------------------------------- start_document(DocKey, FactMod, Opts) -> erod_document_sup:start_child(DocKey, FactMod, Opts).
null
https://raw.githubusercontent.com/sylane/erod/b0c435f8546ea38b1501d3e22614fe7951c61c9a/apps/erod/src/erod.erl
erlang
========================================================================== This file is part of erod. Erod 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 </>. ========================================================================== @doc TODO: Document module erod. @end ========================================================================== ========================================================================== Includes ========================================================================== ========================================================================== Exports ========================================================================== API functions ========================================================================== Types ========================================================================== ========================================================================== API Functions ========================================================================== ----------------------------------------------------------------- @end ----------------------------------------------------------------- -----------------------------------------------------------------
Copyright ( c ) 2014 < > 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 2014 < > @author < > -module(erod). -author('Sebastien Merle'). -include("erod_document.hrl"). -include("erod_policy.hrl"). -export([start_document/3]). -type key() :: erodlib:erod_key(). -type version() :: erodlib:erod_version(). -type patch_path_part() :: erodlib:erod_patch_path_part(). -type patch_entry() :: erodlib:erod_patch_entry(). -type patch() :: erodlib:erod_patch(). -type view_id() :: atom(). -type page_id() :: pos_integer(). -type user_id() :: pos_integer(). -type session_id() :: pos_integer(). -type session_token() :: binary(). -type content_type() :: entity | patch. -type entity() :: tuple(). -type entity_item() :: {key(), entity()}. -type entity_items() :: list(entity_item()) | []. -type view_spec() :: {ViewId :: atom(), PageSize :: pos_integer(), OrderFun :: function()}. -type view_specs() :: list(view_spec()) | []. -type content() :: #erod_content{}. -type page() :: #erod_page{}. -type policy() :: #erod_policy{}. -type action_id() :: atom(). -type action_args() :: [term()] | []. -type action() :: {action_id(), action_args()}. -type actions() :: [action()] | []. -type document() :: erod_document:document(). -type context() :: erod_context:context(). -type proxy() :: erod_proxy:proxy(). -export_type([key/0, version/0, view_id/0, page_id/0, user_id/0, session_id/0, session_token/0, content_type/0, view_spec/0, view_specs/0, entity/0, entity_item/0, entity_items/0, patch_path_part/0, patch_entry/0, patch/0, content/0, page/0, policy/0, action_id/0, action_args/0, action/0, actions/0, document/0, context/0, proxy/0]). @doc Starts a document process for the gien document factory and options . -spec start_document(DocKey, FactMod, Opts) -> {ok, Pid} | {error, Reason} when DocKey :: erod:key(), FactMod :: module(), Opts :: term(), Pid :: pid(), Reason :: term(). start_document(DocKey, FactMod, Opts) -> erod_document_sup:start_child(DocKey, FactMod, Opts).
55abd67a938ee1ae9230a11dca164c2434770203057921a5fede7c2114ace073
tomjaguarpaw/haskell-opaleye
Unpackspec.hs
# LANGUAGE MultiParamTypeClasses , FlexibleInstances # module Opaleye.SQLite.Internal.Unpackspec where import qualified Opaleye.SQLite.Internal.PackMap as PM import qualified Opaleye.SQLite.Internal.Column as IC import qualified Opaleye.SQLite.Column as C import Control.Applicative (Applicative, pure, (<*>)) import Data.Profunctor (Profunctor, dimap) import Data.Profunctor.Product (ProductProfunctor, empty, (***!)) import qualified Data.Profunctor.Product as PP import qualified Data.Profunctor.Product.Default as D import qualified Opaleye.SQLite.Internal.HaskellDB.PrimQuery as HPQ newtype Unpackspec columns columns' = | An ' Unpackspec ' @columns@ @columns'@ allows you to extract and modify a sequence of ' HPQ.PrimExpr 's inside a value of type -- @columns@. -- For example , the ' Default ' instance of type ' Unpackspec ' @(Column a , Column b)@ @(Column a , Column b)@ allows you to manipulate or extract the two ' HPQ.PrimExpr 's inside a @(Column a , Column b)@. The ' Default ' instance of type @Foo ( Column a ) ( Column b ) ( Column c)@ will allow you to manipulate or extract the three ' HPQ.PrimExpr 's -- contained therein (for a user-defined product type @Foo@, assuming the @makeAdaptorAndInstance@ splice from -- @Data.Profunctor.Product.TH@ has been run). -- You can create ' Unpackspec 's by hand using ' unpackspecColumn ' and the ' Profunctor ' , ' ProductProfunctor ' and ' SumProfunctor ' -- operations. However, in practice users should almost never need -- to create or manipulate them. Typically they will be created -- automatically by the 'D.Default' instance. Unpackspec (PM.PackMap HPQ.PrimExpr HPQ.PrimExpr columns columns') -- | Target the single 'HPQ.PrimExpr' inside a 'C.Column' unpackspecColumn :: Unpackspec (C.Column a) (C.Column a) unpackspecColumn = Unpackspec (PM.PackMap (\f (IC.Column pe) -> fmap IC.Column (f pe))) -- | Modify all the targeted 'HPQ.PrimExpr's runUnpackspec :: Applicative f => Unpackspec columns b -> (HPQ.PrimExpr -> f HPQ.PrimExpr) -> columns -> f b runUnpackspec (Unpackspec f) = PM.traversePM f -- | Extract all the targeted 'HPQ.PrimExpr's collectPEs :: Unpackspec s t -> s -> [HPQ.PrimExpr] collectPEs unpackspec = fst . runUnpackspec unpackspec f where f pe = ([pe], pe) instance D.Default Unpackspec (C.Column a) (C.Column a) where def = unpackspecColumn -- { -- Boilerplate instance definitions. Theoretically, these are derivable. instance Functor (Unpackspec a) where fmap f (Unpackspec g) = Unpackspec (fmap f g) instance Applicative (Unpackspec a) where pure = Unpackspec . pure Unpackspec f <*> Unpackspec x = Unpackspec (f <*> x) instance Profunctor Unpackspec where dimap f g (Unpackspec q) = Unpackspec (dimap f g q) instance ProductProfunctor Unpackspec where empty = PP.defaultEmpty (***!) = PP.defaultProfunctorProduct instance PP.SumProfunctor Unpackspec where Unpackspec x1 +++! Unpackspec x2 = Unpackspec (x1 PP.+++! x2) --}
null
https://raw.githubusercontent.com/tomjaguarpaw/haskell-opaleye/b7aacc07c6392654cae439fc3b997620c3aa7a87/opaleye-sqlite/src/Opaleye/SQLite/Internal/Unpackspec.hs
haskell
@columns@. contained therein (for a user-defined product type @Foo@, assuming @Data.Profunctor.Product.TH@ has been run). operations. However, in practice users should almost never need to create or manipulate them. Typically they will be created automatically by the 'D.Default' instance. | Target the single 'HPQ.PrimExpr' inside a 'C.Column' | Modify all the targeted 'HPQ.PrimExpr's | Extract all the targeted 'HPQ.PrimExpr's { Boilerplate instance definitions. Theoretically, these are derivable. }
# LANGUAGE MultiParamTypeClasses , FlexibleInstances # module Opaleye.SQLite.Internal.Unpackspec where import qualified Opaleye.SQLite.Internal.PackMap as PM import qualified Opaleye.SQLite.Internal.Column as IC import qualified Opaleye.SQLite.Column as C import Control.Applicative (Applicative, pure, (<*>)) import Data.Profunctor (Profunctor, dimap) import Data.Profunctor.Product (ProductProfunctor, empty, (***!)) import qualified Data.Profunctor.Product as PP import qualified Data.Profunctor.Product.Default as D import qualified Opaleye.SQLite.Internal.HaskellDB.PrimQuery as HPQ newtype Unpackspec columns columns' = | An ' Unpackspec ' @columns@ @columns'@ allows you to extract and modify a sequence of ' HPQ.PrimExpr 's inside a value of type For example , the ' Default ' instance of type ' Unpackspec ' @(Column a , Column b)@ @(Column a , Column b)@ allows you to manipulate or extract the two ' HPQ.PrimExpr 's inside a @(Column a , Column b)@. The ' Default ' instance of type @Foo ( Column a ) ( Column b ) ( Column c)@ will allow you to manipulate or extract the three ' HPQ.PrimExpr 's the @makeAdaptorAndInstance@ splice from You can create ' Unpackspec 's by hand using ' unpackspecColumn ' and the ' Profunctor ' , ' ProductProfunctor ' and ' SumProfunctor ' Unpackspec (PM.PackMap HPQ.PrimExpr HPQ.PrimExpr columns columns') unpackspecColumn :: Unpackspec (C.Column a) (C.Column a) unpackspecColumn = Unpackspec (PM.PackMap (\f (IC.Column pe) -> fmap IC.Column (f pe))) runUnpackspec :: Applicative f => Unpackspec columns b -> (HPQ.PrimExpr -> f HPQ.PrimExpr) -> columns -> f b runUnpackspec (Unpackspec f) = PM.traversePM f collectPEs :: Unpackspec s t -> s -> [HPQ.PrimExpr] collectPEs unpackspec = fst . runUnpackspec unpackspec f where f pe = ([pe], pe) instance D.Default Unpackspec (C.Column a) (C.Column a) where def = unpackspecColumn instance Functor (Unpackspec a) where fmap f (Unpackspec g) = Unpackspec (fmap f g) instance Applicative (Unpackspec a) where pure = Unpackspec . pure Unpackspec f <*> Unpackspec x = Unpackspec (f <*> x) instance Profunctor Unpackspec where dimap f g (Unpackspec q) = Unpackspec (dimap f g q) instance ProductProfunctor Unpackspec where empty = PP.defaultEmpty (***!) = PP.defaultProfunctorProduct instance PP.SumProfunctor Unpackspec where Unpackspec x1 +++! Unpackspec x2 = Unpackspec (x1 PP.+++! x2)
e6cf36b69ef83b900b2db3061327fc666be72820fe18d9a4bb5103eac670d847
haskell-opengl/OpenGLRaw
TextureEnvCombine4.hs
# LANGUAGE PatternSynonyms # -------------------------------------------------------------------------------- -- | -- Module : Graphics.GL.NV.TextureEnvCombine4 Copyright : ( c ) 2019 -- License : BSD3 -- Maintainer : < > -- Stability : stable -- Portability : portable -- -------------------------------------------------------------------------------- module Graphics.GL.NV.TextureEnvCombine4 ( -- * Extension Support glGetNVTextureEnvCombine4, gl_NV_texture_env_combine4, -- * Enums pattern GL_COMBINE4_NV, pattern GL_OPERAND3_ALPHA_NV, pattern GL_OPERAND3_RGB_NV, pattern GL_SOURCE3_ALPHA_NV, pattern GL_SOURCE3_RGB_NV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
null
https://raw.githubusercontent.com/haskell-opengl/OpenGLRaw/57e50c9d28dfa62d6a87ae9b561af28f64ce32a0/src/Graphics/GL/NV/TextureEnvCombine4.hs
haskell
------------------------------------------------------------------------------ | Module : Graphics.GL.NV.TextureEnvCombine4 License : BSD3 Stability : stable Portability : portable ------------------------------------------------------------------------------ * Extension Support * Enums
# LANGUAGE PatternSynonyms # Copyright : ( c ) 2019 Maintainer : < > module Graphics.GL.NV.TextureEnvCombine4 ( glGetNVTextureEnvCombine4, gl_NV_texture_env_combine4, pattern GL_COMBINE4_NV, pattern GL_OPERAND3_ALPHA_NV, pattern GL_OPERAND3_RGB_NV, pattern GL_SOURCE3_ALPHA_NV, pattern GL_SOURCE3_RGB_NV ) where import Graphics.GL.ExtensionPredicates import Graphics.GL.Tokens
9d32659e349599b61c7eb1e20f702cfdc7de8b8e839cfcdba579218791e1642a
bsaleil/lc
etape1-sub2.scm
(let ((a 7) (b 3)) (println (- a b))) (let ((a -7) (b 3)) (println (- a b))) (let ((a 7) (b -3)) (println (- a b))) (let ((a -7) (b -3)) (println (- a b))) 4 ;-10 10 ;-4
null
https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/unit-tests/IFT3065/1/etape1-sub2.scm
scheme
-10 -4
(let ((a 7) (b 3)) (println (- a b))) (let ((a -7) (b 3)) (println (- a b))) (let ((a 7) (b -3)) (println (- a b))) (let ((a -7) (b -3)) (println (- a b))) 4 10
824445019f296e8fbc420530e34bec054e6e8a0181d59e7f493d0d20a9c81aa0
awkward-squad/ki
Scope.hs
module Ki.Internal.Scope ( Scope, scoped, awaitAll, fork, forkWith, forkWith_, fork_, forkTry, forkTryWith, ) where import qualified Control.Concurrent import Control.Exception ( Exception (fromException, toException), MaskingState (..), SomeAsyncException, asyncExceptionFromException, asyncExceptionToException, catch, pattern ErrorCall, ) import qualified Data.IntMap.Lazy as IntMap import Data.Void (Void, absurd) import GHC.Conc ( STM, TVar, atomically, enableAllocationLimit, labelThread, newTVarIO, readTVar, retry, setAllocationCounter, throwSTM, writeTVar, ) import GHC.IO (unsafeUnmask) import Ki.Internal.ByteCount import Ki.Internal.Counter import Ki.Internal.Prelude import Ki.Internal.Thread import GHC.Conc.Sync (readTVarIO) -- | A scope. -- -- ==== __👉 Details__ -- -- * A scope delimits the lifetime of all threads created within it. -- -- * A scope is only valid during the callback provided to 'Ki.scoped'. -- -- * The thread that creates a scope is considered the parent of all threads created within it. -- * All threads created within a scope can be awaited together ( see ' ' ) . -- -- * All threads created within a scope are terminated when the scope closes. data Scope = Scope The MVar that a child tries to put to , in the case that it tries to propagate an exception to its parent , but -- gets delivered an exception from its parent concurrently (which interrupts the throw). The parent must raise -- exceptions in its children with asynchronous exceptions uninterruptibly masked for correctness, yet we don't want -- a parent in the process of tearing down to miss/ignore this exception that we're trying to propagate? -- Why a single - celled MVar ? What if two siblings are fighting to inform their parent of their death ? Well , only one exception can be propagated by the parent anyway , so we would n't need or want both . childExceptionVar :: {-# UNPACK #-} !(MVar SomeException), -- The set of child threads that are currently running, each keyed by a monotonically increasing int. childrenVar :: {-# UNPACK #-} !(TVar (IntMap ThreadId)), -- The counter that holds the (int) key to use for the next child thread. nextChildIdCounter :: {-# UNPACK #-} !Counter, -- The id of the thread that created the scope, which is considered the parent of all threads created within it. parentThreadId :: {-# UNPACK #-} !ThreadId, The number of child threads that are guaranteed to be about to start , in the sense that only the GHC scheduler can continue to delay ; there 's no opportunity for an async exception to strike and prevent one of these threads -- from starting. -- -- Sentinel value: -1 means the scope is closed. startingVar :: {-# UNPACK #-} !(TVar Int) } Internal async exception thrown by a parent thread to its children when the scope is closing . data ScopeClosing = ScopeClosing instance Show ScopeClosing where show _ = "ScopeClosing" instance Exception ScopeClosing where toException = asyncExceptionToException fromException = asyncExceptionFromException -- Trust without verifying that any 'ScopeClosed' exception, which is not exported by this module, was indeed thrown to -- a thread by its parent. It is possible to write a program that violates this (just catch the async exception and -- throw it to some other thread)... but who would do that? isScopeClosingException :: SomeException -> Bool isScopeClosingException exception = case fromException exception of Just ScopeClosing -> True _ -> False pattern IsScopeClosingException :: SomeException pattern IsScopeClosingException <- (isScopeClosingException -> True) -- | Open a scope, perform an IO action with it, then close the scope. -- -- ==== __👉 Details__ -- -- * The thread that creates a scope is considered the parent of all threads created within it. -- -- * A scope is only valid during the callback provided to 'Ki.scoped'. -- -- * When a scope closes (/i.e./ just before 'Ki.scoped' returns): -- -- * The parent thread raises an exception in all of its living children. -- * The parent thread blocks until those threads terminate. scoped :: (Scope -> IO a) -> IO a scoped action = do scope@Scope {childExceptionVar, childrenVar, startingVar} <- allocateScope uninterruptibleMask \restore -> do result <- try (restore (action scope)) !livingChildren <- do livingChildren0 <- atomically do -- Block until we haven't committed to starting any threads. Without this, we may create a thread concurrently -- with closing its scope, and not grab its thread id to throw an exception to. blockUntil0 startingVar -- Write the sentinel value indicating that this scope is closed, and it is an error to try to create a thread -- within it. writeTVar startingVar (-1) -- Return the list of currently-running children to kill. Some of them may have *just* started (e.g. if we -- initially retried in `blockUntil0` above). That's fine - kill them all! readTVar childrenVar -- If one of our children propagated an exception to us, then we know it's about to terminate, so we don't bother -- throwing an exception to it. pure case result of Left (fromException -> Just ThreadFailed {childId}) -> IntMap.delete childId livingChildren0 _ -> livingChildren0 -- Deliver a ScopeClosing exception to every living child. -- -- This happens to throw in the order the children were created... but I think we decided this feature isn't very -- useful in practice, so maybe we should simplify the internals and just keep a set of children? for_ (IntMap.elems livingChildren) \livingChild -> throwTo livingChild ScopeClosing -- Block until all children have terminated; this relies on children respecting the async exception, which they -- must, for correctness. Otherwise, a thread could indeed outlive the scope in which it's created, which is -- definitely not structured concurrency! atomically (blockUntilEmpty childrenVar) By now there are three sources of exception : -- -- 1) A sync or async exception thrown during the callback, captured in `result`. If applicable, we want to unwrap -- the `ThreadFailed` off of this, which was only used to indicate it came from one of our children. -- -- 2) A sync or async exception left for us in `childExceptionVar` by a child that tried to propagate it to us -- directly, but failed (because we killed it concurrently). -- -- 3) An async exception waiting in our exception queue, because we still have async exceptions uninterruptibly -- masked. -- We can not throw more than one , so throw them in that priority order . case result of Left exception -> throwIO (unwrapThreadFailed exception) Right value -> tryTakeMVar childExceptionVar >>= \case Nothing -> pure value Just exception -> throwIO exception -- Allocate a new scope. allocateScope :: IO Scope allocateScope = do childExceptionVar <- newEmptyMVar childrenVar <- newTVarIO IntMap.empty nextChildIdCounter <- newCounter parentThreadId <- myThreadId startingVar <- newTVarIO 0 pure Scope {childExceptionVar, childrenVar, nextChildIdCounter, parentThreadId, startingVar} -- Spawn a thread in a scope, providing it its child id and a function that sets the masking state to the requested masking state . The given action is called with async exceptions interruptibly masked . spawn :: Scope -> ThreadOptions -> (Int -> (forall x. IO x -> IO x) -> UnexceptionalIO ()) -> IO ThreadId spawn Scope {childrenVar, nextChildIdCounter, startingVar} ThreadOptions {affinity, allocationLimit, label, maskingState = requestedChildMaskingState} action = do Interruptible mask is enough so long as none of the STM operations below block . -- Unconditionally set masking state to MaskedInterruptible , even though we might already be at MaskedInterruptible or MaskedUninterruptible , to avoid a branch on parentMaskingState . interruptiblyMasked do -- Record the thread as being about to start. Not allowed to retry. atomically do n <- readTVar startingVar if n < 0 then throwSTM (ErrorCall "ki: scope closed") else writeTVar startingVar $! n + 1 childId <- incrCounter nextChildIdCounter childThreadId <- forkWithAffinity affinity do when (not (null label)) do childThreadId <- myThreadId labelThread childThreadId label case allocationLimit of Nothing -> pure () Just bytes -> do setAllocationCounter (byteCountToInt64 bytes) enableAllocationLimit Action that sets the masking state from the current ( MaskedInterruptible ) to the requested one . atRequestedMaskingState :: IO a -> IO a atRequestedMaskingState = case requestedChildMaskingState of Unmasked -> unsafeUnmask MaskedInterruptible -> id MaskedUninterruptible -> uninterruptiblyMasked runUnexceptionalIO (action childId atRequestedMaskingState) atomically (unrecordChild childrenVar childId) -- Record the child as having started. Not allowed to retry. atomically do n <- readTVar startingVar writeTVar startingVar $! n - 1 -- it's actually ok to go from e.g. -1 to -2 here (very unlikely) recordChild childrenVar childId childThreadId pure childThreadId -- Record our child by either: -- -- * Flipping `Nothing` to `Just childThreadId` (common case: we record child before it unrecords itself) -- * Flipping `Just _` to `Nothing` (uncommon case: we observe that a child already unrecorded itself) -- -- Never retries. recordChild :: TVar (IntMap ThreadId) -> Int -> ThreadId -> STM () recordChild childrenVar childId childThreadId = do children <- readTVar childrenVar writeTVar childrenVar $! IntMap.alter (maybe (Just childThreadId) (const Nothing)) childId children Unrecord a child ( ourselves ) by either : -- * Flipping ` Just childThreadId ` to ` Nothing ` ( common case : parent recorded us first ) * Flipping ` Nothing ` to ` Just undefined ` ( uncommon case : we terminate and unrecord before parent can record us ) . -- -- Never retries. unrecordChild :: TVar (IntMap ThreadId) -> Int -> STM () unrecordChild childrenVar childId = do children <- readTVar childrenVar writeTVar childrenVar $! IntMap.alter (maybe (Just undefined) (const Nothing)) childId children -- forkIO/forkOn/forkOS, switching on affinity forkWithAffinity :: ThreadAffinity -> IO () -> IO ThreadId forkWithAffinity = \case Unbound -> forkIO Capability n -> forkOn n OsThread -> Control.Concurrent.forkOS -- | Wait until all threads created within a scope terminate. awaitAll :: Scope -> STM () awaitAll Scope {childrenVar, startingVar} = do blockUntilEmpty childrenVar blockUntil0 startingVar Block until an IntMap becomes empty . blockUntilEmpty :: TVar (IntMap a) -> STM () blockUntilEmpty var = do x <- readTVar var if IntMap.null x then pure () else retry Block until a TVar becomes 0 . blockUntil0 :: TVar Int -> STM () blockUntil0 var = do x <- readTVar var if x == 0 then pure () else retry -- | Create a child thread to execute an action within a scope. -- -- /Note/: The child thread does not mask asynchronous exceptions, regardless of the parent thread's masking state. To -- create a child thread with a different initial masking state, use 'Ki.forkWith'. fork :: Scope -> IO a -> IO (Thread a) fork scope = forkWith scope defaultThreadOptions -- | Variant of 'Ki.fork' for threads that never return. fork_ :: Scope -> IO Void -> IO () fork_ scope = forkWith_ scope defaultThreadOptions -- | Variant of 'Ki.fork' that takes an additional options argument. forkWith :: Scope -> ThreadOptions -> IO a -> IO (Thread a) forkWith scope opts action = do resultVar <- newTVarIO Nothing ident <- spawn scope opts \childId masking -> do result <- unexceptionalTry (masking action) case result of Left exception -> when (not (isScopeClosingException exception)) (propagateException scope childId exception) Right _ -> pure () -- even put async exceptions that we propagated. this isn't totally ideal because a caller awaiting this thread -- would not be able to distinguish between async exceptions delivered to this thread, or itself UnexceptionalIO (atomically (writeTVar resultVar (Just result))) let doAwait = readTVar resultVar >>= \case Nothing -> retry Just (Left exception) -> throwSTM exception Just (Right value) -> pure value pure (makeThread ident doAwait) -- | Variant of 'Ki.forkWith' for threads that never return. forkWith_ :: Scope -> ThreadOptions -> IO Void -> IO () forkWith_ scope opts action = do _childThreadId <- spawn scope opts \childId masking -> unexceptionalTryEither (\exception -> when (not (isScopeClosingException exception)) (propagateException scope childId exception)) absurd (masking action) pure () -- | Like 'Ki.fork', but the child thread does not propagate exceptions that are both: -- -- * Synchronous (/i.e./ not an instance of 'SomeAsyncException'). * An instance of @e@. forkTry :: forall e a. Exception e => Scope -> IO a -> IO (Thread (Either e a)) forkTry scope = forkTryWith scope defaultThreadOptions -- | Variant of 'Ki.forkTry' that takes an additional options argument. forkTryWith :: forall e a. Exception e => Scope -> ThreadOptions -> IO a -> IO (Thread (Either e a)) forkTryWith scope opts action = do resultVar <- newTVarIO Nothing childThreadId <- spawn scope opts \childId masking -> do result <- unexceptionalTry (masking action) case result of Left exception -> do let shouldPropagate = if isScopeClosingException exception then False else case fromException @e exception of Nothing -> True -- if the user calls `forkTry @MyAsyncException`, we still want to propagate the async exception Just _ -> isAsyncException exception when shouldPropagate (propagateException scope childId exception) Right _value -> pure () UnexceptionalIO (atomically (writeTVar resultVar (Just result))) let doAwait = readTVar resultVar >>= \case Nothing -> retry Just (Left exception) -> case fromException @e exception of Nothing -> throwSTM exception Just expectedException -> pure (Left expectedException) Just (Right value) -> pure (Right value) pure (makeThread childThreadId doAwait) where isAsyncException :: SomeException -> Bool isAsyncException exception = case fromException @SomeAsyncException exception of Nothing -> False Just _ -> True -- We have a non-`ScopeClosing` exception to propagate to our parent. -- -- If our scope has already begun closing (`startingVar` is -1), then either... -- ( A ) We already received a ` ScopeClosing ` , but then ended up trying to propagate an exception anyway , because we -- threw a synchronous exception (or were hit by a different asynchronous exception) during our teardown procedure. -- -- or -- ( B ) We will receive a ` ScopeClosing ` imminently , because our parent has * just * finished setting ` startingVar ` to -- -1, and will proceed to throw ScopeClosing to all of its children. -- -- If (A), our parent has asynchronous exceptions masked, so we must inform it of our exception via `childExceptionVar` -- rather than throwTo. If (B), either mechanism would work. And because we don't if we're in case (A) or (B), we just -- `childExceptionVar`. -- -- And if our scope has not already begun closing (`startingVar` is not -1), then we ought to throw our exception to it. -- But that might fail due to either... -- ( C ) Our parent concurrently closing the scope and sending us a ` ScopeClosing ` ; because it has asynchronous -- exceptions uninterruptibly masked and we only have asynchronous exception *synchronously* masked, its `throwTo` will return ` ( ) ` , and ours will throw that ` ScopeClosing ` asynchronous exception . In this case , since we now know -- our parent is tearing down and has asynchronous exceptions masked, we again inform it via `childExceptionVar`. -- -- (D) Some *other* non-`ScopeClosing` asynchronous exception is raised here. This is truly odd: maybe it's a heap overflow exception from the GHC runtime ? Maybe some other thread has smuggled our ` ThreadId ` out and has manually -- thrown us an exception for some reason? Either way, because we already have an exception that we are trying to -- propagate, we just scoot these freaky exceptions under the rug. -- Precondition : interruptibly masked propagateException :: Scope -> Int -> SomeException -> UnexceptionalIO () propagateException Scope {childExceptionVar, parentThreadId, startingVar} childId exception = UnexceptionalIO (readTVarIO startingVar) >>= \case -1 -> tryPutChildExceptionVar -- (A) / (B) _ -> loop where loop :: UnexceptionalIO () loop = unexceptionalTry (throwTo parentThreadId ThreadFailed {childId, exception}) >>= \case Left IsScopeClosingException -> tryPutChildExceptionVar -- (C) Left _ -> loop -- (D) Right _ -> pure () tryPutChildExceptionVar :: UnexceptionalIO () tryPutChildExceptionVar = UnexceptionalIO (void (tryPutMVar childExceptionVar exception)) -- A little promise that this IO action cannot throw an exception. -- -- Yeah it's verbose, and maybe not that necessary, but the code that bothers to use it really does require -- un-exceptiony IO actions for correctness, so here we are. newtype UnexceptionalIO a = UnexceptionalIO {runUnexceptionalIO :: IO a} deriving newtype (Applicative, Functor, Monad) unexceptionalTry :: forall a. IO a -> UnexceptionalIO (Either SomeException a) unexceptionalTry = coerce @(IO a -> IO (Either SomeException a)) try -- Like try, but with continuations. Also, catches all exceptions, because that's the only flavor we need. unexceptionalTryEither :: forall a b. (SomeException -> UnexceptionalIO b) -> (a -> UnexceptionalIO b) -> IO a -> UnexceptionalIO b unexceptionalTryEither onFailure onSuccess action = UnexceptionalIO do join do catch (coerce @_ @(a -> IO b) onSuccess <$> action) (pure . coerce @_ @(SomeException -> IO b) onFailure)
null
https://raw.githubusercontent.com/awkward-squad/ki/efbccde4bbf24d5983386b9621cd0868dbe163c0/ki/src/Ki/Internal/Scope.hs
haskell
| A scope. ==== __👉 Details__ * A scope delimits the lifetime of all threads created within it. * A scope is only valid during the callback provided to 'Ki.scoped'. * The thread that creates a scope is considered the parent of all threads created within it. * All threads created within a scope are terminated when the scope closes. gets delivered an exception from its parent concurrently (which interrupts the throw). The parent must raise exceptions in its children with asynchronous exceptions uninterruptibly masked for correctness, yet we don't want a parent in the process of tearing down to miss/ignore this exception that we're trying to propagate? # UNPACK # The set of child threads that are currently running, each keyed by a monotonically increasing int. # UNPACK # The counter that holds the (int) key to use for the next child thread. # UNPACK # The id of the thread that created the scope, which is considered the parent of all threads created within it. # UNPACK # from starting. Sentinel value: -1 means the scope is closed. # UNPACK # Trust without verifying that any 'ScopeClosed' exception, which is not exported by this module, was indeed thrown to a thread by its parent. It is possible to write a program that violates this (just catch the async exception and throw it to some other thread)... but who would do that? | Open a scope, perform an IO action with it, then close the scope. ==== __👉 Details__ * The thread that creates a scope is considered the parent of all threads created within it. * A scope is only valid during the callback provided to 'Ki.scoped'. * When a scope closes (/i.e./ just before 'Ki.scoped' returns): * The parent thread raises an exception in all of its living children. * The parent thread blocks until those threads terminate. Block until we haven't committed to starting any threads. Without this, we may create a thread concurrently with closing its scope, and not grab its thread id to throw an exception to. Write the sentinel value indicating that this scope is closed, and it is an error to try to create a thread within it. Return the list of currently-running children to kill. Some of them may have *just* started (e.g. if we initially retried in `blockUntil0` above). That's fine - kill them all! If one of our children propagated an exception to us, then we know it's about to terminate, so we don't bother throwing an exception to it. Deliver a ScopeClosing exception to every living child. This happens to throw in the order the children were created... but I think we decided this feature isn't very useful in practice, so maybe we should simplify the internals and just keep a set of children? Block until all children have terminated; this relies on children respecting the async exception, which they must, for correctness. Otherwise, a thread could indeed outlive the scope in which it's created, which is definitely not structured concurrency! 1) A sync or async exception thrown during the callback, captured in `result`. If applicable, we want to unwrap the `ThreadFailed` off of this, which was only used to indicate it came from one of our children. 2) A sync or async exception left for us in `childExceptionVar` by a child that tried to propagate it to us directly, but failed (because we killed it concurrently). 3) An async exception waiting in our exception queue, because we still have async exceptions uninterruptibly masked. Allocate a new scope. Spawn a thread in a scope, providing it its child id and a function that sets the masking state to the requested Record the thread as being about to start. Not allowed to retry. Record the child as having started. Not allowed to retry. it's actually ok to go from e.g. -1 to -2 here (very unlikely) Record our child by either: * Flipping `Nothing` to `Just childThreadId` (common case: we record child before it unrecords itself) * Flipping `Just _` to `Nothing` (uncommon case: we observe that a child already unrecorded itself) Never retries. Never retries. forkIO/forkOn/forkOS, switching on affinity | Wait until all threads created within a scope terminate. | Create a child thread to execute an action within a scope. /Note/: The child thread does not mask asynchronous exceptions, regardless of the parent thread's masking state. To create a child thread with a different initial masking state, use 'Ki.forkWith'. | Variant of 'Ki.fork' for threads that never return. | Variant of 'Ki.fork' that takes an additional options argument. even put async exceptions that we propagated. this isn't totally ideal because a caller awaiting this thread would not be able to distinguish between async exceptions delivered to this thread, or itself | Variant of 'Ki.forkWith' for threads that never return. | Like 'Ki.fork', but the child thread does not propagate exceptions that are both: * Synchronous (/i.e./ not an instance of 'SomeAsyncException'). | Variant of 'Ki.forkTry' that takes an additional options argument. if the user calls `forkTry @MyAsyncException`, we still want to propagate the async exception We have a non-`ScopeClosing` exception to propagate to our parent. If our scope has already begun closing (`startingVar` is -1), then either... threw a synchronous exception (or were hit by a different asynchronous exception) during our teardown procedure. or -1, and will proceed to throw ScopeClosing to all of its children. If (A), our parent has asynchronous exceptions masked, so we must inform it of our exception via `childExceptionVar` rather than throwTo. If (B), either mechanism would work. And because we don't if we're in case (A) or (B), we just `childExceptionVar`. And if our scope has not already begun closing (`startingVar` is not -1), then we ought to throw our exception to it. But that might fail due to either... exceptions uninterruptibly masked and we only have asynchronous exception *synchronously* masked, its `throwTo` our parent is tearing down and has asynchronous exceptions masked, we again inform it via `childExceptionVar`. (D) Some *other* non-`ScopeClosing` asynchronous exception is raised here. This is truly odd: maybe it's a heap thrown us an exception for some reason? Either way, because we already have an exception that we are trying to propagate, we just scoot these freaky exceptions under the rug. (A) / (B) (C) (D) A little promise that this IO action cannot throw an exception. Yeah it's verbose, and maybe not that necessary, but the code that bothers to use it really does require un-exceptiony IO actions for correctness, so here we are. Like try, but with continuations. Also, catches all exceptions, because that's the only flavor we need.
module Ki.Internal.Scope ( Scope, scoped, awaitAll, fork, forkWith, forkWith_, fork_, forkTry, forkTryWith, ) where import qualified Control.Concurrent import Control.Exception ( Exception (fromException, toException), MaskingState (..), SomeAsyncException, asyncExceptionFromException, asyncExceptionToException, catch, pattern ErrorCall, ) import qualified Data.IntMap.Lazy as IntMap import Data.Void (Void, absurd) import GHC.Conc ( STM, TVar, atomically, enableAllocationLimit, labelThread, newTVarIO, readTVar, retry, setAllocationCounter, throwSTM, writeTVar, ) import GHC.IO (unsafeUnmask) import Ki.Internal.ByteCount import Ki.Internal.Counter import Ki.Internal.Prelude import Ki.Internal.Thread import GHC.Conc.Sync (readTVarIO) * All threads created within a scope can be awaited together ( see ' ' ) . data Scope = Scope The MVar that a child tries to put to , in the case that it tries to propagate an exception to its parent , but Why a single - celled MVar ? What if two siblings are fighting to inform their parent of their death ? Well , only one exception can be propagated by the parent anyway , so we would n't need or want both . The number of child threads that are guaranteed to be about to start , in the sense that only the GHC scheduler can continue to delay ; there 's no opportunity for an async exception to strike and prevent one of these threads } Internal async exception thrown by a parent thread to its children when the scope is closing . data ScopeClosing = ScopeClosing instance Show ScopeClosing where show _ = "ScopeClosing" instance Exception ScopeClosing where toException = asyncExceptionToException fromException = asyncExceptionFromException isScopeClosingException :: SomeException -> Bool isScopeClosingException exception = case fromException exception of Just ScopeClosing -> True _ -> False pattern IsScopeClosingException :: SomeException pattern IsScopeClosingException <- (isScopeClosingException -> True) scoped :: (Scope -> IO a) -> IO a scoped action = do scope@Scope {childExceptionVar, childrenVar, startingVar} <- allocateScope uninterruptibleMask \restore -> do result <- try (restore (action scope)) !livingChildren <- do livingChildren0 <- atomically do blockUntil0 startingVar writeTVar startingVar (-1) readTVar childrenVar pure case result of Left (fromException -> Just ThreadFailed {childId}) -> IntMap.delete childId livingChildren0 _ -> livingChildren0 for_ (IntMap.elems livingChildren) \livingChild -> throwTo livingChild ScopeClosing atomically (blockUntilEmpty childrenVar) By now there are three sources of exception : We can not throw more than one , so throw them in that priority order . case result of Left exception -> throwIO (unwrapThreadFailed exception) Right value -> tryTakeMVar childExceptionVar >>= \case Nothing -> pure value Just exception -> throwIO exception allocateScope :: IO Scope allocateScope = do childExceptionVar <- newEmptyMVar childrenVar <- newTVarIO IntMap.empty nextChildIdCounter <- newCounter parentThreadId <- myThreadId startingVar <- newTVarIO 0 pure Scope {childExceptionVar, childrenVar, nextChildIdCounter, parentThreadId, startingVar} masking state . The given action is called with async exceptions interruptibly masked . spawn :: Scope -> ThreadOptions -> (Int -> (forall x. IO x -> IO x) -> UnexceptionalIO ()) -> IO ThreadId spawn Scope {childrenVar, nextChildIdCounter, startingVar} ThreadOptions {affinity, allocationLimit, label, maskingState = requestedChildMaskingState} action = do Interruptible mask is enough so long as none of the STM operations below block . Unconditionally set masking state to MaskedInterruptible , even though we might already be at MaskedInterruptible or MaskedUninterruptible , to avoid a branch on parentMaskingState . interruptiblyMasked do atomically do n <- readTVar startingVar if n < 0 then throwSTM (ErrorCall "ki: scope closed") else writeTVar startingVar $! n + 1 childId <- incrCounter nextChildIdCounter childThreadId <- forkWithAffinity affinity do when (not (null label)) do childThreadId <- myThreadId labelThread childThreadId label case allocationLimit of Nothing -> pure () Just bytes -> do setAllocationCounter (byteCountToInt64 bytes) enableAllocationLimit Action that sets the masking state from the current ( MaskedInterruptible ) to the requested one . atRequestedMaskingState :: IO a -> IO a atRequestedMaskingState = case requestedChildMaskingState of Unmasked -> unsafeUnmask MaskedInterruptible -> id MaskedUninterruptible -> uninterruptiblyMasked runUnexceptionalIO (action childId atRequestedMaskingState) atomically (unrecordChild childrenVar childId) atomically do n <- readTVar startingVar recordChild childrenVar childId childThreadId pure childThreadId recordChild :: TVar (IntMap ThreadId) -> Int -> ThreadId -> STM () recordChild childrenVar childId childThreadId = do children <- readTVar childrenVar writeTVar childrenVar $! IntMap.alter (maybe (Just childThreadId) (const Nothing)) childId children Unrecord a child ( ourselves ) by either : * Flipping ` Just childThreadId ` to ` Nothing ` ( common case : parent recorded us first ) * Flipping ` Nothing ` to ` Just undefined ` ( uncommon case : we terminate and unrecord before parent can record us ) . unrecordChild :: TVar (IntMap ThreadId) -> Int -> STM () unrecordChild childrenVar childId = do children <- readTVar childrenVar writeTVar childrenVar $! IntMap.alter (maybe (Just undefined) (const Nothing)) childId children forkWithAffinity :: ThreadAffinity -> IO () -> IO ThreadId forkWithAffinity = \case Unbound -> forkIO Capability n -> forkOn n OsThread -> Control.Concurrent.forkOS awaitAll :: Scope -> STM () awaitAll Scope {childrenVar, startingVar} = do blockUntilEmpty childrenVar blockUntil0 startingVar Block until an IntMap becomes empty . blockUntilEmpty :: TVar (IntMap a) -> STM () blockUntilEmpty var = do x <- readTVar var if IntMap.null x then pure () else retry Block until a TVar becomes 0 . blockUntil0 :: TVar Int -> STM () blockUntil0 var = do x <- readTVar var if x == 0 then pure () else retry fork :: Scope -> IO a -> IO (Thread a) fork scope = forkWith scope defaultThreadOptions fork_ :: Scope -> IO Void -> IO () fork_ scope = forkWith_ scope defaultThreadOptions forkWith :: Scope -> ThreadOptions -> IO a -> IO (Thread a) forkWith scope opts action = do resultVar <- newTVarIO Nothing ident <- spawn scope opts \childId masking -> do result <- unexceptionalTry (masking action) case result of Left exception -> when (not (isScopeClosingException exception)) (propagateException scope childId exception) Right _ -> pure () UnexceptionalIO (atomically (writeTVar resultVar (Just result))) let doAwait = readTVar resultVar >>= \case Nothing -> retry Just (Left exception) -> throwSTM exception Just (Right value) -> pure value pure (makeThread ident doAwait) forkWith_ :: Scope -> ThreadOptions -> IO Void -> IO () forkWith_ scope opts action = do _childThreadId <- spawn scope opts \childId masking -> unexceptionalTryEither (\exception -> when (not (isScopeClosingException exception)) (propagateException scope childId exception)) absurd (masking action) pure () * An instance of @e@. forkTry :: forall e a. Exception e => Scope -> IO a -> IO (Thread (Either e a)) forkTry scope = forkTryWith scope defaultThreadOptions forkTryWith :: forall e a. Exception e => Scope -> ThreadOptions -> IO a -> IO (Thread (Either e a)) forkTryWith scope opts action = do resultVar <- newTVarIO Nothing childThreadId <- spawn scope opts \childId masking -> do result <- unexceptionalTry (masking action) case result of Left exception -> do let shouldPropagate = if isScopeClosingException exception then False else case fromException @e exception of Nothing -> True Just _ -> isAsyncException exception when shouldPropagate (propagateException scope childId exception) Right _value -> pure () UnexceptionalIO (atomically (writeTVar resultVar (Just result))) let doAwait = readTVar resultVar >>= \case Nothing -> retry Just (Left exception) -> case fromException @e exception of Nothing -> throwSTM exception Just expectedException -> pure (Left expectedException) Just (Right value) -> pure (Right value) pure (makeThread childThreadId doAwait) where isAsyncException :: SomeException -> Bool isAsyncException exception = case fromException @SomeAsyncException exception of Nothing -> False Just _ -> True ( A ) We already received a ` ScopeClosing ` , but then ended up trying to propagate an exception anyway , because we ( B ) We will receive a ` ScopeClosing ` imminently , because our parent has * just * finished setting ` startingVar ` to ( C ) Our parent concurrently closing the scope and sending us a ` ScopeClosing ` ; because it has asynchronous will return ` ( ) ` , and ours will throw that ` ScopeClosing ` asynchronous exception . In this case , since we now know overflow exception from the GHC runtime ? Maybe some other thread has smuggled our ` ThreadId ` out and has manually Precondition : interruptibly masked propagateException :: Scope -> Int -> SomeException -> UnexceptionalIO () propagateException Scope {childExceptionVar, parentThreadId, startingVar} childId exception = UnexceptionalIO (readTVarIO startingVar) >>= \case _ -> loop where loop :: UnexceptionalIO () loop = unexceptionalTry (throwTo parentThreadId ThreadFailed {childId, exception}) >>= \case Right _ -> pure () tryPutChildExceptionVar :: UnexceptionalIO () tryPutChildExceptionVar = UnexceptionalIO (void (tryPutMVar childExceptionVar exception)) newtype UnexceptionalIO a = UnexceptionalIO {runUnexceptionalIO :: IO a} deriving newtype (Applicative, Functor, Monad) unexceptionalTry :: forall a. IO a -> UnexceptionalIO (Either SomeException a) unexceptionalTry = coerce @(IO a -> IO (Either SomeException a)) try unexceptionalTryEither :: forall a b. (SomeException -> UnexceptionalIO b) -> (a -> UnexceptionalIO b) -> IO a -> UnexceptionalIO b unexceptionalTryEither onFailure onSuccess action = UnexceptionalIO do join do catch (coerce @_ @(a -> IO b) onSuccess <$> action) (pure . coerce @_ @(SomeException -> IO b) onFailure)
dba4fe3fa34dd3f77e5e96bcfaf087a463b56fe990b9af2f2c281bf0cc441004
joearms/music_experiments
midi.erl
-module(midi). -compile(export_all). test1() -> %% test the internal driver midi_event_gen:start(internal), scale(60,70,100), instruments(20,30). instruments(Min, Max) -> for(Min, Max, fun(I) -> set_instrument(1, I), scale(60,70,50) end). set_instrument(Channel, Instrument) -> io:format("changing instrument to:~p~n", [instrument_name(Instrument)]), midi_player:do({programChange,1,Instrument}). scale(N, K, T) -> for(60,70, fun(I) -> play_note(I,T) end ). for(I,I,F) -> F(I); for(I,J,F) -> F(I), for(I+1,J,F). play_note(I,T) -> midi_player:do({noteOn,1,I,80}), timer:sleep(T), midi_player:do({noteOn,1,I,0}). instrument_name(I) -> element(I, instrument_names()). instrument_names() -> {"Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano", "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavi", "Celesta", "Glockenspiel", "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ", "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica", "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)", "Electric Guitar (clean)", "Electric Guitar (muted)", "Overdriven Guitar", "Distortion Guitar", "Guitar harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)", "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin", "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp", "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2", "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba", "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet", "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle", "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)", "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass + lead)", "Pad 1 (new age)", "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)", "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)", "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)", "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal", "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter", "Applause", "Gunshot"}.
null
https://raw.githubusercontent.com/joearms/music_experiments/3c0db01d03571599a3506fcb1a001d0b8dd205d9/midi_mac_driver/midi.erl
erlang
test the internal driver
-module(midi). -compile(export_all). test1() -> midi_event_gen:start(internal), scale(60,70,100), instruments(20,30). instruments(Min, Max) -> for(Min, Max, fun(I) -> set_instrument(1, I), scale(60,70,50) end). set_instrument(Channel, Instrument) -> io:format("changing instrument to:~p~n", [instrument_name(Instrument)]), midi_player:do({programChange,1,Instrument}). scale(N, K, T) -> for(60,70, fun(I) -> play_note(I,T) end ). for(I,I,F) -> F(I); for(I,J,F) -> F(I), for(I+1,J,F). play_note(I,T) -> midi_player:do({noteOn,1,I,80}), timer:sleep(T), midi_player:do({noteOn,1,I,0}). instrument_name(I) -> element(I, instrument_names()). instrument_names() -> {"Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano", "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavi", "Celesta", "Glockenspiel", "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ", "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica", "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)", "Electric Guitar (clean)", "Electric Guitar (muted)", "Overdriven Guitar", "Distortion Guitar", "Guitar harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)", "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin", "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp", "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2", "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba", "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax", "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet", "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle", "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)", "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass + lead)", "Pad 1 (new age)", "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)", "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)", "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)", "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell", "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal", "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter", "Applause", "Gunshot"}.
d4b9b9f1375d018d9420c71648f59dd7a1a7461d4b8e8bf7d401e37cd4e85795
glondu/belenios
web_types.ml
(**************************************************************************) (* BELENIOS *) (* *) Copyright © 2012 - 2022 (* *) (* This program is free software: you can redistribute it and/or modify *) it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the (* License, or (at your option) any later version, with the additional *) exemption that compiling , linking , and/or using OpenSSL is allowed . (* *) (* This program is distributed in the hope that it will be useful, but *) (* WITHOUT ANY WARRANTY; without even the implied warranty of *) (* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *) (* Affero General Public License for more details. *) (* *) You should have received a copy of the GNU Affero General Public (* License along with this program. If not, see *) (* </>. *) (**************************************************************************) module Datetime = struct open CalendarLib let datetime_format = "%Y-%m-%d %H:%M:%S" type t = Calendar.Precise.t let now () = Calendar.Precise.now () let unwrap n = let n = Calendar.Precise.to_gmt n in Printer.Precise_Calendar.sprint datetime_format n let wrap s = match String.index_opt s '.' with | None -> let l = Printer.Precise_Calendar.from_fstring datetime_format s in Calendar.Precise.from_gmt l | Some i -> let l = Printer.Precise_Calendar.from_fstring datetime_format (String.sub s 0 i) in let l = Calendar.Precise.from_gmt l in let r = float_of_string ("0" ^ String.sub s i (String.length s - i)) in let r = int_of_float (Float.round r) in Calendar.Precise.add l (Calendar.Precise.Period.second r) let compare = Calendar.Precise.compare let format ?(fmt = datetime_format) a = Printer.Precise_Calendar.sprint fmt a let to_unixfloat a = Calendar.Precise.to_unixfloat a |> Float.round let from_unixfloat t = Calendar.Precise.from_unixfloat t end module Period = struct open CalendarLib type t = Calendar.Precise.Period.t let day = Calendar.Precise.Period.day let second = Calendar.Precise.Period.second let add = Calendar.Precise.add let sub = Calendar.Precise.sub let ymds = Calendar.Precise.Period.ymds end
null
https://raw.githubusercontent.com/glondu/belenios/de4a3205c3d2adb91863965a706fa6028177d78f/src/web/server/common/web_types.ml
ocaml
************************************************************************ BELENIOS This program is free software: you can redistribute it and/or modify License, or (at your option) any later version, with the additional This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. License along with this program. If not, see </>. ************************************************************************
Copyright © 2012 - 2022 it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the exemption that compiling , linking , and/or using OpenSSL is allowed . You should have received a copy of the GNU Affero General Public module Datetime = struct open CalendarLib let datetime_format = "%Y-%m-%d %H:%M:%S" type t = Calendar.Precise.t let now () = Calendar.Precise.now () let unwrap n = let n = Calendar.Precise.to_gmt n in Printer.Precise_Calendar.sprint datetime_format n let wrap s = match String.index_opt s '.' with | None -> let l = Printer.Precise_Calendar.from_fstring datetime_format s in Calendar.Precise.from_gmt l | Some i -> let l = Printer.Precise_Calendar.from_fstring datetime_format (String.sub s 0 i) in let l = Calendar.Precise.from_gmt l in let r = float_of_string ("0" ^ String.sub s i (String.length s - i)) in let r = int_of_float (Float.round r) in Calendar.Precise.add l (Calendar.Precise.Period.second r) let compare = Calendar.Precise.compare let format ?(fmt = datetime_format) a = Printer.Precise_Calendar.sprint fmt a let to_unixfloat a = Calendar.Precise.to_unixfloat a |> Float.round let from_unixfloat t = Calendar.Precise.from_unixfloat t end module Period = struct open CalendarLib type t = Calendar.Precise.Period.t let day = Calendar.Precise.Period.day let second = Calendar.Precise.Period.second let add = Calendar.Precise.add let sub = Calendar.Precise.sub let ymds = Calendar.Precise.Period.ymds end
782204c9964bf50b24db5f2f306b30705b34d89ac04eba8abffdf9803a8c23bd
f-o-a-m/kepler
Class.hs
# LANGUAGE UndecidableInstances # module Tendermint.Utils.QueryClient.Class where import Control.Lens ((^.)) import Control.Monad.Reader (ReaderT) import qualified Data.ByteArray.Base64String as Base64 import qualified Data.ByteArray.HexString as Hex import Data.ByteString (ByteString) import Data.Kind (Type) import Data.Proxy import Data.String.Conversions (cs) import Data.Text (Text, intercalate) import Data.Word (Word64) import GHC.TypeLits (KnownSymbol, symbolVal) import Network.ABCI.Types.Messages.FieldTypes (WrappedVal (..)) import qualified Network.ABCI.Types.Messages.Request as Req import qualified Network.ABCI.Types.Messages.Response as Resp import qualified Network.Tendermint.Client as RPC import Servant.API import Servant.API.Modifiers import Tendermint.SDK.BaseApp.Errors (queryAppError) import Tendermint.SDK.BaseApp.Query.Store (StoreLeaf) import Tendermint.SDK.BaseApp.Query.Types (EmptyQueryServer, Leaf, QA, QueryArgs (..), QueryData (..), QueryResult (..)) import qualified Tendermint.SDK.BaseApp.Store.Array as A import qualified Tendermint.SDK.BaseApp.Store.Map as M import qualified Tendermint.SDK.BaseApp.Store.Var as V import Tendermint.SDK.Codec (HasCodec (decode)) import Tendermint.Utils.QueryClient.Types class Monad m => RunQueryClient m where -- | How to make a request. runQuery :: Req.Query -> m Resp.Query instance RunQueryClient (ReaderT RPC.Config IO) where runQuery Req.Query{..} = let rpcQ = RPC.RequestABCIQuery { RPC.requestABCIQueryPath = Just queryPath , RPC.requestABCIQueryData = Hex.fromBytes @ByteString . Base64.toBytes $ queryData , RPC.requestABCIQueryHeight = Just $ queryHeight , RPC.requestABCIQueryProve = queryProve } in RPC.resultABCIQueryResponse <$> RPC.abciQuery rpcQ type QueryStringList = [(Text, Text)] class HasQueryClient m layout where type ClientQ (m :: Type -> Type) layout :: Type genClientQ :: Proxy m -> Proxy layout -> (Req.Query, QueryStringList) -> ClientQ m layout instance (HasQueryClient m a, HasQueryClient m b) => HasQueryClient m (a :<|> b) where type ClientQ m (a :<|> b) = ClientQ m a :<|> ClientQ m b genClientQ pm _ (q,qs) = genClientQ pm (Proxy @a) (q,qs) :<|> genClientQ pm (Proxy @b) (q,qs) instance (KnownSymbol path, HasQueryClient m a) => HasQueryClient m (path :> a) where type ClientQ m (path :> a) = ClientQ m a genClientQ pm _ (q,qs) = genClientQ pm (Proxy @a) (q {Req.queryPath = Req.queryPath q <> "/" <> cs (symbolVal (Proxy @path))}, qs) appendToQueryString :: Text -- ^ param name -> Maybe Text -- ^ param value -> QueryStringList -> QueryStringList appendToQueryString pname pvalue qs = maybe qs (\v -> (pname, v) : qs) pvalue instance (KnownSymbol sym, ToHttpApiData a, HasQueryClient m api, SBoolI (FoldRequired mods)) => HasQueryClient m (QueryParam' mods sym a :> api) where type ClientQ m (QueryParam' mods sym a :> api) = RequiredArgument mods a -> ClientQ m api -- if mparam = Nothing, we don't add it to the query string genClientQ pm Proxy (q,qs) mparam = genClientQ pm (Proxy :: Proxy api) $ foldRequiredArgument (Proxy :: Proxy mods) add (maybe (q,qs) add) mparam where add :: a -> (Req.Query, QueryStringList) add param = (q, appendToQueryString pname (Just $ toQueryParam param) qs) pname :: Text pname = cs $ symbolVal (Proxy :: Proxy sym) instance (QueryData k, HasQueryClient m a) => HasQueryClient m (QA k :> a) where type ClientQ m (QA k :> a) = QueryArgs k -> ClientQ m a genClientQ pm _ (q,qs) QueryArgs{..} = genClientQ pm (Proxy @a) (q { Req.queryData = toQueryData queryArgsData , Req.queryHeight = WrappedVal queryArgsHeight , Req.queryProve = queryArgsProve }, qs) instance (ToHttpApiData a, HasQueryClient m api) => HasQueryClient m (Capture' mods capture a :> api) where type ClientQ m (Capture' mods capture a :> api) = a -> ClientQ m api genClientQ pm _ (q,qs) val = let p = toUrlPiece val q' = q { Req.queryPath = Req.queryPath q <> "/" <> p } in genClientQ pm (Proxy :: Proxy api) (q', qs) addQueryParamsToPath :: QueryStringList -> Text -> Text addQueryParamsToPath qs path = let qParams = intercalate "&" $ map (\(n,v) -> n <> "=" <> v) qs in case qs of [] -> path _ -> path <> "?" <> qParams instance (HasCodec a, RunQueryClient m) => HasQueryClient m (Leaf a) where type ClientQ m (Leaf a) = m (QueryClientResponse a) genClientQ _ _ = leafGenClient leafGenClient :: HasCodec a => RunQueryClient m => (Req.Query, QueryStringList) -> m (QueryClientResponse a) leafGenClient (q,qs) = do let reqPath = addQueryParamsToPath qs $ Req.queryPath q {..} <- runQuery q { Req.queryPath = reqPath } -- anything other than 0 code is a failure: -spec.html -- and will result in queryValue decoding to a "empty/default" object return $ case queryCode of 0 -> case decode $ Base64.toBytes queryValue of Left err -> error $ "Impossible parse error: " <> cs err Right a -> QueryResponse $ QueryResult { queryResultData = a , queryResultIndex = unWrappedVal queryIndex , queryResultHeight = unWrappedVal queryHeight , queryResultProof = queryProof , queryResultKey = queryKey } _ -> QueryError $ r ^. queryAppError instance (HasCodec a, RunQueryClient m) => HasQueryClient m (StoreLeaf (V.Var a)) where type ClientQ m (StoreLeaf (V.Var a)) = ClientQ m (QA () :> Leaf a) genClientQ pm _ = genClientQ pm (Proxy @(QA () :> Leaf a)) instance (HasCodec a, RunQueryClient m) => HasQueryClient m (StoreLeaf (A.Array a)) where type ClientQ m (StoreLeaf (A.Array a)) = ClientQ m (QA Word64 :> Leaf a) genClientQ pm _ = genClientQ pm (Proxy @(QA Word64 :> Leaf a)) instance (QueryData k, HasCodec v, RunQueryClient m) => HasQueryClient m (StoreLeaf (M.Map k v)) where type ClientQ m (StoreLeaf (M.Map k v)) = ClientQ m (QA k :> Leaf v) genClientQ pm _ = genClientQ pm (Proxy @(QA k :> Leaf v)) -- | Singleton type representing a client for an empty API. data EmptyQueryClient = EmptyQueryClient deriving (Eq, Show, Bounded, Enum) instance HasQueryClient m EmptyQueryServer where type ClientQ m EmptyQueryServer = EmptyQueryClient genClientQ _ _ _ = EmptyQueryClient
null
https://raw.githubusercontent.com/f-o-a-m/kepler/6c1ad7f37683f509c2f1660e3561062307d3056b/hs-abci-test-utils/src/Tendermint/Utils/QueryClient/Class.hs
haskell
| How to make a request. ^ param name ^ param value if mparam = Nothing, we don't add it to the query string anything other than 0 code is a failure: -spec.html and will result in queryValue decoding to a "empty/default" object | Singleton type representing a client for an empty API.
# LANGUAGE UndecidableInstances # module Tendermint.Utils.QueryClient.Class where import Control.Lens ((^.)) import Control.Monad.Reader (ReaderT) import qualified Data.ByteArray.Base64String as Base64 import qualified Data.ByteArray.HexString as Hex import Data.ByteString (ByteString) import Data.Kind (Type) import Data.Proxy import Data.String.Conversions (cs) import Data.Text (Text, intercalate) import Data.Word (Word64) import GHC.TypeLits (KnownSymbol, symbolVal) import Network.ABCI.Types.Messages.FieldTypes (WrappedVal (..)) import qualified Network.ABCI.Types.Messages.Request as Req import qualified Network.ABCI.Types.Messages.Response as Resp import qualified Network.Tendermint.Client as RPC import Servant.API import Servant.API.Modifiers import Tendermint.SDK.BaseApp.Errors (queryAppError) import Tendermint.SDK.BaseApp.Query.Store (StoreLeaf) import Tendermint.SDK.BaseApp.Query.Types (EmptyQueryServer, Leaf, QA, QueryArgs (..), QueryData (..), QueryResult (..)) import qualified Tendermint.SDK.BaseApp.Store.Array as A import qualified Tendermint.SDK.BaseApp.Store.Map as M import qualified Tendermint.SDK.BaseApp.Store.Var as V import Tendermint.SDK.Codec (HasCodec (decode)) import Tendermint.Utils.QueryClient.Types class Monad m => RunQueryClient m where runQuery :: Req.Query -> m Resp.Query instance RunQueryClient (ReaderT RPC.Config IO) where runQuery Req.Query{..} = let rpcQ = RPC.RequestABCIQuery { RPC.requestABCIQueryPath = Just queryPath , RPC.requestABCIQueryData = Hex.fromBytes @ByteString . Base64.toBytes $ queryData , RPC.requestABCIQueryHeight = Just $ queryHeight , RPC.requestABCIQueryProve = queryProve } in RPC.resultABCIQueryResponse <$> RPC.abciQuery rpcQ type QueryStringList = [(Text, Text)] class HasQueryClient m layout where type ClientQ (m :: Type -> Type) layout :: Type genClientQ :: Proxy m -> Proxy layout -> (Req.Query, QueryStringList) -> ClientQ m layout instance (HasQueryClient m a, HasQueryClient m b) => HasQueryClient m (a :<|> b) where type ClientQ m (a :<|> b) = ClientQ m a :<|> ClientQ m b genClientQ pm _ (q,qs) = genClientQ pm (Proxy @a) (q,qs) :<|> genClientQ pm (Proxy @b) (q,qs) instance (KnownSymbol path, HasQueryClient m a) => HasQueryClient m (path :> a) where type ClientQ m (path :> a) = ClientQ m a genClientQ pm _ (q,qs) = genClientQ pm (Proxy @a) (q {Req.queryPath = Req.queryPath q <> "/" <> cs (symbolVal (Proxy @path))}, qs) appendToQueryString -> QueryStringList -> QueryStringList appendToQueryString pname pvalue qs = maybe qs (\v -> (pname, v) : qs) pvalue instance (KnownSymbol sym, ToHttpApiData a, HasQueryClient m api, SBoolI (FoldRequired mods)) => HasQueryClient m (QueryParam' mods sym a :> api) where type ClientQ m (QueryParam' mods sym a :> api) = RequiredArgument mods a -> ClientQ m api genClientQ pm Proxy (q,qs) mparam = genClientQ pm (Proxy :: Proxy api) $ foldRequiredArgument (Proxy :: Proxy mods) add (maybe (q,qs) add) mparam where add :: a -> (Req.Query, QueryStringList) add param = (q, appendToQueryString pname (Just $ toQueryParam param) qs) pname :: Text pname = cs $ symbolVal (Proxy :: Proxy sym) instance (QueryData k, HasQueryClient m a) => HasQueryClient m (QA k :> a) where type ClientQ m (QA k :> a) = QueryArgs k -> ClientQ m a genClientQ pm _ (q,qs) QueryArgs{..} = genClientQ pm (Proxy @a) (q { Req.queryData = toQueryData queryArgsData , Req.queryHeight = WrappedVal queryArgsHeight , Req.queryProve = queryArgsProve }, qs) instance (ToHttpApiData a, HasQueryClient m api) => HasQueryClient m (Capture' mods capture a :> api) where type ClientQ m (Capture' mods capture a :> api) = a -> ClientQ m api genClientQ pm _ (q,qs) val = let p = toUrlPiece val q' = q { Req.queryPath = Req.queryPath q <> "/" <> p } in genClientQ pm (Proxy :: Proxy api) (q', qs) addQueryParamsToPath :: QueryStringList -> Text -> Text addQueryParamsToPath qs path = let qParams = intercalate "&" $ map (\(n,v) -> n <> "=" <> v) qs in case qs of [] -> path _ -> path <> "?" <> qParams instance (HasCodec a, RunQueryClient m) => HasQueryClient m (Leaf a) where type ClientQ m (Leaf a) = m (QueryClientResponse a) genClientQ _ _ = leafGenClient leafGenClient :: HasCodec a => RunQueryClient m => (Req.Query, QueryStringList) -> m (QueryClientResponse a) leafGenClient (q,qs) = do let reqPath = addQueryParamsToPath qs $ Req.queryPath q {..} <- runQuery q { Req.queryPath = reqPath } return $ case queryCode of 0 -> case decode $ Base64.toBytes queryValue of Left err -> error $ "Impossible parse error: " <> cs err Right a -> QueryResponse $ QueryResult { queryResultData = a , queryResultIndex = unWrappedVal queryIndex , queryResultHeight = unWrappedVal queryHeight , queryResultProof = queryProof , queryResultKey = queryKey } _ -> QueryError $ r ^. queryAppError instance (HasCodec a, RunQueryClient m) => HasQueryClient m (StoreLeaf (V.Var a)) where type ClientQ m (StoreLeaf (V.Var a)) = ClientQ m (QA () :> Leaf a) genClientQ pm _ = genClientQ pm (Proxy @(QA () :> Leaf a)) instance (HasCodec a, RunQueryClient m) => HasQueryClient m (StoreLeaf (A.Array a)) where type ClientQ m (StoreLeaf (A.Array a)) = ClientQ m (QA Word64 :> Leaf a) genClientQ pm _ = genClientQ pm (Proxy @(QA Word64 :> Leaf a)) instance (QueryData k, HasCodec v, RunQueryClient m) => HasQueryClient m (StoreLeaf (M.Map k v)) where type ClientQ m (StoreLeaf (M.Map k v)) = ClientQ m (QA k :> Leaf v) genClientQ pm _ = genClientQ pm (Proxy @(QA k :> Leaf v)) data EmptyQueryClient = EmptyQueryClient deriving (Eq, Show, Bounded, Enum) instance HasQueryClient m EmptyQueryServer where type ClientQ m EmptyQueryServer = EmptyQueryClient genClientQ _ _ _ = EmptyQueryClient
e01a796e8a63087b97c9541a30d0f21c624758fd514c985c6aebccbdcb066bea
alesaccoia/festival_flinger
duration.scm
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;; Centre for Speech Technology Research ; ; University of Edinburgh , UK ; ; ;;; Copyright (c) 1996,1997 ;; All Rights Reserved . ; ; ;;; ;; ;;; Permission is hereby granted, free of charge, to use and distribute ;; ;;; this software and its documentation without restriction, including ;; ;;; without limitation the rights to use, copy, modify, merge, publish, ;; ;;; distribute, sublicense, and/or sell copies of this work, and to ;; ;;; permit persons to whom this work is furnished to do so, subject to ;; ;;; the following conditions: ;; ;;; 1. The code must retain the above copyright notice, this list of ;; ;;; conditions and the following disclaimer. ;; ;;; 2. Any modifications must be clearly marked as such. ;; 3 . Original authors ' names are not deleted . ; ; ;;; 4. The authors' names are not used to endorse or promote products ;; ;;; derived from this software without specific prior written ;; ;;; permission. ;; ;;; ;; ;;; THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK ;; ;;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;; ;;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;; ;;; SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE ;; ;;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;; WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , IN ; ; ;;; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;; ;;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;; ;;; THIS SOFTWARE. ;; ;;; ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; ;;; Basic Duration module which will call appropriate duration ;;; (C++) modules based on set parameter ;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; These modules should predict intonation events/labels ;;; based on information in the phrase and word streams (define (Duration utt) "(Duration utt) Predict segmental durations using Duration_Method defined in Parameters. Four methods are currently available: averages, Klatt rules, CART tree based, and fixed duration." (let ((rval (apply_method 'Duration_Method utt))) (cond (rval rval) ;; new style ;; 1.1.1 voices still use other names ((eq 'Averages (Parameter.get 'Duration_Method)) (Duration_Averages utt)) ((eq 'Klatt (Parameter.get 'Duration_Method)) (Duration_Klatt utt)) ((eq 'Tree_ZScores (Parameter.get 'Duration_Method)) (Duration_Tree_ZScores utt)) ((eq 'Tree (Parameter.get 'Duration_Method)) (Duration_Tree utt)) (t (Duration_Default utt))))) (define (Duration_LogZScores utt) "(Duration_LogZScores utt) Predicts duration to segments using the CART tree in duration_logzscore_tree and duration_logzscore_tree_silence which produces a zscore of the log duration. The variable duration_logzscore_ph_info contains (log) means and std for each phone in the set." (let ((silence (car (car (cdr (assoc 'silences (PhoneSet.description)))))) ldurinfo) (mapcar (lambda (s) (if (string-equal silence (item.name s)) (set! ldurinfo (wagon s duration_logzscore_tree_silence)) (set! ldurinfo (wagon s duration_logzscore_tree))) (set! dur (exp (duration_unzscore (item.name s) (car (last ldurinfo)) duration_logzscore_ph_info))) (set! dur (* dur (duration_find_stretch s))) (item.set_feat s "end" (+ dur (item.feat s "start_segment")))) (utt.relation.items utt 'Segment)) utt)) (define (duration_unzscore phname zscore table) "(duration_unzscore phname zscore table) Look up phname in table and convert xscore back to absolute domain." (let ((phinfo (assoc phname table)) mean std) (if phinfo (begin (set! mean (car (cdr phinfo))) (set! std (car (cdr (cdr phinfo))))) (begin (format t "Duration: unzscore no info for %s\n" phname) (set! mean 0.100) (set! std 0.25))) (+ mean (* zscore std)))) (define (duration_find_stretch seg) "(duration_find_stretch utt seg) Find any relavant duration stretch." (let ((global (Parameter.get 'Duration_Stretch)) (local (item.feat seg "R:SylStructure.parent.parent.R:Token.parent.dur_stretch"))) (if (or (not global) (equal? global 0.0)) (set! global 1.0)) (if (string-equal local 0.0) (set! local 1.0)) (* global local))) ;; These provide lisp level functions, some of which have been converted in C++ ( in festival / src / modules / base / ff.cc ) (define (onset_has_ctype seg type) ;; "1" if onset contains ctype (let ((syl (item.relation.parent seg 'SylStructure))) (if (not syl) "0" ;; a silence (let ((segs (item.relation.daughters syl 'SylStructure)) (v "0")) (while (and segs (not (string-equal "+" (item.feat (car segs) "ph_vc")))) (if (string-equal type (item.feat (car segs) "ph_ctype")) (set! v "1")) (set! segs (cdr segs))) v)))) (define (coda_has_ctype seg type) ;; "1" if coda contains ctype (let ((syl (item.relation.parent seg 'SylStructure))) (if (not syl) "0" ;; a silence (let ((segs (reverse (item.relation.daughters syl 'SylStructure))) (v "0")) (while (and segs (not (string-equal "+" (item.feat (car segs) "ph_vc")))) (if (string-equal type (item.feat (car segs) "ph_ctype")) (set! v "1")) (set! segs (cdr segs))) v)))) (define (onset_stop seg) (onset_has_ctype seg "s")) (define (onset_fric seg) (onset_has_ctype seg "f")) (define (onset_nasal seg) (onset_has_ctype seg "n")) (define (onset_glide seg) (let ((l (onset_has_ctype seg "l"))) (if (string-equal l "0") (onset_has_ctype seg "r") "1"))) (define (coda_stop seg) (coda_has_ctype seg "s")) (define (coda_fric seg) (coda_has_ctype seg "f")) (define (coda_nasal seg) (coda_has_ctype seg "n")) (define (coda_glide seg) (let ((l (coda_has_ctype seg "l"))) (if (string-equal l "0") (coda_has_ctype seg "r") "1"))) (define (Unisyn_Duration utt) "(UniSyn_Duration utt) predicts Segment durations is some speficied way but holds the result in a way necessary for other Unisyn code." (let ((end 0)) (mapcar (lambda (s) (item.get_utt s) (let ((dur (wagon_predict s duration_cart_tree))) (set! dur (* (Parameter.get 'Duration_Stretch) dur)) (set! end (+ dur end)) (item.set_feat s "target_dur" dur) (item.set_function s "start" "unisyn_start") (item.set_feat s "end" end) (item.set_feat s "dur" dur) )) (utt.relation.items utt 'Segment)) utt)) (provide 'duration)
null
https://raw.githubusercontent.com/alesaccoia/festival_flinger/87345aad3a3230751a8ff479f74ba1676217accd/lib/duration.scm
scheme
;; ; ; Copyright (c) 1996,1997 ;; ; ;; Permission is hereby granted, free of charge, to use and distribute ;; this software and its documentation without restriction, including ;; without limitation the rights to use, copy, modify, merge, publish, ;; distribute, sublicense, and/or sell copies of this work, and to ;; permit persons to whom this work is furnished to do so, subject to ;; the following conditions: ;; 1. The code must retain the above copyright notice, this list of ;; conditions and the following disclaimer. ;; 2. Any modifications must be clearly marked as such. ;; ; 4. The authors' names are not used to endorse or promote products ;; derived from this software without specific prior written ;; permission. ;; ;; THE UNIVERSITY OF EDINBURGH AND THE CONTRIBUTORS TO THIS WORK ;; DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ;; ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT ;; SHALL THE UNIVERSITY OF EDINBURGH NOR THE CONTRIBUTORS BE LIABLE ;; FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ;; ; AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ;; ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF ;; THIS SOFTWARE. ;; ;; Basic Duration module which will call appropriate duration (C++) modules based on set parameter These modules should predict intonation events/labels based on information in the phrase and word streams new style 1.1.1 voices still use other names These provide lisp level functions, some of which have "1" if onset contains ctype a silence "1" if coda contains ctype a silence
(define (Duration utt) "(Duration utt) Predict segmental durations using Duration_Method defined in Parameters. Four methods are currently available: averages, Klatt rules, CART tree based, and fixed duration." (let ((rval (apply_method 'Duration_Method utt))) (cond ((eq 'Averages (Parameter.get 'Duration_Method)) (Duration_Averages utt)) ((eq 'Klatt (Parameter.get 'Duration_Method)) (Duration_Klatt utt)) ((eq 'Tree_ZScores (Parameter.get 'Duration_Method)) (Duration_Tree_ZScores utt)) ((eq 'Tree (Parameter.get 'Duration_Method)) (Duration_Tree utt)) (t (Duration_Default utt))))) (define (Duration_LogZScores utt) "(Duration_LogZScores utt) Predicts duration to segments using the CART tree in duration_logzscore_tree and duration_logzscore_tree_silence which produces a zscore of the log duration. The variable duration_logzscore_ph_info contains (log) means and std for each phone in the set." (let ((silence (car (car (cdr (assoc 'silences (PhoneSet.description)))))) ldurinfo) (mapcar (lambda (s) (if (string-equal silence (item.name s)) (set! ldurinfo (wagon s duration_logzscore_tree_silence)) (set! ldurinfo (wagon s duration_logzscore_tree))) (set! dur (exp (duration_unzscore (item.name s) (car (last ldurinfo)) duration_logzscore_ph_info))) (set! dur (* dur (duration_find_stretch s))) (item.set_feat s "end" (+ dur (item.feat s "start_segment")))) (utt.relation.items utt 'Segment)) utt)) (define (duration_unzscore phname zscore table) "(duration_unzscore phname zscore table) Look up phname in table and convert xscore back to absolute domain." (let ((phinfo (assoc phname table)) mean std) (if phinfo (begin (set! mean (car (cdr phinfo))) (set! std (car (cdr (cdr phinfo))))) (begin (format t "Duration: unzscore no info for %s\n" phname) (set! mean 0.100) (set! std 0.25))) (+ mean (* zscore std)))) (define (duration_find_stretch seg) "(duration_find_stretch utt seg) Find any relavant duration stretch." (let ((global (Parameter.get 'Duration_Stretch)) (local (item.feat seg "R:SylStructure.parent.parent.R:Token.parent.dur_stretch"))) (if (or (not global) (equal? global 0.0)) (set! global 1.0)) (if (string-equal local 0.0) (set! local 1.0)) (* global local))) been converted in C++ ( in festival / src / modules / base / ff.cc ) (define (onset_has_ctype seg type) (let ((syl (item.relation.parent seg 'SylStructure))) (if (not syl) (let ((segs (item.relation.daughters syl 'SylStructure)) (v "0")) (while (and segs (not (string-equal "+" (item.feat (car segs) "ph_vc")))) (if (string-equal type (item.feat (car segs) "ph_ctype")) (set! v "1")) (set! segs (cdr segs))) v)))) (define (coda_has_ctype seg type) (let ((syl (item.relation.parent seg 'SylStructure))) (if (not syl) (let ((segs (reverse (item.relation.daughters syl 'SylStructure))) (v "0")) (while (and segs (not (string-equal "+" (item.feat (car segs) "ph_vc")))) (if (string-equal type (item.feat (car segs) "ph_ctype")) (set! v "1")) (set! segs (cdr segs))) v)))) (define (onset_stop seg) (onset_has_ctype seg "s")) (define (onset_fric seg) (onset_has_ctype seg "f")) (define (onset_nasal seg) (onset_has_ctype seg "n")) (define (onset_glide seg) (let ((l (onset_has_ctype seg "l"))) (if (string-equal l "0") (onset_has_ctype seg "r") "1"))) (define (coda_stop seg) (coda_has_ctype seg "s")) (define (coda_fric seg) (coda_has_ctype seg "f")) (define (coda_nasal seg) (coda_has_ctype seg "n")) (define (coda_glide seg) (let ((l (coda_has_ctype seg "l"))) (if (string-equal l "0") (coda_has_ctype seg "r") "1"))) (define (Unisyn_Duration utt) "(UniSyn_Duration utt) predicts Segment durations is some speficied way but holds the result in a way necessary for other Unisyn code." (let ((end 0)) (mapcar (lambda (s) (item.get_utt s) (let ((dur (wagon_predict s duration_cart_tree))) (set! dur (* (Parameter.get 'Duration_Stretch) dur)) (set! end (+ dur end)) (item.set_feat s "target_dur" dur) (item.set_function s "start" "unisyn_start") (item.set_feat s "end" end) (item.set_feat s "dur" dur) )) (utt.relation.items utt 'Segment)) utt)) (provide 'duration)
07ec7d9acbb81e0e839d0c2a6a4a255cd36bea840db031902e198655fed0f6b1
jgm/markdown-peg
XML.hs
Copyright ( C ) 2006 - 7 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA Copyright (C) 2006-7 John MacFarlane <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} | Module : Text . Pandoc . XML Copyright : Copyright ( C ) 2006 - 7 License : GNU GPL , version 2 or above Maintainer : < > Stability : alpha Portability : portable Functions for escaping and formatting XML . Module : Text.Pandoc.XML Copyright : Copyright (C) 2006-7 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <> Stability : alpha Portability : portable Functions for escaping and formatting XML. -} module Text.Pandoc.XML ( escapeCharForXML, escapeStringForXML, inTags, selfClosingTag, inTagsSimple, inTagsIndented ) where import Text.PrettyPrint.HughesPJ | Escape one character as needed for XML . escapeCharForXML :: Char -> String escapeCharForXML x = case x of '&' -> "&amp;" '<' -> "&lt;" '>' -> "&gt;" '"' -> "&quot;" '\160' -> "&nbsp;" c -> [c] -- | True if the character needs to be escaped. needsEscaping :: Char -> Bool needsEscaping c = c `elem` "&<>\"\160" | Escape string as needed for XML . Entity references are not preserved . escapeStringForXML :: String -> String escapeStringForXML "" = "" escapeStringForXML str = case break needsEscaping str of (okay, "") -> okay (okay, (c:cs)) -> okay ++ escapeCharForXML c ++ escapeStringForXML cs -- | Return a text object with a string of formatted XML attributes. attributeList :: [(String, String)] -> Doc attributeList = text . concatMap (\(a, b) -> " " ++ escapeStringForXML a ++ "=\"" ++ escapeStringForXML b ++ "\"") | Put the supplied contents between start and end tags of tagType , -- with specified attributes and (if specified) indentation. inTags:: Bool -> String -> [(String, String)] -> Doc -> Doc inTags isIndented tagType attribs contents = let openTag = char '<' <> text tagType <> attributeList attribs <> char '>' closeTag = text "</" <> text tagType <> char '>' in if isIndented then openTag $$ nest 2 contents $$ closeTag else openTag <> contents <> closeTag | Return a self - closing tag of tagType with specified attributes selfClosingTag :: String -> [(String, String)] -> Doc selfClosingTag tagType attribs = char '<' <> text tagType <> attributeList attribs <> text " />" | Put the supplied contents between start and end tags of tagType . inTagsSimple :: String -> Doc -> Doc inTagsSimple tagType = inTags False tagType [] -- | Put the supplied contents in indented block btw start and end tags. inTagsIndented :: String -> Doc -> Doc inTagsIndented tagType = inTags True tagType []
null
https://raw.githubusercontent.com/jgm/markdown-peg/dd79c1b3bc794e3f795f4c06224e24d5d053500d/Text/Pandoc/XML.hs
haskell
| True if the character needs to be escaped. | Return a text object with a string of formatted XML attributes. with specified attributes and (if specified) indentation. | Put the supplied contents in indented block btw start and end tags.
Copyright ( C ) 2006 - 7 < > This program is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 2 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU General Public License for more details . You should have received a copy of the GNU General Public License along with this program ; if not , write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA Copyright (C) 2006-7 John MacFarlane <> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} | Module : Text . Pandoc . XML Copyright : Copyright ( C ) 2006 - 7 License : GNU GPL , version 2 or above Maintainer : < > Stability : alpha Portability : portable Functions for escaping and formatting XML . Module : Text.Pandoc.XML Copyright : Copyright (C) 2006-7 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <> Stability : alpha Portability : portable Functions for escaping and formatting XML. -} module Text.Pandoc.XML ( escapeCharForXML, escapeStringForXML, inTags, selfClosingTag, inTagsSimple, inTagsIndented ) where import Text.PrettyPrint.HughesPJ | Escape one character as needed for XML . escapeCharForXML :: Char -> String escapeCharForXML x = case x of '&' -> "&amp;" '<' -> "&lt;" '>' -> "&gt;" '"' -> "&quot;" '\160' -> "&nbsp;" c -> [c] needsEscaping :: Char -> Bool needsEscaping c = c `elem` "&<>\"\160" | Escape string as needed for XML . Entity references are not preserved . escapeStringForXML :: String -> String escapeStringForXML "" = "" escapeStringForXML str = case break needsEscaping str of (okay, "") -> okay (okay, (c:cs)) -> okay ++ escapeCharForXML c ++ escapeStringForXML cs attributeList :: [(String, String)] -> Doc attributeList = text . concatMap (\(a, b) -> " " ++ escapeStringForXML a ++ "=\"" ++ escapeStringForXML b ++ "\"") | Put the supplied contents between start and end tags of tagType , inTags:: Bool -> String -> [(String, String)] -> Doc -> Doc inTags isIndented tagType attribs contents = let openTag = char '<' <> text tagType <> attributeList attribs <> char '>' closeTag = text "</" <> text tagType <> char '>' in if isIndented then openTag $$ nest 2 contents $$ closeTag else openTag <> contents <> closeTag | Return a self - closing tag of tagType with specified attributes selfClosingTag :: String -> [(String, String)] -> Doc selfClosingTag tagType attribs = char '<' <> text tagType <> attributeList attribs <> text " />" | Put the supplied contents between start and end tags of tagType . inTagsSimple :: String -> Doc -> Doc inTagsSimple tagType = inTags False tagType [] inTagsIndented :: String -> Doc -> Doc inTagsIndented tagType = inTags True tagType []
aa7597b2c1b6317c0692c8feaa6b9e4678e3937f45920c8707d1e8152d8c181a
quchen/prettyprinter
Internal.hs
module Data.Text.Prettyprint.Doc.Render.Terminal.Internal {-# DEPRECATED "Use \"Prettyprinter.Render.Terminal.Internal\" instead." #-} ( module Prettyprinter.Render.Terminal.Internal ) where import Prettyprinter.Render.Terminal.Internal
null
https://raw.githubusercontent.com/quchen/prettyprinter/880f41eac31edfac71d2d66d338e6cfdae4f3715/prettyprinter-ansi-terminal/src/Data/Text/Prettyprint/Doc/Render/Terminal/Internal.hs
haskell
# DEPRECATED "Use \"Prettyprinter.Render.Terminal.Internal\" instead." #
module Prettyprinter.Render.Terminal.Internal ) where import Prettyprinter.Render.Terminal.Internal
7ae274ffcb98bf7fb8fa7730e6de7188d58ecb5f98b786bf3cb74af0b31d18fc
JoelSanchez/ventas
zoomable_image.cljs
(ns ventas.components.zoomable-image (:require [js-image-zoom :as zoom] [re-frame.core :as rf] [reagent.core :as reagent])) (def state-key ::state) (rf/reg-event-db ::set-loaded (fn [db [_ id]] (assoc-in db [state-key id :loaded?] true))) (rf/reg-sub ::loaded? (fn [db [_ id]] (get-in db [state-key id :loaded?]))) (defn- zoom-component [_ _ config] (let [image-zoom (atom nil)] (reagent/create-class {:component-will-unmount #(.kill @image-zoom) :display-name "zoom-component" :component-did-mount (fn [this] (reset! image-zoom (zoom. (reagent/dom-node this) (clj->js config)))) :reagent-render (fn [id src _] [:div [:img {:src src :onLoad #(rf/dispatch [::set-loaded id])}]])}))) (defn main-view [id size-kw zoomed-size-kw] {:pre [(keyword? size-kw)]} (let [size @(rf/subscribe [:db [:image-sizes size-kw]]) loaded? @(rf/subscribe [::loaded? id])] (when size [:div.zoomable-image (when-not loaded? {:style {:position "absolute" :top -9999}}) ^{:key (hash [loaded? id])} [zoom-component id (str "images/" id "/resize/" (name zoomed-size-kw)) {:width (dec (:width size)) :height (:height size) :scale 0.7}]])))
null
https://raw.githubusercontent.com/JoelSanchez/ventas/dc8fc8ff9f63dfc8558ecdaacfc4983903b8e9a1/src/cljs/ventas/components/zoomable_image.cljs
clojure
(ns ventas.components.zoomable-image (:require [js-image-zoom :as zoom] [re-frame.core :as rf] [reagent.core :as reagent])) (def state-key ::state) (rf/reg-event-db ::set-loaded (fn [db [_ id]] (assoc-in db [state-key id :loaded?] true))) (rf/reg-sub ::loaded? (fn [db [_ id]] (get-in db [state-key id :loaded?]))) (defn- zoom-component [_ _ config] (let [image-zoom (atom nil)] (reagent/create-class {:component-will-unmount #(.kill @image-zoom) :display-name "zoom-component" :component-did-mount (fn [this] (reset! image-zoom (zoom. (reagent/dom-node this) (clj->js config)))) :reagent-render (fn [id src _] [:div [:img {:src src :onLoad #(rf/dispatch [::set-loaded id])}]])}))) (defn main-view [id size-kw zoomed-size-kw] {:pre [(keyword? size-kw)]} (let [size @(rf/subscribe [:db [:image-sizes size-kw]]) loaded? @(rf/subscribe [::loaded? id])] (when size [:div.zoomable-image (when-not loaded? {:style {:position "absolute" :top -9999}}) ^{:key (hash [loaded? id])} [zoom-component id (str "images/" id "/resize/" (name zoomed-size-kw)) {:width (dec (:width size)) :height (:height size) :scale 0.7}]])))
b88dadf8980c04c71434597236910b480574413b49a5c992f3e5fd2f561ba60e
basho/riak_core
riak_core_node_watcher_events.erl
%% ------------------------------------------------------------------- %% %% riak_core: Core Riak Application %% Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved . %% This file is provided to you under the Apache License , %% Version 2.0 (the "License"); you may not use this file except in compliance with the License . You may obtain %% a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY %% KIND, either express or implied. See the License for the %% specific language governing permissions and limitations %% under the License. %% %% ------------------------------------------------------------------- -module(riak_core_node_watcher_events). -behaviour(gen_event). %% API -export([start_link/0, add_handler/2, add_sup_handler/2, add_guarded_handler/2, add_callback/1, add_sup_callback/1, add_guarded_callback/1, service_update/1]). %% gen_event callbacks -export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, code_change/3]). -record(state, { callback }). %% =================================================================== %% API functions %% =================================================================== start_link() -> gen_event:start_link({local, ?MODULE}). add_handler(Handler, Args) -> gen_event:add_handler(?MODULE, Handler, Args). add_sup_handler(Handler, Args) -> gen_event:add_sup_handler(?MODULE, Handler, Args). add_guarded_handler(Handler, Args) -> riak_core:add_guarded_event_handler(?MODULE, Handler, Args). add_callback(Fn) when is_function(Fn) -> gen_event:add_handler(?MODULE, {?MODULE, make_ref()}, [Fn]). add_sup_callback(Fn) when is_function(Fn) -> gen_event:add_sup_handler(?MODULE, {?MODULE, make_ref()}, [Fn]). add_guarded_callback(Fn) when is_function(Fn) -> riak_core:add_guarded_event_handler(?MODULE, {?MODULE, make_ref()}, [Fn]). service_update(Services) -> gen_event:notify(?MODULE, {service_update, Services}). %% =================================================================== %% gen_event callbacks %% =================================================================== init([Fn]) -> %% Get the initial list of available services Fn(riak_core_node_watcher:services()), {ok, #state { callback = Fn }}. handle_event({service_update, Services}, State) -> (State#state.callback)(Services), {ok, State}. handle_call(_Request, State) -> {ok, ok, State}. handle_info(_Info, State) -> {ok, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
null
https://raw.githubusercontent.com/basho/riak_core/762ec81ae9af9a278e853f1feca418b9dcf748a3/src/riak_core_node_watcher_events.erl
erlang
------------------------------------------------------------------- riak_core: Core Riak Application Version 2.0 (the "License"); you may not use this file a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ------------------------------------------------------------------- API gen_event callbacks =================================================================== API functions =================================================================== =================================================================== gen_event callbacks =================================================================== Get the initial list of available services
Copyright ( c ) 2007 - 2010 Basho Technologies , Inc. All Rights Reserved . This file is provided to you under the Apache License , except in compliance with the License . You may obtain software distributed under the License is distributed on an " AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY -module(riak_core_node_watcher_events). -behaviour(gen_event). -export([start_link/0, add_handler/2, add_sup_handler/2, add_guarded_handler/2, add_callback/1, add_sup_callback/1, add_guarded_callback/1, service_update/1]). -export([init/1, handle_event/2, handle_call/2, handle_info/2, terminate/2, code_change/3]). -record(state, { callback }). start_link() -> gen_event:start_link({local, ?MODULE}). add_handler(Handler, Args) -> gen_event:add_handler(?MODULE, Handler, Args). add_sup_handler(Handler, Args) -> gen_event:add_sup_handler(?MODULE, Handler, Args). add_guarded_handler(Handler, Args) -> riak_core:add_guarded_event_handler(?MODULE, Handler, Args). add_callback(Fn) when is_function(Fn) -> gen_event:add_handler(?MODULE, {?MODULE, make_ref()}, [Fn]). add_sup_callback(Fn) when is_function(Fn) -> gen_event:add_sup_handler(?MODULE, {?MODULE, make_ref()}, [Fn]). add_guarded_callback(Fn) when is_function(Fn) -> riak_core:add_guarded_event_handler(?MODULE, {?MODULE, make_ref()}, [Fn]). service_update(Services) -> gen_event:notify(?MODULE, {service_update, Services}). init([Fn]) -> Fn(riak_core_node_watcher:services()), {ok, #state { callback = Fn }}. handle_event({service_update, Services}, State) -> (State#state.callback)(Services), {ok, State}. handle_call(_Request, State) -> {ok, ok, State}. handle_info(_Info, State) -> {ok, State}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}.
9b7a735148e08d16bb57e4326d2d824648b49d0988fae35c7fde0fcbffb415ec
jgpc42/jmh-clojure
exec.clj
(ns ^:internal ^:no-doc jmh.exec "Build command arguments and run benchmarks." (:require [jmh.util :as util] [jmh.option :as option] [clojure.java.io :as io]) (:import [java.io ByteArrayOutputStream File OutputStream PrintStream] [java.lang.management ManagementFactory] [org.openjdk.jmh.runner BenchmarkException NoBenchmarksException Runner RunnerException] [org.openjdk.jmh.runner.options OptionsBuilder TimeValue])) (defmulti ^:private build "Update the options builder using the given map entry." (fn [b entry] (first entry)) :default ::default) (def ^{:doc "A registry map of aliases to profilers."} profiler-aliases (atom {})) ;;; (defn re-escape "Return a pattern that will match the literal string." [s] (str "\\Q" s "\\E")) (defn re-join "Returns a pattern that is the alternation of the pattern sequence." [xs] (apply str (interpose "|" xs))) (defn re-class "Return a pattern that will match members of the given class." [cname members-pattern] (let [cname (if (class? cname) (.getName ^Class cname) cname)] (str "^" (re-escape cname) "\\." members-pattern))) (defn forked-with-arguments? "Return true if the benchmark will run forked with new JVM arguments." [{opts :options}] (let [forks (or (some-> opts :fork :count) (some-> opts :fork) 0)] (and (pos? (long forks)) (-> opts :jvm :args)))) (defn- tiered-stop-argument? [arg] (re-find #"^-XX:TieredStopAtLevel=[123]$" arg)) (defn- check-jvm-arguments "Based on code from ." [benchmarks] (let [compiler (.getName (ManagementFactory/getCompilationMXBean)) args (.getInputArguments (ManagementFactory/getRuntimeMXBean)) stop (some tiered-stop-argument? args) problem? (fn [b] (when-not (forked-with-arguments? b) (util/warn "At least one benchmark will run" "with problematic JVM argument:" stop) true))] (and (.contains compiler "Tiered") stop (some problem? benchmarks)))) ;;; (defn- get-cause "Get at the reason of the benchmark failure." [^Throwable t] (let [t (.getCause t)] (when (instance? BenchmarkException t) (when-let [[^Throwable e & more] (.getSuppressed t)] (doseq [s more] (.addSuppressed e s)) e)))) (defn include-patterns "Returns a seq of include pattern strings." ([benchmarks externs] (include-patterns benchmarks externs false)) ([benchmarks externs warmup?] (distinct (concat (for [b benchmarks :when (= warmup? (boolean (:warmup b)))] (if-let [g (-> b :options :group)] (re-class (:class b) (str (munge (name g)) "$")) (re-class (:class b) (str (:method b) "$")))) (for [x externs :when (= warmup? (boolean (:warmup x)))] (re-class (:class x x) (:select x ".+"))))))) (defn- run* "Run the given command-line arguments and return the result data." [benchmarks opts] (let [status (:jmh/status opts) log (cond (string? status) (io/file status) (not status) (doto (File/createTempFile "jmh" ".txt") .deleteOnExit)) builder (OptionsBuilder.) warmups (include-patterns benchmarks (:externs opts) true) include (remove (set warmups) (include-patterns benchmarks (:externs opts)))] (doseq [entry opts] (build builder entry)) (when (seq warmups) (.includeWarmup builder (re-join warmups))) (if (seq include) (.include builder (re-join include)) (.exclude builder ".")) (when log (.output builder (str log))) (try (.run (Runner. (.build builder))) (catch NoBenchmarksException e (throw (RunnerException. "no benchmarks defined/selected."))) (catch RunnerException e (if-let [cause (get-cause e)] (throw cause) (if (.contains (or (.getMessage e) "") option/ignore-lock) (let [msg (str "could not acquire jmh lock file " "(is another benchmark in progress?): " "use :ignore-lock to bypass.")] (throw (RunnerException. msg))) (throw e)))) (finally (when-not status (.delete log)))))) (defn line-output-stream "Return a stream that will invoke the supplied callback fn for each line read." ^OutputStream [callback] (let [buf (ByteArrayOutputStream. 128)] (proxy [OutputStream] [] (write ([x] (if (number? x) (.write ^OutputStream this (byte-array [x])) (.write ^OutputStream this x 0 (alength ^bytes x)))) ([^bytes arr ^long off ^long len] (let [end (+ off len)] (loop [off off] (if (< off end) (let [b (aget arr off)] (if (== b 10) (do (callback (.toString buf)) (.reset buf)) (.write buf (int b))) (recur (inc off))))))))))) (defn- long-value "Parse the given string and return its primitive long value." ^long [^String s] (.longValue (Long/valueOf s))) (defn progress-print-stream "Return a PrintStream that will parse output into callback data." ^PrintStream [callback] (let [progress-re #"^# Run progress: ([\d.]+)% complete, ETA (\d+):(\d+):(\d+)$" complete-re #"^# Run complete. Total time: (\d+):(\d+):(\d+)$" seconds #(+ (* (long-value %) 60 60) (* (long-value %2) 60) (long-value %3)) on-line (fn [line] (if-let [[_ pct hr min sec] (re-find progress-re line)] (let [pct (* (.doubleValue (Double/valueOf ^String pct)) 0.01) eta (seconds hr min sec)] (when-not (>= pct 1.0) (let [event {:eta eta, :percent pct} event (if (== pct 0.0) (assoc event :start true) event)] (callback event)))) (when-let [[_ hr min sec] (re-find complete-re line)] (let [event {:eta 0, :percent 1.0, :complete true :duration (seconds hr min sec)}] (callback event)))))] (PrintStream. (line-output-stream on-line)))) (defn run "Run and update the benchmark environment with the jmh results." [{benchmarks :jmh/benchmarks, opts :jmh/options :as env}] (let [ignore-orig (System/getProperty option/ignore-lock) out-orig System/out out (if-let [f (and (not (:status opts)) (:progress opts))] (progress-print-stream f) out-orig) status (or (:status opts) (boolean (:progress opts))) opts (assoc opts :jmh/status status)] (when (:warnings opts true) (check-jvm-arguments benchmarks)) (when (option/debug? opts) (util/debug "Running jmh")) (try (when (not= out out-orig) (System/setOut out)) (when (:ignore-lock opts) (System/setProperty option/ignore-lock "true")) (assoc env :jmh/result (run* benchmarks opts)) (finally (when (not= out out-orig) (.flush ^PrintStream out) (System/setOut out-orig)) (when ignore-orig (System/setProperty option/ignore-lock ignore-orig)))))) ;;; (defn- str-array [x] (into-array String (map str (if (coll? x) x [x])))) (defn- time-unit "Convert a time unit keyword to a TimeUnit." [x] (util/check-valid "time-unit" util/time-unit? x)) (defn- time-value "Convert a time tuple to TimeValue." [[n u]] (TimeValue. n (time-unit u))) (defmethod build :fail-on-error [^OptionsBuilder b [_ v]] (.shouldFailOnError b (boolean v))) (defmethod build :fork [^OptionsBuilder b [_ v]] (when-let [x (:count v)] (.forks b (int x))) (when-let [x (:warmups v)] (.warmupForks b (int x))) (when-let [x (get-in v [:jvm :java])] (.jvm b (str x))) (when-let [x (get-in v [:jvm :args])] (.jvmArgs b (str-array x))) (when-let [x (get-in v [:jvm :prepend-args])] (.jvmArgsPrepend b (str-array x))) (when-let [x (get-in v [:jvm :append-args])] (.jvmArgsAppend b (str-array x)))) (defmethod build :iterations [^OptionsBuilder b [_ v]] (.shouldDoGC b (boolean (:gc v (:gc option/defaults)))) (.syncIterations b (boolean (:synchronize v (:synchronize option/defaults))))) (defmethod build :measurement [^OptionsBuilder b [_ v]] (when-let [x (:iterations v)] (.measurementIterations b (int x))) (when-let [x (:count v)] (.measurementBatchSize b (int x))) (when-let [x (:time v)] (.measurementTime b (time-value x)))) (defmethod build :mode [^OptionsBuilder b [_ v]] (doseq [k (util/keyword-seq v)] (.mode b (util/check-valid "mode" util/mode? k)))) (defmethod build :ops-per-invocation [^OptionsBuilder b [_ v]] (.operationsPerInvocation b (int v))) (defmethod build :output-time-unit [^OptionsBuilder b [_ v]] (.timeUnit b (time-unit v))) (defmethod build :params [^OptionsBuilder b [_ v]] (doseq [[k x] (:jmh/externs v)] (.param b (name k) (str-array x)))) (defmethod build :profilers [^OptionsBuilder b [_ v]] (util/check (or (coll? v) (nil? v)) "expected seq of profilers") (doseq [x v] (let [[prof ^String init] (if (coll? x) x [x ""]) prof (get @profiler-aliases prof prof) prof (if (symbol? prof) (Class/forName (name prof)) prof)] (if (string? prof) (.addProfiler b ^String prof init) (.addProfiler b ^Class prof init))))) (defmethod build :thread-groups [^OptionsBuilder b [_ v]] (.threadGroups b (int-array (if (number? v) [v] v)))) (defmethod build :threads [^OptionsBuilder b [_ v]] (.threads b (int v))) (defmethod build :timeout [^OptionsBuilder b [_ v]] (.timeout b (time-value v))) (defmethod build :verbose [^OptionsBuilder b [_ v]] (.verbosity b (util/check-valid "verbose mode" util/verbose-mode? v))) (defmethod build :warmup [^OptionsBuilder b [_ v]] (when-let [x (:iterations v)] (.warmupIterations b (int x))) (when-let [x (:count v)] (.warmupBatchSize b (int x))) (when-let [x (:time v)] (.warmupTime b (time-value x)))) (defmethod build :warmups [^OptionsBuilder b [_ v]] (when-let [x (:mode v)] (.warmupMode b (util/check-valid "warmup mode" util/warmup-mode? x)))) (defmethod build ::default [_ _])
null
https://raw.githubusercontent.com/jgpc42/jmh-clojure/78f6ebcd59d782b0ca3b4f04d15a037657b87304/src/jmh/exec.clj
clojure
(ns ^:internal ^:no-doc jmh.exec "Build command arguments and run benchmarks." (:require [jmh.util :as util] [jmh.option :as option] [clojure.java.io :as io]) (:import [java.io ByteArrayOutputStream File OutputStream PrintStream] [java.lang.management ManagementFactory] [org.openjdk.jmh.runner BenchmarkException NoBenchmarksException Runner RunnerException] [org.openjdk.jmh.runner.options OptionsBuilder TimeValue])) (defmulti ^:private build "Update the options builder using the given map entry." (fn [b entry] (first entry)) :default ::default) (def ^{:doc "A registry map of aliases to profilers."} profiler-aliases (atom {})) (defn re-escape "Return a pattern that will match the literal string." [s] (str "\\Q" s "\\E")) (defn re-join "Returns a pattern that is the alternation of the pattern sequence." [xs] (apply str (interpose "|" xs))) (defn re-class "Return a pattern that will match members of the given class." [cname members-pattern] (let [cname (if (class? cname) (.getName ^Class cname) cname)] (str "^" (re-escape cname) "\\." members-pattern))) (defn forked-with-arguments? "Return true if the benchmark will run forked with new JVM arguments." [{opts :options}] (let [forks (or (some-> opts :fork :count) (some-> opts :fork) 0)] (and (pos? (long forks)) (-> opts :jvm :args)))) (defn- tiered-stop-argument? [arg] (re-find #"^-XX:TieredStopAtLevel=[123]$" arg)) (defn- check-jvm-arguments "Based on code from ." [benchmarks] (let [compiler (.getName (ManagementFactory/getCompilationMXBean)) args (.getInputArguments (ManagementFactory/getRuntimeMXBean)) stop (some tiered-stop-argument? args) problem? (fn [b] (when-not (forked-with-arguments? b) (util/warn "At least one benchmark will run" "with problematic JVM argument:" stop) true))] (and (.contains compiler "Tiered") stop (some problem? benchmarks)))) (defn- get-cause "Get at the reason of the benchmark failure." [^Throwable t] (let [t (.getCause t)] (when (instance? BenchmarkException t) (when-let [[^Throwable e & more] (.getSuppressed t)] (doseq [s more] (.addSuppressed e s)) e)))) (defn include-patterns "Returns a seq of include pattern strings." ([benchmarks externs] (include-patterns benchmarks externs false)) ([benchmarks externs warmup?] (distinct (concat (for [b benchmarks :when (= warmup? (boolean (:warmup b)))] (if-let [g (-> b :options :group)] (re-class (:class b) (str (munge (name g)) "$")) (re-class (:class b) (str (:method b) "$")))) (for [x externs :when (= warmup? (boolean (:warmup x)))] (re-class (:class x x) (:select x ".+"))))))) (defn- run* "Run the given command-line arguments and return the result data." [benchmarks opts] (let [status (:jmh/status opts) log (cond (string? status) (io/file status) (not status) (doto (File/createTempFile "jmh" ".txt") .deleteOnExit)) builder (OptionsBuilder.) warmups (include-patterns benchmarks (:externs opts) true) include (remove (set warmups) (include-patterns benchmarks (:externs opts)))] (doseq [entry opts] (build builder entry)) (when (seq warmups) (.includeWarmup builder (re-join warmups))) (if (seq include) (.include builder (re-join include)) (.exclude builder ".")) (when log (.output builder (str log))) (try (.run (Runner. (.build builder))) (catch NoBenchmarksException e (throw (RunnerException. "no benchmarks defined/selected."))) (catch RunnerException e (if-let [cause (get-cause e)] (throw cause) (if (.contains (or (.getMessage e) "") option/ignore-lock) (let [msg (str "could not acquire jmh lock file " "(is another benchmark in progress?): " "use :ignore-lock to bypass.")] (throw (RunnerException. msg))) (throw e)))) (finally (when-not status (.delete log)))))) (defn line-output-stream "Return a stream that will invoke the supplied callback fn for each line read." ^OutputStream [callback] (let [buf (ByteArrayOutputStream. 128)] (proxy [OutputStream] [] (write ([x] (if (number? x) (.write ^OutputStream this (byte-array [x])) (.write ^OutputStream this x 0 (alength ^bytes x)))) ([^bytes arr ^long off ^long len] (let [end (+ off len)] (loop [off off] (if (< off end) (let [b (aget arr off)] (if (== b 10) (do (callback (.toString buf)) (.reset buf)) (.write buf (int b))) (recur (inc off))))))))))) (defn- long-value "Parse the given string and return its primitive long value." ^long [^String s] (.longValue (Long/valueOf s))) (defn progress-print-stream "Return a PrintStream that will parse output into callback data." ^PrintStream [callback] (let [progress-re #"^# Run progress: ([\d.]+)% complete, ETA (\d+):(\d+):(\d+)$" complete-re #"^# Run complete. Total time: (\d+):(\d+):(\d+)$" seconds #(+ (* (long-value %) 60 60) (* (long-value %2) 60) (long-value %3)) on-line (fn [line] (if-let [[_ pct hr min sec] (re-find progress-re line)] (let [pct (* (.doubleValue (Double/valueOf ^String pct)) 0.01) eta (seconds hr min sec)] (when-not (>= pct 1.0) (let [event {:eta eta, :percent pct} event (if (== pct 0.0) (assoc event :start true) event)] (callback event)))) (when-let [[_ hr min sec] (re-find complete-re line)] (let [event {:eta 0, :percent 1.0, :complete true :duration (seconds hr min sec)}] (callback event)))))] (PrintStream. (line-output-stream on-line)))) (defn run "Run and update the benchmark environment with the jmh results." [{benchmarks :jmh/benchmarks, opts :jmh/options :as env}] (let [ignore-orig (System/getProperty option/ignore-lock) out-orig System/out out (if-let [f (and (not (:status opts)) (:progress opts))] (progress-print-stream f) out-orig) status (or (:status opts) (boolean (:progress opts))) opts (assoc opts :jmh/status status)] (when (:warnings opts true) (check-jvm-arguments benchmarks)) (when (option/debug? opts) (util/debug "Running jmh")) (try (when (not= out out-orig) (System/setOut out)) (when (:ignore-lock opts) (System/setProperty option/ignore-lock "true")) (assoc env :jmh/result (run* benchmarks opts)) (finally (when (not= out out-orig) (.flush ^PrintStream out) (System/setOut out-orig)) (when ignore-orig (System/setProperty option/ignore-lock ignore-orig)))))) (defn- str-array [x] (into-array String (map str (if (coll? x) x [x])))) (defn- time-unit "Convert a time unit keyword to a TimeUnit." [x] (util/check-valid "time-unit" util/time-unit? x)) (defn- time-value "Convert a time tuple to TimeValue." [[n u]] (TimeValue. n (time-unit u))) (defmethod build :fail-on-error [^OptionsBuilder b [_ v]] (.shouldFailOnError b (boolean v))) (defmethod build :fork [^OptionsBuilder b [_ v]] (when-let [x (:count v)] (.forks b (int x))) (when-let [x (:warmups v)] (.warmupForks b (int x))) (when-let [x (get-in v [:jvm :java])] (.jvm b (str x))) (when-let [x (get-in v [:jvm :args])] (.jvmArgs b (str-array x))) (when-let [x (get-in v [:jvm :prepend-args])] (.jvmArgsPrepend b (str-array x))) (when-let [x (get-in v [:jvm :append-args])] (.jvmArgsAppend b (str-array x)))) (defmethod build :iterations [^OptionsBuilder b [_ v]] (.shouldDoGC b (boolean (:gc v (:gc option/defaults)))) (.syncIterations b (boolean (:synchronize v (:synchronize option/defaults))))) (defmethod build :measurement [^OptionsBuilder b [_ v]] (when-let [x (:iterations v)] (.measurementIterations b (int x))) (when-let [x (:count v)] (.measurementBatchSize b (int x))) (when-let [x (:time v)] (.measurementTime b (time-value x)))) (defmethod build :mode [^OptionsBuilder b [_ v]] (doseq [k (util/keyword-seq v)] (.mode b (util/check-valid "mode" util/mode? k)))) (defmethod build :ops-per-invocation [^OptionsBuilder b [_ v]] (.operationsPerInvocation b (int v))) (defmethod build :output-time-unit [^OptionsBuilder b [_ v]] (.timeUnit b (time-unit v))) (defmethod build :params [^OptionsBuilder b [_ v]] (doseq [[k x] (:jmh/externs v)] (.param b (name k) (str-array x)))) (defmethod build :profilers [^OptionsBuilder b [_ v]] (util/check (or (coll? v) (nil? v)) "expected seq of profilers") (doseq [x v] (let [[prof ^String init] (if (coll? x) x [x ""]) prof (get @profiler-aliases prof prof) prof (if (symbol? prof) (Class/forName (name prof)) prof)] (if (string? prof) (.addProfiler b ^String prof init) (.addProfiler b ^Class prof init))))) (defmethod build :thread-groups [^OptionsBuilder b [_ v]] (.threadGroups b (int-array (if (number? v) [v] v)))) (defmethod build :threads [^OptionsBuilder b [_ v]] (.threads b (int v))) (defmethod build :timeout [^OptionsBuilder b [_ v]] (.timeout b (time-value v))) (defmethod build :verbose [^OptionsBuilder b [_ v]] (.verbosity b (util/check-valid "verbose mode" util/verbose-mode? v))) (defmethod build :warmup [^OptionsBuilder b [_ v]] (when-let [x (:iterations v)] (.warmupIterations b (int x))) (when-let [x (:count v)] (.warmupBatchSize b (int x))) (when-let [x (:time v)] (.warmupTime b (time-value x)))) (defmethod build :warmups [^OptionsBuilder b [_ v]] (when-let [x (:mode v)] (.warmupMode b (util/check-valid "warmup mode" util/warmup-mode? x)))) (defmethod build ::default [_ _])
cf3db7ed6baa287840073f9d1b5c086345e9bdb3be9212485b487b6ed0040409
nklein/draw
page.lisp
(in-package #:draw) (defvar *in-document-p* nil "Tracks if we are currently in a document.") (defvar *in-page-p* nil "Tracks if we are currently in a page.") (defvar *page-number* nil "Track the current page number.") (defmacro with-document ((&rest arguments &key &allow-other-keys) &body body) "Run the BODY in a new document context made with the given ARGUMENTS." (let ((argv (gensym "ARGV"))) `(let ((,argv (list ,@arguments))) (forbid-nested-with-document 'with-document ,argv) (let ((*in-document-p* t) (*page-number* 0)) (%with-document *renderer* ,argv (lambda () ,@body)))))) (defmacro with-page ((&rest arguments &key &allow-other-keys) &body body) "Run the BODY in a new page context made with the given ARGUMENTS." (let ((argv (gensym "ARGV"))) `(let ((,argv (list ,@arguments))) (require-with-document 'with-page ,argv) (forbid-nested-with-page 'with-page ,argv) (let ((*in-page-p* t)) (%with-page *renderer* ,argv (lambda () ,@body) (incf *page-number*)))))) (defun page-numbered-filename (output-filename &optional (digits 1)) (let* ((basename (pathname-name output-filename)) (numbered-name (format nil "~A~V,'0D" basename digits *page-number*))) (make-pathname :name numbered-name :defaults output-filename))) (defun write-document (output-filename) "Saves the current document to the OUTPUT-FILENAME with the appropriate extension." (require-with-document 'write-document output-filename) (%write-document *renderer* output-filename))
null
https://raw.githubusercontent.com/nklein/draw/2b7a51fa06c81a46dffc439a35b3b0ac18c94893/src/base/page.lisp
lisp
(in-package #:draw) (defvar *in-document-p* nil "Tracks if we are currently in a document.") (defvar *in-page-p* nil "Tracks if we are currently in a page.") (defvar *page-number* nil "Track the current page number.") (defmacro with-document ((&rest arguments &key &allow-other-keys) &body body) "Run the BODY in a new document context made with the given ARGUMENTS." (let ((argv (gensym "ARGV"))) `(let ((,argv (list ,@arguments))) (forbid-nested-with-document 'with-document ,argv) (let ((*in-document-p* t) (*page-number* 0)) (%with-document *renderer* ,argv (lambda () ,@body)))))) (defmacro with-page ((&rest arguments &key &allow-other-keys) &body body) "Run the BODY in a new page context made with the given ARGUMENTS." (let ((argv (gensym "ARGV"))) `(let ((,argv (list ,@arguments))) (require-with-document 'with-page ,argv) (forbid-nested-with-page 'with-page ,argv) (let ((*in-page-p* t)) (%with-page *renderer* ,argv (lambda () ,@body) (incf *page-number*)))))) (defun page-numbered-filename (output-filename &optional (digits 1)) (let* ((basename (pathname-name output-filename)) (numbered-name (format nil "~A~V,'0D" basename digits *page-number*))) (make-pathname :name numbered-name :defaults output-filename))) (defun write-document (output-filename) "Saves the current document to the OUTPUT-FILENAME with the appropriate extension." (require-with-document 'write-document output-filename) (%write-document *renderer* output-filename))
f87041b8f745b20c8388939095c1f9f99b1ac7e3b85d03898f0c591b56af4c47
agrison/cljwebauthn
core_test.clj
(ns cljwebauthn.core-test (:require [clojure.test :refer :all] [cljwebauthn.core :refer :all] [cljwebauthn.b64 :as b64])) (def site-properties {:site-id "grison.me", :site-name "Stuff and Thoughts about IT Stuff", :protocol "https", :port 443, :host "grison.me"}) (def REGISTER-CHALLENGE "foobar") (def LOGIN-CHALLENGE "foobar2") (def EMAIL "") (deftest test-prepare-challenge (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [prep (prepare-registration EMAIL site-properties)] (is (not (nil? prep))) (is (every? prep [:rp :user :cred :challenge])) (is (= {:rp {:id (:site-id site-properties) :name (:site-name site-properties)} :user {:id (b64/encode EMAIL)} :cred [{:type "public-key" :alg -7}] :challenge REGISTER-CHALLENGE} prep)) (is (contains? (:register @*challenges*) REGISTER-CHALLENGE))))) (def register-payload {:attestation "o2NmbXRmcGFja2VkZ2F0dFN0bXSiY2FsZyZjc2lnWEcwRQIgeOSXUhr3sMAO2WVq/fzmqAJn5RSf00y+2JHWSnrfBH4CIQDX9OvQGKb5q8Fj/SgJuiT2HwAcxtJ2q1FaWugkfiY32mhhdXRoRGF0YVjF09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk1FXo81/q3OAAI1vMYKZIsLJfHwVQMAQQEZBainwiWsYFxuJud3Nst81qcUmRq4jdLB/sOo2EJxZbDa4vF+xh31DS+XYCw9/6Csm75edLI9yIffVJaree8lpQECAyYgASFYIO7qcEAfShtfCKN8k1hJ0Vo1GtJ3toA0+agxwJcu24xzIlggEfYFr083E++o65vZ/I8hCZ3+Jpd1FdbaqAkCY1nvQuI=" :client-data "eyJjaGFsbGVuZ2UiOiJabTl2WW1GeSIsIm9yaWdpbiI6Imh0dHBzOi8vZ3Jpc29uLm1lIiwidHlwZSI6IndlYmF1dGhuLmNyZWF0ZSJ9" :challenge REGISTER-CHALLENGE}) (deftest test-register (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [auth (atom nil) _ (prepare-registration EMAIL site-properties) user (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user " user-id) (reset! auth authenticator))) auth-value @auth] (is (contains? (:register @*challenges*) REGISTER-CHALLENGE)) (is (= {:user-id EMAIL :challenge REGISTER-CHALLENGE} user)) (is (not (nil? auth-value)))))) (deftest test-prepare-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator)))] (with-redefs [generate-challenge (fn [] LOGIN-CHALLENGE)] (let [prep (prepare-login EMAIL (fn [user-id] @auth))] (is (contains? (:login @*challenges*) LOGIN-CHALLENGE)) (is (every? prep [:challenge :credentials])) (is (= LOGIN-CHALLENGE (:challenge prep))) (is (every? (-> prep :credentials first) [:type :id])))))))) (def login-payload {:credential-id "ARkFqKfCJaxgXG4m53c2y3zWpxSZGriN0sH+w6jYQnFlsNri8X7GHfUNL5dgLD3/oKybvl50sj3Ih99Ulqt57yU=" :user-handle "Wm05dlFHSmhjaTVqYjIwPQ==" :authenticator-data "09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk0FXo82Tg==" :client-data "eyJjaGFsbGVuZ2UiOiJabTl2WW1GeU1nIiwib3JpZ2luIjoiaHR0cHM6Ly9ncmlzb24ubWUiLCJ0eXBlIjoid2ViYXV0aG4uZ2V0In0=" :signature "MEUCIQCkfqWpAhi7CRO0exa2wenWgDaakqJq2uUKpDix4UrlcQIgFeDV8HEki7WSjRkz4j+MVLBjypqBD8hSm7gv+gI1roY=" :challenge LOGIN-CHALLENGE}) (deftest test-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator))) user (login-user login-payload site-properties (fn [user-id] @auth))] (is (every? user [:user-id :challenge])) (is (= LOGIN-CHALLENGE (:challenge user))) (is (= EMAIL (b64/decode (b64/decode (:user-id user)))))))))
null
https://raw.githubusercontent.com/agrison/cljwebauthn/3b3577ff126dd5bc42ac0f226ca4de63be33b8ef/test/cljwebauthn/core_test.clj
clojure
(ns cljwebauthn.core-test (:require [clojure.test :refer :all] [cljwebauthn.core :refer :all] [cljwebauthn.b64 :as b64])) (def site-properties {:site-id "grison.me", :site-name "Stuff and Thoughts about IT Stuff", :protocol "https", :port 443, :host "grison.me"}) (def REGISTER-CHALLENGE "foobar") (def LOGIN-CHALLENGE "foobar2") (def EMAIL "") (deftest test-prepare-challenge (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [prep (prepare-registration EMAIL site-properties)] (is (not (nil? prep))) (is (every? prep [:rp :user :cred :challenge])) (is (= {:rp {:id (:site-id site-properties) :name (:site-name site-properties)} :user {:id (b64/encode EMAIL)} :cred [{:type "public-key" :alg -7}] :challenge REGISTER-CHALLENGE} prep)) (is (contains? (:register @*challenges*) REGISTER-CHALLENGE))))) (def register-payload {:attestation "o2NmbXRmcGFja2VkZ2F0dFN0bXSiY2FsZyZjc2lnWEcwRQIgeOSXUhr3sMAO2WVq/fzmqAJn5RSf00y+2JHWSnrfBH4CIQDX9OvQGKb5q8Fj/SgJuiT2HwAcxtJ2q1FaWugkfiY32mhhdXRoRGF0YVjF09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk1FXo81/q3OAAI1vMYKZIsLJfHwVQMAQQEZBainwiWsYFxuJud3Nst81qcUmRq4jdLB/sOo2EJxZbDa4vF+xh31DS+XYCw9/6Csm75edLI9yIffVJaree8lpQECAyYgASFYIO7qcEAfShtfCKN8k1hJ0Vo1GtJ3toA0+agxwJcu24xzIlggEfYFr083E++o65vZ/I8hCZ3+Jpd1FdbaqAkCY1nvQuI=" :client-data "eyJjaGFsbGVuZ2UiOiJabTl2WW1GeSIsIm9yaWdpbiI6Imh0dHBzOi8vZ3Jpc29uLm1lIiwidHlwZSI6IndlYmF1dGhuLmNyZWF0ZSJ9" :challenge REGISTER-CHALLENGE}) (deftest test-register (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [auth (atom nil) _ (prepare-registration EMAIL site-properties) user (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user " user-id) (reset! auth authenticator))) auth-value @auth] (is (contains? (:register @*challenges*) REGISTER-CHALLENGE)) (is (= {:user-id EMAIL :challenge REGISTER-CHALLENGE} user)) (is (not (nil? auth-value)))))) (deftest test-prepare-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator)))] (with-redefs [generate-challenge (fn [] LOGIN-CHALLENGE)] (let [prep (prepare-login EMAIL (fn [user-id] @auth))] (is (contains? (:login @*challenges*) LOGIN-CHALLENGE)) (is (every? prep [:challenge :credentials])) (is (= LOGIN-CHALLENGE (:challenge prep))) (is (every? (-> prep :credentials first) [:type :id])))))))) (def login-payload {:credential-id "ARkFqKfCJaxgXG4m53c2y3zWpxSZGriN0sH+w6jYQnFlsNri8X7GHfUNL5dgLD3/oKybvl50sj3Ih99Ulqt57yU=" :user-handle "Wm05dlFHSmhjaTVqYjIwPQ==" :authenticator-data "09CVCOxdEGxTwSc5mFMLk7vvUH763HGL3Wl3siTnwk0FXo82Tg==" :client-data "eyJjaGFsbGVuZ2UiOiJabTl2WW1GeU1nIiwib3JpZ2luIjoiaHR0cHM6Ly9ncmlzb24ubWUiLCJ0eXBlIjoid2ViYXV0aG4uZ2V0In0=" :signature "MEUCIQCkfqWpAhi7CRO0exa2wenWgDaakqJq2uUKpDix4UrlcQIgFeDV8HEki7WSjRkz4j+MVLBjypqBD8hSm7gv+gI1roY=" :challenge LOGIN-CHALLENGE}) (deftest test-login (let [auth (atom nil)] (with-redefs [generate-challenge (fn [] REGISTER-CHALLENGE)] (let [_ (prepare-registration EMAIL site-properties) _ (register-user register-payload site-properties (fn [user-id authenticator] (println "Registering user" user-id) (reset! auth authenticator))) user (login-user login-payload site-properties (fn [user-id] @auth))] (is (every? user [:user-id :challenge])) (is (= LOGIN-CHALLENGE (:challenge user))) (is (= EMAIL (b64/decode (b64/decode (:user-id user)))))))))
8083aee74c8e3cc9283f7e36d506255131e0a406e97f560b163e79838f6ea67d
vimus/vimus
Util.hs
module Vimus.Util where import Control.Applicative import Data.List (isPrefixOf) import Data.Char as Char import Data.Maybe (fromJust) import System.FilePath ((</>)) import System.Environment (getEnvironment) import Network.MPD (MonadMPD, PlaylistName, Id) import qualified Network.MPD as MPD -- | Remove leading and trailing whitespace strip :: String -> String strip = dropWhile Char.isSpace . reverse . dropWhile Char.isSpace . reverse data MatchResult = None | Match String | Ambiguous [String] deriving (Eq, Show) match :: String -> [String] -> MatchResult match s l = case filter (isPrefixOf s) l of [] -> None [x] -> Match x xs -> if s `elem` xs then Match s else Ambiguous xs -- | Get longest common prefix of a list of strings. -- > > > commonPrefix [ " foobar " , " foobaz " , " foosomething " ] -- "foo" commonPrefix :: [String] -> String commonPrefix [] = "" commonPrefix xs = foldr1 go xs where go (y:ys) (z:zs) | y == z = y : go ys zs go _ _ = [] -- | Add a song which is inside a playlist, returning its id. addPlaylistSong :: MonadMPD m => PlaylistName -> Int -> m Id addPlaylistSong plist index = do current <- MPD.playlistInfo Nothing MPD.load plist new <- MPD.playlistInfo Nothing let (first, this:rest) = splitAt index . map (fromJust . MPD.sgId) $ drop (length current) new mapM_ MPD.deleteId $ first ++ rest return this | A copy of ` System.Process.Internals.translate ` . posixEscape :: String -> String posixEscape str = '\'' : foldr escape "'" str where escape '\'' = showString "'\\''" escape c = showChar c -- | Expand a tilde at the start of a string to the users home directory. -- -- Expansion is only performed if the tilde is either followed by a slash or -- the only character in the string. expandHome :: FilePath -> IO (Either String FilePath) expandHome path = do home <- maybe err Right . lookup "HOME" <$> getEnvironment case path of "~" -> return home '~' : '/' : xs -> return $ (</> xs) `fmap` home xs -> return (Right xs) where err = Left ("expansion of " ++ show path ++ " failed: $HOME is not defined") -- | Confine a number to an interval. -- -- The result will be greater or equal to a given lower bound and (if still -- possible) smaller than a given upper bound. clamp :: Int -- ^ lower bound (inclusive) -> Int -- ^ upper bound (exclusive) -> Int -> Int clamp lower upper n = max lower $ min (pred upper) n -- | Emit ANSI sequence to change the console window title. setTitle :: String -> IO () setTitle title = putStrLn $ "\ESC]0;" ++ filter (/= '\007') title ++ "\007"
null
https://raw.githubusercontent.com/vimus/vimus/26a164fb50870f8112ca4b6c30820431c015916f/src/Vimus/Util.hs
haskell
| Remove leading and trailing whitespace | Get longest common prefix of a list of strings. "foo" | Add a song which is inside a playlist, returning its id. | Expand a tilde at the start of a string to the users home directory. Expansion is only performed if the tilde is either followed by a slash or the only character in the string. | Confine a number to an interval. The result will be greater or equal to a given lower bound and (if still possible) smaller than a given upper bound. ^ lower bound (inclusive) ^ upper bound (exclusive) | Emit ANSI sequence to change the console window title.
module Vimus.Util where import Control.Applicative import Data.List (isPrefixOf) import Data.Char as Char import Data.Maybe (fromJust) import System.FilePath ((</>)) import System.Environment (getEnvironment) import Network.MPD (MonadMPD, PlaylistName, Id) import qualified Network.MPD as MPD strip :: String -> String strip = dropWhile Char.isSpace . reverse . dropWhile Char.isSpace . reverse data MatchResult = None | Match String | Ambiguous [String] deriving (Eq, Show) match :: String -> [String] -> MatchResult match s l = case filter (isPrefixOf s) l of [] -> None [x] -> Match x xs -> if s `elem` xs then Match s else Ambiguous xs > > > commonPrefix [ " foobar " , " foobaz " , " foosomething " ] commonPrefix :: [String] -> String commonPrefix [] = "" commonPrefix xs = foldr1 go xs where go (y:ys) (z:zs) | y == z = y : go ys zs go _ _ = [] addPlaylistSong :: MonadMPD m => PlaylistName -> Int -> m Id addPlaylistSong plist index = do current <- MPD.playlistInfo Nothing MPD.load plist new <- MPD.playlistInfo Nothing let (first, this:rest) = splitAt index . map (fromJust . MPD.sgId) $ drop (length current) new mapM_ MPD.deleteId $ first ++ rest return this | A copy of ` System.Process.Internals.translate ` . posixEscape :: String -> String posixEscape str = '\'' : foldr escape "'" str where escape '\'' = showString "'\\''" escape c = showChar c expandHome :: FilePath -> IO (Either String FilePath) expandHome path = do home <- maybe err Right . lookup "HOME" <$> getEnvironment case path of "~" -> return home '~' : '/' : xs -> return $ (</> xs) `fmap` home xs -> return (Right xs) where err = Left ("expansion of " ++ show path ++ " failed: $HOME is not defined") -> Int -> Int clamp lower upper n = max lower $ min (pred upper) n setTitle :: String -> IO () setTitle title = putStrLn $ "\ESC]0;" ++ filter (/= '\007') title ++ "\007"
72dbb2843ee18a2acd9100f6d4fe0a3ca14f48e4d6451493c38303d6c3c6faf5
ReactiveX/RxClojure
interop_test.clj
(ns rx.lang.clojure.interop-test (:require [rx.lang.clojure.interop :as rx] [clojure.test :refer [deftest testing is]]) (:import [rx Observable] [rx.observables BlockingObservable] [rx.lang.clojure.interop DummyObservable])) (deftest test-fn* (testing "implements Func0-9" (let [f (rx/fn* vector)] (is (instance? rx.functions.Func0 f)) (is (instance? rx.functions.Func1 f)) (is (instance? rx.functions.Func2 f)) (is (instance? rx.functions.Func3 f)) (is (instance? rx.functions.Func4 f)) (is (instance? rx.functions.Func5 f)) (is (instance? rx.functions.Func6 f)) (is (instance? rx.functions.Func7 f)) (is (instance? rx.functions.Func8 f)) (is (instance? rx.functions.Func9 f)) (is (= [] (.call f))) (is (= [1] (.call f 1))) (is (= [1 2] (.call f 1 2))) (is (= [1 2 3] (.call f 1 2 3))) (is (= [1 2 3 4] (.call f 1 2 3 4))) (is (= [1 2 3 4 5] (.call f 1 2 3 4 5))) (is (= [1 2 3 4 5 6] (.call f 1 2 3 4 5 6))) (is (= [1 2 3 4 5 6 7] (.call f 1 2 3 4 5 6 7))) (is (= [1 2 3 4 5 6 7 8] (.call f 1 2 3 4 5 6 7 8))) (is (= [1 2 3 4 5 6 7 8 9] (.call f 1 2 3 4 5 6 7 8 9))))) (let [dummy (DummyObservable.)] (testing "preserves metadata applied to form" ; No type hint, picks Object overload (is (= "Object" (.call dummy (rx/fn* +)))) (is (= "rx.functions.Func1" (.call dummy ^rx.functions.Func1 (rx/fn* +)))) (is (= "rx.functions.Func2" (.call dummy ^rx.functions.Func2 (rx/fn* *))))))) (deftest test-fn (testing "makes appropriate Func*" (let [f (rx/fn [a b c] (println "test-fn") (+ a b c))] (is (= 6 (.call f 1 2 3))))) (let [dummy (DummyObservable.)] (testing "preserves metadata applied to form" ; No type hint, picks Object overload (is (= "Object" (.call dummy (rx/fn [a] a)))) (is (= "rx.functions.Func1" (.call dummy ^rx.functions.Func1 (rx/fn [a] a)))) (is (= "rx.functions.Func2" (.call dummy ^rx.functions.Func2 (rx/fn [a b] (* a b)))))))) (deftest test-fnN* (testing "implements FuncN" (is (= (vec (range 99)) (.call (rx/fnN* vector) (into-array Object (range 99))))))) (deftest test-action* (testing "implements Action0-3" (let [calls (atom []) a (rx/action* #(swap! calls conj (vec %&)))] (is (instance? rx.Observable$OnSubscribe a)) (is (instance? rx.functions.Action0 a)) (is (instance? rx.functions.Action1 a)) (is (instance? rx.functions.Action2 a)) (is (instance? rx.functions.Action3 a)) (.call a) (.call a 1) (.call a 1 2) (.call a 1 2 3) (is (= [[] [1] [1 2] [1 2 3]])))) (let [dummy (DummyObservable.)] (testing "preserves metadata applied to form" ; no meta, picks Object overload (is (= "Object" (.call dummy (rx/action* println)))) (is (= "rx.functions.Action1" (.call dummy ^rx.functions.Action1 (rx/action* println)))) (is (= "rx.functions.Action2" (.call dummy ^rx.functions.Action2 (rx/action* prn))))))) (deftest test-action (testing "makes appropriate Action*" (let [called (atom nil) a (rx/action [a b] (reset! called [a b]))] (.call a 9 10) (is (= [9 10] @called)))) (let [dummy (DummyObservable.)] (testing "preserves metadata applied to form" ; no meta, picks Object overload (is (= "Object" (.call dummy (rx/action [a] a)))) (is (= "rx.functions.Action1" (.call dummy ^rx.functions.Action1 (rx/action [a] a)))) (is (= "rx.functions.Action2" (.call dummy ^rx.functions.Action2 (rx/action [a b] (* a b)))))))) (deftest test-basic-usage (testing "can create an observable with new-style action" (is (= 99 (-> (Observable/create (rx/action [^rx.Subscriber s] (when-not (.isUnsubscribed s) (.onNext s 99)) (.onCompleted s))) BlockingObservable/from .single)))) (testing "can pass rx/fn to map and friends" (is (= (+ 1 4 9) (-> (Observable/from [1 2 3]) (.map (rx/fn [v] (* v v))) (.reduce (rx/fn* +)) BlockingObservable/from .single)))) (testing "can pass rx/action to subscribe and friends" (let [finally-called (atom nil) complete-called (promise) result (atom []) o (-> (Observable/from ["4" "5" "6"]) (.map (rx/fn* #(Long/parseLong %))) (.finallyDo (rx/action [] (reset! finally-called true))) (.reduce (rx/fn [a v] (* a v))) (.subscribe (rx/action [v] (swap! result conj v)) (rx/action [e]) (rx/action [] (deliver complete-called true)))) ] (is (= true @complete-called)) (is (= true @finally-called)) (is (= [(* 4 5 6)] @result))))) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
null
https://raw.githubusercontent.com/ReactiveX/RxClojure/8f8e454f447ae24549bcf5f001c9d2458af21cac/src/test/clojure/rx/lang/clojure/interop_test.clj
clojure
No type hint, picks Object overload No type hint, picks Object overload no meta, picks Object overload no meta, picks Object overload
(ns rx.lang.clojure.interop-test (:require [rx.lang.clojure.interop :as rx] [clojure.test :refer [deftest testing is]]) (:import [rx Observable] [rx.observables BlockingObservable] [rx.lang.clojure.interop DummyObservable])) (deftest test-fn* (testing "implements Func0-9" (let [f (rx/fn* vector)] (is (instance? rx.functions.Func0 f)) (is (instance? rx.functions.Func1 f)) (is (instance? rx.functions.Func2 f)) (is (instance? rx.functions.Func3 f)) (is (instance? rx.functions.Func4 f)) (is (instance? rx.functions.Func5 f)) (is (instance? rx.functions.Func6 f)) (is (instance? rx.functions.Func7 f)) (is (instance? rx.functions.Func8 f)) (is (instance? rx.functions.Func9 f)) (is (= [] (.call f))) (is (= [1] (.call f 1))) (is (= [1 2] (.call f 1 2))) (is (= [1 2 3] (.call f 1 2 3))) (is (= [1 2 3 4] (.call f 1 2 3 4))) (is (= [1 2 3 4 5] (.call f 1 2 3 4 5))) (is (= [1 2 3 4 5 6] (.call f 1 2 3 4 5 6))) (is (= [1 2 3 4 5 6 7] (.call f 1 2 3 4 5 6 7))) (is (= [1 2 3 4 5 6 7 8] (.call f 1 2 3 4 5 6 7 8))) (is (= [1 2 3 4 5 6 7 8 9] (.call f 1 2 3 4 5 6 7 8 9))))) (let [dummy (DummyObservable.)] (testing "preserves metadata applied to form" (is (= "Object" (.call dummy (rx/fn* +)))) (is (= "rx.functions.Func1" (.call dummy ^rx.functions.Func1 (rx/fn* +)))) (is (= "rx.functions.Func2" (.call dummy ^rx.functions.Func2 (rx/fn* *))))))) (deftest test-fn (testing "makes appropriate Func*" (let [f (rx/fn [a b c] (println "test-fn") (+ a b c))] (is (= 6 (.call f 1 2 3))))) (let [dummy (DummyObservable.)] (testing "preserves metadata applied to form" (is (= "Object" (.call dummy (rx/fn [a] a)))) (is (= "rx.functions.Func1" (.call dummy ^rx.functions.Func1 (rx/fn [a] a)))) (is (= "rx.functions.Func2" (.call dummy ^rx.functions.Func2 (rx/fn [a b] (* a b)))))))) (deftest test-fnN* (testing "implements FuncN" (is (= (vec (range 99)) (.call (rx/fnN* vector) (into-array Object (range 99))))))) (deftest test-action* (testing "implements Action0-3" (let [calls (atom []) a (rx/action* #(swap! calls conj (vec %&)))] (is (instance? rx.Observable$OnSubscribe a)) (is (instance? rx.functions.Action0 a)) (is (instance? rx.functions.Action1 a)) (is (instance? rx.functions.Action2 a)) (is (instance? rx.functions.Action3 a)) (.call a) (.call a 1) (.call a 1 2) (.call a 1 2 3) (is (= [[] [1] [1 2] [1 2 3]])))) (let [dummy (DummyObservable.)] (testing "preserves metadata applied to form" (is (= "Object" (.call dummy (rx/action* println)))) (is (= "rx.functions.Action1" (.call dummy ^rx.functions.Action1 (rx/action* println)))) (is (= "rx.functions.Action2" (.call dummy ^rx.functions.Action2 (rx/action* prn))))))) (deftest test-action (testing "makes appropriate Action*" (let [called (atom nil) a (rx/action [a b] (reset! called [a b]))] (.call a 9 10) (is (= [9 10] @called)))) (let [dummy (DummyObservable.)] (testing "preserves metadata applied to form" (is (= "Object" (.call dummy (rx/action [a] a)))) (is (= "rx.functions.Action1" (.call dummy ^rx.functions.Action1 (rx/action [a] a)))) (is (= "rx.functions.Action2" (.call dummy ^rx.functions.Action2 (rx/action [a b] (* a b)))))))) (deftest test-basic-usage (testing "can create an observable with new-style action" (is (= 99 (-> (Observable/create (rx/action [^rx.Subscriber s] (when-not (.isUnsubscribed s) (.onNext s 99)) (.onCompleted s))) BlockingObservable/from .single)))) (testing "can pass rx/fn to map and friends" (is (= (+ 1 4 9) (-> (Observable/from [1 2 3]) (.map (rx/fn [v] (* v v))) (.reduce (rx/fn* +)) BlockingObservable/from .single)))) (testing "can pass rx/action to subscribe and friends" (let [finally-called (atom nil) complete-called (promise) result (atom []) o (-> (Observable/from ["4" "5" "6"]) (.map (rx/fn* #(Long/parseLong %))) (.finallyDo (rx/action [] (reset! finally-called true))) (.reduce (rx/fn [a v] (* a v))) (.subscribe (rx/action [v] (swap! result conj v)) (rx/action [e]) (rx/action [] (deliver complete-called true)))) ] (is (= true @complete-called)) (is (= true @finally-called)) (is (= [(* 4 5 6)] @result))))) # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
dc86d9f2e82f7c0c2e46d3c88ec1a7280def1a2d12758be9d459744ce0217c09
ollef/sixten
Scoped.hs
{-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # # LANGUAGE DeriveGeneric # {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE GADTs #-} # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # module Syntax.Pre.Scoped ( module Definition , module Pre , Expr(..), Type , clause, pi_, telePis, lam, case_ , apps , appsView , LetRec(..), LetBinding(..), Branches(..), Branch(..) ) where import Protolude hiding (Type) import qualified Bound import Data.Bifoldable import Data.Deriving import Data.Bitraversable import Data.Foldable as Foldable import Data.Functor.Classes import Data.Hashable.Lifted import Data.HashSet(HashSet) import Data.Vector(Vector) import qualified Data.Vector as Vector import Syntax hiding (Branches, LetBinding, LetRec, Pat) import qualified Syntax import Syntax.Pre.Definition as Definition import Syntax.Pre.Literal as Pre import Util import Util.Tsil data Expr v = Var v | Global QName | Lit Pre.Literal | Con (HashSet QConstr) | Pi !Plicitness (Pat Expr v) (PatternScope Expr v) | Lam !Plicitness (Pat Expr v) (PatternScope Expr v) | App (Expr v) !Plicitness (Expr v) | Let (LetRec Expr v) (Scope LetVar Expr v) | Case (Expr v) (Branches Expr v) | ExternCode (Extern (Expr v)) | Wildcard | SourceLoc !SourceLoc (Expr v) deriving (Generic, Hashable, Generic1, Hashable1, Functor, Foldable, Traversable) type Pat expr v = Syntax.Pat (HashSet QConstr) Pre.Literal NameHint (PatternScope expr v) newtype Branches expr v = Branches [Branch expr v] deriving (Generic, Hashable, Generic1, Hashable1, Functor, Foldable, Traversable, Eq) data Branch expr v = Branch !SourceLoc (Pat expr v) (PatternScope expr v) deriving (Generic, Hashable, Generic1, Hashable1, Functor, Foldable, Traversable, Eq) newtype LetRec expr v = LetRec (Vector (LetBinding expr v)) deriving (Generic, Hashable, Generic1, Hashable1, Functor, Foldable, Traversable) data LetBinding expr v = LetBinding !SourceLoc !NameHint (ConstantDef expr (Bound.Var LetVar v)) deriving (Generic, Generic1, Hashable1, Functor, Foldable, Traversable) deriving instance (Monad expr, Eq (expr (Bound.Var LetVar v)), Eq v, Eq1 expr) => Eq (LetBinding expr v) deriving instance (Monad expr, Eq (expr (Bound.Var LetVar v)), Eq v, Eq1 expr) => Eq (LetRec expr v) -- | Synonym for documentation purposes type Type = Expr ------------------------------------------------------------------------------- -- Helpers clause :: (Monad expr, Hashable v, Eq v) => SourceLoc -> (v -> NameHint) -> Vector (Plicitness, Syntax.Pat (HashSet QConstr) Pre.Literal v (expr v)) -> expr v -> Clause expr v clause loc h plicitPats e = do let pats = snd <$> plicitPats vars = pats >>= bifoldMap pure mempty typedPats = fmap (bimap h abstr) <$> plicitPats abstr = abstract $ patternAbstraction vars Clause loc typedPats $ abstr e pi_ :: (Hashable v, Eq v) => (v -> NameHint) -> Plicitness -> Syntax.Pat (HashSet QConstr) Pre.Literal v (Expr v) -> Expr v -> Expr v pi_ h p pat = Pi p (bimap h abstr pat) . abstr where abstr = abstract $ patternAbstraction vs vs = bifoldMap pure mempty pat pis :: (Hashable v, Eq v, Foldable t) => (v -> NameHint) -> t (Plicitness, Syntax.Pat (HashSet QConstr) Pre.Literal v (Expr v)) -> Expr v -> Expr v pis h pats e = foldr (uncurry $ pi_ h) e pats telePis :: (Hashable v, Eq v) => (v -> NameHint) -> Telescope Type v -> Expr v -> Expr v telePis h tele e = fmap (unvar (panic "telePis") identity) $ pis h' pats $ F <$> e where h' = unvar (\(TeleVar v) -> teleHints tele Vector.! v) h pats = iforTele tele $ \i _ p s -> (p, AnnoPat (VarPat $ B $ TeleVar i) $ fromScope s) lam :: (Hashable v, Eq v) => (v -> NameHint) -> Plicitness -> Syntax.Pat (HashSet QConstr) Pre.Literal v (Type v) -> Expr v -> Expr v lam h p pat = Lam p (bimap h abstr pat) . abstr where abstr = abstract $ patternAbstraction vs vs = bifoldMap pure mempty pat case_ :: (Hashable v, Eq v) => (v -> NameHint) -> Expr v -> [(SourceLoc, Syntax.Pat (HashSet QConstr) Pre.Literal v (Type v), Expr v)] -> Expr v case_ h expr pats = Case expr $ Branches $ go <$> pats where go (loc, pat, e) = Branch loc (bimap h abstr pat) (abstr e) where abstr = abstract $ patternAbstraction vs vs = bifoldMap pure mempty pat apps :: Foldable t => Expr v -> t (Plicitness, Expr v) -> Expr v apps = Foldable.foldl' (uncurry . App) appsView :: Expr v -> (Expr v, [(Plicitness, Expr v)]) appsView = second toList . go where go (SourceLoc _ e) = go e go (App e1 p e2) = second (`Snoc` (p, e2)) $ go e1 go e = (e, Nil) ------------------------------------------------------------------------------- -- Instances instance Applicative Expr where pure = return (<*>) = ap instance Monad Expr where return = Var expr >>= f = case expr of Var v -> f v Global v -> Global v Lit l -> Lit l Con c -> Con c Pi p pat s -> Pi p ((>>>= f) <$> pat) (s >>>= f) Lam p pat s -> Lam p ((>>>= f) <$> pat) (s >>>= f) App e1 p e2 -> App (e1 >>= f) p (e2 >>= f) Let defs s -> Let (defs >>>= f) (s >>>= f) Case e brs -> Case (e >>= f) (brs >>>= f) ExternCode c -> ExternCode ((>>= f) <$> c) Wildcard -> Wildcard SourceLoc r e -> SourceLoc r (e >>= f) instance Bound Branches where Branches brs >>>= f = Branches $ (>>>= f) <$> brs instance Bound Branch where Branch loc pat s >>>= f = Branch loc ((>>>= f) <$> pat) $ s >>>= f instance Bound LetRec where LetRec ds >>>= f = LetRec $ (>>>= f) <$> ds instance Bound LetBinding where LetBinding loc h def >>>= f = LetBinding loc h $ def >>>= bitraverse pure f instance GBound Branches where gbound f (Branches brs) = Branches $ gbound f <$> brs instance GBound Branch where gbound f (Branch loc pat s) = Branch loc (gbound f <$> pat) (gbound f s) instance GBound LetRec where gbound f (LetRec ds) = LetRec $ gbound f <$> ds instance GBound LetBinding where gbound f (LetBinding loc h def) = LetBinding loc h $ gbound (fmap pure . f) def instance (Monad expr, Hashable1 expr, Hashable v) => Hashable (LetBinding expr v) where hashWithSalt salt (LetBinding loc h cd) = liftHashWithSalt hashWithSalt (salt `hashWithSalt` loc `hashWithSalt` h) cd instance GBind Expr QName where global = Global gbind f expr = case expr of Var _ -> expr Global v -> f v Lit _ -> expr Con _ -> expr Pi p pat s -> Pi p (gbound f <$> pat) (gbound f s) Lam p pat s -> Lam p (gbound f <$> pat) (gbound f s) App e1 p e2 -> App (gbind f e1) p (gbind f e2) Let defs s -> Let (gbound f defs) (gbound f s) Case e brs -> Case (gbind f e) (gbound f brs) ExternCode c -> ExternCode (gbind f <$> c) Wildcard -> Wildcard SourceLoc r e -> SourceLoc r (gbind f e) instance v ~ Doc => Pretty (Expr v) where prettyM expr = case expr of Var v -> prettyM v Global g -> prettyM g Lit l -> prettyM l Con c -> prettyM $ toList c Pi p (AnnoPat WildcardPat t) s -> parens `above` arrPrec $ do let inst = instantiatePattern (pure . fromName) mempty prettyAnnotation p (prettyM $ inst t) <+> "->" <+> associate arrPrec (prettyM $ inst s) Pi p pat s -> withNameHints (bifoldMap pure mempty pat) $ \ns -> do let inst = instantiatePattern (pure . fromName) ns parens `above` arrPrec $ prettyAnnotation p (prettyPattern ns $ inst <$> pat) <+> "->" <+> associate arrPrec (prettyM $ inst s) Lam p pat s -> withNameHints (bifoldMap pure mempty pat) $ \ns -> do let inst = instantiatePattern (pure . fromName) ns parens `above` absPrec $ "\\" <> prettyAnnotation p (prettyPattern ns $ inst <$> pat) <> "." <+> associate absPrec (prettyM $ inst s) App e1 p e2 -> prettyApp (prettyM e1) (prettyAnnotation p $ prettyM e2) Let (LetRec defs) scope -> parens `above` letPrec $ withNameHints ((\(LetBinding _ h _) -> h) <$> defs) $ \ns -> let go = ifor defs $ \i (LetBinding _ _ cl) -> prettyNamed (prettyM $ ns Vector.! i) (instantiateConstantDef (pure . fromName . (ns Vector.!) . unLetVar) cl) in "let" <+> align (vcat go) <+> "in" <+> prettyM (instantiateLet (pure . fromName) ns scope) Case e (Branches brs) -> parens `above` casePrec $ "case" <+> inviolable (prettyM e) <+> "of" <$$> indent 2 (vcat $ prettyBranch <$> brs) ExternCode c -> prettyM c Wildcard -> "_" SourceLoc _ e -> prettyM e where prettyBranch (Branch _ pat br) = withNameHints (bifoldMap pure mempty pat) $ \ns -> do let inst = instantiatePattern (pure . fromName) ns prettyPattern ns (inst <$> pat) <+> "->" <+> prettyM (inst br) return [] deriveEq ''Expr deriveEq1 ''Expr deriveShow1 ''Expr instance (Eq1 expr, Monad expr) => Eq1 (LetRec expr) where liftEq = $(makeLiftEq ''LetRec) instance (Show1 expr, Monad expr) => Show1 (LetRec expr) where liftShowsPrec = $(makeLiftShowsPrec ''LetRec) instance (Eq1 expr, Monad expr) => Eq1 (LetBinding expr) where liftEq = $(makeLiftEq ''LetBinding) instance (Show1 expr, Monad expr) => Show1 (LetBinding expr) where liftShowsPrec = $(makeLiftShowsPrec ''LetBinding) instance (Eq1 expr, Monad expr) => Eq1 (Branches expr) where liftEq = $(makeLiftEq ''Branches) instance (Show1 expr, Monad expr) => Show1 (Branches expr) where liftShowsPrec = $(makeLiftShowsPrec ''Branches) instance (Eq1 expr, Monad expr) => Eq1 (Branch expr) where liftEq = $(makeLiftEq ''Branch) instance (Show1 expr, Monad expr) => Show1 (Branch expr) where liftShowsPrec = $(makeLiftShowsPrec ''Branch)
null
https://raw.githubusercontent.com/ollef/sixten/60d46eee20abd62599badea85774a9365c81af45/src/Syntax/Pre/Scoped.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE DeriveTraversable # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # | Synonym for documentation purposes ----------------------------------------------------------------------------- Helpers ----------------------------------------------------------------------------- Instances
# LANGUAGE DeriveFoldable # # LANGUAGE DeriveFunctor # # LANGUAGE DeriveGeneric # # LANGUAGE MultiParamTypeClasses # # LANGUAGE StandaloneDeriving # # LANGUAGE TemplateHaskell # # LANGUAGE UndecidableInstances # module Syntax.Pre.Scoped ( module Definition , module Pre , Expr(..), Type , clause, pi_, telePis, lam, case_ , apps , appsView , LetRec(..), LetBinding(..), Branches(..), Branch(..) ) where import Protolude hiding (Type) import qualified Bound import Data.Bifoldable import Data.Deriving import Data.Bitraversable import Data.Foldable as Foldable import Data.Functor.Classes import Data.Hashable.Lifted import Data.HashSet(HashSet) import Data.Vector(Vector) import qualified Data.Vector as Vector import Syntax hiding (Branches, LetBinding, LetRec, Pat) import qualified Syntax import Syntax.Pre.Definition as Definition import Syntax.Pre.Literal as Pre import Util import Util.Tsil data Expr v = Var v | Global QName | Lit Pre.Literal | Con (HashSet QConstr) | Pi !Plicitness (Pat Expr v) (PatternScope Expr v) | Lam !Plicitness (Pat Expr v) (PatternScope Expr v) | App (Expr v) !Plicitness (Expr v) | Let (LetRec Expr v) (Scope LetVar Expr v) | Case (Expr v) (Branches Expr v) | ExternCode (Extern (Expr v)) | Wildcard | SourceLoc !SourceLoc (Expr v) deriving (Generic, Hashable, Generic1, Hashable1, Functor, Foldable, Traversable) type Pat expr v = Syntax.Pat (HashSet QConstr) Pre.Literal NameHint (PatternScope expr v) newtype Branches expr v = Branches [Branch expr v] deriving (Generic, Hashable, Generic1, Hashable1, Functor, Foldable, Traversable, Eq) data Branch expr v = Branch !SourceLoc (Pat expr v) (PatternScope expr v) deriving (Generic, Hashable, Generic1, Hashable1, Functor, Foldable, Traversable, Eq) newtype LetRec expr v = LetRec (Vector (LetBinding expr v)) deriving (Generic, Hashable, Generic1, Hashable1, Functor, Foldable, Traversable) data LetBinding expr v = LetBinding !SourceLoc !NameHint (ConstantDef expr (Bound.Var LetVar v)) deriving (Generic, Generic1, Hashable1, Functor, Foldable, Traversable) deriving instance (Monad expr, Eq (expr (Bound.Var LetVar v)), Eq v, Eq1 expr) => Eq (LetBinding expr v) deriving instance (Monad expr, Eq (expr (Bound.Var LetVar v)), Eq v, Eq1 expr) => Eq (LetRec expr v) type Type = Expr clause :: (Monad expr, Hashable v, Eq v) => SourceLoc -> (v -> NameHint) -> Vector (Plicitness, Syntax.Pat (HashSet QConstr) Pre.Literal v (expr v)) -> expr v -> Clause expr v clause loc h plicitPats e = do let pats = snd <$> plicitPats vars = pats >>= bifoldMap pure mempty typedPats = fmap (bimap h abstr) <$> plicitPats abstr = abstract $ patternAbstraction vars Clause loc typedPats $ abstr e pi_ :: (Hashable v, Eq v) => (v -> NameHint) -> Plicitness -> Syntax.Pat (HashSet QConstr) Pre.Literal v (Expr v) -> Expr v -> Expr v pi_ h p pat = Pi p (bimap h abstr pat) . abstr where abstr = abstract $ patternAbstraction vs vs = bifoldMap pure mempty pat pis :: (Hashable v, Eq v, Foldable t) => (v -> NameHint) -> t (Plicitness, Syntax.Pat (HashSet QConstr) Pre.Literal v (Expr v)) -> Expr v -> Expr v pis h pats e = foldr (uncurry $ pi_ h) e pats telePis :: (Hashable v, Eq v) => (v -> NameHint) -> Telescope Type v -> Expr v -> Expr v telePis h tele e = fmap (unvar (panic "telePis") identity) $ pis h' pats $ F <$> e where h' = unvar (\(TeleVar v) -> teleHints tele Vector.! v) h pats = iforTele tele $ \i _ p s -> (p, AnnoPat (VarPat $ B $ TeleVar i) $ fromScope s) lam :: (Hashable v, Eq v) => (v -> NameHint) -> Plicitness -> Syntax.Pat (HashSet QConstr) Pre.Literal v (Type v) -> Expr v -> Expr v lam h p pat = Lam p (bimap h abstr pat) . abstr where abstr = abstract $ patternAbstraction vs vs = bifoldMap pure mempty pat case_ :: (Hashable v, Eq v) => (v -> NameHint) -> Expr v -> [(SourceLoc, Syntax.Pat (HashSet QConstr) Pre.Literal v (Type v), Expr v)] -> Expr v case_ h expr pats = Case expr $ Branches $ go <$> pats where go (loc, pat, e) = Branch loc (bimap h abstr pat) (abstr e) where abstr = abstract $ patternAbstraction vs vs = bifoldMap pure mempty pat apps :: Foldable t => Expr v -> t (Plicitness, Expr v) -> Expr v apps = Foldable.foldl' (uncurry . App) appsView :: Expr v -> (Expr v, [(Plicitness, Expr v)]) appsView = second toList . go where go (SourceLoc _ e) = go e go (App e1 p e2) = second (`Snoc` (p, e2)) $ go e1 go e = (e, Nil) instance Applicative Expr where pure = return (<*>) = ap instance Monad Expr where return = Var expr >>= f = case expr of Var v -> f v Global v -> Global v Lit l -> Lit l Con c -> Con c Pi p pat s -> Pi p ((>>>= f) <$> pat) (s >>>= f) Lam p pat s -> Lam p ((>>>= f) <$> pat) (s >>>= f) App e1 p e2 -> App (e1 >>= f) p (e2 >>= f) Let defs s -> Let (defs >>>= f) (s >>>= f) Case e brs -> Case (e >>= f) (brs >>>= f) ExternCode c -> ExternCode ((>>= f) <$> c) Wildcard -> Wildcard SourceLoc r e -> SourceLoc r (e >>= f) instance Bound Branches where Branches brs >>>= f = Branches $ (>>>= f) <$> brs instance Bound Branch where Branch loc pat s >>>= f = Branch loc ((>>>= f) <$> pat) $ s >>>= f instance Bound LetRec where LetRec ds >>>= f = LetRec $ (>>>= f) <$> ds instance Bound LetBinding where LetBinding loc h def >>>= f = LetBinding loc h $ def >>>= bitraverse pure f instance GBound Branches where gbound f (Branches brs) = Branches $ gbound f <$> brs instance GBound Branch where gbound f (Branch loc pat s) = Branch loc (gbound f <$> pat) (gbound f s) instance GBound LetRec where gbound f (LetRec ds) = LetRec $ gbound f <$> ds instance GBound LetBinding where gbound f (LetBinding loc h def) = LetBinding loc h $ gbound (fmap pure . f) def instance (Monad expr, Hashable1 expr, Hashable v) => Hashable (LetBinding expr v) where hashWithSalt salt (LetBinding loc h cd) = liftHashWithSalt hashWithSalt (salt `hashWithSalt` loc `hashWithSalt` h) cd instance GBind Expr QName where global = Global gbind f expr = case expr of Var _ -> expr Global v -> f v Lit _ -> expr Con _ -> expr Pi p pat s -> Pi p (gbound f <$> pat) (gbound f s) Lam p pat s -> Lam p (gbound f <$> pat) (gbound f s) App e1 p e2 -> App (gbind f e1) p (gbind f e2) Let defs s -> Let (gbound f defs) (gbound f s) Case e brs -> Case (gbind f e) (gbound f brs) ExternCode c -> ExternCode (gbind f <$> c) Wildcard -> Wildcard SourceLoc r e -> SourceLoc r (gbind f e) instance v ~ Doc => Pretty (Expr v) where prettyM expr = case expr of Var v -> prettyM v Global g -> prettyM g Lit l -> prettyM l Con c -> prettyM $ toList c Pi p (AnnoPat WildcardPat t) s -> parens `above` arrPrec $ do let inst = instantiatePattern (pure . fromName) mempty prettyAnnotation p (prettyM $ inst t) <+> "->" <+> associate arrPrec (prettyM $ inst s) Pi p pat s -> withNameHints (bifoldMap pure mempty pat) $ \ns -> do let inst = instantiatePattern (pure . fromName) ns parens `above` arrPrec $ prettyAnnotation p (prettyPattern ns $ inst <$> pat) <+> "->" <+> associate arrPrec (prettyM $ inst s) Lam p pat s -> withNameHints (bifoldMap pure mempty pat) $ \ns -> do let inst = instantiatePattern (pure . fromName) ns parens `above` absPrec $ "\\" <> prettyAnnotation p (prettyPattern ns $ inst <$> pat) <> "." <+> associate absPrec (prettyM $ inst s) App e1 p e2 -> prettyApp (prettyM e1) (prettyAnnotation p $ prettyM e2) Let (LetRec defs) scope -> parens `above` letPrec $ withNameHints ((\(LetBinding _ h _) -> h) <$> defs) $ \ns -> let go = ifor defs $ \i (LetBinding _ _ cl) -> prettyNamed (prettyM $ ns Vector.! i) (instantiateConstantDef (pure . fromName . (ns Vector.!) . unLetVar) cl) in "let" <+> align (vcat go) <+> "in" <+> prettyM (instantiateLet (pure . fromName) ns scope) Case e (Branches brs) -> parens `above` casePrec $ "case" <+> inviolable (prettyM e) <+> "of" <$$> indent 2 (vcat $ prettyBranch <$> brs) ExternCode c -> prettyM c Wildcard -> "_" SourceLoc _ e -> prettyM e where prettyBranch (Branch _ pat br) = withNameHints (bifoldMap pure mempty pat) $ \ns -> do let inst = instantiatePattern (pure . fromName) ns prettyPattern ns (inst <$> pat) <+> "->" <+> prettyM (inst br) return [] deriveEq ''Expr deriveEq1 ''Expr deriveShow1 ''Expr instance (Eq1 expr, Monad expr) => Eq1 (LetRec expr) where liftEq = $(makeLiftEq ''LetRec) instance (Show1 expr, Monad expr) => Show1 (LetRec expr) where liftShowsPrec = $(makeLiftShowsPrec ''LetRec) instance (Eq1 expr, Monad expr) => Eq1 (LetBinding expr) where liftEq = $(makeLiftEq ''LetBinding) instance (Show1 expr, Monad expr) => Show1 (LetBinding expr) where liftShowsPrec = $(makeLiftShowsPrec ''LetBinding) instance (Eq1 expr, Monad expr) => Eq1 (Branches expr) where liftEq = $(makeLiftEq ''Branches) instance (Show1 expr, Monad expr) => Show1 (Branches expr) where liftShowsPrec = $(makeLiftShowsPrec ''Branches) instance (Eq1 expr, Monad expr) => Eq1 (Branch expr) where liftEq = $(makeLiftEq ''Branch) instance (Show1 expr, Monad expr) => Show1 (Branch expr) where liftShowsPrec = $(makeLiftShowsPrec ''Branch)
27f657ef32b2f8611044fa8b1b512ce67f4413fa94421ff206da5a7a24078708
softlab-ntua/bencherl
dialyzer_timing.erl
-*- erlang - indent - level : 2 -*- %%------------------------------------------------------------------- %% %CopyrightBegin% %% Copyright Ericsson AB 2006 - 2012 . All Rights Reserved . %% The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at /. %% Software distributed under the License is distributed on an " AS IS " %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% %%%------------------------------------------------------------------- %%% File : dialyzer_timing.erl Authors : < > Description : Timing reports for %%%------------------------------------------------------------------- -module(dialyzer_timing). -export([init/1, start_stamp/2, send_size_info/3, end_stamp/1, stop/1]). -export_type([timing_server/0]). -type timing_server() :: pid() | 'none'. -spec init(boolean() | 'debug') -> timing_server(). init(Active) -> case Active of true -> io:format("\n"), spawn_link(fun() -> loop(now(), 0, "") end); debug -> io:format("\n"), spawn_link(fun() -> debug_loop("") end); false -> none end. loop(LastNow, Size, Unit) -> receive {stamp, Msg, Now} -> io:format(" ~-10s (+~4.2fs):", [Msg, diff(Now, LastNow)]), loop(Now, 0, ""); {stamp, Now} -> SizeStr = case Size of 0 -> ""; _ -> Data = io_lib:format("~p ~s",[Size, Unit]), io_lib:format(" (~12s)",[Data]) end, io:format("~7.2fs~s\n", [diff(Now, LastNow), SizeStr]), loop(Now, 0, ""); {size, NewSize, NewUnit} -> loop(LastNow, NewSize, NewUnit); {Pid, stop, Now} -> io:format(" ~-9s (+~5.2fs)\n", ["",diff(Now, LastNow)]), Pid ! ok; {Pid, stop} -> Pid ! ok end. debug_loop(Phase) -> receive Message -> {Runtime,_} = statistics(wall_clock), Procs = erlang:system_info(process_count), ProcMem = erlang:memory(total), Status = io_lib:format("~12w ~6w ~20w", [Runtime, Procs, ProcMem]), case Message of {stamp, Msg, _Now} -> io:format("~s ~s_start\n", [Status, Msg]), debug_loop(Msg); {stamp, _Now} -> io:format("~s ~s_stop\n", [Status, Phase]), debug_loop(""); {Pid, stop, _Now} -> Pid ! ok; {Pid, stop} -> Pid ! ok; _ -> debug_loop(Phase) end after 50 -> {Runtime,_} = statistics(wall_clock), Procs = erlang:system_info(process_count), ProcMem = erlang:memory(total), Status = io_lib:format("~12w ~6w ~20w", [Runtime, Procs, ProcMem]), io:format("~s\n", [Status]), debug_loop(Phase) end. -spec start_stamp(timing_server(), string()) -> ok. start_stamp(none, _) -> ok; start_stamp(Pid, Msg) -> Pid ! {stamp, Msg, now()}, ok. -spec end_stamp(timing_server()) -> ok. end_stamp(none) -> ok; end_stamp(Pid) -> Pid ! {stamp, now()}, ok. -spec send_size_info(timing_server(), integer(), string()) -> ok. send_size_info(none, _, _) -> ok; send_size_info(Pid, Size, Unit) -> Pid ! {size, Size, Unit}, ok. -spec stop(timing_server()) -> ok. stop(none) -> ok; stop(Pid) -> Pid ! {self(), stop, now()}, receive ok -> ok end. diff(T2, T1) -> timer:now_diff(T2,T1) / 1000000.
null
https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/dialyzer/src/dialyzer_timing.erl
erlang
------------------------------------------------------------------- %CopyrightBegin% compliance with the License. You should have received a copy of the Erlang Public License along with this software. If not, it can be retrieved online at /. basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. %CopyrightEnd% ------------------------------------------------------------------- File : dialyzer_timing.erl -------------------------------------------------------------------
-*- erlang - indent - level : 2 -*- Copyright Ericsson AB 2006 - 2012 . All Rights Reserved . The contents of this file are subject to the Erlang Public License , Version 1.1 , ( the " License " ) ; you may not use this file except in Software distributed under the License is distributed on an " AS IS " Authors : < > Description : Timing reports for -module(dialyzer_timing). -export([init/1, start_stamp/2, send_size_info/3, end_stamp/1, stop/1]). -export_type([timing_server/0]). -type timing_server() :: pid() | 'none'. -spec init(boolean() | 'debug') -> timing_server(). init(Active) -> case Active of true -> io:format("\n"), spawn_link(fun() -> loop(now(), 0, "") end); debug -> io:format("\n"), spawn_link(fun() -> debug_loop("") end); false -> none end. loop(LastNow, Size, Unit) -> receive {stamp, Msg, Now} -> io:format(" ~-10s (+~4.2fs):", [Msg, diff(Now, LastNow)]), loop(Now, 0, ""); {stamp, Now} -> SizeStr = case Size of 0 -> ""; _ -> Data = io_lib:format("~p ~s",[Size, Unit]), io_lib:format(" (~12s)",[Data]) end, io:format("~7.2fs~s\n", [diff(Now, LastNow), SizeStr]), loop(Now, 0, ""); {size, NewSize, NewUnit} -> loop(LastNow, NewSize, NewUnit); {Pid, stop, Now} -> io:format(" ~-9s (+~5.2fs)\n", ["",diff(Now, LastNow)]), Pid ! ok; {Pid, stop} -> Pid ! ok end. debug_loop(Phase) -> receive Message -> {Runtime,_} = statistics(wall_clock), Procs = erlang:system_info(process_count), ProcMem = erlang:memory(total), Status = io_lib:format("~12w ~6w ~20w", [Runtime, Procs, ProcMem]), case Message of {stamp, Msg, _Now} -> io:format("~s ~s_start\n", [Status, Msg]), debug_loop(Msg); {stamp, _Now} -> io:format("~s ~s_stop\n", [Status, Phase]), debug_loop(""); {Pid, stop, _Now} -> Pid ! ok; {Pid, stop} -> Pid ! ok; _ -> debug_loop(Phase) end after 50 -> {Runtime,_} = statistics(wall_clock), Procs = erlang:system_info(process_count), ProcMem = erlang:memory(total), Status = io_lib:format("~12w ~6w ~20w", [Runtime, Procs, ProcMem]), io:format("~s\n", [Status]), debug_loop(Phase) end. -spec start_stamp(timing_server(), string()) -> ok. start_stamp(none, _) -> ok; start_stamp(Pid, Msg) -> Pid ! {stamp, Msg, now()}, ok. -spec end_stamp(timing_server()) -> ok. end_stamp(none) -> ok; end_stamp(Pid) -> Pid ! {stamp, now()}, ok. -spec send_size_info(timing_server(), integer(), string()) -> ok. send_size_info(none, _, _) -> ok; send_size_info(Pid, Size, Unit) -> Pid ! {size, Size, Unit}, ok. -spec stop(timing_server()) -> ok. stop(none) -> ok; stop(Pid) -> Pid ! {self(), stop, now()}, receive ok -> ok end. diff(T2, T1) -> timer:now_diff(T2,T1) / 1000000.
16784335855573940addd53253175dba772fec697036189d6cb95214810c5c68
erlang/corba
notify_test_impl.erl
%% %% %CopyrightBegin% %% Copyright Ericsson AB 1999 - 2016 . All Rights Reserved . %% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %% you may not use this file except in compliance with the License. %% You may obtain a copy of the License at %% %% -2.0 %% %% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %% See the License for the specific language governing permissions and %% limitations under the License. %% %% %CopyrightEnd% %% %% %%---------------------------------------------------------------------- %% File : notify_test_impl.erl %%---------------------------------------------------------------------- -module(notify_test_impl). -include_lib("orber/include/corba.hrl"). -include("idl_output/notify_test.hrl"). %%--------------- specified functions ------------------------ -export([stop_normal/2, stop_brutal/2, print/2, doAction/3, delay/5, %% Exports from CosNotifyComm::StructuredPushConsumer push_structured_event/3, disconnect_structured_push_consumer/2, Exports from " CosNotifyComm::SequencePushConsumer " push_structured_events/3, disconnect_sequence_push_consumer/2, %% Exports from CosEventComm::PushConsumer push/3, disconnect_push_consumer/2, %% Exports from CosNotifyComm::NotifyPublish disconnect_sequence_pull_consumer/2, Exports from CosNotifyComm::StructuredPullConsumer disconnect_structured_pull_consumer/2, Exports from CosEventComm::PullConsumer disconnect_pull_consumer/2, %% Exports from CosNotifyComm::SequencePushSupplier disconnect_sequence_push_supplier/2, %% Exports from CosNotifyComm::StructuredPushSupplier disconnect_structured_push_supplier/2, %% Exports from CosEventComm::PushSupplier disconnect_push_supplier/2, %% Exports from CosNotifyComm::SequencePullSupplier pull_structured_events/3, try_pull_structured_events/3, disconnect_sequence_pull_supplier/2, %% Exports from CosNotifyComm::StructuredPullSupplier pull_structured_event/2, try_pull_structured_event/2, disconnect_structured_pull_supplier/2, %% Exports from CosEventComm::PullSupplier pull/2, try_pull/2, disconnect_pull_supplier/2, %% Exports from CosNotifyComm::SequencePullConsumer offer_change/4, %% Exports from CosNotifyComm::NotifySubscribe subscription_change/4]). %%--------------- gen_server specific ------------------------ -export([init/1, terminate/2]). -export([handle_call/3, handle_cast/2, handle_info/2, code_change/3]). %% Data structures -record(state, {myType, proxy, data, action}). %%--------------- LOCAL DATA --------------------------------- %%------------------------------------------------------------ %% function : init, terminate %%------------------------------------------------------------ init([MyType, Proxy]) -> process_flag(trap_exit,true), {ok, #state{myType=MyType, proxy=Proxy, data=[]}}. terminate(Reason, State) -> io:format("notify_test:terminate(~p ~p)~n",[Reason, State#state.myType]), ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. handle_call(_,_, State) -> {noreply, State}. handle_cast(_, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. %%--------------- SERVER FUNCTIONS --------------------------- print(Self, State) -> io:format("notify_test:print(~p ~p)~n",[Self, State]), {reply, ok, State}. doAction(_Self, State, {set_data, Data}) -> io:format("notify_test:doAction(add_data) ~p~n",[Data]), {reply, ok, State#state{data=Data}}; doAction(_Self, State, {add_data, Data}) -> io:format("notify_test:doAction(add_data) ~p~n",[Data]), {reply, ok, State#state{data=State#state.data++Data}}; doAction(_Self, State, return_data) -> io:format("notify_test:doAction(return_data)~n",[]), {reply, State#state.data, State#state{data=[]}}; doAction(_Self, State, clear_data) -> io:format("notify_test:doAction(return_data)~n",[]), {reply, ok, State#state{data=[]}}; doAction(_Self, State, pull_any) -> io:format("notify_test:doAction(pull_any)~n",[]), Event='CosNotifyChannelAdmin_ProxyPullSupplier':pull(State#state.proxy), {reply, Event, State}; doAction(_Self, State, {pull_seq, Max}) -> io:format("notify_test:doAction(pull_sequence)~n",[]), Event='CosNotifyChannelAdmin_SequenceProxyPullSupplier':pull_structured_events(State#state.proxy, Max), {reply, Event, State}; doAction(_Self, State, pull_str) -> Event='CosNotifyChannelAdmin_StructuredProxyPullSupplier':pull_structured_event(State#state.proxy), io:format("notify_test:doAction(pull_structured)~n",[]), {reply, Event, State}; doAction(_Self, State, try_pull_any) -> io:format("notify_test:doAction(try_pull_any)~n",[]), Event='CosNotifyChannelAdmin_ProxyPullSupplier':try_pull(State#state.proxy), {reply, Event, State}; doAction(_Self, State, {try_pull_seq, Max}) -> io:format("notify_test:doAction(try_pull_sequence)~n",[]), Event='CosNotifyChannelAdmin_SequenceProxyPullSupplier':try_pull_structured_events(State#state.proxy, Max), {reply, Event, State}; doAction(_Self, State, try_pull_str) -> Event='CosNotifyChannelAdmin_StructuredProxyPullSupplier':try_pull_structured_event(State#state.proxy), io:format("notify_test:doAction(try_pull_structured)~n",[]), {reply, Event, State}; doAction(_Self, State, {action, Action}) -> io:format("notify_test:doAction(~p)~n",[Action]), {reply, ok, State#state{action = Action}}; doAction(_, State, _) -> {reply, nop, State}. stop_normal(_Self, State) -> {stop, normal, ok, State}. stop_brutal(_Self, _State) -> exit("killed_brutal"). %%--------------- CosNotifyComm::NotifyPublish -------- offer_change(_Self, State, Added, Removed) -> ND=loop(Removed, State#state.data), ND2=Added++ND, {reply, ok, State#state{data=ND2}}. loop([],Data) -> Data; loop([H|T], Data) -> ND=lists:delete(H,Data), loop(T, ND). %%--------------- CosNotifyComm::NotifySubscribe -------- subscription_change(_Self, State, Added, Removed) -> ND=loop(Removed, State#state.data), ND2=Added++ND, {reply, ok, State#state{data=ND2}}. %%--------------- CosNotifyComm::SequencePushConsumer -------- push_structured_events(_Self, #state{action = undefined} = State, Event) -> io:format("notify_test:push_structured_events(~p)~n",[Event]), {reply, ok, State#state{data=State#state.data++Event}}; push_structured_events(_Self, #state{action = Action} = State, Event) -> io:format("notify_test:push_structured_events(~p)~nAction: ~p~n", [Event, Action]), corba:raise(#'INTERNAL'{completion_status=?COMPLETED_NO}), {reply, ok, State#state{data=State#state.data++Event}}. disconnect_sequence_push_consumer(_Self, State) -> io:format("disconnect_sequence_push_consumer~n",[]), {stop, normal, ok, State}. %%--------------- CosNotifyComm::StructuredPushConsumer -------- push_structured_event(_Self, State, Event) -> io:format("notify_test:push_structured_event(~p)~n",[Event]), {reply, ok, State#state{data=State#state.data++[Event]}}. disconnect_structured_push_consumer(_Self, State) -> io:format("disconnect_structured_push_consumer~n",[]), {stop, normal, ok, State}. %%--------------- CosEventComm::PushConsumer -------- push(_Self, State, Event) -> io:format("notify_test:push(~p)~n",[Event]), {reply, ok, State#state{data=State#state.data++[Event]}}. disconnect_push_consumer(_Self, State) -> io:format("disconnect_push_consumer~n",[]), {stop, normal, ok, State}. %%--------------- CosNotifyComm::SequencePullConsumer -------- disconnect_sequence_pull_consumer(_Self, State) -> io:format("disconnect_sequence_pull_consumer~n",[]), {stop, normal, ok, State}. --------------- CosNotifyComm::StructuredPullConsumer -------- disconnect_structured_pull_consumer(_Self, State) -> io:format("disconnect_structured_pull_consumer~n",[]), {stop, normal, ok, State}. %%--------------- CosEventComm::PullConsumer -------- disconnect_pull_consumer(_Self, State) -> io:format("disconnect_pull_consumer~n",[]), {stop, normal, ok, State}. %%--------------- CosNotifyComm::SequencePushSupplier -------- disconnect_sequence_push_supplier(_Self, State) -> io:format("disconnect_sequence_push_supplier~n",[]), {stop, normal, ok, State}. %%--------------- CosNotifyComm::StructuredPushSupplier -------- disconnect_structured_push_supplier(_Self, State) -> io:format("disconnect_structured_push_supplier~n",[]), {stop, normal, ok, State}. %%--------------- CosEventComm::PushSupplier -------- disconnect_push_supplier(_Self, State) -> io:format("disconnect_push_supplier~n",[]), {stop, normal, ok, State}. %%--------------- CosNotifyComm::SequencePullSupplier -------- pull_structured_events(_Self, State, _Max) -> io:format("notify_test:pullstructured_events()~n",[]), {reply, ok, State}. try_pull_structured_events(_Self, State, Max) -> io:format("notify_test:try_pull_structured_events()~n",[]), case State#state.data of [] -> {reply, {[],false}, State}; List -> R = split(List,Max), {reply, {lists:sublist(List, Max), true}, State#state{data=R}} end. split([],_) -> []; split(R,0) -> R; split([_H|T],Max) -> split(T, Max-1). disconnect_sequence_pull_supplier(_Self, State) -> io:format("disconnect_sequence_pull_supplier~n",[]), {stop, normal, ok, State}. %%--------------- CosNotifyComm::StructuredPullSupplier -------- pull_structured_event(_Self, State) -> io:format("notify_test:pull_structured_event()~n",[]), {reply, ok, State}. try_pull_structured_event(_Self, State) -> io:format("notify_test:try_pull_structured_event()~n",[]), case State#state.data of [] -> {reply, {[],false}, State}; [H|T] -> {reply, {H, true}, State#state{data=T}} end. disconnect_structured_pull_supplier(_Self, State) -> io:format("disconnect_structured_pull_supplier~n",[]), {stop, normal, ok, State}. %%--------------- CosEventComm::PullSupplier -------- pull(_Self, State) -> io:format("notify_test:pull()~n",[]), {reply, 'CosEventComm_PullSupplier':pull(State#state.proxy), State}. try_pull(_Self, State) -> io:format("notify_test:try_pull()~n",[]), case State#state.data of [] -> {reply, {[],false}, State}; [H|T] -> {reply, {H, true}, State#state{data=T}} end. disconnect_pull_supplier(_Self, State) -> io:format("disconnect_pull_supplier~n",[]), {stop, normal, ok, State}. %%--------------- LOCAL FUNCTIONS ---------------------------- delay(Obj, Event, Time, Mod, F) -> io:format("notify_test:delay(~p) TIME: ~p~n",[Event, erlang:timestamp()]), timer:sleep(Time), Mod:F(Obj, Event), io:format("notify_test:delay() DONE: ~p~n",[erlang:timestamp()]), ok. %%--------------- END OF MODULE ------------------------------
null
https://raw.githubusercontent.com/erlang/corba/396df81473a386d0315bbba830db6f9d4b12a04f/lib/cosNotification/test/notify_test_impl.erl
erlang
%CopyrightBegin% you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. %CopyrightEnd% ---------------------------------------------------------------------- File : notify_test_impl.erl ---------------------------------------------------------------------- --------------- specified functions ------------------------ Exports from CosNotifyComm::StructuredPushConsumer Exports from CosEventComm::PushConsumer Exports from CosNotifyComm::NotifyPublish Exports from CosNotifyComm::SequencePushSupplier Exports from CosNotifyComm::StructuredPushSupplier Exports from CosEventComm::PushSupplier Exports from CosNotifyComm::SequencePullSupplier Exports from CosNotifyComm::StructuredPullSupplier Exports from CosEventComm::PullSupplier Exports from CosNotifyComm::SequencePullConsumer Exports from CosNotifyComm::NotifySubscribe --------------- gen_server specific ------------------------ Data structures --------------- LOCAL DATA --------------------------------- ------------------------------------------------------------ function : init, terminate ------------------------------------------------------------ --------------- SERVER FUNCTIONS --------------------------- --------------- CosNotifyComm::NotifyPublish -------- --------------- CosNotifyComm::NotifySubscribe -------- --------------- CosNotifyComm::SequencePushConsumer -------- --------------- CosNotifyComm::StructuredPushConsumer -------- --------------- CosEventComm::PushConsumer -------- --------------- CosNotifyComm::SequencePullConsumer -------- --------------- CosEventComm::PullConsumer -------- --------------- CosNotifyComm::SequencePushSupplier -------- --------------- CosNotifyComm::StructuredPushSupplier -------- --------------- CosEventComm::PushSupplier -------- --------------- CosNotifyComm::SequencePullSupplier -------- --------------- CosNotifyComm::StructuredPullSupplier -------- --------------- CosEventComm::PullSupplier -------- --------------- LOCAL FUNCTIONS ---------------------------- --------------- END OF MODULE ------------------------------
Copyright Ericsson AB 1999 - 2016 . All Rights Reserved . Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(notify_test_impl). -include_lib("orber/include/corba.hrl"). -include("idl_output/notify_test.hrl"). -export([stop_normal/2, stop_brutal/2, print/2, doAction/3, delay/5, push_structured_event/3, disconnect_structured_push_consumer/2, Exports from " CosNotifyComm::SequencePushConsumer " push_structured_events/3, disconnect_sequence_push_consumer/2, push/3, disconnect_push_consumer/2, disconnect_sequence_pull_consumer/2, Exports from CosNotifyComm::StructuredPullConsumer disconnect_structured_pull_consumer/2, Exports from CosEventComm::PullConsumer disconnect_pull_consumer/2, disconnect_sequence_push_supplier/2, disconnect_structured_push_supplier/2, disconnect_push_supplier/2, pull_structured_events/3, try_pull_structured_events/3, disconnect_sequence_pull_supplier/2, pull_structured_event/2, try_pull_structured_event/2, disconnect_structured_pull_supplier/2, pull/2, try_pull/2, disconnect_pull_supplier/2, offer_change/4, subscription_change/4]). -export([init/1, terminate/2]). -export([handle_call/3, handle_cast/2, handle_info/2, code_change/3]). -record(state, {myType, proxy, data, action}). init([MyType, Proxy]) -> process_flag(trap_exit,true), {ok, #state{myType=MyType, proxy=Proxy, data=[]}}. terminate(Reason, State) -> io:format("notify_test:terminate(~p ~p)~n",[Reason, State#state.myType]), ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. handle_call(_,_, State) -> {noreply, State}. handle_cast(_, State) -> {noreply, State}. handle_info(_Info, State) -> {noreply, State}. print(Self, State) -> io:format("notify_test:print(~p ~p)~n",[Self, State]), {reply, ok, State}. doAction(_Self, State, {set_data, Data}) -> io:format("notify_test:doAction(add_data) ~p~n",[Data]), {reply, ok, State#state{data=Data}}; doAction(_Self, State, {add_data, Data}) -> io:format("notify_test:doAction(add_data) ~p~n",[Data]), {reply, ok, State#state{data=State#state.data++Data}}; doAction(_Self, State, return_data) -> io:format("notify_test:doAction(return_data)~n",[]), {reply, State#state.data, State#state{data=[]}}; doAction(_Self, State, clear_data) -> io:format("notify_test:doAction(return_data)~n",[]), {reply, ok, State#state{data=[]}}; doAction(_Self, State, pull_any) -> io:format("notify_test:doAction(pull_any)~n",[]), Event='CosNotifyChannelAdmin_ProxyPullSupplier':pull(State#state.proxy), {reply, Event, State}; doAction(_Self, State, {pull_seq, Max}) -> io:format("notify_test:doAction(pull_sequence)~n",[]), Event='CosNotifyChannelAdmin_SequenceProxyPullSupplier':pull_structured_events(State#state.proxy, Max), {reply, Event, State}; doAction(_Self, State, pull_str) -> Event='CosNotifyChannelAdmin_StructuredProxyPullSupplier':pull_structured_event(State#state.proxy), io:format("notify_test:doAction(pull_structured)~n",[]), {reply, Event, State}; doAction(_Self, State, try_pull_any) -> io:format("notify_test:doAction(try_pull_any)~n",[]), Event='CosNotifyChannelAdmin_ProxyPullSupplier':try_pull(State#state.proxy), {reply, Event, State}; doAction(_Self, State, {try_pull_seq, Max}) -> io:format("notify_test:doAction(try_pull_sequence)~n",[]), Event='CosNotifyChannelAdmin_SequenceProxyPullSupplier':try_pull_structured_events(State#state.proxy, Max), {reply, Event, State}; doAction(_Self, State, try_pull_str) -> Event='CosNotifyChannelAdmin_StructuredProxyPullSupplier':try_pull_structured_event(State#state.proxy), io:format("notify_test:doAction(try_pull_structured)~n",[]), {reply, Event, State}; doAction(_Self, State, {action, Action}) -> io:format("notify_test:doAction(~p)~n",[Action]), {reply, ok, State#state{action = Action}}; doAction(_, State, _) -> {reply, nop, State}. stop_normal(_Self, State) -> {stop, normal, ok, State}. stop_brutal(_Self, _State) -> exit("killed_brutal"). offer_change(_Self, State, Added, Removed) -> ND=loop(Removed, State#state.data), ND2=Added++ND, {reply, ok, State#state{data=ND2}}. loop([],Data) -> Data; loop([H|T], Data) -> ND=lists:delete(H,Data), loop(T, ND). subscription_change(_Self, State, Added, Removed) -> ND=loop(Removed, State#state.data), ND2=Added++ND, {reply, ok, State#state{data=ND2}}. push_structured_events(_Self, #state{action = undefined} = State, Event) -> io:format("notify_test:push_structured_events(~p)~n",[Event]), {reply, ok, State#state{data=State#state.data++Event}}; push_structured_events(_Self, #state{action = Action} = State, Event) -> io:format("notify_test:push_structured_events(~p)~nAction: ~p~n", [Event, Action]), corba:raise(#'INTERNAL'{completion_status=?COMPLETED_NO}), {reply, ok, State#state{data=State#state.data++Event}}. disconnect_sequence_push_consumer(_Self, State) -> io:format("disconnect_sequence_push_consumer~n",[]), {stop, normal, ok, State}. push_structured_event(_Self, State, Event) -> io:format("notify_test:push_structured_event(~p)~n",[Event]), {reply, ok, State#state{data=State#state.data++[Event]}}. disconnect_structured_push_consumer(_Self, State) -> io:format("disconnect_structured_push_consumer~n",[]), {stop, normal, ok, State}. push(_Self, State, Event) -> io:format("notify_test:push(~p)~n",[Event]), {reply, ok, State#state{data=State#state.data++[Event]}}. disconnect_push_consumer(_Self, State) -> io:format("disconnect_push_consumer~n",[]), {stop, normal, ok, State}. disconnect_sequence_pull_consumer(_Self, State) -> io:format("disconnect_sequence_pull_consumer~n",[]), {stop, normal, ok, State}. --------------- CosNotifyComm::StructuredPullConsumer -------- disconnect_structured_pull_consumer(_Self, State) -> io:format("disconnect_structured_pull_consumer~n",[]), {stop, normal, ok, State}. disconnect_pull_consumer(_Self, State) -> io:format("disconnect_pull_consumer~n",[]), {stop, normal, ok, State}. disconnect_sequence_push_supplier(_Self, State) -> io:format("disconnect_sequence_push_supplier~n",[]), {stop, normal, ok, State}. disconnect_structured_push_supplier(_Self, State) -> io:format("disconnect_structured_push_supplier~n",[]), {stop, normal, ok, State}. disconnect_push_supplier(_Self, State) -> io:format("disconnect_push_supplier~n",[]), {stop, normal, ok, State}. pull_structured_events(_Self, State, _Max) -> io:format("notify_test:pullstructured_events()~n",[]), {reply, ok, State}. try_pull_structured_events(_Self, State, Max) -> io:format("notify_test:try_pull_structured_events()~n",[]), case State#state.data of [] -> {reply, {[],false}, State}; List -> R = split(List,Max), {reply, {lists:sublist(List, Max), true}, State#state{data=R}} end. split([],_) -> []; split(R,0) -> R; split([_H|T],Max) -> split(T, Max-1). disconnect_sequence_pull_supplier(_Self, State) -> io:format("disconnect_sequence_pull_supplier~n",[]), {stop, normal, ok, State}. pull_structured_event(_Self, State) -> io:format("notify_test:pull_structured_event()~n",[]), {reply, ok, State}. try_pull_structured_event(_Self, State) -> io:format("notify_test:try_pull_structured_event()~n",[]), case State#state.data of [] -> {reply, {[],false}, State}; [H|T] -> {reply, {H, true}, State#state{data=T}} end. disconnect_structured_pull_supplier(_Self, State) -> io:format("disconnect_structured_pull_supplier~n",[]), {stop, normal, ok, State}. pull(_Self, State) -> io:format("notify_test:pull()~n",[]), {reply, 'CosEventComm_PullSupplier':pull(State#state.proxy), State}. try_pull(_Self, State) -> io:format("notify_test:try_pull()~n",[]), case State#state.data of [] -> {reply, {[],false}, State}; [H|T] -> {reply, {H, true}, State#state{data=T}} end. disconnect_pull_supplier(_Self, State) -> io:format("disconnect_pull_supplier~n",[]), {stop, normal, ok, State}. delay(Obj, Event, Time, Mod, F) -> io:format("notify_test:delay(~p) TIME: ~p~n",[Event, erlang:timestamp()]), timer:sleep(Time), Mod:F(Obj, Event), io:format("notify_test:delay() DONE: ~p~n",[erlang:timestamp()]), ok.
2fe3665d13066a1b729adeb8332e9673e84a789050d005766fad42266a92b988
elektronaut/advent-of-code
day04.clj
(ns advent-of-code.2020.04 (:require [clojure.string :as str])) (def passports (map #(apply hash-map (str/split % #"[^\w\d#]+")) (str/split (slurp "2020/day04/input.txt") #"\n\n"))) (def required-fields ["byr" "iyr" "eyr" "hgt" "hcl" "ecl" "pid"]) (defn required-fields? [p] (= (count (keep p required-fields)) (count required-fields))) (defn in-range? [min max s] (let [n (Integer/parseInt s)] (and (>= n min) (<= n max)))) (defn valid-height? [s] (let [value (re-find #"^[\d]+" s) unit (re-find #"[^\d]+$" s)] (case unit "cm" (in-range? 150 193 value) "in" (in-range? 59 76 value) nil))) (defn valid-passport? [p] (and (required-fields? p) (in-range? 1920 2002 (p "byr")) (in-range? 2010 2020 (p "iyr")) (in-range? 2020 2030 (p "eyr")) (valid-height? (p "hgt")) (re-matches #"#[\d\w]{6}" (p "hcl")) (some #{(p "ecl")} ["amb" "blu" "brn" "gry" "grn" "hzl" "oth"]) (re-matches #"[\d]{9}" (p "pid")))) (println "Part 1:" (count (filter required-fields? passports))) (println "Part 2:" (count (filter valid-passport? passports)))
null
https://raw.githubusercontent.com/elektronaut/advent-of-code/a8bb7bbadc8167ebb1df0d532493317705bb7f0d/2020/day04/day04.clj
clojure
(ns advent-of-code.2020.04 (:require [clojure.string :as str])) (def passports (map #(apply hash-map (str/split % #"[^\w\d#]+")) (str/split (slurp "2020/day04/input.txt") #"\n\n"))) (def required-fields ["byr" "iyr" "eyr" "hgt" "hcl" "ecl" "pid"]) (defn required-fields? [p] (= (count (keep p required-fields)) (count required-fields))) (defn in-range? [min max s] (let [n (Integer/parseInt s)] (and (>= n min) (<= n max)))) (defn valid-height? [s] (let [value (re-find #"^[\d]+" s) unit (re-find #"[^\d]+$" s)] (case unit "cm" (in-range? 150 193 value) "in" (in-range? 59 76 value) nil))) (defn valid-passport? [p] (and (required-fields? p) (in-range? 1920 2002 (p "byr")) (in-range? 2010 2020 (p "iyr")) (in-range? 2020 2030 (p "eyr")) (valid-height? (p "hgt")) (re-matches #"#[\d\w]{6}" (p "hcl")) (some #{(p "ecl")} ["amb" "blu" "brn" "gry" "grn" "hzl" "oth"]) (re-matches #"[\d]{9}" (p "pid")))) (println "Part 1:" (count (filter required-fields? passports))) (println "Part 2:" (count (filter valid-passport? passports)))
876ae2f257cc290989c6a98fb49707d6cef200d5c686f6ed3588056b27fbba58
tmfg/mmtis-national-access-point
localization.clj
(ns ote.services.localization "Services for fetching localization messages." (:require [com.stuartsierra.component :as component] [ote.components.http :as http] [ote.localization :as localization] [compojure.core :refer [routes GET]] [clojure.string :as str])) (defn- fetch-language [language-name] (http/transit-response (localization/translations (keyword language-name)))) (defn- set-language "Change NAP language to fi,sv,en. E.g. www.finap.fi/ote/lang/en" [language-name] {:status 302 :headers {"Location" "/"} :cookies {"finap_lang" {:path "/" :value language-name}}}) (defrecord Localization [] component/Lifecycle (start [{http :http :as this}] (assoc this ::stop (http/publish! http {:authenticated? false} (routes (GET "/language/:lang" [lang] (fetch-language lang)) (GET "/lang/:lang" [lang] (set-language lang)))))) (stop [{stop ::stop :as this}] (stop) (dissoc this ::stop)))
null
https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/ote/src/clj/ote/services/localization.clj
clojure
(ns ote.services.localization "Services for fetching localization messages." (:require [com.stuartsierra.component :as component] [ote.components.http :as http] [ote.localization :as localization] [compojure.core :refer [routes GET]] [clojure.string :as str])) (defn- fetch-language [language-name] (http/transit-response (localization/translations (keyword language-name)))) (defn- set-language "Change NAP language to fi,sv,en. E.g. www.finap.fi/ote/lang/en" [language-name] {:status 302 :headers {"Location" "/"} :cookies {"finap_lang" {:path "/" :value language-name}}}) (defrecord Localization [] component/Lifecycle (start [{http :http :as this}] (assoc this ::stop (http/publish! http {:authenticated? false} (routes (GET "/language/:lang" [lang] (fetch-language lang)) (GET "/lang/:lang" [lang] (set-language lang)))))) (stop [{stop ::stop :as this}] (stop) (dissoc this ::stop)))
9f0c51d09f301135bb35124dd5cc0ee51f2e95049af57a23e58f3fd8ee1c02ca
dvdt/xvsy
plot.cljc
(ns xvsy.plot "This namespace is responsible for generating svg plots from sql data." (:require [xvsy.utils :as utils :refer [translate fmap]] [xvsy.conf :as conf] [xvsy.scale :as scale] [xvsy.geom :as geom] [xvsy.legend :as legend])) (defn area-dims "Given the overall plot width and height and facet scalars, returns the facet-area dimensions, which is the width and height of the space that all facets fit into; facet dimensions, for a single facet; and the geom dimensions, which is where the actual plot geom elements go. Example below has a single facet. Global legends can go in (a), and per-facet legends go in (b). width |-------------------------------------------------| | | | facet-area-width | | |------------------------------| | | | | | height | | facet-width | | | | |---------------| (b) | (a) | | | | | | | geom-width | | | | |--------| | | | | | | | | | | | |------------------------------| | | | | (a) | |-------------------------------------------------|" [width height [facet-x-scalar facet-y-scalar]] (let [[plot-padding-left plot-padding-right plot-padding-top plot-padding-bottom] conf/*plot-padding* [facet-padding-left facet-padding-right facet-padding-top facet-padding-bottom] conf/*facet-padding* [facet-area-w facet-area-h] [(- width plot-padding-left plot-padding-right) (- height plot-padding-top plot-padding-bottom)] facet-w (/ facet-area-w (count (scale/->ticks facet-x-scalar))) facet-h (/ facet-area-h (count (scale/->ticks facet-y-scalar))) [geom-w geom-h] [(- facet-w facet-padding-left facet-padding-right) (- facet-h facet-padding-top facet-padding-bottom)]] [[facet-area-w facet-area-h] [facet-w facet-h] [geom-w geom-h]])) (defn plot-width [width] (- width (nth conf/*plot-padding* 0) (nth conf/*plot-padding* 1))) (defn plot-height [height] (- height (nth conf/*plot-padding* 2) (nth conf/*plot-padding* 3))) (defn facet-width "assumes facets are of same width. returns the width in pixels of a facet, given with width of the entire plot." [width facet-scalar] (let [facet-full-length (second ((scale/->scale facet-scalar [0 (plot-width width)]) (first (scale/->ticks facet-scalar))))] (- facet-full-length (nth conf/*facet-padding* 0) (nth conf/*facet-padding* 1)))) (defn facet-height "assumes facets are of same width" [height facet-scalar] (let [facet-full-length (second ((scale/->scale facet-scalar [0 (plot-height height)]) (first (scale/->ticks facet-scalar))))] (- facet-full-length (nth conf/*facet-padding* 2) (nth conf/*facet-padding* 3)))) (defn geom-height "assumes facets are of same width" [facet-scalar facet-area-length] (let [facet-length (/ facet-area-length (count (scale/->ticks facet-scalar)))] (- facet-length (nth conf/*facet-padding* 2) (nth conf/*facet-padding* 3)))) (defn make-discrete-scale [scalar range-vals] (if (nil? scalar) nil (let [t (scale/->ticks scalar) s (scale/->scale scalar [0 (count t)]) s (if (coll? (s (first t))) (comp first s) (comp #(if (< % (count range-vals)) % (- (count range-vals) 1)) s)) ] (fn [v] (nth range-vals (mod (s v) (count range-vals))))))) (defn make-continuous-scale [scalar svg-fn] (comp svg-fn (scale/->scale scalar [0 1]))) (defn- gen-scales "Returns scales from the scalars and dynamically bound ranges" [scalar-map] (-> scalar-map (update-in [:color] #(make-discrete-scale % conf/*color*)) (update-in [:fill] #(make-discrete-scale % conf/*fill*)))) (defn- scale-geoms [scale-map geom-data] (map (fn scale-geom [g] (merge-with #(%1 %2) scale-map g)) geom-data)) (defn wrap-facet "returns translated [:g] elements for each facet-val" [[x-scale y-scale] [x-val y-val]] [:g {:class "facet" :transform (translate [(apply min (x-scale x-val)) (apply min (y-scale y-val))])}]) (defn last-row? [[x-scalar y-scalar] [x y]] (-> y ((scale/->scale y-scalar [0 10000])) first int (= 0))) (defn first-col? [[x-scalar y-scalar] [x y]] (-> x ((scale/->scale x-scalar [0 10000])) first int (= 0))) ;; TODO: The impl is super ugly right now, but I think the API is right. (defn wrap-geoms "Draws legends around a facet." [{:keys [facet-scalars facet-scales geom-scalars geom-scales] :as plot} [width height] [facet rendered-geoms]] (let [[facet-w facet-h] [(facet-width width (first facet-scalars)) (facet-height height (second facet-scalars))] x-legend (legend/render-legend :x (get-in geom-scalars [facet :x]) (get-in geom-scales [facet :x])) y-legend (legend/render-legend :y (get-in geom-scalars [facet :y]) (get-in geom-scales [facet :y])) aes-legends (map #(legend/render-legend % (get-in geom-scalars [facet %]) (get-in geom-scales [facet %])) (keys geom-scales))] [:g {:class "geoms"} [:g {:transform (translate [0 facet-h])} (:ticks x-legend) (if (last-row? facet-scalars facet) [:g {:transform (translate [0 15])} (:labels x-legend)])] [:g {:transform (translate [0 0])} (:ticks y-legend) (if (first-col? facet-scalars facet) (:labels y-legend))] [:rect {:x 0 :y 0 :width facet-w :height facet-h :fill :none :stroke "grey" :class "facet-outline"}] rendered-geoms])) (defn bind-facetting-scales "Given a width and height, generates :facet-scales based on the bound conf. Facet scales is a vec: [facet-x-scale facet-y-scale]" [{:keys [facet-scalars geom-scalars facetted-geom-data] :as plot} [width height]] (assoc plot :facet-scales [(scale/->scale (first facet-scalars) [0 (plot-width width)]) (scale/->scale (second facet-scalars) [(plot-height height) 0])])) (defn bind-geom-scales "Returns a plot with the key :geom-scales set as a map of: [facet-x facet-y] => (aes => (data-coords -> svg-coords)). args: facet-scalars is a vec: [facet-x-scalar facet-y-scalar] geom-scalars is a map: [facet-x facet-y] => (aes => scalar) facetted-geom-data is a map: [facet-x facet-y] => [aes => data]" [{:keys [facet-scalars geom-scalars facetted-geom-data] :as plot}] (assoc plot :geom-scales (fmap scale/guess-svg-scales geom-scalars))) (defn facet-by "returns a hashmap of facet -> data" [[[x-facet x-mapping] [y-facet y-mapping]] data] (group-by (juxt x-facet y-facet) data)) (defn ->plot "Returns trained scales and positioned geom hashmaps. scalar-trainer is hashmap of aes-kw => ([data] -> scalar) facetter-trainers is ([facet] -> [facet-x-scalar facet-y-scalar])" [geom scalar-trainers facetter-trainers sql-data] (let [facetted-col-data (->> sql-data (facet-by [[:facet_x nil] [:facet_y nil]]) (fmap (partial geom/adj-position geom)) (fmap utils/to-columnar)) trained-geom-scalars (utils/apply-map #(%1 %2) scalar-trainers (utils/to-columnar (vals facetted-col-data))) trained-geom-scalars (zipmap (keys facetted-col-data) (utils/to-row trained-geom-scalars)) trained-facet-scalars (facetter-trainers (keys facetted-col-data))] {:facet-scalars trained-facet-scalars :geom-scalars trained-geom-scalars :facetted-geom-data (fmap utils/to-row facetted-col-data)})) (defn render-facet-geoms "Returns facet=>[svg-geom-elems]" [facetted-geom-scales facetted-geom-data] (as-> facetted-geom-data $ ;; Transform geoms to svg-coords (utils/apply-map scale-geoms facetted-geom-scales $) Transform svg - coord geom maps to svg elements (fmap (fn render-geoms [scaled-geoms] (map (partial geom/->svg conf/*geom*) scaled-geoms)) $))) (defn render-facet-legends "Returns facet=>(aes=>Legend)" [facet=>aes-scalars facet=>aes-scales] (let [facet=>aes-scalar-scales (utils/apply-map #(merge-with vector %1 %2) facet=>aes-scalars facet=>aes-scales)] (fmap legend/render-legends facet=>aes-scalar-scales))) (defn draw-xy-iscales-ticks [legends] (list [:g {:class "x-iscale" :transform (translate [0 (first conf/*y*)])} (get-in legends [:x :iscale]) (get-in legends [:x :ticks])] [:g {:class "y-iscale" :transform (translate [(first conf/*x*) 0])} (get-in legends [:y :iscale]) (get-in legends [:y :ticks])])) (defn draw-facet-xy-labels "Draws labels if facet is first column or last row" [facet-scalars {x-legend :x y-legend :y} facet] [:g [:g {:transform (translate [0 (first conf/*y*)])} (if (last-row? facet-scalars facet) [:g {:transform (translate [0 10])} (:labels x-legend)])] [:g {:transform (translate [(first conf/*x*) 0])} (if (first-col? facet-scalars facet) (:labels y-legend))]]) (defn facet-labeller [facet-x facet-y] (let [attrs {:transform (translate [0 0]) :text-anchor "start" :font-family conf/*font-family* :font-size conf/*font-size*}] (cond (and (nil? facet-x) (nil? facet-y)) nil (and facet-x facet-y) [:text attrs (str \( facet-x ", " facet-y \))] (nil? facet-x) [:text attrs (str facet-y)] (nil? facet-y) [:text attrs (str facet-x)]))) (defn layout-geoms "Returns a svg hiccup vector plot. Takes width, height of the svg elem; trained facet and layer scalars; and geom positioned data. expects conf/*[aes]* and conf/*[aes]-label* vars to be bound args facet-scalars: scalar for positioning facets geom-scalars: a map of facet => aes-scalars, where aes-scalars is itself a map of aes => scalar facetted-geom-data: a map of facet => positioned data" [[width height] geom {:keys [facet-scalars geom-scalars facetted-geom-data] :as plot}] {:pre [(not (nil? conf/*x*)) (not (nil? conf/*y*))]} (let [[[facet-area-w facet-area-h] [facet-w facet-h] [geom-w geom-h]] (area-dims width height facet-scalars) scaled-plot (-> plot (bind-facetting-scales [width height]) bind-geom-scales) facet=>svg-wrapper (fmap (partial wrap-facet (:facet-scales scaled-plot)) (zipmap (keys facetted-geom-data) (keys facetted-geom-data))) facet=>svg-geoms (render-facet-geoms (:geom-scales scaled-plot) facetted-geom-data) facet=>Legends (render-facet-legends geom-scalars (:geom-scales scaled-plot)) facet=>svg-elem (as-> facet=>svg-wrapper $ ;; translate facet-padding (fmap (fn [_] (vector :g {:transform (translate [(nth conf/*facet-padding* 0) (nth conf/*facet-padding* 2)])})) $) ;; Draw xy scale bars in each facet (utils/apply-map #(conj %1 (draw-xy-iscales-ticks %2)) $ facet=>Legends) Draw text labels for xy legends (utils/apply-key-map (fn [facet facet-elem facet-legend] (conj facet-elem (draw-facet-xy-labels facet-scalars facet-legend facet))) $ facet=>Legends) ;; Draw geoms in each facet (utils/apply-map conj $ facet=>svg-geoms) ;; wrap facet (utils/apply-map (fn [wrapper geoms] (conj wrapper geoms)) facet=>svg-wrapper $) ;; draw facet-x and facet-y label (utils/apply-key-map (fn [[facet-x facet-y] wrapper] (conj wrapper (facet-labeller facet-x facet-y))) $))] [:svg {:width width :height height :xmlns "" :version "1.1"} [:defs #_[:style {:type "text/css"} "text {font-family: \"Courer New\", \"Courier\", \"monospace\"; font-size: 0.8em}"]] [:g {:transform (translate [(nth conf/*plot-padding* 0) (nth conf/*plot-padding* 2)])} (vals facet=>svg-elem)] ;; draw global aesthetic legends (except for x, y) [:g {:class "legends" :transform (translate [(- width (nth conf/*plot-padding* 1)) (nth conf/*plot-padding* 2)])} (let [[_ {:keys [color fill]}] (first facet=>Legends)] (list (if color [:g {:class "color-legend"} conf/*color-label* (:iscale color) [:g {:transform (translate [conf/*color-legend-size* (/ conf/*color-legend-size* 2)])} (:ticks color) [:g {:transform (translate [3 0])} (:labels color)]]]) (if fill [:g {:class "fill-legend" :transform (translate [conf/*color-legend-size* 0])} conf/*fill-label* (:iscale fill) [:g {:transform (translate [conf/*fill-legend-size* (/ conf/*fill-legend-size* 2)])} (:ticks fill) [:g {:transform (translate [3 0])} (:labels fill)]]])))] ;; draw x and y labels [:g {:transform (translate [(/ width 2) (- height (nth conf/*plot-padding* 3))])} conf/*x-label*] [:g {:transform (translate [0 (/ height 2)])} conf/*y-label*]]))
null
https://raw.githubusercontent.com/dvdt/xvsy/ff29b96affc6723bb9c66da1011f31900af679dd/src/cljc/xvsy/plot.cljc
clojure
facet dimensions, for a single and the geom dimensions, which is where the actual plot geom TODO: The impl is super ugly right now, but I think the API is right. Transform geoms to svg-coords and geom positioned data. translate facet-padding Draw xy scale bars in each facet Draw geoms in each facet wrap facet draw facet-x and facet-y label draw global aesthetic legends (except for x, y) draw x and y labels
(ns xvsy.plot "This namespace is responsible for generating svg plots from sql data." (:require [xvsy.utils :as utils :refer [translate fmap]] [xvsy.conf :as conf] [xvsy.scale :as scale] [xvsy.geom :as geom] [xvsy.legend :as legend])) (defn area-dims "Given the overall plot width and height and facet scalars, returns the facet-area dimensions, which is the width and height of the elements go. Example below has a single facet. Global legends can go in (a), and per-facet legends go in (b). width |-------------------------------------------------| | | | facet-area-width | | |------------------------------| | | | | | height | | facet-width | | | | |---------------| (b) | (a) | | | | | | | geom-width | | | | |--------| | | | | | | | | | | | |------------------------------| | | | | (a) | |-------------------------------------------------|" [width height [facet-x-scalar facet-y-scalar]] (let [[plot-padding-left plot-padding-right plot-padding-top plot-padding-bottom] conf/*plot-padding* [facet-padding-left facet-padding-right facet-padding-top facet-padding-bottom] conf/*facet-padding* [facet-area-w facet-area-h] [(- width plot-padding-left plot-padding-right) (- height plot-padding-top plot-padding-bottom)] facet-w (/ facet-area-w (count (scale/->ticks facet-x-scalar))) facet-h (/ facet-area-h (count (scale/->ticks facet-y-scalar))) [geom-w geom-h] [(- facet-w facet-padding-left facet-padding-right) (- facet-h facet-padding-top facet-padding-bottom)]] [[facet-area-w facet-area-h] [facet-w facet-h] [geom-w geom-h]])) (defn plot-width [width] (- width (nth conf/*plot-padding* 0) (nth conf/*plot-padding* 1))) (defn plot-height [height] (- height (nth conf/*plot-padding* 2) (nth conf/*plot-padding* 3))) (defn facet-width "assumes facets are of same width. returns the width in pixels of a facet, given with width of the entire plot." [width facet-scalar] (let [facet-full-length (second ((scale/->scale facet-scalar [0 (plot-width width)]) (first (scale/->ticks facet-scalar))))] (- facet-full-length (nth conf/*facet-padding* 0) (nth conf/*facet-padding* 1)))) (defn facet-height "assumes facets are of same width" [height facet-scalar] (let [facet-full-length (second ((scale/->scale facet-scalar [0 (plot-height height)]) (first (scale/->ticks facet-scalar))))] (- facet-full-length (nth conf/*facet-padding* 2) (nth conf/*facet-padding* 3)))) (defn geom-height "assumes facets are of same width" [facet-scalar facet-area-length] (let [facet-length (/ facet-area-length (count (scale/->ticks facet-scalar)))] (- facet-length (nth conf/*facet-padding* 2) (nth conf/*facet-padding* 3)))) (defn make-discrete-scale [scalar range-vals] (if (nil? scalar) nil (let [t (scale/->ticks scalar) s (scale/->scale scalar [0 (count t)]) s (if (coll? (s (first t))) (comp first s) (comp #(if (< % (count range-vals)) % (- (count range-vals) 1)) s)) ] (fn [v] (nth range-vals (mod (s v) (count range-vals))))))) (defn make-continuous-scale [scalar svg-fn] (comp svg-fn (scale/->scale scalar [0 1]))) (defn- gen-scales "Returns scales from the scalars and dynamically bound ranges" [scalar-map] (-> scalar-map (update-in [:color] #(make-discrete-scale % conf/*color*)) (update-in [:fill] #(make-discrete-scale % conf/*fill*)))) (defn- scale-geoms [scale-map geom-data] (map (fn scale-geom [g] (merge-with #(%1 %2) scale-map g)) geom-data)) (defn wrap-facet "returns translated [:g] elements for each facet-val" [[x-scale y-scale] [x-val y-val]] [:g {:class "facet" :transform (translate [(apply min (x-scale x-val)) (apply min (y-scale y-val))])}]) (defn last-row? [[x-scalar y-scalar] [x y]] (-> y ((scale/->scale y-scalar [0 10000])) first int (= 0))) (defn first-col? [[x-scalar y-scalar] [x y]] (-> x ((scale/->scale x-scalar [0 10000])) first int (= 0))) (defn wrap-geoms "Draws legends around a facet." [{:keys [facet-scalars facet-scales geom-scalars geom-scales] :as plot} [width height] [facet rendered-geoms]] (let [[facet-w facet-h] [(facet-width width (first facet-scalars)) (facet-height height (second facet-scalars))] x-legend (legend/render-legend :x (get-in geom-scalars [facet :x]) (get-in geom-scales [facet :x])) y-legend (legend/render-legend :y (get-in geom-scalars [facet :y]) (get-in geom-scales [facet :y])) aes-legends (map #(legend/render-legend % (get-in geom-scalars [facet %]) (get-in geom-scales [facet %])) (keys geom-scales))] [:g {:class "geoms"} [:g {:transform (translate [0 facet-h])} (:ticks x-legend) (if (last-row? facet-scalars facet) [:g {:transform (translate [0 15])} (:labels x-legend)])] [:g {:transform (translate [0 0])} (:ticks y-legend) (if (first-col? facet-scalars facet) (:labels y-legend))] [:rect {:x 0 :y 0 :width facet-w :height facet-h :fill :none :stroke "grey" :class "facet-outline"}] rendered-geoms])) (defn bind-facetting-scales "Given a width and height, generates :facet-scales based on the bound conf. Facet scales is a vec: [facet-x-scale facet-y-scale]" [{:keys [facet-scalars geom-scalars facetted-geom-data] :as plot} [width height]] (assoc plot :facet-scales [(scale/->scale (first facet-scalars) [0 (plot-width width)]) (scale/->scale (second facet-scalars) [(plot-height height) 0])])) (defn bind-geom-scales "Returns a plot with the key :geom-scales set as a map of: [facet-x facet-y] => (aes => (data-coords -> svg-coords)). args: facet-scalars is a vec: [facet-x-scalar facet-y-scalar] geom-scalars is a map: [facet-x facet-y] => (aes => scalar) facetted-geom-data is a map: [facet-x facet-y] => [aes => data]" [{:keys [facet-scalars geom-scalars facetted-geom-data] :as plot}] (assoc plot :geom-scales (fmap scale/guess-svg-scales geom-scalars))) (defn facet-by "returns a hashmap of facet -> data" [[[x-facet x-mapping] [y-facet y-mapping]] data] (group-by (juxt x-facet y-facet) data)) (defn ->plot "Returns trained scales and positioned geom hashmaps. scalar-trainer is hashmap of aes-kw => ([data] -> scalar) facetter-trainers is ([facet] -> [facet-x-scalar facet-y-scalar])" [geom scalar-trainers facetter-trainers sql-data] (let [facetted-col-data (->> sql-data (facet-by [[:facet_x nil] [:facet_y nil]]) (fmap (partial geom/adj-position geom)) (fmap utils/to-columnar)) trained-geom-scalars (utils/apply-map #(%1 %2) scalar-trainers (utils/to-columnar (vals facetted-col-data))) trained-geom-scalars (zipmap (keys facetted-col-data) (utils/to-row trained-geom-scalars)) trained-facet-scalars (facetter-trainers (keys facetted-col-data))] {:facet-scalars trained-facet-scalars :geom-scalars trained-geom-scalars :facetted-geom-data (fmap utils/to-row facetted-col-data)})) (defn render-facet-geoms "Returns facet=>[svg-geom-elems]" [facetted-geom-scales facetted-geom-data] (as-> facetted-geom-data $ (utils/apply-map scale-geoms facetted-geom-scales $) Transform svg - coord geom maps to svg elements (fmap (fn render-geoms [scaled-geoms] (map (partial geom/->svg conf/*geom*) scaled-geoms)) $))) (defn render-facet-legends "Returns facet=>(aes=>Legend)" [facet=>aes-scalars facet=>aes-scales] (let [facet=>aes-scalar-scales (utils/apply-map #(merge-with vector %1 %2) facet=>aes-scalars facet=>aes-scales)] (fmap legend/render-legends facet=>aes-scalar-scales))) (defn draw-xy-iscales-ticks [legends] (list [:g {:class "x-iscale" :transform (translate [0 (first conf/*y*)])} (get-in legends [:x :iscale]) (get-in legends [:x :ticks])] [:g {:class "y-iscale" :transform (translate [(first conf/*x*) 0])} (get-in legends [:y :iscale]) (get-in legends [:y :ticks])])) (defn draw-facet-xy-labels "Draws labels if facet is first column or last row" [facet-scalars {x-legend :x y-legend :y} facet] [:g [:g {:transform (translate [0 (first conf/*y*)])} (if (last-row? facet-scalars facet) [:g {:transform (translate [0 10])} (:labels x-legend)])] [:g {:transform (translate [(first conf/*x*) 0])} (if (first-col? facet-scalars facet) (:labels y-legend))]]) (defn facet-labeller [facet-x facet-y] (let [attrs {:transform (translate [0 0]) :text-anchor "start" :font-family conf/*font-family* :font-size conf/*font-size*}] (cond (and (nil? facet-x) (nil? facet-y)) nil (and facet-x facet-y) [:text attrs (str \( facet-x ", " facet-y \))] (nil? facet-x) [:text attrs (str facet-y)] (nil? facet-y) [:text attrs (str facet-x)]))) (defn layout-geoms expects conf/*[aes]* and conf/*[aes]-label* vars to be bound args facet-scalars: scalar for positioning facets geom-scalars: a map of facet => aes-scalars, where aes-scalars is itself a map of aes => scalar facetted-geom-data: a map of facet => positioned data" [[width height] geom {:keys [facet-scalars geom-scalars facetted-geom-data] :as plot}] {:pre [(not (nil? conf/*x*)) (not (nil? conf/*y*))]} (let [[[facet-area-w facet-area-h] [facet-w facet-h] [geom-w geom-h]] (area-dims width height facet-scalars) scaled-plot (-> plot (bind-facetting-scales [width height]) bind-geom-scales) facet=>svg-wrapper (fmap (partial wrap-facet (:facet-scales scaled-plot)) (zipmap (keys facetted-geom-data) (keys facetted-geom-data))) facet=>svg-geoms (render-facet-geoms (:geom-scales scaled-plot) facetted-geom-data) facet=>Legends (render-facet-legends geom-scalars (:geom-scales scaled-plot)) facet=>svg-elem (as-> facet=>svg-wrapper $ (fmap (fn [_] (vector :g {:transform (translate [(nth conf/*facet-padding* 0) (nth conf/*facet-padding* 2)])})) $) (utils/apply-map #(conj %1 (draw-xy-iscales-ticks %2)) $ facet=>Legends) Draw text labels for xy legends (utils/apply-key-map (fn [facet facet-elem facet-legend] (conj facet-elem (draw-facet-xy-labels facet-scalars facet-legend facet))) $ facet=>Legends) (utils/apply-map conj $ facet=>svg-geoms) (utils/apply-map (fn [wrapper geoms] (conj wrapper geoms)) facet=>svg-wrapper $) (utils/apply-key-map (fn [[facet-x facet-y] wrapper] (conj wrapper (facet-labeller facet-x facet-y))) $))] [:svg {:width width :height height :xmlns "" :version "1.1"} [:defs #_[:style {:type "text/css"} "text {font-family: font-size: 0.8em}"]] [:g {:transform (translate [(nth conf/*plot-padding* 0) (nth conf/*plot-padding* 2)])} (vals facet=>svg-elem)] [:g {:class "legends" :transform (translate [(- width (nth conf/*plot-padding* 1)) (nth conf/*plot-padding* 2)])} (let [[_ {:keys [color fill]}] (first facet=>Legends)] (list (if color [:g {:class "color-legend"} conf/*color-label* (:iscale color) [:g {:transform (translate [conf/*color-legend-size* (/ conf/*color-legend-size* 2)])} (:ticks color) [:g {:transform (translate [3 0])} (:labels color)]]]) (if fill [:g {:class "fill-legend" :transform (translate [conf/*color-legend-size* 0])} conf/*fill-label* (:iscale fill) [:g {:transform (translate [conf/*fill-legend-size* (/ conf/*fill-legend-size* 2)])} (:ticks fill) [:g {:transform (translate [3 0])} (:labels fill)]]])))] [:g {:transform (translate [(/ width 2) (- height (nth conf/*plot-padding* 3))])} conf/*x-label*] [:g {:transform (translate [0 (/ height 2)])} conf/*y-label*]]))
750cb44bc175613c3fbeaba9d5b0e583a9780bc58d7634b448f7eb79ab8236df
macourtney/Dark-Exchange
identity.clj
(ns darkexchange.model.identity (:require [clj-record.boot :as clj-record-boot] [clojure.contrib.logging :as logging] [darkexchange.model.client :as client] [darkexchange.model.peer :as peer] [darkexchange.model.security :as security] [darkexchange.model.terms :as terms] [darkexchange.model.user :as user]) (:use darkexchange.model.base) (:import [org.apache.commons.codec.binary Base64])) (def identity-add-listeners (atom [])) (def identity-update-listeners (atom [])) (def identity-delete-listeners (atom [])) (defn add-identity-add-listener [listener] (swap! identity-add-listeners conj listener)) (defn add-identity-update-listener [listener] (swap! identity-update-listeners conj listener)) (defn add-identity-delete-listener [listener] (swap! identity-delete-listeners conj listener)) (defn identity-add [identity] (doseq [listener @identity-add-listeners] (listener identity))) (defn identity-update [identity] (doseq [listener @identity-update-listeners] (listener identity))) (defn identity-delete [identity] (doseq [listener @identity-delete-listeners] (listener identity))) (clj-record.core/init-model (:associations (belongs-to peer) (has-many scorer_trust_scores :fk target_id) (has-many target-trust-scores :fk target_id :model trust-score)) (:callbacks (:after-update identity-update) (:after-insert identity-add) (:after-destroy identity-delete))) (defn add-identity [user-name public-key public-key-algorithm destination] (when-let [peer (peer/find-peer destination)] (insert { :name user-name :public_key public-key :public_key_algorithm public-key-algorithm :peer_id (:id peer) :is_online 1 }))) (defn update-identity-name [current-identity user-name] (when (not (= user-name (:name current-identity))) (update { :id (:id current-identity) :name user-name }))) (defn update-identity-peer [current-identity destination] (when-let [peer (peer/find-peer destination)] (when (not (= (:id peer) (:peer_id current-identity))) (update { :id (:id current-identity) :peer_id (:id peer) })))) (defn update-identity-is-online [current-identity is-online] (when current-identity (update { :id (:id current-identity) :is_online (if is-online 1 0) }))) (defn update-identity [current-identity user-name destination] (update-identity-name current-identity user-name) (update-identity-peer current-identity destination) (update-identity-is-online current-identity true) (:id current-identity)) (defn find-identity [user-name public-key public-key-algorithm] (find-record { :name user-name :public_key public-key :public_key_algorithm public-key-algorithm })) (defn find-identity-by-peer [peer] (when peer (find-record { :peer_id (:id peer) }))) (defn find-identity-by-destination [destination] (find-identity-by-peer (peer/find-peer destination))) (defn add-or-update-identity [user-name public-key public-key-algorithm destination] (if-let [current-identity (find-identity user-name public-key public-key-algorithm)] (update-identity current-identity user-name destination) (add-identity user-name public-key public-key-algorithm destination))) (defn identity-not-online [destination] (update-identity-is-online (find-identity-by-destination destination) false)) (defn find-or-create-identity [user-name public-key public-key-algorithm destination] (when (and user-name public-key destination) (or (find-identity user-name public-key public-key-algorithm) (get-record (add-identity user-name public-key public-key-algorithm destination))))) (defn destination-for ([user-name public-key public-key-algorithm] (destination-for (find-identity user-name public-key public-key-algorithm))) ([target-identity] (when target-identity (when-let [peer-id (:peer_id target-identity)] (when-let [peer (peer/find-record { :id peer-id })] (peer/destination-for peer)))))) (defn send-message ([user-name public-key public-key-algorithm action data] (send-message (find-identity user-name public-key public-key-algorithm) action data)) ([target-identity action data] (client/send-message (destination-for target-identity) action data))) (defn decode-base64 [string] (when string (.decode (new Base64) string))) (defn public-key [target-identity] (security/decode-public-key { :algorithm (:public_key_algorithm target-identity) :bytes (decode-base64 (:public_key target-identity)) })) (defn verify-signature [target-identity data signature] (security/verify-signature (public-key target-identity) data (decode-base64 signature))) (defn current-user-identity [] (let [user (user/current-user)] (find-identity (:name user) (:public_key user) (:public_key_algorithm user)))) (defn shortened-public-key-str [public-key] (when public-key (if (> (.length public-key) 60) (str ".." (.substring public-key 40 60) "..") ".."))) (defn shortened-public-key [identity] (shortened-public-key-str (:public_key identity))) (defn identity-text [identity] (str (:name identity) " (" (shortened-public-key identity) ")")) (defn is-online? [identity] (as-boolean (:is_online identity))) (defn table-identity [identity] (let [destination (destination-for identity)] (merge (select-keys identity [:id :name :public_key_algorithm]) { :destination destination :public_key (shortened-public-key identity) :is_online (when (is-online? identity) (terms/yes)) }))) (defn all-online-identities [] (find-records ["is_online = 1"])) (defn all-identities ([] (all-identities false)) ([only-online-identities] (if only-online-identities (all-online-identities) (find-records [true])))) (defn non-user-identities ([] (non-user-identities false)) ([only-online-identities] (if-let [user-identity (current-user-identity)] (filter #(not (= (:id user-identity) (:id %))) (all-identities only-online-identities)) (all-identities only-online-identities)))) (defn is-user-identity? [identity] (if (and (:name identity) (:public_key identity) (:public_key_algorithm identity)) (let [user (user/current-user)] (and (= (:name identity) (:name user)) (= (:public_key identity) (:public_key user)) (= (:public_key_algorithm identity) (:public_key_algorithm user)))) (= (:id identity) (:id (current-user-identity))))) (defn table-identities [only-online-identities] (map table-identity (non-user-identities only-online-identities))) (defn get-table-identity [id] (table-identity (get-record id)))
null
https://raw.githubusercontent.com/macourtney/Dark-Exchange/1654d05cda0c81585da7b8e64f9ea3e2944b27f1/src/darkexchange/model/identity.clj
clojure
(ns darkexchange.model.identity (:require [clj-record.boot :as clj-record-boot] [clojure.contrib.logging :as logging] [darkexchange.model.client :as client] [darkexchange.model.peer :as peer] [darkexchange.model.security :as security] [darkexchange.model.terms :as terms] [darkexchange.model.user :as user]) (:use darkexchange.model.base) (:import [org.apache.commons.codec.binary Base64])) (def identity-add-listeners (atom [])) (def identity-update-listeners (atom [])) (def identity-delete-listeners (atom [])) (defn add-identity-add-listener [listener] (swap! identity-add-listeners conj listener)) (defn add-identity-update-listener [listener] (swap! identity-update-listeners conj listener)) (defn add-identity-delete-listener [listener] (swap! identity-delete-listeners conj listener)) (defn identity-add [identity] (doseq [listener @identity-add-listeners] (listener identity))) (defn identity-update [identity] (doseq [listener @identity-update-listeners] (listener identity))) (defn identity-delete [identity] (doseq [listener @identity-delete-listeners] (listener identity))) (clj-record.core/init-model (:associations (belongs-to peer) (has-many scorer_trust_scores :fk target_id) (has-many target-trust-scores :fk target_id :model trust-score)) (:callbacks (:after-update identity-update) (:after-insert identity-add) (:after-destroy identity-delete))) (defn add-identity [user-name public-key public-key-algorithm destination] (when-let [peer (peer/find-peer destination)] (insert { :name user-name :public_key public-key :public_key_algorithm public-key-algorithm :peer_id (:id peer) :is_online 1 }))) (defn update-identity-name [current-identity user-name] (when (not (= user-name (:name current-identity))) (update { :id (:id current-identity) :name user-name }))) (defn update-identity-peer [current-identity destination] (when-let [peer (peer/find-peer destination)] (when (not (= (:id peer) (:peer_id current-identity))) (update { :id (:id current-identity) :peer_id (:id peer) })))) (defn update-identity-is-online [current-identity is-online] (when current-identity (update { :id (:id current-identity) :is_online (if is-online 1 0) }))) (defn update-identity [current-identity user-name destination] (update-identity-name current-identity user-name) (update-identity-peer current-identity destination) (update-identity-is-online current-identity true) (:id current-identity)) (defn find-identity [user-name public-key public-key-algorithm] (find-record { :name user-name :public_key public-key :public_key_algorithm public-key-algorithm })) (defn find-identity-by-peer [peer] (when peer (find-record { :peer_id (:id peer) }))) (defn find-identity-by-destination [destination] (find-identity-by-peer (peer/find-peer destination))) (defn add-or-update-identity [user-name public-key public-key-algorithm destination] (if-let [current-identity (find-identity user-name public-key public-key-algorithm)] (update-identity current-identity user-name destination) (add-identity user-name public-key public-key-algorithm destination))) (defn identity-not-online [destination] (update-identity-is-online (find-identity-by-destination destination) false)) (defn find-or-create-identity [user-name public-key public-key-algorithm destination] (when (and user-name public-key destination) (or (find-identity user-name public-key public-key-algorithm) (get-record (add-identity user-name public-key public-key-algorithm destination))))) (defn destination-for ([user-name public-key public-key-algorithm] (destination-for (find-identity user-name public-key public-key-algorithm))) ([target-identity] (when target-identity (when-let [peer-id (:peer_id target-identity)] (when-let [peer (peer/find-record { :id peer-id })] (peer/destination-for peer)))))) (defn send-message ([user-name public-key public-key-algorithm action data] (send-message (find-identity user-name public-key public-key-algorithm) action data)) ([target-identity action data] (client/send-message (destination-for target-identity) action data))) (defn decode-base64 [string] (when string (.decode (new Base64) string))) (defn public-key [target-identity] (security/decode-public-key { :algorithm (:public_key_algorithm target-identity) :bytes (decode-base64 (:public_key target-identity)) })) (defn verify-signature [target-identity data signature] (security/verify-signature (public-key target-identity) data (decode-base64 signature))) (defn current-user-identity [] (let [user (user/current-user)] (find-identity (:name user) (:public_key user) (:public_key_algorithm user)))) (defn shortened-public-key-str [public-key] (when public-key (if (> (.length public-key) 60) (str ".." (.substring public-key 40 60) "..") ".."))) (defn shortened-public-key [identity] (shortened-public-key-str (:public_key identity))) (defn identity-text [identity] (str (:name identity) " (" (shortened-public-key identity) ")")) (defn is-online? [identity] (as-boolean (:is_online identity))) (defn table-identity [identity] (let [destination (destination-for identity)] (merge (select-keys identity [:id :name :public_key_algorithm]) { :destination destination :public_key (shortened-public-key identity) :is_online (when (is-online? identity) (terms/yes)) }))) (defn all-online-identities [] (find-records ["is_online = 1"])) (defn all-identities ([] (all-identities false)) ([only-online-identities] (if only-online-identities (all-online-identities) (find-records [true])))) (defn non-user-identities ([] (non-user-identities false)) ([only-online-identities] (if-let [user-identity (current-user-identity)] (filter #(not (= (:id user-identity) (:id %))) (all-identities only-online-identities)) (all-identities only-online-identities)))) (defn is-user-identity? [identity] (if (and (:name identity) (:public_key identity) (:public_key_algorithm identity)) (let [user (user/current-user)] (and (= (:name identity) (:name user)) (= (:public_key identity) (:public_key user)) (= (:public_key_algorithm identity) (:public_key_algorithm user)))) (= (:id identity) (:id (current-user-identity))))) (defn table-identities [only-online-identities] (map table-identity (non-user-identities only-online-identities))) (defn get-table-identity [id] (table-identity (get-record id)))
473bf01f2aaf6497c5f2952b86c0daf5f0f7b711ffd05a3c4737079edd8ba10a
CrossRef/cayenne
rdf.clj
(ns cayenne.formats.rdf (:import [java.io StringWriter]) (:require [clojure.string :as string] [cayenne.rdf :as rdf] [cayenne.ids.isbn :as isbn-id] [cayenne.ids.issn :as issn-id] [cayenne.ids.contributor :as contributor-id])) ;; TODO full-text links, funders, licenses (defn make-rdf-issn-container [model metadata] (when-let [first-issn (first (:ISSN metadata))] (let [properties (concat [(rdf/rdf model "type") (rdf/bibo-type model "Journal") (rdf/bibo model "issn") first-issn (rdf/prism model "issn") first-issn (rdf/dct model "title") (first (:container-title metadata))] (flatten (map #(vector (rdf/owl model "sameAs") (str "urn:issn:" %) (rdf/bibo model "issn") % (rdf/prism model "issn") %) (set (:ISSN metadata)))))] (apply rdf/make-resource model (issn-id/to-issn-uri first-issn) properties)))) (defn make-rdf-isbn-container [model metadata] (when (first (:ISBN metadata)) (rdf/make-resource model (isbn-id/to-isbn-uri (first (:ISBN metadata))) (rdf/rdf model "type") (rdf/bibo-type model "Book") (rdf/dct model "title") (first (:container-title metadata))))) TODO for a make - rdf - doi - container would need container DOIs in solr and citeproc (defn make-rdf-contributor [model doi contributor] (let [full-name (str (:given contributor) " " (:family contributor))] (rdf/make-resource model (contributor-id/to-contributor-id-uri full-name 0 doi) (rdf/rdf model "type") (rdf/foaf-type model "Person") (rdf/owl model "sameAs") (rdf/make-resource model (:ORCID contributor)) (rdf/foaf model "givenName") (:given contributor) (rdf/foaf model "familyName") (:family contributor) (rdf/foaf model "name") full-name))) (defn get-pages [metadata] (when (:page metadata) (string/split (:page metadata) #"\-+"))) (defn get-issued [metadata] (when-let [dateules (get-in metadata [:issued :date-parts 0])] (apply rdf/make-date dateules))) (defn make-rdf-work [model metadata] (concat (when (not= (string/lower-case (:URL metadata)) (:URL metadata)) [(rdf/owl model "sameAs") (rdf/make-resource model (string/lower-case (:URL metadata)))]) [(rdf/dct model "identifier") (:DOI metadata) (rdf/owl model "sameAs") (rdf/make-resource model (str "doi:" (:DOI metadata))) (rdf/owl model "sameAs") (rdf/make-resource model (str "info:doi/" (:DOI metadata))) (rdf/dct model "date") (get-issued metadata) (rdf/prism model "doi") (:DOI metadata) (rdf/bibo model "doi") (:DOI metadata) (rdf/prism model "volume") (:volume metadata) (rdf/bibo model "volume") (:volume metadata) (rdf/bibo model "pageStart") (first (get-pages metadata)) (rdf/bibo model "pageEnd") (second (get-pages metadata)) (rdf/prism model "startingPage") (first (get-pages metadata)) (rdf/prism model "endingPage") (second (get-pages metadata)) (rdf/dct model "title") (first (:title metadata)) (rdf/dct model "publisher") (:publisher metadata) (rdf/dct model "isPartOf") (make-rdf-issn-container model metadata) (rdf/dct model "isPartOf") (make-rdf-isbn-container model metadata)] (flatten (map #(vector (rdf/dct model "creator") (make-rdf-contributor model (:DOI metadata) %)) (concat (:author metadata) (:editor metadata) (:translator metadata) (:chair metadata)))))) (defn ->rdf-model [metadata] (let [model (rdf/make-model) properties (make-rdf-work model metadata)] (apply rdf/make-resource model (:URL metadata) properties) model)) (defn ->rdf-lang [metadata lang] (let [writer (StringWriter.)] (.write (->rdf-model metadata) writer lang) (.toString writer))) (defn ->xml [metadata] (->rdf-lang metadata "RDF/XML-ABBREV")) (defn ->n3 [metadata] (->rdf-lang metadata "N3")) (defn ->n-triples [metadata] (->rdf-lang metadata "N-TRIPLE")) (defn ->turtle [metadata] (->rdf-lang metadata "TURTLE"))
null
https://raw.githubusercontent.com/CrossRef/cayenne/02321ad23dbb1edd3f203a415f4a4b11ebf810d7/src/cayenne/formats/rdf.clj
clojure
TODO full-text links, funders, licenses
(ns cayenne.formats.rdf (:import [java.io StringWriter]) (:require [clojure.string :as string] [cayenne.rdf :as rdf] [cayenne.ids.isbn :as isbn-id] [cayenne.ids.issn :as issn-id] [cayenne.ids.contributor :as contributor-id])) (defn make-rdf-issn-container [model metadata] (when-let [first-issn (first (:ISSN metadata))] (let [properties (concat [(rdf/rdf model "type") (rdf/bibo-type model "Journal") (rdf/bibo model "issn") first-issn (rdf/prism model "issn") first-issn (rdf/dct model "title") (first (:container-title metadata))] (flatten (map #(vector (rdf/owl model "sameAs") (str "urn:issn:" %) (rdf/bibo model "issn") % (rdf/prism model "issn") %) (set (:ISSN metadata)))))] (apply rdf/make-resource model (issn-id/to-issn-uri first-issn) properties)))) (defn make-rdf-isbn-container [model metadata] (when (first (:ISBN metadata)) (rdf/make-resource model (isbn-id/to-isbn-uri (first (:ISBN metadata))) (rdf/rdf model "type") (rdf/bibo-type model "Book") (rdf/dct model "title") (first (:container-title metadata))))) TODO for a make - rdf - doi - container would need container DOIs in solr and citeproc (defn make-rdf-contributor [model doi contributor] (let [full-name (str (:given contributor) " " (:family contributor))] (rdf/make-resource model (contributor-id/to-contributor-id-uri full-name 0 doi) (rdf/rdf model "type") (rdf/foaf-type model "Person") (rdf/owl model "sameAs") (rdf/make-resource model (:ORCID contributor)) (rdf/foaf model "givenName") (:given contributor) (rdf/foaf model "familyName") (:family contributor) (rdf/foaf model "name") full-name))) (defn get-pages [metadata] (when (:page metadata) (string/split (:page metadata) #"\-+"))) (defn get-issued [metadata] (when-let [dateules (get-in metadata [:issued :date-parts 0])] (apply rdf/make-date dateules))) (defn make-rdf-work [model metadata] (concat (when (not= (string/lower-case (:URL metadata)) (:URL metadata)) [(rdf/owl model "sameAs") (rdf/make-resource model (string/lower-case (:URL metadata)))]) [(rdf/dct model "identifier") (:DOI metadata) (rdf/owl model "sameAs") (rdf/make-resource model (str "doi:" (:DOI metadata))) (rdf/owl model "sameAs") (rdf/make-resource model (str "info:doi/" (:DOI metadata))) (rdf/dct model "date") (get-issued metadata) (rdf/prism model "doi") (:DOI metadata) (rdf/bibo model "doi") (:DOI metadata) (rdf/prism model "volume") (:volume metadata) (rdf/bibo model "volume") (:volume metadata) (rdf/bibo model "pageStart") (first (get-pages metadata)) (rdf/bibo model "pageEnd") (second (get-pages metadata)) (rdf/prism model "startingPage") (first (get-pages metadata)) (rdf/prism model "endingPage") (second (get-pages metadata)) (rdf/dct model "title") (first (:title metadata)) (rdf/dct model "publisher") (:publisher metadata) (rdf/dct model "isPartOf") (make-rdf-issn-container model metadata) (rdf/dct model "isPartOf") (make-rdf-isbn-container model metadata)] (flatten (map #(vector (rdf/dct model "creator") (make-rdf-contributor model (:DOI metadata) %)) (concat (:author metadata) (:editor metadata) (:translator metadata) (:chair metadata)))))) (defn ->rdf-model [metadata] (let [model (rdf/make-model) properties (make-rdf-work model metadata)] (apply rdf/make-resource model (:URL metadata) properties) model)) (defn ->rdf-lang [metadata lang] (let [writer (StringWriter.)] (.write (->rdf-model metadata) writer lang) (.toString writer))) (defn ->xml [metadata] (->rdf-lang metadata "RDF/XML-ABBREV")) (defn ->n3 [metadata] (->rdf-lang metadata "N3")) (defn ->n-triples [metadata] (->rdf-lang metadata "N-TRIPLE")) (defn ->turtle [metadata] (->rdf-lang metadata "TURTLE"))
0d4539438758eb4520c423342a0a88a5e1068b25464b5c6a3f4e7e7e5f86f32c
martinsumner/kv_index_tictactree
aae_treecache.erl
%% -------- Overview --------- %% -module(aae_treecache). -behaviour(gen_server). -include("include/aae.hrl"). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3, format_status/2]). -export([cache_open/3, cache_new/3, cache_alter/4, cache_root/1, cache_leaves/2, cache_markdirtysegments/3, cache_replacedirtysegments/3, cache_destroy/1, cache_startload/1, cache_completeload/2, cache_loglevel/2, cache_close/1]). -include_lib("eunit/include/eunit.hrl"). -define(PENDING_EXT, ".pnd"). -define(FINAL_EXT, ".aae"). -define(START_SQN, 1). -define(SYNC_TIMEOUT, 30000). -record(state, {save_sqn = 0 :: integer(), is_restored = false :: boolean(), tree :: leveled_tictac:tictactree()|undefined, root_path :: list()|undefined, partition_id :: integer()|undefined, loading = false :: boolean(), dirty_segments = [] :: list(), active_fold :: string()|undefined, change_queue = [] :: list()|not_logged, queued_changes = 0 :: non_neg_integer(), log_levels :: aae_util:log_levels()|undefined, safe_save = false :: boolean()}). -type partition_id() :: integer()|{integer(), integer()}. %%%============================================================================ %%% API %%%============================================================================ -spec cache_open(list(), partition_id(), aae_util:log_levels()|undefined) -> {boolean(), pid()}. %% @doc Open a tree cache , using any previously saved one for this tree cache as a %% starting point. Return is_empty boolean as true to indicate if a new cache was created , as well as the PID of this FSM cache_open(RootPath, PartitionID, LogLevels) -> Opts = [{root_path, RootPath}, {partition_id, PartitionID}, {log_levels, LogLevels}], {ok, Pid} = gen_server:start_link(?MODULE, [Opts], []), IsRestored = gen_server:call(Pid, is_restored, infinity), {IsRestored, Pid}. -spec cache_new(list(), partition_id(), aae_util:log_levels()|undefined) -> {ok, pid()}. %% @doc %% Open a tree cache, without restoring from file cache_new(RootPath, PartitionID, LogLevels) -> Opts = [{root_path, RootPath}, {partition_id, PartitionID}, {ignore_disk, true}, {log_levels, LogLevels}], gen_server:start_link(?MODULE, [Opts], []). -spec cache_destroy(pid()) -> ok. %% @doc %% Close a cache without saving cache_destroy(AAECache) -> gen_server:cast(AAECache, destroy). -spec cache_close(pid()) -> ok. %% @doc %% Close a cache with saving cache_close(AAECache) -> gen_server:call(AAECache, close, ?SYNC_TIMEOUT). -spec cache_alter(pid(), binary(), integer(), integer()) -> ok. %% @doc %% Change the hash tree to reflect an addition and removal of a hash value cache_alter(AAECache, Key, CurrentHash, OldHash) -> gen_server:cast(AAECache, {alter, Key, CurrentHash, OldHash}). -spec cache_root(pid()) -> binary(). %% @doc %% Fetch the root of the cache tree to compare cache_root(Pid) -> gen_server:call(Pid, fetch_root, infinity). -spec cache_leaves(pid(), list(integer())) -> list(). %% @doc %% Fetch the leaves for a given list of branch IDs. cache_leaves(Pid, BranchIDs) -> gen_server:call(Pid, {fetch_leaves, BranchIDs}, infinity). -spec cache_markdirtysegments(pid(), list(integer()), string()) -> ok. %% @doc %% Mark dirty segments. These segments are currently subject to a fetch_clocks %% fold. If they aren't touched until the fold is complete, the segment can be %% safely replaced with the value in the fold. %% %% The FoldGUID is used to identify the request that prompted the marking. %% This becomes the active_fold, replacing any previous marking. Dirty %% segments can only be replaced by the last active fold. Need to avoid race %% conditions between multiple dirtysegment markings (as well as updates %% clearing dirty segments) cache_markdirtysegments(Pid, SegmentIDs, FoldGUID) -> gen_server:cast(Pid, {mark_dirtysegments, SegmentIDs, FoldGUID}). -spec cache_replacedirtysegments(pid(), list({integer(), integer()}), string()) -> ok. %% @doc %% When a fold_clocks is complete, replace any dirty_segments which remain %% clean from other interventions cache_replacedirtysegments(Pid, ReplacementSegments, FoldGUID) -> gen_server:cast(Pid, {replace_dirtysegments, ReplacementSegments, FoldGUID}). -spec cache_startload(pid()) -> ok. %% @doc %% Sets the cache loading state to true, now as well as maintaining the %% current tree the cache should keep a queue of all the changes from this %% point. %% %% Eventually cache_completeload should be called with a tree built from %% a loading process snapshotted at the startload point, and the changes can %% all be applied cache_startload(Pid) -> gen_server:cast(Pid, start_load). -spec cache_completeload(pid(), leveled_tictac:tictactree()) -> ok. %% @doc Take a tree which has been produced from a fold of the KeyStore , and make %% this the new tree cache_completeload(Pid, LoadedTree) -> gen_server:cast(Pid, {complete_load, LoadedTree}). -spec cache_loglevel(pid(), aae_util:log_levels()) -> ok. %% @doc Alter the log level at runtime cache_loglevel(Pid, LogLevels) -> gen_server:cast(Pid, {log_levels, LogLevels}). %%%============================================================================ %%% gen_server callbacks %%%============================================================================ init([Opts]) -> PartitionID = aae_util:get_opt(partition_id, Opts), RootPath = aae_util:get_opt(root_path, Opts), IgnoreDisk = aae_util:get_opt(ignore_disk, Opts, false), LogLevels = aae_util:get_opt(log_levels, Opts), RootPath0 = filename:join(RootPath, flatten_id(PartitionID)) ++ "/", {StartTree, SaveSQN, IsRestored} = case {open_from_disk(RootPath0, LogLevels), IgnoreDisk} of % Always run open_from_disk even if the result is to be ignored, % as any files present must still be cleared {{Tree, SQN}, false} when Tree =/= none -> {Tree, SQN, true}; _ -> {leveled_tictac:new_tree(PartitionID, ?TREE_SIZE), ?START_SQN, false} end, aae_util:log("C0005", [IsRestored, PartitionID], logs(), LogLevels), process_flag(trap_exit, true), {ok, #state{save_sqn = SaveSQN, tree = StartTree, is_restored = IsRestored, root_path = RootPath0, partition_id = PartitionID, log_levels = LogLevels, safe_save = IsRestored or IgnoreDisk}}. handle_call(is_restored, _From, State) -> {reply, State#state.is_restored, State}; handle_call(fetch_root, _From, State) -> {reply, leveled_tictac:fetch_root(State#state.tree), State}; handle_call({fetch_leaves, BranchIDs}, _From, State) -> {reply, leveled_tictac:fetch_leaves(State#state.tree, BranchIDs), State}; handle_call(close, _From, State) -> case State#state.safe_save of true -> save_to_disk(State#state.root_path, State#state.save_sqn, State#state.tree, State#state.log_levels); false -> ok end, {stop, normal, ok, State}. handle_cast({alter, Key, CurrentHash, OldHash}, State) -> {Tree0, Segment} = leveled_tictac:add_kv(State#state.tree, Key, {CurrentHash, OldHash}, fun binary_extractfun/2, true), State0 = case State#state.loading of true -> CQ = State#state.change_queue, QCnt = State#state.queued_changes, State#state{change_queue = [{Key, CurrentHash, OldHash}|CQ], queued_changes = QCnt + 1}; false -> State end, case State#state.dirty_segments of [] -> {noreply, State0#state{tree = Tree0}}; DirtyList -> DirtyList0 = lists:delete(Segment, DirtyList), {noreply, State0#state{tree = Tree0, dirty_segments = DirtyList0}} end; handle_cast(start_load, State=#state{loading=Loading}) when Loading == false -> {noreply, State#state{loading = true, change_queue = [], queued_changes = 0, dirty_segments = [], active_fold = undefined}}; handle_cast({complete_load, Tree}, State=#state{loading=Loading}) when Loading == true -> LoadFun = fun({Key, CH, OH}, AccTree) -> leveled_tictac:add_kv(AccTree, Key, {CH, OH}, fun binary_extractfun/2) end, Tree0 = lists:foldr(LoadFun, Tree, State#state.change_queue), aae_util:log("C0008", [length(State#state.change_queue)], logs(), State#state.log_levels), {noreply, State#state{loading = false, change_queue = [], queued_changes = 0, tree = Tree0, safe_save = true}}; handle_cast({mark_dirtysegments, SegmentList, FoldGUID}, State) -> case State#state.loading of true -> % don't mess about with dirty segments, loading anyway {noreply, State}; false -> {noreply, State#state{dirty_segments = SegmentList, active_fold = FoldGUID}} end; handle_cast({replace_dirtysegments, SegmentMap, FoldGUID}, State) -> ChangeSegmentFoldFun = fun({SegID, NewHash}, TreeAcc) -> case lists:member(SegID, State#state.dirty_segments) of true -> aae_util:log("C0006", [State#state.partition_id, SegID, NewHash], logs(), State#state.log_levels), leveled_tictac:alter_segment(SegID, NewHash, TreeAcc); false -> TreeAcc end end, case State#state.active_fold of FoldGUID -> UpdTree = lists:foldl(ChangeSegmentFoldFun, State#state.tree, SegmentMap), {noreply, State#state{tree = UpdTree}}; _ -> {noreply, State} end; handle_cast(destroy, State) -> aae_util:log("C0004", [State#state.partition_id], logs(), State#state.log_levels), {stop, normal, State}; handle_cast({log_levels, LogLevels}, State) -> {noreply, State#state{log_levels = LogLevels}}. handle_info(_Info, State) -> {stop, normal, State}. format_status(normal, [_PDict, State]) -> State; format_status(terminate, [_PDict, State]) -> State#state{change_queue = not_logged}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. %%%============================================================================ Internal functions %%%============================================================================ -spec flatten_id(partition_id()) -> list(). %% @doc %% Flatten partition ID to make a folder name flatten_id({Index, N}) -> integer_to_list(Index) ++ "_" ++ integer_to_list(N); flatten_id(ID) -> integer_to_list(ID). -spec save_to_disk(list(), integer(), leveled_tictac:tictactree(), aae_util:log_levels()|undefined) -> ok. %% @doc Save the TreeCache to disk , with a checksum so thatit can be %% validated on read. save_to_disk(RootPath, SaveSQN, TreeCache, LogLevels) -> Serialised = term_to_binary(leveled_tictac:export_tree(TreeCache)), CRC32 = erlang:crc32(Serialised), ok = filelib:ensure_dir(RootPath), PendingName = integer_to_list(SaveSQN) ++ ?PENDING_EXT, aae_util:log("C0003", [RootPath, PendingName], logs(), LogLevels), ok = file:write_file(filename:join(RootPath, PendingName), <<CRC32:32/integer, Serialised/binary>>, [raw]), file:rename(filename:join(RootPath, PendingName), form_cache_filename(RootPath, SaveSQN)). -spec open_from_disk(list(), aae_util:log_levels()|undefined) -> {leveled_tictac:tictactree()|none, integer()}. %% @doc %% Open most recently saved TicTac tree cache file on disk, deleting all %% others both used and unused - to save an out of date tree from being used %% following a subsequent crash open_from_disk(RootPath, LogLevels) -> ok = filelib:ensure_dir(RootPath), {ok, Filenames} = file:list_dir(RootPath), FileFilterFun = fun(FN, FinalFiles) -> case filename:extension(FN) of ?PENDING_EXT -> aae_util:log("C0001", [FN], logs(), LogLevels), ok = file:delete(filename:join(RootPath, FN)), FinalFiles; ?FINAL_EXT -> BaseFN = filename:basename(filename:rootname(FN, ?FINAL_EXT)), [list_to_integer(BaseFN)|FinalFiles]; _ -> FinalFiles end end, SQNList = lists:reverse(lists:sort(lists:foldl(FileFilterFun, [], Filenames))), case SQNList of [] -> {none, 1}; [HeadSQN|Tail] -> DeleteFun = fun(SQN) -> ok = file:delete(form_cache_filename(RootPath, SQN)) end, lists:foreach(DeleteFun, Tail), FileToUse = form_cache_filename(RootPath, HeadSQN), case aae_util:safe_open(FileToUse) of {ok, STC} -> ok = file:delete(FileToUse), {leveled_tictac:import_tree(binary_to_term(STC)), HeadSQN + 1}; {error, Reason} -> aae_util:log("C0002", [FileToUse, Reason], logs(), LogLevels), {none, 1} end end. -spec form_cache_filename(list(), integer()) -> list(). %% @doc Return the cache filename by combining the Root Path with the SQN form_cache_filename(RootPath, SaveSQN) -> filename:join(RootPath, integer_to_list(SaveSQN) ++ ?FINAL_EXT). -spec binary_extractfun(binary(), {integer(), integer()}) -> {binary(), {is_hash, integer()}}. %% @doc %% Function to calulate the hash change need to make an alter into a straight %% add as the BinExtractfun in leveled_tictac binary_extractfun(Key, {CurrentHash, OldHash}) -> % TODO: Should move this function to leveled_tictac % - requires secret knowledge of implementation to perform % alter RemoveH = case {CurrentHash, OldHash} of {0, _} -> % Remove - treat like adding back in the tictac will this with the key - so do n't need to this here again OldHash; {_, 0} -> % Add 0; _ -> Alter - need to account for hashing with key % to remove the original {_SegmentHash, AltHash} = leveled_tictac:keyto_doublesegment32(Key), OldHash bxor AltHash end, {Key, {is_hash, CurrentHash bxor RemoveH}}. %%%============================================================================ %%% log definitions %%%============================================================================ -spec logs() -> list(tuple()). %% @doc %% Define log lines for this module logs() -> [{"C0001", {info, "Pending filename ~s found and will delete"}}, {"C0002", {warn, "File ~w opened with error=~w so will be ignored"}}, {"C0003", {info, "Saving tree cache to path ~s and filename ~s"}}, {"C0004", {info, "Destroying tree cache for partition ~w"}}, {"C0005", {info, "Starting cache with is_restored=~w and IndexN of ~w"}}, {"C0006", {debug, "Altering segment for PartitionID=~w ID=~w Hash=~w"}}, {"C0007", {warn, "Treecache exiting after trapping exit from Pid=~w"}}, {"C0008", {info, "Complete load of tree with length of change_queue=~w"}}, {"C0009", {info, "During cache rebuild reached length of change_queue=~w"}}]. %%%============================================================================ %%% Test %%%============================================================================ -ifdef(TEST). setup_savedcaches(RootPath) -> Tree0 = leveled_tictac:new_tree(test), Tree1 = leveled_tictac:add_kv(Tree0, {<<"K1">>}, {<<"V1">>}, fun({K}, {V}) -> {K, V} end), Tree2 = leveled_tictac:add_kv(Tree1, {<<"K2">>}, {<<"V2">>}, fun({K}, {V}) -> {K, V} end), ok = save_to_disk(RootPath, 1, Tree1, undefined), ok = save_to_disk(RootPath, 2, Tree2, undefined), Tree2. clean_saveopen_test() -> Check that pending files , and that the highest SQN that is % not pending is the one opened RootPath = "test/cache0/", aae_util:clean_subdir(RootPath), Tree2 = setup_savedcaches(RootPath), NextFN = filename:join(RootPath, integer_to_list(3) ++ ?PENDING_EXT), ok = file:write_file(NextFN, <<"delete">>), UnrelatedFN = filename:join(RootPath, "alt.file"), ok = file:write_file(UnrelatedFN, <<"no_delete">>), {Tree3, SaveSQN} = open_from_disk(RootPath, undefined), ?assertMatch(3, SaveSQN), ?assertMatch([], leveled_tictac:find_dirtyleaves(Tree2, Tree3)), ?assertMatch({none, 1}, open_from_disk(RootPath, undefined)), ?assertMatch({ok, <<"no_delete">>}, file:read_file(UnrelatedFN)), ?assertMatch({error, enoent}, file:read_file(NextFN)), aae_util:clean_subdir(RootPath). clear_old_cache_test() -> RootPath = "test/oldcache0/", PartitionID = 1, RP0 = filename:join(RootPath, integer_to_list(PartitionID)) ++ "/", aae_util:clean_subdir(RP0), _Tree2 = setup_savedcaches(RP0), {ok, FN0s} = file:list_dir(RP0), ?assertMatch(2, length(FN0s)), {ok, Cpid} = cache_new(RootPath, 1, undefined), {ok, FN1s} = file:list_dir(RP0), ?assertMatch(0, length(FN1s)), ok = cache_close(Cpid), {ok, FN2s} = file:list_dir(RP0), ?assertMatch(1, length(FN2s)), aae_util:clean_subdir(RootPath). dirty_saveopen_test() -> RootPath = "test/dirtycache0/", aae_util:clean_subdir(RootPath), RP0 = filename:join(RootPath, integer_to_list(1)) ++ "/", {ok, Cpid0} = cache_new(RootPath, 1, undefined), Hash0 = erlang:phash2({<<"K1">>, <<"C1">>}), cache_alter(Cpid0, <<"K1">>, Hash0, 0), ok = cache_close(Cpid0), ?assertMatch(true, filelib:is_file(form_cache_filename(RP0, 1))), {true, Cpid1} = cache_open(RootPath, 1, undefined), Hash1 = erlang:phash2({<<"K1">>, <<"C2">>}), cache_alter(Cpid1, <<"K1">>, Hash1, Hash0), ok = cache_close(Cpid1), ?assertMatch(true, filelib:is_file(form_cache_filename(RP0, 2))), aae_util:clean_subdir(RootPath), {false, Cpid2} = cache_open(RootPath, 1, undefined), Hash2 = erlang:phash2({<<"K1">>, <<"C3">>}), cache_alter(Cpid2, <<"K1">>, Hash2, Hash1), ok = cache_close(Cpid2), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 1))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 2))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 3))), {false, Cpid3} = cache_open(RootPath, 1, undefined), Hash3 = erlang:phash2({<<"K1">>, <<"C4">>}), cache_alter(Cpid3, <<"K1">>, Hash3, Hash2), ok = cache_close(Cpid3), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 1))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 2))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 3))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 4))), {false, Cpid4} = cache_open(RootPath, 1, undefined), cache_startload(Cpid4), cache_alter(Cpid4, <<"K1">>, Hash3, 0), T0 = leveled_tictac:new_tree(raw, ?TREE_SIZE), cache_completeload(Cpid4, T0), ok = cache_close(Cpid4), ?assertMatch(true, filelib:is_file(form_cache_filename(RP0, 1))), {true, Cpid5} = cache_open(RootPath, 1, undefined), R0 = cache_root(Cpid5), [BranchID] = leveled_tictac:find_dirtysegments(R0, leveled_tictac:fetch_root(T0)), [{BranchID, Branch5}] = cache_leaves(Cpid5, [BranchID]), [{BranchID, Branch0}] = leveled_tictac:fetch_leaves(T0, [BranchID]), [SegmentID] = leveled_tictac:find_dirtysegments(Branch0, Branch5), Pos = SegmentID * 4, <<_Pre:Pos/binary, HashToCheck:32/integer, _Post/binary>> = Branch5, {_SegmentHash, AltHash} = leveled_tictac:keyto_doublesegment32(<<"K1">>), ?assertMatch(Hash3, HashToCheck bxor AltHash), ok = cache_close(Cpid5), ?assertMatch(true, filelib:is_file(form_cache_filename(RP0, 2))), aae_util:clean_subdir(RootPath). corrupt_save_test_() -> {timeout, 60, fun corrupt_save_tester/0}. corrupt_save_tester() -> % If any byte is corrupted on disk - then the result should be a failure to open and the TreeCache reverting to empty RootPath = "test/cachecs/", aae_util:clean_subdir(RootPath), _Tree2 = setup_savedcaches(RootPath), BestFN = form_cache_filename(RootPath, 2), {ok, LatestCache} = file:read_file(BestFN), FlipByteFun = fun(Offset) -> aae_util:flip_byte(LatestCache, 1, Offset) end, BrokenCaches = lists:map(FlipByteFun, lists:seq(1, byte_size(LatestCache) - 1)), BrokenCacheCheckFun = fun(BrokenCache) -> ok = file:write_file(BestFN, BrokenCache), R = open_from_disk(RootPath, undefined), ?assertMatch({none, 1}, R) end, ok = lists:foreach(BrokenCacheCheckFun, BrokenCaches), aae_util:clean_subdir(RootPath). format_status_test() -> RootPath = "test/foratstatus/", PartitionID = 99, aae_util:clean_subdir(RootPath ++ "/" ++ integer_to_list(PartitionID)), {ok, C0} = cache_new(RootPath, PartitionID, undefined), {status, C0, {module, gen_server}, SItemL} = sys:get_status(C0), S = lists:keyfind(state, 1, lists:nth(5, SItemL)), ?assert(is_list(S#state.change_queue)), ST = format_status(terminate, [dict:new(), S]), ?assertMatch(not_logged, ST#state.change_queue), ok = cache_destroy(C0). simple_test() -> RootPath = "test/cache1/", PartitionID = 99, aae_util:clean_subdir(RootPath ++ "/" ++ integer_to_list(PartitionID)), GenerateKeyFun = aae_util:test_key_generator(hash), InitialKeys = lists:map(GenerateKeyFun, lists:seq(1,100)), AlternateKeys = lists:map(GenerateKeyFun, lists:seq(61, 80)), RemoveKeys = lists:map(GenerateKeyFun, lists:seq(81, 100)), {ok, AAECache0} = cache_new(RootPath, PartitionID, undefined), {AddFun, AlterFun, RemoveFun} = test_setup_funs(InitialKeys), lists:foreach(AddFun(AAECache0), InitialKeys), ok = cache_close(AAECache0), {true, AAECache1} = cache_open(RootPath, PartitionID, undefined), lists:foreach(AlterFun(AAECache1), AlternateKeys), lists:foreach(RemoveFun(AAECache1), RemoveKeys), %% Now build the equivalent outside of the process %% Accouting up-fron for the removals and the alterations KHL0 = lists:sublist(InitialKeys, 60) ++ AlternateKeys, DirectAddFun = fun({K, H}, TreeAcc) -> leveled_tictac:add_kv(TreeAcc, K, H, fun(Key, Value) -> {Key, {is_hash, Value}} end) end, CompareTree = lists:foldl(DirectAddFun, leveled_tictac:new_tree(raw, ?TREE_SIZE), KHL0), CompareRoot = leveled_tictac:fetch_root(CompareTree), Root = cache_root(AAECache1), ?assertMatch(Root, CompareRoot), ok = cache_destroy(AAECache1). replace_test() -> RootPath = "test/cache1/", PartitionID = 99, aae_util:clean_subdir(RootPath ++ "/" ++ integer_to_list(PartitionID)), GenerateKeyFun = aae_util:test_key_generator(hash), InitialKeys = lists:map(GenerateKeyFun, lists:seq(1,100)), AlternateKeys = lists:map(GenerateKeyFun, lists:seq(61, 80)), RemoveKeys = lists:map(GenerateKeyFun, lists:seq(81, 100)), {ok, AAECache0} = cache_new(RootPath, PartitionID, undefined), {AddFun, AlterFun, RemoveFun} = test_setup_funs(InitialKeys), lists:foreach(AddFun(AAECache0), InitialKeys), ok = cache_startload(AAECache0), lists:foreach(AlterFun(AAECache0), AlternateKeys), lists:foreach(RemoveFun(AAECache0), RemoveKeys), %% Now build the equivalent outside of the process %% Accouting up-fron for the removals and the alterations KHL0 = lists:sublist(InitialKeys, 60) ++ AlternateKeys, DirectAddFun = fun({K, H}, TreeAcc) -> leveled_tictac:add_kv(TreeAcc, K, H, fun(Key, Value) -> {Key, {is_hash, Value}} end) end, CompareTree = lists:foldl(DirectAddFun, leveled_tictac:new_tree(raw, ?TREE_SIZE), KHL0), %% The load tree is a tree as would have been produced by a fold over a %% snapshot taken at the time all the initial keys added. %% %% If we now complete the load using this tree, the comparison should still match . The cache should be replaced by one playing the stored %% alterations ont the load tree. LoadTree = lists:foldl(DirectAddFun, leveled_tictac:new_tree(raw, ?TREE_SIZE), InitialKeys), ok = cache_completeload(AAECache0, LoadTree), CompareRoot = leveled_tictac:fetch_root(CompareTree), Root = cache_root(AAECache0), ?assertMatch(Root, CompareRoot), ok = cache_destroy(AAECache0). dirty_segment_test() -> % Segments based on GetSegFun = fun(BinaryKey) -> SegmentID = leveled_tictac:keyto_segment48(BinaryKey), aae_keystore:generate_treesegment(SegmentID) end, Have clashes with keys of integer_to_binary/1 and integers - [ 4241217,2576207,2363385 ] RootPath = "test/dirtysegment/", PartitionID = 99, aae_util:clean_subdir(RootPath ++ "/" ++ integer_to_list(PartitionID)), {ok, AAECache0} = cache_new(RootPath, PartitionID, undefined), AddFun = fun(I) -> K = integer_to_binary(I), H = erlang:phash2(leveled_rand:uniform(100000)), cache_alter(AAECache0, K, H, 0) end, lists:foreach(AddFun, lists:seq(2350000, 2380000)), K0 = integer_to_binary(2363385), K1 = integer_to_binary(2576207), K2 = integer_to_binary(4241217), S0 = GetSegFun(K0), S1 = GetSegFun(K1), S2 = GetSegFun(K2), ?assertMatch(true, S0 == S1), ?assertMatch(true, S0 == S2), BranchID = S0 bsr 8, LeafID = S0 band 255, Leaf0 = get_leaf(AAECache0, BranchID, LeafID), ?assertMatch(false, Leaf0 == 0), H1 = erlang:phash2(leveled_rand:uniform(100000)), H2 = erlang:phash2(leveled_rand:uniform(100000)), {_HK1, TTH1} = leveled_tictac:tictac_hash(K1, {is_hash, H1}), {_HK2, TTH2} = leveled_tictac:tictac_hash(K2, {is_hash, H2}), cache_alter(AAECache0, K1, H1, 0), Leaf1 = get_leaf(AAECache0, BranchID, LeafID), ?assertMatch(Leaf1, Leaf0 bxor TTH1), GUID0 = leveled_util:generate_uuid(), NOTGUID = "NOT GUID", cache_markdirtysegments(AAECache0, [S0], GUID0), % Replace with wrong GUID ignored cache_replacedirtysegments(AAECache0, [{S0, Leaf0}], NOTGUID), ?assertMatch(Leaf1, get_leaf(AAECache0, BranchID, LeafID)), Replace with right GUID succeeds cache_replacedirtysegments(AAECache0, [{S0, Leaf0}], GUID0), ?assertMatch(Leaf0, get_leaf(AAECache0, BranchID, LeafID)), GUID1 = leveled_util:generate_uuid(), cache_markdirtysegments(AAECache0, [S0], GUID1), cache_alter(AAECache0, K2, H2, 0), Leaf2 = get_leaf(AAECache0, BranchID, LeafID), ?assertMatch(Leaf2, Leaf0 bxor TTH2), cache_replacedirtysegments(AAECache0, [{S0, Leaf0}], GUID1), Replace has been ignored due to update - so still ?assertMatch(Leaf2, get_leaf(AAECache0, BranchID, LeafID)), GUID2 = leveled_util:generate_uuid(), cache_markdirtysegments(AAECache0, [S0], GUID2), cache_startload(AAECache0), cache_replacedirtysegments(AAECache0, [{S0, Leaf0}], GUID2), Replace has been ignored due to load - so still ?assertMatch(Leaf2, get_leaf(AAECache0, BranchID, LeafID)), ok = cache_destroy(AAECache0). get_leaf(AAECache0, BranchID, LeafID) -> [{BranchID, LeafBin}] = cache_leaves(AAECache0, [BranchID]), LeafStartPos = LeafID * 4, <<_Pre:LeafStartPos/binary, Leaf:32/integer, _Rest/binary>> = LeafBin, Leaf. coverage_cheat_test() -> {ok, _State1} = code_change(null, #state{}, null), {stop, normal, _State2} = handle_info({'EXIT', self(), "Test"}, #state{}). test_setup_funs(InitialKeys) -> AddFun = fun(CachePid) -> fun({K, H}) -> cache_alter(CachePid, K, H, 0) end end, AlterFun = fun(CachePid) -> fun({K, H}) -> {K, OH} = lists:keyfind(K, 1, InitialKeys), cache_alter(CachePid, K, H, OH) end end, RemoveFun = fun(CachePid) -> fun({K, _H}) -> {K, OH} = lists:keyfind(K, 1, InitialKeys), cache_alter(CachePid, K, 0, OH) end end, {AddFun, AlterFun, RemoveFun}. -endif.
null
https://raw.githubusercontent.com/martinsumner/kv_index_tictactree/a2b4620aaad6b61a76f48fc5a43857c305d4c834/src/aae_treecache.erl
erlang
-------- Overview --------- ============================================================================ API ============================================================================ @doc starting point. Return is_empty boolean as true to indicate if a new cache @doc Open a tree cache, without restoring from file @doc Close a cache without saving @doc Close a cache with saving @doc Change the hash tree to reflect an addition and removal of a hash value @doc Fetch the root of the cache tree to compare @doc Fetch the leaves for a given list of branch IDs. @doc Mark dirty segments. These segments are currently subject to a fetch_clocks fold. If they aren't touched until the fold is complete, the segment can be safely replaced with the value in the fold. The FoldGUID is used to identify the request that prompted the marking. This becomes the active_fold, replacing any previous marking. Dirty segments can only be replaced by the last active fold. Need to avoid race conditions between multiple dirtysegment markings (as well as updates clearing dirty segments) @doc When a fold_clocks is complete, replace any dirty_segments which remain clean from other interventions @doc Sets the cache loading state to true, now as well as maintaining the current tree the cache should keep a queue of all the changes from this point. Eventually cache_completeload should be called with a tree built from a loading process snapshotted at the startload point, and the changes can all be applied @doc this the new tree @doc ============================================================================ gen_server callbacks ============================================================================ Always run open_from_disk even if the result is to be ignored, as any files present must still be cleared don't mess about with dirty segments, loading anyway ============================================================================ ============================================================================ @doc Flatten partition ID to make a folder name @doc validated on read. @doc Open most recently saved TicTac tree cache file on disk, deleting all others both used and unused - to save an out of date tree from being used following a subsequent crash @doc @doc Function to calulate the hash change need to make an alter into a straight add as the BinExtractfun in leveled_tictac TODO: Should move this function to leveled_tictac - requires secret knowledge of implementation to perform alter Remove - treat like adding back in Add to remove the original ============================================================================ log definitions ============================================================================ @doc Define log lines for this module ============================================================================ Test ============================================================================ not pending is the one opened If any byte is corrupted on disk - then the result should be a failure Now build the equivalent outside of the process Accouting up-fron for the removals and the alterations Now build the equivalent outside of the process Accouting up-fron for the removals and the alterations The load tree is a tree as would have been produced by a fold over a snapshot taken at the time all the initial keys added. If we now complete the load using this tree, the comparison should alterations ont the load tree. Segments based on Replace with wrong GUID ignored
-module(aae_treecache). -behaviour(gen_server). -include("include/aae.hrl"). -export([ init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3, format_status/2]). -export([cache_open/3, cache_new/3, cache_alter/4, cache_root/1, cache_leaves/2, cache_markdirtysegments/3, cache_replacedirtysegments/3, cache_destroy/1, cache_startload/1, cache_completeload/2, cache_loglevel/2, cache_close/1]). -include_lib("eunit/include/eunit.hrl"). -define(PENDING_EXT, ".pnd"). -define(FINAL_EXT, ".aae"). -define(START_SQN, 1). -define(SYNC_TIMEOUT, 30000). -record(state, {save_sqn = 0 :: integer(), is_restored = false :: boolean(), tree :: leveled_tictac:tictactree()|undefined, root_path :: list()|undefined, partition_id :: integer()|undefined, loading = false :: boolean(), dirty_segments = [] :: list(), active_fold :: string()|undefined, change_queue = [] :: list()|not_logged, queued_changes = 0 :: non_neg_integer(), log_levels :: aae_util:log_levels()|undefined, safe_save = false :: boolean()}). -type partition_id() :: integer()|{integer(), integer()}. -spec cache_open(list(), partition_id(), aae_util:log_levels()|undefined) -> {boolean(), pid()}. Open a tree cache , using any previously saved one for this tree cache as a was created , as well as the PID of this FSM cache_open(RootPath, PartitionID, LogLevels) -> Opts = [{root_path, RootPath}, {partition_id, PartitionID}, {log_levels, LogLevels}], {ok, Pid} = gen_server:start_link(?MODULE, [Opts], []), IsRestored = gen_server:call(Pid, is_restored, infinity), {IsRestored, Pid}. -spec cache_new(list(), partition_id(), aae_util:log_levels()|undefined) -> {ok, pid()}. cache_new(RootPath, PartitionID, LogLevels) -> Opts = [{root_path, RootPath}, {partition_id, PartitionID}, {ignore_disk, true}, {log_levels, LogLevels}], gen_server:start_link(?MODULE, [Opts], []). -spec cache_destroy(pid()) -> ok. cache_destroy(AAECache) -> gen_server:cast(AAECache, destroy). -spec cache_close(pid()) -> ok. cache_close(AAECache) -> gen_server:call(AAECache, close, ?SYNC_TIMEOUT). -spec cache_alter(pid(), binary(), integer(), integer()) -> ok. cache_alter(AAECache, Key, CurrentHash, OldHash) -> gen_server:cast(AAECache, {alter, Key, CurrentHash, OldHash}). -spec cache_root(pid()) -> binary(). cache_root(Pid) -> gen_server:call(Pid, fetch_root, infinity). -spec cache_leaves(pid(), list(integer())) -> list(). cache_leaves(Pid, BranchIDs) -> gen_server:call(Pid, {fetch_leaves, BranchIDs}, infinity). -spec cache_markdirtysegments(pid(), list(integer()), string()) -> ok. cache_markdirtysegments(Pid, SegmentIDs, FoldGUID) -> gen_server:cast(Pid, {mark_dirtysegments, SegmentIDs, FoldGUID}). -spec cache_replacedirtysegments(pid(), list({integer(), integer()}), string()) -> ok. cache_replacedirtysegments(Pid, ReplacementSegments, FoldGUID) -> gen_server:cast(Pid, {replace_dirtysegments, ReplacementSegments, FoldGUID}). -spec cache_startload(pid()) -> ok. cache_startload(Pid) -> gen_server:cast(Pid, start_load). -spec cache_completeload(pid(), leveled_tictac:tictactree()) -> ok. Take a tree which has been produced from a fold of the KeyStore , and make cache_completeload(Pid, LoadedTree) -> gen_server:cast(Pid, {complete_load, LoadedTree}). -spec cache_loglevel(pid(), aae_util:log_levels()) -> ok. Alter the log level at runtime cache_loglevel(Pid, LogLevels) -> gen_server:cast(Pid, {log_levels, LogLevels}). init([Opts]) -> PartitionID = aae_util:get_opt(partition_id, Opts), RootPath = aae_util:get_opt(root_path, Opts), IgnoreDisk = aae_util:get_opt(ignore_disk, Opts, false), LogLevels = aae_util:get_opt(log_levels, Opts), RootPath0 = filename:join(RootPath, flatten_id(PartitionID)) ++ "/", {StartTree, SaveSQN, IsRestored} = case {open_from_disk(RootPath0, LogLevels), IgnoreDisk} of {{Tree, SQN}, false} when Tree =/= none -> {Tree, SQN, true}; _ -> {leveled_tictac:new_tree(PartitionID, ?TREE_SIZE), ?START_SQN, false} end, aae_util:log("C0005", [IsRestored, PartitionID], logs(), LogLevels), process_flag(trap_exit, true), {ok, #state{save_sqn = SaveSQN, tree = StartTree, is_restored = IsRestored, root_path = RootPath0, partition_id = PartitionID, log_levels = LogLevels, safe_save = IsRestored or IgnoreDisk}}. handle_call(is_restored, _From, State) -> {reply, State#state.is_restored, State}; handle_call(fetch_root, _From, State) -> {reply, leveled_tictac:fetch_root(State#state.tree), State}; handle_call({fetch_leaves, BranchIDs}, _From, State) -> {reply, leveled_tictac:fetch_leaves(State#state.tree, BranchIDs), State}; handle_call(close, _From, State) -> case State#state.safe_save of true -> save_to_disk(State#state.root_path, State#state.save_sqn, State#state.tree, State#state.log_levels); false -> ok end, {stop, normal, ok, State}. handle_cast({alter, Key, CurrentHash, OldHash}, State) -> {Tree0, Segment} = leveled_tictac:add_kv(State#state.tree, Key, {CurrentHash, OldHash}, fun binary_extractfun/2, true), State0 = case State#state.loading of true -> CQ = State#state.change_queue, QCnt = State#state.queued_changes, State#state{change_queue = [{Key, CurrentHash, OldHash}|CQ], queued_changes = QCnt + 1}; false -> State end, case State#state.dirty_segments of [] -> {noreply, State0#state{tree = Tree0}}; DirtyList -> DirtyList0 = lists:delete(Segment, DirtyList), {noreply, State0#state{tree = Tree0, dirty_segments = DirtyList0}} end; handle_cast(start_load, State=#state{loading=Loading}) when Loading == false -> {noreply, State#state{loading = true, change_queue = [], queued_changes = 0, dirty_segments = [], active_fold = undefined}}; handle_cast({complete_load, Tree}, State=#state{loading=Loading}) when Loading == true -> LoadFun = fun({Key, CH, OH}, AccTree) -> leveled_tictac:add_kv(AccTree, Key, {CH, OH}, fun binary_extractfun/2) end, Tree0 = lists:foldr(LoadFun, Tree, State#state.change_queue), aae_util:log("C0008", [length(State#state.change_queue)], logs(), State#state.log_levels), {noreply, State#state{loading = false, change_queue = [], queued_changes = 0, tree = Tree0, safe_save = true}}; handle_cast({mark_dirtysegments, SegmentList, FoldGUID}, State) -> case State#state.loading of true -> {noreply, State}; false -> {noreply, State#state{dirty_segments = SegmentList, active_fold = FoldGUID}} end; handle_cast({replace_dirtysegments, SegmentMap, FoldGUID}, State) -> ChangeSegmentFoldFun = fun({SegID, NewHash}, TreeAcc) -> case lists:member(SegID, State#state.dirty_segments) of true -> aae_util:log("C0006", [State#state.partition_id, SegID, NewHash], logs(), State#state.log_levels), leveled_tictac:alter_segment(SegID, NewHash, TreeAcc); false -> TreeAcc end end, case State#state.active_fold of FoldGUID -> UpdTree = lists:foldl(ChangeSegmentFoldFun, State#state.tree, SegmentMap), {noreply, State#state{tree = UpdTree}}; _ -> {noreply, State} end; handle_cast(destroy, State) -> aae_util:log("C0004", [State#state.partition_id], logs(), State#state.log_levels), {stop, normal, State}; handle_cast({log_levels, LogLevels}, State) -> {noreply, State#state{log_levels = LogLevels}}. handle_info(_Info, State) -> {stop, normal, State}. format_status(normal, [_PDict, State]) -> State; format_status(terminate, [_PDict, State]) -> State#state{change_queue = not_logged}. terminate(_Reason, _State) -> ok. code_change(_OldVsn, State, _Extra) -> {ok, State}. Internal functions -spec flatten_id(partition_id()) -> list(). flatten_id({Index, N}) -> integer_to_list(Index) ++ "_" ++ integer_to_list(N); flatten_id(ID) -> integer_to_list(ID). -spec save_to_disk(list(), integer(), leveled_tictac:tictactree(), aae_util:log_levels()|undefined) -> ok. Save the TreeCache to disk , with a checksum so thatit can be save_to_disk(RootPath, SaveSQN, TreeCache, LogLevels) -> Serialised = term_to_binary(leveled_tictac:export_tree(TreeCache)), CRC32 = erlang:crc32(Serialised), ok = filelib:ensure_dir(RootPath), PendingName = integer_to_list(SaveSQN) ++ ?PENDING_EXT, aae_util:log("C0003", [RootPath, PendingName], logs(), LogLevels), ok = file:write_file(filename:join(RootPath, PendingName), <<CRC32:32/integer, Serialised/binary>>, [raw]), file:rename(filename:join(RootPath, PendingName), form_cache_filename(RootPath, SaveSQN)). -spec open_from_disk(list(), aae_util:log_levels()|undefined) -> {leveled_tictac:tictactree()|none, integer()}. open_from_disk(RootPath, LogLevels) -> ok = filelib:ensure_dir(RootPath), {ok, Filenames} = file:list_dir(RootPath), FileFilterFun = fun(FN, FinalFiles) -> case filename:extension(FN) of ?PENDING_EXT -> aae_util:log("C0001", [FN], logs(), LogLevels), ok = file:delete(filename:join(RootPath, FN)), FinalFiles; ?FINAL_EXT -> BaseFN = filename:basename(filename:rootname(FN, ?FINAL_EXT)), [list_to_integer(BaseFN)|FinalFiles]; _ -> FinalFiles end end, SQNList = lists:reverse(lists:sort(lists:foldl(FileFilterFun, [], Filenames))), case SQNList of [] -> {none, 1}; [HeadSQN|Tail] -> DeleteFun = fun(SQN) -> ok = file:delete(form_cache_filename(RootPath, SQN)) end, lists:foreach(DeleteFun, Tail), FileToUse = form_cache_filename(RootPath, HeadSQN), case aae_util:safe_open(FileToUse) of {ok, STC} -> ok = file:delete(FileToUse), {leveled_tictac:import_tree(binary_to_term(STC)), HeadSQN + 1}; {error, Reason} -> aae_util:log("C0002", [FileToUse, Reason], logs(), LogLevels), {none, 1} end end. -spec form_cache_filename(list(), integer()) -> list(). Return the cache filename by combining the Root Path with the SQN form_cache_filename(RootPath, SaveSQN) -> filename:join(RootPath, integer_to_list(SaveSQN) ++ ?FINAL_EXT). -spec binary_extractfun(binary(), {integer(), integer()}) -> {binary(), {is_hash, integer()}}. binary_extractfun(Key, {CurrentHash, OldHash}) -> RemoveH = case {CurrentHash, OldHash} of {0, _} -> the tictac will this with the key - so do n't need to this here again OldHash; {_, 0} -> 0; _ -> Alter - need to account for hashing with key {_SegmentHash, AltHash} = leveled_tictac:keyto_doublesegment32(Key), OldHash bxor AltHash end, {Key, {is_hash, CurrentHash bxor RemoveH}}. -spec logs() -> list(tuple()). logs() -> [{"C0001", {info, "Pending filename ~s found and will delete"}}, {"C0002", {warn, "File ~w opened with error=~w so will be ignored"}}, {"C0003", {info, "Saving tree cache to path ~s and filename ~s"}}, {"C0004", {info, "Destroying tree cache for partition ~w"}}, {"C0005", {info, "Starting cache with is_restored=~w and IndexN of ~w"}}, {"C0006", {debug, "Altering segment for PartitionID=~w ID=~w Hash=~w"}}, {"C0007", {warn, "Treecache exiting after trapping exit from Pid=~w"}}, {"C0008", {info, "Complete load of tree with length of change_queue=~w"}}, {"C0009", {info, "During cache rebuild reached length of change_queue=~w"}}]. -ifdef(TEST). setup_savedcaches(RootPath) -> Tree0 = leveled_tictac:new_tree(test), Tree1 = leveled_tictac:add_kv(Tree0, {<<"K1">>}, {<<"V1">>}, fun({K}, {V}) -> {K, V} end), Tree2 = leveled_tictac:add_kv(Tree1, {<<"K2">>}, {<<"V2">>}, fun({K}, {V}) -> {K, V} end), ok = save_to_disk(RootPath, 1, Tree1, undefined), ok = save_to_disk(RootPath, 2, Tree2, undefined), Tree2. clean_saveopen_test() -> Check that pending files , and that the highest SQN that is RootPath = "test/cache0/", aae_util:clean_subdir(RootPath), Tree2 = setup_savedcaches(RootPath), NextFN = filename:join(RootPath, integer_to_list(3) ++ ?PENDING_EXT), ok = file:write_file(NextFN, <<"delete">>), UnrelatedFN = filename:join(RootPath, "alt.file"), ok = file:write_file(UnrelatedFN, <<"no_delete">>), {Tree3, SaveSQN} = open_from_disk(RootPath, undefined), ?assertMatch(3, SaveSQN), ?assertMatch([], leveled_tictac:find_dirtyleaves(Tree2, Tree3)), ?assertMatch({none, 1}, open_from_disk(RootPath, undefined)), ?assertMatch({ok, <<"no_delete">>}, file:read_file(UnrelatedFN)), ?assertMatch({error, enoent}, file:read_file(NextFN)), aae_util:clean_subdir(RootPath). clear_old_cache_test() -> RootPath = "test/oldcache0/", PartitionID = 1, RP0 = filename:join(RootPath, integer_to_list(PartitionID)) ++ "/", aae_util:clean_subdir(RP0), _Tree2 = setup_savedcaches(RP0), {ok, FN0s} = file:list_dir(RP0), ?assertMatch(2, length(FN0s)), {ok, Cpid} = cache_new(RootPath, 1, undefined), {ok, FN1s} = file:list_dir(RP0), ?assertMatch(0, length(FN1s)), ok = cache_close(Cpid), {ok, FN2s} = file:list_dir(RP0), ?assertMatch(1, length(FN2s)), aae_util:clean_subdir(RootPath). dirty_saveopen_test() -> RootPath = "test/dirtycache0/", aae_util:clean_subdir(RootPath), RP0 = filename:join(RootPath, integer_to_list(1)) ++ "/", {ok, Cpid0} = cache_new(RootPath, 1, undefined), Hash0 = erlang:phash2({<<"K1">>, <<"C1">>}), cache_alter(Cpid0, <<"K1">>, Hash0, 0), ok = cache_close(Cpid0), ?assertMatch(true, filelib:is_file(form_cache_filename(RP0, 1))), {true, Cpid1} = cache_open(RootPath, 1, undefined), Hash1 = erlang:phash2({<<"K1">>, <<"C2">>}), cache_alter(Cpid1, <<"K1">>, Hash1, Hash0), ok = cache_close(Cpid1), ?assertMatch(true, filelib:is_file(form_cache_filename(RP0, 2))), aae_util:clean_subdir(RootPath), {false, Cpid2} = cache_open(RootPath, 1, undefined), Hash2 = erlang:phash2({<<"K1">>, <<"C3">>}), cache_alter(Cpid2, <<"K1">>, Hash2, Hash1), ok = cache_close(Cpid2), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 1))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 2))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 3))), {false, Cpid3} = cache_open(RootPath, 1, undefined), Hash3 = erlang:phash2({<<"K1">>, <<"C4">>}), cache_alter(Cpid3, <<"K1">>, Hash3, Hash2), ok = cache_close(Cpid3), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 1))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 2))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 3))), ?assertMatch(false, filelib:is_file(form_cache_filename(RP0, 4))), {false, Cpid4} = cache_open(RootPath, 1, undefined), cache_startload(Cpid4), cache_alter(Cpid4, <<"K1">>, Hash3, 0), T0 = leveled_tictac:new_tree(raw, ?TREE_SIZE), cache_completeload(Cpid4, T0), ok = cache_close(Cpid4), ?assertMatch(true, filelib:is_file(form_cache_filename(RP0, 1))), {true, Cpid5} = cache_open(RootPath, 1, undefined), R0 = cache_root(Cpid5), [BranchID] = leveled_tictac:find_dirtysegments(R0, leveled_tictac:fetch_root(T0)), [{BranchID, Branch5}] = cache_leaves(Cpid5, [BranchID]), [{BranchID, Branch0}] = leveled_tictac:fetch_leaves(T0, [BranchID]), [SegmentID] = leveled_tictac:find_dirtysegments(Branch0, Branch5), Pos = SegmentID * 4, <<_Pre:Pos/binary, HashToCheck:32/integer, _Post/binary>> = Branch5, {_SegmentHash, AltHash} = leveled_tictac:keyto_doublesegment32(<<"K1">>), ?assertMatch(Hash3, HashToCheck bxor AltHash), ok = cache_close(Cpid5), ?assertMatch(true, filelib:is_file(form_cache_filename(RP0, 2))), aae_util:clean_subdir(RootPath). corrupt_save_test_() -> {timeout, 60, fun corrupt_save_tester/0}. corrupt_save_tester() -> to open and the TreeCache reverting to empty RootPath = "test/cachecs/", aae_util:clean_subdir(RootPath), _Tree2 = setup_savedcaches(RootPath), BestFN = form_cache_filename(RootPath, 2), {ok, LatestCache} = file:read_file(BestFN), FlipByteFun = fun(Offset) -> aae_util:flip_byte(LatestCache, 1, Offset) end, BrokenCaches = lists:map(FlipByteFun, lists:seq(1, byte_size(LatestCache) - 1)), BrokenCacheCheckFun = fun(BrokenCache) -> ok = file:write_file(BestFN, BrokenCache), R = open_from_disk(RootPath, undefined), ?assertMatch({none, 1}, R) end, ok = lists:foreach(BrokenCacheCheckFun, BrokenCaches), aae_util:clean_subdir(RootPath). format_status_test() -> RootPath = "test/foratstatus/", PartitionID = 99, aae_util:clean_subdir(RootPath ++ "/" ++ integer_to_list(PartitionID)), {ok, C0} = cache_new(RootPath, PartitionID, undefined), {status, C0, {module, gen_server}, SItemL} = sys:get_status(C0), S = lists:keyfind(state, 1, lists:nth(5, SItemL)), ?assert(is_list(S#state.change_queue)), ST = format_status(terminate, [dict:new(), S]), ?assertMatch(not_logged, ST#state.change_queue), ok = cache_destroy(C0). simple_test() -> RootPath = "test/cache1/", PartitionID = 99, aae_util:clean_subdir(RootPath ++ "/" ++ integer_to_list(PartitionID)), GenerateKeyFun = aae_util:test_key_generator(hash), InitialKeys = lists:map(GenerateKeyFun, lists:seq(1,100)), AlternateKeys = lists:map(GenerateKeyFun, lists:seq(61, 80)), RemoveKeys = lists:map(GenerateKeyFun, lists:seq(81, 100)), {ok, AAECache0} = cache_new(RootPath, PartitionID, undefined), {AddFun, AlterFun, RemoveFun} = test_setup_funs(InitialKeys), lists:foreach(AddFun(AAECache0), InitialKeys), ok = cache_close(AAECache0), {true, AAECache1} = cache_open(RootPath, PartitionID, undefined), lists:foreach(AlterFun(AAECache1), AlternateKeys), lists:foreach(RemoveFun(AAECache1), RemoveKeys), KHL0 = lists:sublist(InitialKeys, 60) ++ AlternateKeys, DirectAddFun = fun({K, H}, TreeAcc) -> leveled_tictac:add_kv(TreeAcc, K, H, fun(Key, Value) -> {Key, {is_hash, Value}} end) end, CompareTree = lists:foldl(DirectAddFun, leveled_tictac:new_tree(raw, ?TREE_SIZE), KHL0), CompareRoot = leveled_tictac:fetch_root(CompareTree), Root = cache_root(AAECache1), ?assertMatch(Root, CompareRoot), ok = cache_destroy(AAECache1). replace_test() -> RootPath = "test/cache1/", PartitionID = 99, aae_util:clean_subdir(RootPath ++ "/" ++ integer_to_list(PartitionID)), GenerateKeyFun = aae_util:test_key_generator(hash), InitialKeys = lists:map(GenerateKeyFun, lists:seq(1,100)), AlternateKeys = lists:map(GenerateKeyFun, lists:seq(61, 80)), RemoveKeys = lists:map(GenerateKeyFun, lists:seq(81, 100)), {ok, AAECache0} = cache_new(RootPath, PartitionID, undefined), {AddFun, AlterFun, RemoveFun} = test_setup_funs(InitialKeys), lists:foreach(AddFun(AAECache0), InitialKeys), ok = cache_startload(AAECache0), lists:foreach(AlterFun(AAECache0), AlternateKeys), lists:foreach(RemoveFun(AAECache0), RemoveKeys), KHL0 = lists:sublist(InitialKeys, 60) ++ AlternateKeys, DirectAddFun = fun({K, H}, TreeAcc) -> leveled_tictac:add_kv(TreeAcc, K, H, fun(Key, Value) -> {Key, {is_hash, Value}} end) end, CompareTree = lists:foldl(DirectAddFun, leveled_tictac:new_tree(raw, ?TREE_SIZE), KHL0), still match . The cache should be replaced by one playing the stored LoadTree = lists:foldl(DirectAddFun, leveled_tictac:new_tree(raw, ?TREE_SIZE), InitialKeys), ok = cache_completeload(AAECache0, LoadTree), CompareRoot = leveled_tictac:fetch_root(CompareTree), Root = cache_root(AAECache0), ?assertMatch(Root, CompareRoot), ok = cache_destroy(AAECache0). dirty_segment_test() -> GetSegFun = fun(BinaryKey) -> SegmentID = leveled_tictac:keyto_segment48(BinaryKey), aae_keystore:generate_treesegment(SegmentID) end, Have clashes with keys of integer_to_binary/1 and integers - [ 4241217,2576207,2363385 ] RootPath = "test/dirtysegment/", PartitionID = 99, aae_util:clean_subdir(RootPath ++ "/" ++ integer_to_list(PartitionID)), {ok, AAECache0} = cache_new(RootPath, PartitionID, undefined), AddFun = fun(I) -> K = integer_to_binary(I), H = erlang:phash2(leveled_rand:uniform(100000)), cache_alter(AAECache0, K, H, 0) end, lists:foreach(AddFun, lists:seq(2350000, 2380000)), K0 = integer_to_binary(2363385), K1 = integer_to_binary(2576207), K2 = integer_to_binary(4241217), S0 = GetSegFun(K0), S1 = GetSegFun(K1), S2 = GetSegFun(K2), ?assertMatch(true, S0 == S1), ?assertMatch(true, S0 == S2), BranchID = S0 bsr 8, LeafID = S0 band 255, Leaf0 = get_leaf(AAECache0, BranchID, LeafID), ?assertMatch(false, Leaf0 == 0), H1 = erlang:phash2(leveled_rand:uniform(100000)), H2 = erlang:phash2(leveled_rand:uniform(100000)), {_HK1, TTH1} = leveled_tictac:tictac_hash(K1, {is_hash, H1}), {_HK2, TTH2} = leveled_tictac:tictac_hash(K2, {is_hash, H2}), cache_alter(AAECache0, K1, H1, 0), Leaf1 = get_leaf(AAECache0, BranchID, LeafID), ?assertMatch(Leaf1, Leaf0 bxor TTH1), GUID0 = leveled_util:generate_uuid(), NOTGUID = "NOT GUID", cache_markdirtysegments(AAECache0, [S0], GUID0), cache_replacedirtysegments(AAECache0, [{S0, Leaf0}], NOTGUID), ?assertMatch(Leaf1, get_leaf(AAECache0, BranchID, LeafID)), Replace with right GUID succeeds cache_replacedirtysegments(AAECache0, [{S0, Leaf0}], GUID0), ?assertMatch(Leaf0, get_leaf(AAECache0, BranchID, LeafID)), GUID1 = leveled_util:generate_uuid(), cache_markdirtysegments(AAECache0, [S0], GUID1), cache_alter(AAECache0, K2, H2, 0), Leaf2 = get_leaf(AAECache0, BranchID, LeafID), ?assertMatch(Leaf2, Leaf0 bxor TTH2), cache_replacedirtysegments(AAECache0, [{S0, Leaf0}], GUID1), Replace has been ignored due to update - so still ?assertMatch(Leaf2, get_leaf(AAECache0, BranchID, LeafID)), GUID2 = leveled_util:generate_uuid(), cache_markdirtysegments(AAECache0, [S0], GUID2), cache_startload(AAECache0), cache_replacedirtysegments(AAECache0, [{S0, Leaf0}], GUID2), Replace has been ignored due to load - so still ?assertMatch(Leaf2, get_leaf(AAECache0, BranchID, LeafID)), ok = cache_destroy(AAECache0). get_leaf(AAECache0, BranchID, LeafID) -> [{BranchID, LeafBin}] = cache_leaves(AAECache0, [BranchID]), LeafStartPos = LeafID * 4, <<_Pre:LeafStartPos/binary, Leaf:32/integer, _Rest/binary>> = LeafBin, Leaf. coverage_cheat_test() -> {ok, _State1} = code_change(null, #state{}, null), {stop, normal, _State2} = handle_info({'EXIT', self(), "Test"}, #state{}). test_setup_funs(InitialKeys) -> AddFun = fun(CachePid) -> fun({K, H}) -> cache_alter(CachePid, K, H, 0) end end, AlterFun = fun(CachePid) -> fun({K, H}) -> {K, OH} = lists:keyfind(K, 1, InitialKeys), cache_alter(CachePid, K, H, OH) end end, RemoveFun = fun(CachePid) -> fun({K, _H}) -> {K, OH} = lists:keyfind(K, 1, InitialKeys), cache_alter(CachePid, K, 0, OH) end end, {AddFun, AlterFun, RemoveFun}. -endif.
2c806d0e63049b5c5b12af022962971e2ce99d64a0539920f6344c44313861f2
lukaszcz/coqhammer
hammer_errors.ml
exception HammerError of string exception HammerFailure of string exception HammerTacticError of string let msg_error s = Feedback.msg_notice (Pp.str s) let catch_errors (f : unit -> 'a) (g : exn -> 'a) = try f () with | Sys.Break -> raise Sys.Break | e -> g e let try_bind_fun (x : 'a) (f : 'a -> 'b) (g : Pp.t -> 'b) = try f x with | HammerError(msg) -> g (Pp.str @@ "Hammer error: " ^ msg) | HammerFailure(msg) -> g (Pp.str @@ "Hammer failed: " ^ msg) | HammerTacticError(msg) -> g (Pp.str msg) | Failure s -> g (Pp.str @@ "CoqHammer bug: please report: " ^ s) | Sys.Break -> raise Sys.Break | CErrors.UserError p -> g p | e -> g (Pp.str @@ "CoqHammer bug: please report: " ^ Printexc.to_string e) let try_fun f g = try_bind_fun () f g let try_cmd (f : unit -> unit) = try_fun f (fun p -> Feedback.msg_notice p) let try_bind_tactic (f : 'a -> unit Proofview.tactic) (x : 'a) : unit Proofview.tactic = try_bind_fun x f (fun p -> Tacticals.tclZEROMSG p) let try_tactic (f : unit -> unit Proofview.tactic) : unit Proofview.tactic = try_fun f (fun p -> Tacticals.tclZEROMSG p) let try_goal_tactic f = Proofview.Goal.enter begin fun gl -> try_tactic (fun () -> f gl) end let try_goal_tactic_nofail f = Proofview.Goal.enter begin fun gl -> try_fun (fun () -> f gl) (fun p -> Feedback.msg_notice p; Proofview.tclUNIT ()) end
null
https://raw.githubusercontent.com/lukaszcz/coqhammer/fe83fb0eaf33f56da9ea1983114d0d94a2c41b9b/src/lib/hammer_errors.ml
ocaml
exception HammerError of string exception HammerFailure of string exception HammerTacticError of string let msg_error s = Feedback.msg_notice (Pp.str s) let catch_errors (f : unit -> 'a) (g : exn -> 'a) = try f () with | Sys.Break -> raise Sys.Break | e -> g e let try_bind_fun (x : 'a) (f : 'a -> 'b) (g : Pp.t -> 'b) = try f x with | HammerError(msg) -> g (Pp.str @@ "Hammer error: " ^ msg) | HammerFailure(msg) -> g (Pp.str @@ "Hammer failed: " ^ msg) | HammerTacticError(msg) -> g (Pp.str msg) | Failure s -> g (Pp.str @@ "CoqHammer bug: please report: " ^ s) | Sys.Break -> raise Sys.Break | CErrors.UserError p -> g p | e -> g (Pp.str @@ "CoqHammer bug: please report: " ^ Printexc.to_string e) let try_fun f g = try_bind_fun () f g let try_cmd (f : unit -> unit) = try_fun f (fun p -> Feedback.msg_notice p) let try_bind_tactic (f : 'a -> unit Proofview.tactic) (x : 'a) : unit Proofview.tactic = try_bind_fun x f (fun p -> Tacticals.tclZEROMSG p) let try_tactic (f : unit -> unit Proofview.tactic) : unit Proofview.tactic = try_fun f (fun p -> Tacticals.tclZEROMSG p) let try_goal_tactic f = Proofview.Goal.enter begin fun gl -> try_tactic (fun () -> f gl) end let try_goal_tactic_nofail f = Proofview.Goal.enter begin fun gl -> try_fun (fun () -> f gl) (fun p -> Feedback.msg_notice p; Proofview.tclUNIT ()) end
4836e9334378df952c846f0c4c1fcaa3bc00dd6daa6eccca7d14c90d32ad2765
kana/sicp
ex-3.77.scm
Exercise 3.77 . The integral procedure used above was analogous to the ;;; ``implicit'' definition of the infinite stream of integers in section 3.5.2 . Alternatively , we can give a definition of integral that is more like integers - starting - from ( also in section 3.5.2 ): ;;; ;;; (define (integral integrand initial-value dt) ;;; (cons-stream initial-value ;;; (if (stream-null? integrand) ;;; the-empty-stream ;;; (integral (stream-cdr integrand) ;;; (+ (* dt (stream-car integrand)) ;;; initial-value) ;;; dt)))) ;;; ;;; When used in systems with loops, this procedure has the same problem as ;;; does our original version of integral. Modify the procedure so that it ;;; expects the integrand as a delayed argument and hence can be used in the ;;; solve procedure shown above. (define (integral delayed-integrand initial-value dt) (cons-stream initial-value (let ([integrand (force delayed-integrand)]) (if (stream-null? integrand) the-empty-stream (integral (delay (stream-cdr integrand)) (+ (* dt (stream-car integrand)) initial-value) dt)))))
null
https://raw.githubusercontent.com/kana/sicp/912bda4276995492ffc2ec971618316701e196f6/ex-3.77.scm
scheme
``implicit'' definition of the infinite stream of integers in section (define (integral integrand initial-value dt) (cons-stream initial-value (if (stream-null? integrand) the-empty-stream (integral (stream-cdr integrand) (+ (* dt (stream-car integrand)) initial-value) dt)))) When used in systems with loops, this procedure has the same problem as does our original version of integral. Modify the procedure so that it expects the integrand as a delayed argument and hence can be used in the solve procedure shown above.
Exercise 3.77 . The integral procedure used above was analogous to the 3.5.2 . Alternatively , we can give a definition of integral that is more like integers - starting - from ( also in section 3.5.2 ): (define (integral delayed-integrand initial-value dt) (cons-stream initial-value (let ([integrand (force delayed-integrand)]) (if (stream-null? integrand) the-empty-stream (integral (delay (stream-cdr integrand)) (+ (* dt (stream-car integrand)) initial-value) dt)))))
1db3cbd8a3b66bc65754988814704ac88f6886f19f997dab6a07f1f0cf21e580
reflectionalist/S9fES
replace.scm
Scheme 9 from Empty Space , Function Library By , 2009 ; Placed in the Public Domain ; ; (replace object-old object-new pair) ==> pair ; ; Replace elements of a pair. OBJECT-OLD is the object to be ; replaced and OBJECT-NEW is the new object. ; ; Example: (replace '(x) '(y) '(lambda (x) y)) ==> (lambda (y) y) (define (replace old new obj) (cond ((equal? obj old) new) ((pair? obj) (cons (replace old new (car obj)) (replace old new (cdr obj)))) (else obj)))
null
https://raw.githubusercontent.com/reflectionalist/S9fES/0ade11593cf35f112e197026886fc819042058dd/lib/replace.scm
scheme
Placed in the Public Domain (replace object-old object-new pair) ==> pair Replace elements of a pair. OBJECT-OLD is the object to be replaced and OBJECT-NEW is the new object. Example: (replace '(x) '(y) '(lambda (x) y)) ==> (lambda (y) y)
Scheme 9 from Empty Space , Function Library By , 2009 (define (replace old new obj) (cond ((equal? obj old) new) ((pair? obj) (cons (replace old new (car obj)) (replace old new (cdr obj)))) (else obj)))
8e36577cf7aab61431429829c42806febeba65620dedc1cf33a4000cc9c38f34
Gabriella439/managed
Managed.hs
# LANGUAGE CPP # {-# LANGUAGE RankNTypes #-} | An example program to copy data from one handle to another might look like this : > main = > withFile " inFile.txt " ReadMode $ \inHandle - > > withFile " outFile.txt " WriteMode $ \outHandle - > > copy > > -- A hypothetical function that copies data from one handle to another > copy : : Handle - > Handle - > IO ( ) ` System . IO.withFile ` is one of many functions that acquire some resource in an exception - safe way . These functions take a callback function as an argument and they invoke the callback on the resource when it becomes available , guaranteeing that the resource is properly disposed if the callback throws an exception . These functions usually have a type that ends with the following pattern : > Callback > -- ----------- > withXXX : : ... - > ( a - > IO r ) - > IO r Here are some examples of this pattern from the @base@ libraries : > : : Storable a = > [ a ] - > ( Ptr a - > IO r ) - > IO r > : : Buffer e - > ( Ptr e - > IO r ) - > IO r > withCAString : : String - > ( CString - > IO r ) - > IO r > withForeignPtr : : ForeignPtr a - > ( Ptr a - > IO r ) - > IO r > withMVar : : Mvar a - > ( a - > IO r ) - > IO r > withPool : : ( Pool - > IO r ) - > IO r Acquiring multiple resources in this way requires nesting callbacks . However , you can wrap anything of the form @((a - > IO r ) - > IO r)@ in the ` Managed ` monad , which translates binds to callbacks for you : > import Control . Monad . Managed > import System . IO > > inFile : : FilePath - > Managed Handle > inFile filePath = managed ( withFile filePath ReadMode ) > > outFile : : FilePath - > Managed Handle > outFile filePath = managed ( withFile filePath WriteMode ) > > main = runManaged $ do > " inFile.txt " > " outFile.txt " > liftIO ( copy ) ... or you can just wrap things inline : > main = runManaged $ do > < - managed ( withFile " inFile.txt " ReadMode ) > managed ( withFile " outFile.txt " WriteMode ) > liftIO ( copy ) Additionally , since ` Managed ` is a ` Monad ` , you can take advantage of all your favorite combinators from " Control . Monad " . For example , the ` Foreign . Marshal . Utils.withMany ` function from " Foreign . Marshal . Utils " becomes a trivial wrapper around ` mapM ` : > withMany : : ( a - > ( b - > IO r ) - > IO r ) - > [ a ] - > ( [ b ] - > IO r ) - > IO r > withMany f = with . mapM ( Managed . f ) Another reason to use ` Managed ` is that if you wrap a ` Monoid ` value in ` Managed ` you get back a new ` Monoid ` : > instance Monoid a = > Monoid ( Managed a ) This lets you combine managed resources transparently . You can also lift operations from some numeric type classes this way , too , such as the ` Num ` type class . NOTE : ` Managed ` may leak space if used in an infinite loop like this example : > import Control . Monad > import Control . Monad . Managed > > main = runManaged ( forever ( ( print 1 ) ) ) If you need to acquire a resource for a long - lived loop , you can instead acquire the resource first and run the loop in ` IO ` , using either of the following two equivalent idioms : > with resource ( \r - > forever ( useThe r ) ) > > do r < - resource > liftIO ( forever ( useThe r ) ) look like this: > main = > withFile "inFile.txt" ReadMode $ \inHandle -> > withFile "outFile.txt" WriteMode $ \outHandle -> > copy inHandle outHandle > > -- A hypothetical function that copies data from one handle to another > copy :: Handle -> Handle -> IO () `System.IO.withFile` is one of many functions that acquire some resource in an exception-safe way. These functions take a callback function as an argument and they invoke the callback on the resource when it becomes available, guaranteeing that the resource is properly disposed if the callback throws an exception. These functions usually have a type that ends with the following pattern: > Callback > -- ----------- > withXXX :: ... -> (a -> IO r) -> IO r Here are some examples of this pattern from the @base@ libraries: > withArray :: Storable a => [a] -> (Ptr a -> IO r) -> IO r > withBuffer :: Buffer e -> (Ptr e -> IO r) -> IO r > withCAString :: String -> (CString -> IO r) -> IO r > withForeignPtr :: ForeignPtr a -> (Ptr a -> IO r) -> IO r > withMVar :: Mvar a -> (a -> IO r) -> IO r > withPool :: (Pool -> IO r) -> IO r Acquiring multiple resources in this way requires nesting callbacks. However, you can wrap anything of the form @((a -> IO r) -> IO r)@ in the `Managed` monad, which translates binds to callbacks for you: > import Control.Monad.Managed > import System.IO > > inFile :: FilePath -> Managed Handle > inFile filePath = managed (withFile filePath ReadMode) > > outFile :: FilePath -> Managed Handle > outFile filePath = managed (withFile filePath WriteMode) > > main = runManaged $ do > inHandle <- inFile "inFile.txt" > outHandle <- outFile "outFile.txt" > liftIO (copy inHandle outHandle) ... or you can just wrap things inline: > main = runManaged $ do > inHandle <- managed (withFile "inFile.txt" ReadMode) > outHandle <- managed (withFile "outFile.txt" WriteMode) > liftIO (copy inHandle outHandle) Additionally, since `Managed` is a `Monad`, you can take advantage of all your favorite combinators from "Control.Monad". For example, the `Foreign.Marshal.Utils.withMany` function from "Foreign.Marshal.Utils" becomes a trivial wrapper around `mapM`: > withMany :: (a -> (b -> IO r) -> IO r) -> [a] -> ([b] -> IO r) -> IO r > withMany f = with . mapM (Managed . f) Another reason to use `Managed` is that if you wrap a `Monoid` value in `Managed` you get back a new `Monoid`: > instance Monoid a => Monoid (Managed a) This lets you combine managed resources transparently. You can also lift operations from some numeric type classes this way, too, such as the `Num` type class. NOTE: `Managed` may leak space if used in an infinite loop like this example: > import Control.Monad > import Control.Monad.Managed > > main = runManaged (forever (liftIO (print 1))) If you need to acquire a resource for a long-lived loop, you can instead acquire the resource first and run the loop in `IO`, using either of the following two equivalent idioms: > with resource (\r -> forever (useThe r)) > > do r <- resource > liftIO (forever (useThe r)) -} module Control.Monad.Managed ( -- * Managed Managed, MonadManaged(..), managed, managed_, defer, with, runManaged, -- * Re-exports -- $reexports module Control.Monad.IO.Class ) where import Control.Monad.IO.Class (MonadIO(liftIO)) #if MIN_VERSION_base(4,9,0) import Control.Monad.Fail as MonadFail (MonadFail(..)) #endif import Control.Monad.Trans.Class (lift) #if MIN_VERSION_base(4,8,0) import Control.Applicative (liftA2) #else import Control.Applicative import Data.Monoid (Monoid(..)) #endif #if !(MIN_VERSION_base(4,11,0)) import Data.Semigroup (Semigroup(..)) #endif import qualified Control.Monad.Trans.Cont as Cont #if MIN_VERSION_transformers(0,4,0) import qualified Control.Monad.Trans.Except as Except #endif import qualified Control.Monad.Trans.Identity as Identity import qualified Control.Monad.Trans.Maybe as Maybe import qualified Control.Monad.Trans.Reader as Reader import qualified Control.Monad.Trans.RWS.Lazy as RWS.Lazy import qualified Control.Monad.Trans.RWS.Strict as RWS.Strict import qualified Control.Monad.Trans.State.Lazy as State.Lazy import qualified Control.Monad.Trans.State.Strict as State.Strict import qualified Control.Monad.Trans.Writer.Lazy as Writer.Lazy import qualified Control.Monad.Trans.Writer.Strict as Writer.Strict -- | A managed resource that you acquire using `with` newtype Managed a = Managed { (>>-) :: forall r . (a -> IO r) -> IO r } instance Functor Managed where fmap f mx = Managed (\return_ -> mx >>- \x -> return_ (f x) ) instance Applicative Managed where pure r = Managed (\return_ -> return_ r ) mf <*> mx = Managed (\return_ -> mf >>- \f -> mx >>- \x -> return_ (f x) ) instance Monad Managed where ma >>= f = Managed (\return_ -> ma >>- \a -> f a >>- \b -> return_ b ) instance MonadIO Managed where liftIO m = Managed (\return_ -> do a <- m return_ a ) #if MIN_VERSION_base(4,9,0) instance MonadFail Managed where fail s = Managed (\return_ -> do a <- MonadFail.fail s return_ a ) #endif instance Semigroup a => Semigroup (Managed a) where (<>) = liftA2 (<>) instance Monoid a => Monoid (Managed a) where mempty = pure mempty #if !(MIN_VERSION_base(4,11,0)) mappend = liftA2 mappend #endif instance Num a => Num (Managed a) where fromInteger = pure . fromInteger negate = fmap negate abs = fmap abs signum = fmap signum (+) = liftA2 (+) (*) = liftA2 (*) (-) = liftA2 (-) instance Fractional a => Fractional (Managed a) where fromRational = pure . fromRational recip = fmap recip (/) = liftA2 (/) instance Floating a => Floating (Managed a) where pi = pure pi exp = fmap exp sqrt = fmap sqrt log = fmap log sin = fmap sin tan = fmap tan cos = fmap cos asin = fmap sin atan = fmap atan acos = fmap acos sinh = fmap sinh tanh = fmap tanh cosh = fmap cosh asinh = fmap asinh atanh = fmap atanh acosh = fmap acosh (**) = liftA2 (**) logBase = liftA2 logBase | You can embed a ` Managed ` action within any ` Monad ` that implements ` MonadManaged ` by using the ` using ` function All instances must obey the following two laws : > using ( return x ) = return x > > using ( m > > = f ) = using m > > = \x - > using ( f x ) `MonadManaged` by using the `using` function All instances must obey the following two laws: > using (return x) = return x > > using (m >>= f) = using m >>= \x -> using (f x) -} class MonadIO m => MonadManaged m where using :: Managed a -> m a instance MonadManaged Managed where using = id instance MonadManaged m => MonadManaged (Cont.ContT r m) where using m = lift (using m) #if MIN_VERSION_transformers(0,4,0) instance MonadManaged m => MonadManaged (Except.ExceptT e m) where using m = lift (using m) #endif instance MonadManaged m => MonadManaged (Identity.IdentityT m) where using m = lift (using m) instance MonadManaged m => MonadManaged (Maybe.MaybeT m) where using m = lift (using m) instance MonadManaged m => MonadManaged (Reader.ReaderT r m) where using m = lift (using m) instance (Monoid w, MonadManaged m) => MonadManaged (RWS.Lazy.RWST r w s m) where using m = lift (using m) instance (Monoid w, MonadManaged m) => MonadManaged (RWS.Strict.RWST r w s m) where using m = lift (using m) instance MonadManaged m => MonadManaged (State.Strict.StateT s m) where using m = lift (using m) instance MonadManaged m => MonadManaged (State.Lazy.StateT s m) where using m = lift (using m) instance (Monoid w, MonadManaged m) => MonadManaged (Writer.Strict.WriterT w m) where using m = lift (using m) instance (Monoid w, MonadManaged m) => MonadManaged (Writer.Lazy.WriterT w m) where using m = lift (using m) -- | Build a `Managed` value managed :: MonadManaged m => (forall r . (a -> IO r) -> IO r) -> m a managed f = using (Managed f) -- | Like 'managed' but for resource-less operations. managed_ :: MonadManaged m => (forall r. IO r -> IO r) -> m () managed_ f = managed $ \g -> f $ g () | Defer running an action until exit ( via ` runManaged ` ) . For example , the following code will print \"Hello\ " followed by \"Goodbye\ " : > runManaged $ do > defer $ liftIO $ putStrLn " Goodbye " > liftIO $ putStrLn " Hello " For example, the following code will print \"Hello\" followed by \"Goodbye\": > runManaged $ do > defer $ liftIO $ putStrLn "Goodbye" > liftIO $ putStrLn "Hello" -} defer :: MonadManaged m => IO r -> m () defer m = managed_ (<* m) | Acquire a ` Managed ` value This is a potentially unsafe function since it allows a resource to escape its scope . For example , you might use ` Managed ` to safely acquire a file handle , like this : > import qualified System . IO as IO > > example : : Managed Handle > example = managed ( IO.withFile " foo.txt " IO.ReadMode ) ... and if you never used the ` with ` function then you would never run the risk of accessing the ` Handle ` after the file was closed . However , if you use ` with ` then you can incorrectly access the handle after the handle is closed , like this : > bad : : IO ( ) > bad = do > handle < - with example return > IO.hPutStrLn handle " bar " -- This will fail because the handle is closed ... so only use ` with ` if you know what you are doing and you 're returning a value that is not a resource being managed . This is a potentially unsafe function since it allows a resource to escape its scope. For example, you might use `Managed` to safely acquire a file handle, like this: > import qualified System.IO as IO > > example :: Managed Handle > example = managed (IO.withFile "foo.txt" IO.ReadMode) ... and if you never used the `with` function then you would never run the risk of accessing the `Handle` after the file was closed. However, if you use `with` then you can incorrectly access the handle after the handle is closed, like this: > bad :: IO () > bad = do > handle <- with example return > IO.hPutStrLn handle "bar" -- This will fail because the handle is closed ... so only use `with` if you know what you are doing and you're returning a value that is not a resource being managed. -} with :: Managed a -> (a -> IO r) -> IO r with m = (>>-) m -- | Run a `Managed` computation, enforcing that no acquired resources leak runManaged :: Managed () -> IO () runManaged m = m >>- return $ reexports " Control . Monad . IO.Class " re - exports ' MonadIO ' "Control.Monad.IO.Class" re-exports 'MonadIO' -}
null
https://raw.githubusercontent.com/Gabriella439/managed/7a1d457f3021ab67259bf9033b9792e2ed9e6acc/src/Control/Monad/Managed.hs
haskell
# LANGUAGE RankNTypes # A hypothetical function that copies data from one handle to another ----------- A hypothetical function that copies data from one handle to another ----------- * Managed * Re-exports $reexports | A managed resource that you acquire using `with` | Build a `Managed` value | Like 'managed' but for resource-less operations. This will fail because the handle is closed This will fail because the handle is closed | Run a `Managed` computation, enforcing that no acquired resources leak
# LANGUAGE CPP # | An example program to copy data from one handle to another might look like this : > main = > withFile " inFile.txt " ReadMode $ \inHandle - > > withFile " outFile.txt " WriteMode $ \outHandle - > > copy > > copy : : Handle - > Handle - > IO ( ) ` System . IO.withFile ` is one of many functions that acquire some resource in an exception - safe way . These functions take a callback function as an argument and they invoke the callback on the resource when it becomes available , guaranteeing that the resource is properly disposed if the callback throws an exception . These functions usually have a type that ends with the following pattern : > Callback > withXXX : : ... - > ( a - > IO r ) - > IO r Here are some examples of this pattern from the @base@ libraries : > : : Storable a = > [ a ] - > ( Ptr a - > IO r ) - > IO r > : : Buffer e - > ( Ptr e - > IO r ) - > IO r > withCAString : : String - > ( CString - > IO r ) - > IO r > withForeignPtr : : ForeignPtr a - > ( Ptr a - > IO r ) - > IO r > withMVar : : Mvar a - > ( a - > IO r ) - > IO r > withPool : : ( Pool - > IO r ) - > IO r Acquiring multiple resources in this way requires nesting callbacks . However , you can wrap anything of the form @((a - > IO r ) - > IO r)@ in the ` Managed ` monad , which translates binds to callbacks for you : > import Control . Monad . Managed > import System . IO > > inFile : : FilePath - > Managed Handle > inFile filePath = managed ( withFile filePath ReadMode ) > > outFile : : FilePath - > Managed Handle > outFile filePath = managed ( withFile filePath WriteMode ) > > main = runManaged $ do > " inFile.txt " > " outFile.txt " > liftIO ( copy ) ... or you can just wrap things inline : > main = runManaged $ do > < - managed ( withFile " inFile.txt " ReadMode ) > managed ( withFile " outFile.txt " WriteMode ) > liftIO ( copy ) Additionally , since ` Managed ` is a ` Monad ` , you can take advantage of all your favorite combinators from " Control . Monad " . For example , the ` Foreign . Marshal . Utils.withMany ` function from " Foreign . Marshal . Utils " becomes a trivial wrapper around ` mapM ` : > withMany : : ( a - > ( b - > IO r ) - > IO r ) - > [ a ] - > ( [ b ] - > IO r ) - > IO r > withMany f = with . mapM ( Managed . f ) Another reason to use ` Managed ` is that if you wrap a ` Monoid ` value in ` Managed ` you get back a new ` Monoid ` : > instance Monoid a = > Monoid ( Managed a ) This lets you combine managed resources transparently . You can also lift operations from some numeric type classes this way , too , such as the ` Num ` type class . NOTE : ` Managed ` may leak space if used in an infinite loop like this example : > import Control . Monad > import Control . Monad . Managed > > main = runManaged ( forever ( ( print 1 ) ) ) If you need to acquire a resource for a long - lived loop , you can instead acquire the resource first and run the loop in ` IO ` , using either of the following two equivalent idioms : > with resource ( \r - > forever ( useThe r ) ) > > do r < - resource > liftIO ( forever ( useThe r ) ) look like this: > main = > withFile "inFile.txt" ReadMode $ \inHandle -> > withFile "outFile.txt" WriteMode $ \outHandle -> > copy inHandle outHandle > > copy :: Handle -> Handle -> IO () `System.IO.withFile` is one of many functions that acquire some resource in an exception-safe way. These functions take a callback function as an argument and they invoke the callback on the resource when it becomes available, guaranteeing that the resource is properly disposed if the callback throws an exception. These functions usually have a type that ends with the following pattern: > Callback > withXXX :: ... -> (a -> IO r) -> IO r Here are some examples of this pattern from the @base@ libraries: > withArray :: Storable a => [a] -> (Ptr a -> IO r) -> IO r > withBuffer :: Buffer e -> (Ptr e -> IO r) -> IO r > withCAString :: String -> (CString -> IO r) -> IO r > withForeignPtr :: ForeignPtr a -> (Ptr a -> IO r) -> IO r > withMVar :: Mvar a -> (a -> IO r) -> IO r > withPool :: (Pool -> IO r) -> IO r Acquiring multiple resources in this way requires nesting callbacks. However, you can wrap anything of the form @((a -> IO r) -> IO r)@ in the `Managed` monad, which translates binds to callbacks for you: > import Control.Monad.Managed > import System.IO > > inFile :: FilePath -> Managed Handle > inFile filePath = managed (withFile filePath ReadMode) > > outFile :: FilePath -> Managed Handle > outFile filePath = managed (withFile filePath WriteMode) > > main = runManaged $ do > inHandle <- inFile "inFile.txt" > outHandle <- outFile "outFile.txt" > liftIO (copy inHandle outHandle) ... or you can just wrap things inline: > main = runManaged $ do > inHandle <- managed (withFile "inFile.txt" ReadMode) > outHandle <- managed (withFile "outFile.txt" WriteMode) > liftIO (copy inHandle outHandle) Additionally, since `Managed` is a `Monad`, you can take advantage of all your favorite combinators from "Control.Monad". For example, the `Foreign.Marshal.Utils.withMany` function from "Foreign.Marshal.Utils" becomes a trivial wrapper around `mapM`: > withMany :: (a -> (b -> IO r) -> IO r) -> [a] -> ([b] -> IO r) -> IO r > withMany f = with . mapM (Managed . f) Another reason to use `Managed` is that if you wrap a `Monoid` value in `Managed` you get back a new `Monoid`: > instance Monoid a => Monoid (Managed a) This lets you combine managed resources transparently. You can also lift operations from some numeric type classes this way, too, such as the `Num` type class. NOTE: `Managed` may leak space if used in an infinite loop like this example: > import Control.Monad > import Control.Monad.Managed > > main = runManaged (forever (liftIO (print 1))) If you need to acquire a resource for a long-lived loop, you can instead acquire the resource first and run the loop in `IO`, using either of the following two equivalent idioms: > with resource (\r -> forever (useThe r)) > > do r <- resource > liftIO (forever (useThe r)) -} module Control.Monad.Managed ( Managed, MonadManaged(..), managed, managed_, defer, with, runManaged, module Control.Monad.IO.Class ) where import Control.Monad.IO.Class (MonadIO(liftIO)) #if MIN_VERSION_base(4,9,0) import Control.Monad.Fail as MonadFail (MonadFail(..)) #endif import Control.Monad.Trans.Class (lift) #if MIN_VERSION_base(4,8,0) import Control.Applicative (liftA2) #else import Control.Applicative import Data.Monoid (Monoid(..)) #endif #if !(MIN_VERSION_base(4,11,0)) import Data.Semigroup (Semigroup(..)) #endif import qualified Control.Monad.Trans.Cont as Cont #if MIN_VERSION_transformers(0,4,0) import qualified Control.Monad.Trans.Except as Except #endif import qualified Control.Monad.Trans.Identity as Identity import qualified Control.Monad.Trans.Maybe as Maybe import qualified Control.Monad.Trans.Reader as Reader import qualified Control.Monad.Trans.RWS.Lazy as RWS.Lazy import qualified Control.Monad.Trans.RWS.Strict as RWS.Strict import qualified Control.Monad.Trans.State.Lazy as State.Lazy import qualified Control.Monad.Trans.State.Strict as State.Strict import qualified Control.Monad.Trans.Writer.Lazy as Writer.Lazy import qualified Control.Monad.Trans.Writer.Strict as Writer.Strict newtype Managed a = Managed { (>>-) :: forall r . (a -> IO r) -> IO r } instance Functor Managed where fmap f mx = Managed (\return_ -> mx >>- \x -> return_ (f x) ) instance Applicative Managed where pure r = Managed (\return_ -> return_ r ) mf <*> mx = Managed (\return_ -> mf >>- \f -> mx >>- \x -> return_ (f x) ) instance Monad Managed where ma >>= f = Managed (\return_ -> ma >>- \a -> f a >>- \b -> return_ b ) instance MonadIO Managed where liftIO m = Managed (\return_ -> do a <- m return_ a ) #if MIN_VERSION_base(4,9,0) instance MonadFail Managed where fail s = Managed (\return_ -> do a <- MonadFail.fail s return_ a ) #endif instance Semigroup a => Semigroup (Managed a) where (<>) = liftA2 (<>) instance Monoid a => Monoid (Managed a) where mempty = pure mempty #if !(MIN_VERSION_base(4,11,0)) mappend = liftA2 mappend #endif instance Num a => Num (Managed a) where fromInteger = pure . fromInteger negate = fmap negate abs = fmap abs signum = fmap signum (+) = liftA2 (+) (*) = liftA2 (*) (-) = liftA2 (-) instance Fractional a => Fractional (Managed a) where fromRational = pure . fromRational recip = fmap recip (/) = liftA2 (/) instance Floating a => Floating (Managed a) where pi = pure pi exp = fmap exp sqrt = fmap sqrt log = fmap log sin = fmap sin tan = fmap tan cos = fmap cos asin = fmap sin atan = fmap atan acos = fmap acos sinh = fmap sinh tanh = fmap tanh cosh = fmap cosh asinh = fmap asinh atanh = fmap atanh acosh = fmap acosh (**) = liftA2 (**) logBase = liftA2 logBase | You can embed a ` Managed ` action within any ` Monad ` that implements ` MonadManaged ` by using the ` using ` function All instances must obey the following two laws : > using ( return x ) = return x > > using ( m > > = f ) = using m > > = \x - > using ( f x ) `MonadManaged` by using the `using` function All instances must obey the following two laws: > using (return x) = return x > > using (m >>= f) = using m >>= \x -> using (f x) -} class MonadIO m => MonadManaged m where using :: Managed a -> m a instance MonadManaged Managed where using = id instance MonadManaged m => MonadManaged (Cont.ContT r m) where using m = lift (using m) #if MIN_VERSION_transformers(0,4,0) instance MonadManaged m => MonadManaged (Except.ExceptT e m) where using m = lift (using m) #endif instance MonadManaged m => MonadManaged (Identity.IdentityT m) where using m = lift (using m) instance MonadManaged m => MonadManaged (Maybe.MaybeT m) where using m = lift (using m) instance MonadManaged m => MonadManaged (Reader.ReaderT r m) where using m = lift (using m) instance (Monoid w, MonadManaged m) => MonadManaged (RWS.Lazy.RWST r w s m) where using m = lift (using m) instance (Monoid w, MonadManaged m) => MonadManaged (RWS.Strict.RWST r w s m) where using m = lift (using m) instance MonadManaged m => MonadManaged (State.Strict.StateT s m) where using m = lift (using m) instance MonadManaged m => MonadManaged (State.Lazy.StateT s m) where using m = lift (using m) instance (Monoid w, MonadManaged m) => MonadManaged (Writer.Strict.WriterT w m) where using m = lift (using m) instance (Monoid w, MonadManaged m) => MonadManaged (Writer.Lazy.WriterT w m) where using m = lift (using m) managed :: MonadManaged m => (forall r . (a -> IO r) -> IO r) -> m a managed f = using (Managed f) managed_ :: MonadManaged m => (forall r. IO r -> IO r) -> m () managed_ f = managed $ \g -> f $ g () | Defer running an action until exit ( via ` runManaged ` ) . For example , the following code will print \"Hello\ " followed by \"Goodbye\ " : > runManaged $ do > defer $ liftIO $ putStrLn " Goodbye " > liftIO $ putStrLn " Hello " For example, the following code will print \"Hello\" followed by \"Goodbye\": > runManaged $ do > defer $ liftIO $ putStrLn "Goodbye" > liftIO $ putStrLn "Hello" -} defer :: MonadManaged m => IO r -> m () defer m = managed_ (<* m) | Acquire a ` Managed ` value This is a potentially unsafe function since it allows a resource to escape its scope . For example , you might use ` Managed ` to safely acquire a file handle , like this : > import qualified System . IO as IO > > example : : Managed Handle > example = managed ( IO.withFile " foo.txt " IO.ReadMode ) ... and if you never used the ` with ` function then you would never run the risk of accessing the ` Handle ` after the file was closed . However , if you use ` with ` then you can incorrectly access the handle after the handle is closed , like this : > bad : : IO ( ) > bad = do > handle < - with example return ... so only use ` with ` if you know what you are doing and you 're returning a value that is not a resource being managed . This is a potentially unsafe function since it allows a resource to escape its scope. For example, you might use `Managed` to safely acquire a file handle, like this: > import qualified System.IO as IO > > example :: Managed Handle > example = managed (IO.withFile "foo.txt" IO.ReadMode) ... and if you never used the `with` function then you would never run the risk of accessing the `Handle` after the file was closed. However, if you use `with` then you can incorrectly access the handle after the handle is closed, like this: > bad :: IO () > bad = do > handle <- with example return ... so only use `with` if you know what you are doing and you're returning a value that is not a resource being managed. -} with :: Managed a -> (a -> IO r) -> IO r with m = (>>-) m runManaged :: Managed () -> IO () runManaged m = m >>- return $ reexports " Control . Monad . IO.Class " re - exports ' MonadIO ' "Control.Monad.IO.Class" re-exports 'MonadIO' -}
5ff3ec3ec9431f2b85cbb0f41601291f857e31548312c7fc2843b5b470324f91
janestreet/ecaml
test_directory.ml
open! Core open! Async_kernel open! Import open! Directory let%expect_test "" = (try delete "zzz" ~recursive:true with | _ -> ()); return () ;; let%expect_test "[create], [delete]" = create "zzz"; delete "zzz"; return () ;; let%expect_test "[create ~parents:true], [delete ~recursive:true]" = create "a/b/c" ~parents:true; delete "a" ~recursive:true; return () ;; let%expect_test "[create] raise" = show_raise (fun () -> create "/zzz"); [%expect {| (raised (file-error ("Creating directory" "Permission denied" /zzz))) |}]; return () ;; let%expect_test "[delete] raise" = print_s ~templatize_current_directory:true [%sexp (Or_error.try_with (fun () -> delete "zzz") : _ Or_error.t)]; [%expect {| (Error ( file-missing ( "Removing directory" "No such file or directory" <current-directory>/zzz))) |}]; return () ;; let%expect_test "[files]" = create "zzz"; let show_files () = print_s [%sexp (files "zzz" : Filename.t list)] in show_files (); [%expect {| () |}]; touch "zzz/a"; touch "zzz/b"; show_files (); [%expect {| (a b) |}]; delete "zzz" ~recursive:true; return () ;; let%expect_test "[files_recursively]" = create "a/b/c" ~parents:true; List.iter ~f:touch [ "a/z1"; "a/b/z2"; "a/b/c/z3" ]; print_s [%sexp (files_recursively "a" ~matching:("" |> Regexp.of_pattern) : Filename.t list)]; [%expect {| (a/b/c/z3 a/b/z2 a/z1) |}]; delete "a" ~recursive:true; return () ;;
null
https://raw.githubusercontent.com/janestreet/ecaml/25a5a2972b3a94f5529a46363b37670a6c1de195/test/test_directory.ml
ocaml
open! Core open! Async_kernel open! Import open! Directory let%expect_test "" = (try delete "zzz" ~recursive:true with | _ -> ()); return () ;; let%expect_test "[create], [delete]" = create "zzz"; delete "zzz"; return () ;; let%expect_test "[create ~parents:true], [delete ~recursive:true]" = create "a/b/c" ~parents:true; delete "a" ~recursive:true; return () ;; let%expect_test "[create] raise" = show_raise (fun () -> create "/zzz"); [%expect {| (raised (file-error ("Creating directory" "Permission denied" /zzz))) |}]; return () ;; let%expect_test "[delete] raise" = print_s ~templatize_current_directory:true [%sexp (Or_error.try_with (fun () -> delete "zzz") : _ Or_error.t)]; [%expect {| (Error ( file-missing ( "Removing directory" "No such file or directory" <current-directory>/zzz))) |}]; return () ;; let%expect_test "[files]" = create "zzz"; let show_files () = print_s [%sexp (files "zzz" : Filename.t list)] in show_files (); [%expect {| () |}]; touch "zzz/a"; touch "zzz/b"; show_files (); [%expect {| (a b) |}]; delete "zzz" ~recursive:true; return () ;; let%expect_test "[files_recursively]" = create "a/b/c" ~parents:true; List.iter ~f:touch [ "a/z1"; "a/b/z2"; "a/b/c/z3" ]; print_s [%sexp (files_recursively "a" ~matching:("" |> Regexp.of_pattern) : Filename.t list)]; [%expect {| (a/b/c/z3 a/b/z2 a/z1) |}]; delete "a" ~recursive:true; return () ;;
a1245aa2d5883d60b8b0ec3e3b4c6a2e25695bfa01091a9fa2af07c076eaf415
kowainik/policeman
Version.hs
# LANGUAGE NumericUnderscores # module Test.Policeman.Version ( versionSpec , versionRoundtripText , versionRoundtripInts ) where import Hedgehog (MonadGen, Property, forAll, property, (===)) import Test.Hspec (Spec, describe, it, shouldBe, shouldSatisfy) import Policeman.Core.Version (Version (..), versionFromIntList, versionFromText, versionToIntList, versionToText) import qualified Data.Text as Text import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range -- | Version parsing unit tests. versionSpec :: Spec versionSpec = describe "Version parsing" $ do describe "From Text" $ do it "parses 1.2.3.4" $ versionFromText "1.2.3.4" `shouldBe` Just (Version 1 2 3 4 "1.2.3.4") it "parses 1.2.3" $ versionFromText "1.2.3" `shouldBe` Just (Version 1 2 3 0 "1.2.3") it "parses 1.2" $ versionFromText "1.2" `shouldBe` Just (Version 1 2 0 0 "1.2") it "parses 1" $ versionFromText "1" `shouldBe` Just (Version 1 0 0 0 "1") it "parses 00" $ versionFromText "00" `shouldBe` Just (Version 0 0 0 0 "00") it "does not parse letters" $ versionFromText "1.2.3.a" `shouldSatisfy` isNothing it "does not parse trailing dot" $ versionFromText "1.2.3." `shouldSatisfy` isNothing it "does not parse leading dot" $ versionFromText ".1.2.3" `shouldSatisfy` isNothing describe "From List of Ints" $ do it "parses [1,2,3,4]" $ versionFromIntList [1,2,3,4] `shouldBe` Just (Version 1 2 3 4 "1.2.3.4") it "parses [1,2,3]" $ versionFromIntList [1,2,3] `shouldBe` Just (Version 1 2 3 0 "1.2.3") it "parses [1,2]" $ versionFromIntList [1,2] `shouldBe` Just (Version 1 2 0 0 "1.2") it "parses [1]" $ versionFromIntList [1] `shouldBe` Just (Version 1 0 0 0 "1") it "parses [1,2,3,4,5]" $ versionFromIntList [1,2,3,4,5] `shouldBe` Just (Version 1 2 3 4 "1.2.3.4.5") -- | Parsing to/from 'Text' works properly. versionRoundtripText :: Property versionRoundtripText = property $ do preVersion <- forAll genVersion let version = preVersion { versionText = versionToText preVersion } versionFromText (versionToText version) === Just version -- | Parsing to/from '[Int]' works properly. versionRoundtripInts :: Property versionRoundtripInts = property $ do version <- forAll genVersion versionFromIntList (versionToIntList version) === Just version -- | Generates random version. genVersion :: forall m . (MonadGen m) => m Version genVersion = do versionA <- genInt versionB <- genInt versionC <- genInt versionD <- genInt pure Version { versionText = Text.intercalate "." $ map show [ versionA , versionB , versionC , versionD ] , .. } where genInt :: m Int genInt = Gen.int (Range.constant 0 20_000)
null
https://raw.githubusercontent.com/kowainik/policeman/26a92678c76b145ad9ae30054bf978a0d6ec2a58/test/Test/Policeman/Version.hs
haskell
| Version parsing unit tests. | Parsing to/from 'Text' works properly. | Parsing to/from '[Int]' works properly. | Generates random version.
# LANGUAGE NumericUnderscores # module Test.Policeman.Version ( versionSpec , versionRoundtripText , versionRoundtripInts ) where import Hedgehog (MonadGen, Property, forAll, property, (===)) import Test.Hspec (Spec, describe, it, shouldBe, shouldSatisfy) import Policeman.Core.Version (Version (..), versionFromIntList, versionFromText, versionToIntList, versionToText) import qualified Data.Text as Text import qualified Hedgehog.Gen as Gen import qualified Hedgehog.Range as Range versionSpec :: Spec versionSpec = describe "Version parsing" $ do describe "From Text" $ do it "parses 1.2.3.4" $ versionFromText "1.2.3.4" `shouldBe` Just (Version 1 2 3 4 "1.2.3.4") it "parses 1.2.3" $ versionFromText "1.2.3" `shouldBe` Just (Version 1 2 3 0 "1.2.3") it "parses 1.2" $ versionFromText "1.2" `shouldBe` Just (Version 1 2 0 0 "1.2") it "parses 1" $ versionFromText "1" `shouldBe` Just (Version 1 0 0 0 "1") it "parses 00" $ versionFromText "00" `shouldBe` Just (Version 0 0 0 0 "00") it "does not parse letters" $ versionFromText "1.2.3.a" `shouldSatisfy` isNothing it "does not parse trailing dot" $ versionFromText "1.2.3." `shouldSatisfy` isNothing it "does not parse leading dot" $ versionFromText ".1.2.3" `shouldSatisfy` isNothing describe "From List of Ints" $ do it "parses [1,2,3,4]" $ versionFromIntList [1,2,3,4] `shouldBe` Just (Version 1 2 3 4 "1.2.3.4") it "parses [1,2,3]" $ versionFromIntList [1,2,3] `shouldBe` Just (Version 1 2 3 0 "1.2.3") it "parses [1,2]" $ versionFromIntList [1,2] `shouldBe` Just (Version 1 2 0 0 "1.2") it "parses [1]" $ versionFromIntList [1] `shouldBe` Just (Version 1 0 0 0 "1") it "parses [1,2,3,4,5]" $ versionFromIntList [1,2,3,4,5] `shouldBe` Just (Version 1 2 3 4 "1.2.3.4.5") versionRoundtripText :: Property versionRoundtripText = property $ do preVersion <- forAll genVersion let version = preVersion { versionText = versionToText preVersion } versionFromText (versionToText version) === Just version versionRoundtripInts :: Property versionRoundtripInts = property $ do version <- forAll genVersion versionFromIntList (versionToIntList version) === Just version genVersion :: forall m . (MonadGen m) => m Version genVersion = do versionA <- genInt versionB <- genInt versionC <- genInt versionD <- genInt pure Version { versionText = Text.intercalate "." $ map show [ versionA , versionB , versionC , versionD ] , .. } where genInt :: m Int genInt = Gen.int (Range.constant 0 20_000)
d651f4a1cca550256466ed8a3847739d308fcfd44317355cb9c7d3f8e0ea6384
byteally/dbrecord
Parser.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE TupleSections # module DBRecord.MSSQL.Internal.Sql.Parser ( sqlExpr , parseMSSQLType , SizeInfo (..) , defSizeInfo ) where import DBRecord.Internal.Sql.DML import Data.Attoparsec.Text hiding (number) import qualified Data.Text as T import Data.Text (Text) import Control.Applicative import qualified Debug.Trace as DT import qualified Data.List.NonEmpty as NEL import DBRecord.Internal.DBTypes (DBType (..), DBTypeName (..)) import Data.Functor (($>)) import qualified DBRecord.Internal.Types as Type sqlExpr :: Parser SqlExpr sqlExpr = ( postfixOrWindowExpr <|> binSqlExpr <|> compositeExpr < | > prefixSqlExpr <|> termSqlExpr ) -- <* -- endOfInput where binSqlExpr = do e1 <- termSqlExpr b <- Left <$> binOp <|> Right <$> (symbol "::" $> ()) case b of Right _ -> do ty <- typeExpr pure (CastSqlExpr ty e1) Left binOpRes -> do e2 <- sqlExpr pure $ {-transformBinExprByPrecedence-} (BinSqlExpr binOpRes e1 e2) postfixOrWindowExpr = do e <- binSqlExpr <|> prefixSqlExpr <|> termSqlExpr epRes <- eitherP (symbol "OVER" *> anonWindowExpr e ) postfixOp case epRes of Left w -> pure w Right op -> pure (PostfixSqlExpr op e) anonWindowExpr e = DT.traceShow (show e) $ parens $ do pbys <- optional ( symbol "PARTITION" *> symbol "BY" *> sepBy1 sqlExpr comma ) ords <- orderBy -- NOTE: ROW(s) are also possible here pure (AnonWindowSqlExpr (maybe [] id pbys) ords e) prefixSqlExpr = do op <- prefixOp e <- sqlExpr pure (PrefixSqlExpr op e) termSqlExpr :: Parser SqlExpr termSqlExpr = arraySqlExpr < | > defaultExpr <|> placeholderExpr <|> castExpr <|> caseExpr <|> ParensSqlExpr <$> (parens sqlExpr) <|> ListSqlExpr <$> parens (sepByComma sqlExpr) <|> -- aggrFunSqlExpr <|> FunSqlExpr <$> funcName <*> parens (sepByComma sqlExpr) <|> ColumnSqlExpr <$> column <|> ConstSqlExpr <$> literal -- ParamSqlExpr -- ExistsSqlExpr -- caseExpr :: Parser SqlExpr caseExpr = do _ <- symbol "CASE" cbs <- some $ do _ <- symbol "WHEN" c <- sqlExpr _ <- symbol "THEN" b <- sqlExpr return (c, b) me <- option Nothing (Just <$> (symbol "ELSE" *> sqlExpr)) _ <- symbol "END" pure (CaseSqlExpr (NEL.fromList cbs) me) funcName :: Parser String funcName = do funNameQual <- identifier <|> brackets identifier funName <- (singleton <$> (char '.' *> (brackets identifier <|> identifier))) <|> pure [] -- TODO: FunSqlExpr needs to be changed or we need to intercalate a separator. pure (concat $ funNameQual : funName) aggrFunSqlExpr : : Parser SqlExpr aggrFunSqlExpr = do n < - funcName ( es , obys ) < - parens $ do es < - sepByComma sqlExpr -- obys < - orderBy pure ( es , [ ] ) -- obys ) pure ( AggrFunSqlExpr n es obys ) arraySqlExpr : : Parser SqlExpr arraySqlExpr = do _ < - symbol " ARRAY " es < - brackets ( sepByComma sqlExpr ) pure ( ArraySqlExpr es ) aggrFunSqlExpr :: Parser SqlExpr aggrFunSqlExpr = do n <- funcName (es, obys) <- parens $ do es <- sepByComma sqlExpr -- obys <- orderBy pure (es, []) -- obys) pure (AggrFunSqlExpr n es obys) arraySqlExpr :: Parser SqlExpr arraySqlExpr = do _ <- symbol "ARRAY" es <- brackets (sepByComma sqlExpr) pure (ArraySqlExpr es) -} castExpr :: Parser SqlExpr castExpr = do _ <- symbol "CAST" (e, typ) <- parens $ do e <- sqlExpr _ <- symbol "AS" typ <- typeExpr pure (e, typ) pure (CastSqlExpr typ e) Note : For MSSQL , Columns can also be of the form [ foo ] , " foo " , or just foo . column :: Parser SqlColumn column = do pieces <- sepBy1 columnPiece (char '.') pure (SqlColumn (map T.pack pieces)) where columnPiece = doubleQuoted identifier <|> brackets identifier <|> identifier -- -- TODO: Identify prefix operators prefixOp : : Parser String -- prefixOp = symbol "NOT" *> pure "NOT" prefixOp :: Parser UnOp prefixOp = symbol "NOT" $> OpNot <|> symbol "LENGTH" $> OpLength <|> symbol "-" $> OpNegate <|> symbol "LOWER" $> OpLower <|> symbol "UPPER" $> OpUpper <|> -- NOTE: missing custom prefixes Added to support MSSQL + prefix Op symbol "+" $> OpPositive <|> symbol "~" $> OpBitwiseNot postfixOp :: Parser UnOp postfixOp = symbol "IS" *> symbol "NULL" $> OpIsNull <|> symbol "IS" *> symbol "NOT" *> symbol "NULL" $> OpIsNotNull -- NOTE: missing custom postfixes binOp :: Parser BinOp binOp = symbol "+" $> OpPlus <|> symbol "=" $> OpEq <|> symbol "<>" $> OpNotEq <|> symbol "!=" $> OpNotEq <|> symbol "-" $> OpMinus <|> symbol ">=" $> OpGtEq <|> symbol "<=" $> OpLtEq <|> symbol ">" $> OpGt <|> symbol "<" $> OpLt <|> symbol "!<" $> OpNotLt <|> symbol "!>" $> OpNotGt <|> symbol "||" $> OpCat <|> symbol "AND" $> OpAnd <|> symbol "OR" $> OpOr <|> symbol "LIKE" $> OpLike <|> symbol "IN" $> OpIn <|> symbol "ALL" $> OpAll <|> symbol "ANY" $> OpAny <|> symbol "EXISTS" $> OpExists <|> symbol "SOME" $> OpSome <|> symbol "BETWEEN" $> OpBetween <|> symbol "/" $> OpDiv <|> symbol "%" $> OpMod <|> symbol "*" $> OpMul <|> symbol "~" $> OpBitNot <|> symbol "&" $> OpBitAnd <|> symbol "|" $> OpBitOr <|> symbol "^" $> OpBitXor <|> -- symbol "::" <|> symbol "AT" *> symbol "TIME" *> symbol "ZONE" $> OpAtTimeZone orderBy :: Parser [(SqlExpr, {-Maybe-} SqlOrder)] orderBy = option [] (symbol "KORDER" *> symbol "BY" *> sepBy1 ord comma) ord :: Parser (SqlExpr, {-Maybe-} SqlOrder) ord = do (,) <$> sqlExpr <*> sqlOrder placeholderExpr :: Parser SqlExpr placeholderExpr = symbol "?" *> pure PlaceHolderSqlExpr sqlOrder :: Parser SqlOrder sqlOrder = do dir <- optional (symbol "ASC" *> pure SqlAsc <|> symbol "DESC" *> pure SqlDesc ) nOrd <- optional (symbol "NULLS" *> symbol "FIRST" *> pure SqlNullsFirst <|> symbol "NULLS" *> symbol "LAST" *> pure SqlNullsLast ) pure (SqlOrder (maybe SqlAsc id dir) (maybe SqlNullsLast id nOrd)) typeExpr :: Parser DBType typeExpr = DBInt2 <$ symbol "SMALLINT" <|> DBInt4 <$ symbol "INT" <|> DBInt8 <$ symbol "BIGINT" <|> DBText <$ symbol "NTEXT" <|> DBDate <$ symbol "DATE" <|> numericType <|> floatType <|> binaryType <|> varbinaryType <|> ncharType <|> nvarcharType <|> timestamptzType <|> timestampType <|> timeType <|> bitType <|> customType where numericType = symbol "NUMERIC" *> ( mkNumericType <$> ( do mv <- optional (openParen *> number) case mv of Just v -> Just . (v, ) <$> optional (comma *> number) <* closeParen Nothing -> pure Nothing ) ) mkNumericType Nothing = DBNumeric 0 0 mkNumericType (Just (v , Nothing)) = DBNumeric (read v) 0 mkNumericType (Just (v, Just v')) = DBNumeric (read v) (read v') typeWithOptParam s d f p = symbol s *> fmap (maybe (f d) f) (optional (parens p)) typeWithOptParamNum s f = typeWithOptParam s 0 f (read <$> number) floatType = typeWithOptParamNum "FLOAT" DBFloat binaryType = typeWithOptParamNum "BINARY" DBBinary timestamptzType = typeWithOptParamNum "DATETIMEOFFSET" DBTimestamptz timestampType = typeWithOptParamNum "DATETIME2" DBTimestamp timeType = typeWithOptParamNum "TIME" DBTime bitType = typeWithOptParamNum "BIT" DBBit ncharType = typeWithOptParamNum "CHAR" DBChar nvarcharType = typeWithOptParam "NVARCHAR" (Right 0) DBVarchar ( Left Type.Max <$ symbol "MAX" <|> Right . read <$> number ) varbinaryType = typeWithOptParam "VARBINARY" (Right 0) DBVarbinary ( Left Type.Max <$ symbol "MAX" <|> Right . read <$> number ) customType = undefined ordDir : : -- ordDir = undefined nullOrd : : -- nullOrd = undefined -- limit :: Parser SqlExpr -- limit = undefined defaultExpr :: Parser SqlExpr defaultExpr = symbol "DEFAULT" *> pure DefaultSqlExpr lexeme :: Parser a -> Parser a lexeme p = skipSpace *> p symbol :: Text -> Parser Text symbol = lexeme . string identifier :: Parser String identifier = lexeme (many1 (letter <|> char '_')) word : : Parser String -- word = lexeme (many1 letter) number :: Parser String number = lexeme (many1 digit) singleton :: a -> [a] singleton a = [a] openParen :: Parser () openParen = void (lexeme (char '(')) closeParen :: Parser () closeParen = void (lexeme (char ')')) openBracket :: Parser () openBracket = void (lexeme (char '[')) closeBracket :: Parser () closeBracket = void (lexeme (char ']')) doubleQuote :: Parser () doubleQuote = void (lexeme (char '"')) singleQuote :: Parser () singleQuote = void (lexeme (char '\'')) between :: Parser b -> Parser c -> Parser a -> Parser a between open close p = do open *> (p <* close) doubleQuoted :: Parser a -> Parser a doubleQuoted = between doubleQuote doubleQuote quoted :: Parser a -> Parser a quoted = between singleQuote singleQuote parens :: Parser a -> Parser a parens = between openParen closeParen brackets :: Parser a -> Parser a brackets = between openBracket closeBracket void :: Parser a -> Parser () void a = a *> pure () sepByComma :: Parser a -> Parser [a] sepByComma p = p `sepBy` comma comma :: Parser Char comma = lexeme (char ',') literal :: Parser LitSql literal = symbol "NULL" *> pure NullSql <|> symbol "DEFAULT" *> pure DefaultSql <|> boolLit <|> stringLit <|> oidLit <|> integerLit -- <|> -- doubleLit where boolLit = ( symbol "TRUE" <|> quoted (symbol "true") ) *> pure (BoolSql True) <|> ( symbol "FALSE" <|> quoted (symbol "false") ) *> pure (BoolSql False) integerLit = (IntegerSql . read . concat) <$> many1 number stringLit = (StringSql . T.pack) <$> ( skipSpace *> char '\'' *> manyTill anyChar (char '\'') ) oidLit = (StringSql . T.pack) <$> quoted (doubleQuoted identifier) data SizeInfo = SizeInfo { szCharacterLength :: Maybe Integer , szNumericPrecision :: Maybe Integer , szNumericScale :: Maybe Integer , szDateTimePrecision :: Maybe Integer , szIntervalPrecision :: Maybe Integer } deriving (Show, Eq) defSizeInfo :: SizeInfo defSizeInfo = SizeInfo Nothing Nothing Nothing Nothing Nothing parseMSSQLType :: String -> Bool -> SizeInfo -> String -> DBType parseMSSQLType scn nullInfo sz = wrapNullable nullInfo . go where go "smallint" = DBInt2 go "int" = DBInt4 go "bigint" = DBInt8 go "numeric" = case (,) <$> szNumericPrecision sz <*> szNumericScale sz of Just (pr, sc) -> DBNumeric pr sc _ -> error "Panic: numeric must specify precision and scale" go "float" = case szNumericPrecision sz of Nothing -> DBFloat 24 Just v -> DBFloat v go "nchar" = case szCharacterLength sz of Just v -> DBChar v _ -> error "Panic: character must specify a size" go "nvarchar (max)" = DBVarchar (Left Type.Max) go "nvarchar" = case szCharacterLength sz of Just v -> DBVarchar (Right v) _ -> error "Panic: varying character must specify a size" go "varchar" = case szCharacterLength sz of Just v -> DBVarchar (Right v) _ -> error "Panic: varying character must specify a size" go "ntext" = DBText go "binary" = case szCharacterLength sz of -- TODO: Verify this check Just v -> DBBinary v _ -> error "Panic: Binary type must specify a size or length" go "varbinary (max)" = DBVarbinary (Left Type.Max) go "varbinary" = DBVarbinary (Left Type.Max) -- TODO : Check for sz part? go "image" = DBVarbinary (Left Type.Max) go "datetimeoffset" = case szDateTimePrecision sz of Just v -> DBTimestamptz v Nothing -> DBTimestamptz 6 go "datetime2" = case szDateTimePrecision sz of Just v -> DBTimestamp v Nothing -> DBTimestamp 6 go "datetime" = case szDateTimePrecision sz of Just v -> DBTimestamp v Nothing -> DBTimestamp 6 go "smalldatetime" = case szDateTimePrecision sz of Just v -> DBTimestamp v Nothing -> DBTimestamp 6 go "date" = DBDate go "time" = case szDateTimePrecision sz of Just v -> DBTime v Nothing -> DBTime 6 go "bit" = case szCharacterLength sz of Just v -> DBBit v _ -> DBBit 1 go "tinyint" = DBInt2 go "smallmoney" = DBText go "money" = DBText go "xml" = DBText go "uniqueidentifier" = DBUuid go "char" = DBBinary 16 go "decimal" = DBNumeric 0 32 -- Custom Type go t = DBCustomType (T.pack scn) (DBTypeName (T.pack t) []) -- Add Nullable info wrapNullable True a = DBNullable a wrapNullable False a = a data ExpWrap = Expr SqlExpr | Op BinOp deriving (Show, Eq) data Assoc = LeftAssoc | RightAssoc deriving Show
null
https://raw.githubusercontent.com/byteally/dbrecord/991efe9a293532ee9242b3e9a26434cf16f5b2a0/dbrecord-mssql-odbc/src/DBRecord/MSSQL/Internal/Sql/Parser.hs
haskell
# LANGUAGE OverloadedStrings # <* endOfInput transformBinExprByPrecedence NOTE: ROW(s) are also possible here aggrFunSqlExpr <|> ParamSqlExpr ExistsSqlExpr TODO: FunSqlExpr needs to be changed or we need to intercalate a separator. obys < - orderBy obys ) obys <- orderBy obys) -- TODO: Identify prefix operators prefixOp = symbol "NOT" *> pure "NOT" NOTE: missing custom prefixes NOTE: missing custom postfixes symbol "::" <|> Maybe Maybe ordDir = undefined nullOrd = undefined limit :: Parser SqlExpr limit = undefined word = lexeme (many1 letter) <|> doubleLit TODO: Verify this check TODO : Check for sz part? Custom Type Add Nullable info
# LANGUAGE TupleSections # module DBRecord.MSSQL.Internal.Sql.Parser ( sqlExpr , parseMSSQLType , SizeInfo (..) , defSizeInfo ) where import DBRecord.Internal.Sql.DML import Data.Attoparsec.Text hiding (number) import qualified Data.Text as T import Data.Text (Text) import Control.Applicative import qualified Debug.Trace as DT import qualified Data.List.NonEmpty as NEL import DBRecord.Internal.DBTypes (DBType (..), DBTypeName (..)) import Data.Functor (($>)) import qualified DBRecord.Internal.Types as Type sqlExpr :: Parser SqlExpr sqlExpr = ( postfixOrWindowExpr <|> binSqlExpr <|> compositeExpr < | > prefixSqlExpr <|> termSqlExpr ) where binSqlExpr = do e1 <- termSqlExpr b <- Left <$> binOp <|> Right <$> (symbol "::" $> ()) case b of Right _ -> do ty <- typeExpr pure (CastSqlExpr ty e1) Left binOpRes -> do e2 <- sqlExpr postfixOrWindowExpr = do e <- binSqlExpr <|> prefixSqlExpr <|> termSqlExpr epRes <- eitherP (symbol "OVER" *> anonWindowExpr e ) postfixOp case epRes of Left w -> pure w Right op -> pure (PostfixSqlExpr op e) anonWindowExpr e = DT.traceShow (show e) $ parens $ do pbys <- optional ( symbol "PARTITION" *> symbol "BY" *> sepBy1 sqlExpr comma ) ords <- orderBy pure (AnonWindowSqlExpr (maybe [] id pbys) ords e) prefixSqlExpr = do op <- prefixOp e <- sqlExpr pure (PrefixSqlExpr op e) termSqlExpr :: Parser SqlExpr termSqlExpr = arraySqlExpr < | > defaultExpr <|> placeholderExpr <|> castExpr <|> caseExpr <|> ParensSqlExpr <$> (parens sqlExpr) <|> ListSqlExpr <$> parens (sepByComma sqlExpr) <|> FunSqlExpr <$> funcName <*> parens (sepByComma sqlExpr) <|> ColumnSqlExpr <$> column <|> ConstSqlExpr <$> literal caseExpr :: Parser SqlExpr caseExpr = do _ <- symbol "CASE" cbs <- some $ do _ <- symbol "WHEN" c <- sqlExpr _ <- symbol "THEN" b <- sqlExpr return (c, b) me <- option Nothing (Just <$> (symbol "ELSE" *> sqlExpr)) _ <- symbol "END" pure (CaseSqlExpr (NEL.fromList cbs) me) funcName :: Parser String funcName = do funNameQual <- identifier <|> brackets identifier funName <- (singleton <$> (char '.' *> (brackets identifier <|> identifier))) <|> pure [] pure (concat $ funNameQual : funName) aggrFunSqlExpr : : Parser SqlExpr aggrFunSqlExpr = do n < - funcName ( es , obys ) < - parens $ do es < - sepByComma sqlExpr pure ( AggrFunSqlExpr n es obys ) arraySqlExpr : : Parser SqlExpr arraySqlExpr = do _ < - symbol " ARRAY " es < - brackets ( sepByComma sqlExpr ) pure ( ArraySqlExpr es ) aggrFunSqlExpr :: Parser SqlExpr aggrFunSqlExpr = do n <- funcName (es, obys) <- parens $ do es <- sepByComma sqlExpr pure (AggrFunSqlExpr n es obys) arraySqlExpr :: Parser SqlExpr arraySqlExpr = do _ <- symbol "ARRAY" es <- brackets (sepByComma sqlExpr) pure (ArraySqlExpr es) -} castExpr :: Parser SqlExpr castExpr = do _ <- symbol "CAST" (e, typ) <- parens $ do e <- sqlExpr _ <- symbol "AS" typ <- typeExpr pure (e, typ) pure (CastSqlExpr typ e) Note : For MSSQL , Columns can also be of the form [ foo ] , " foo " , or just foo . column :: Parser SqlColumn column = do pieces <- sepBy1 columnPiece (char '.') pure (SqlColumn (map T.pack pieces)) where columnPiece = doubleQuoted identifier <|> brackets identifier <|> identifier prefixOp : : Parser String prefixOp :: Parser UnOp prefixOp = symbol "NOT" $> OpNot <|> symbol "LENGTH" $> OpLength <|> symbol "-" $> OpNegate <|> symbol "LOWER" $> OpLower <|> symbol "UPPER" $> OpUpper <|> Added to support MSSQL + prefix Op symbol "+" $> OpPositive <|> symbol "~" $> OpBitwiseNot postfixOp :: Parser UnOp postfixOp = symbol "IS" *> symbol "NULL" $> OpIsNull <|> symbol "IS" *> symbol "NOT" *> symbol "NULL" $> OpIsNotNull binOp :: Parser BinOp binOp = symbol "+" $> OpPlus <|> symbol "=" $> OpEq <|> symbol "<>" $> OpNotEq <|> symbol "!=" $> OpNotEq <|> symbol "-" $> OpMinus <|> symbol ">=" $> OpGtEq <|> symbol "<=" $> OpLtEq <|> symbol ">" $> OpGt <|> symbol "<" $> OpLt <|> symbol "!<" $> OpNotLt <|> symbol "!>" $> OpNotGt <|> symbol "||" $> OpCat <|> symbol "AND" $> OpAnd <|> symbol "OR" $> OpOr <|> symbol "LIKE" $> OpLike <|> symbol "IN" $> OpIn <|> symbol "ALL" $> OpAll <|> symbol "ANY" $> OpAny <|> symbol "EXISTS" $> OpExists <|> symbol "SOME" $> OpSome <|> symbol "BETWEEN" $> OpBetween <|> symbol "/" $> OpDiv <|> symbol "%" $> OpMod <|> symbol "*" $> OpMul <|> symbol "~" $> OpBitNot <|> symbol "&" $> OpBitAnd <|> symbol "|" $> OpBitOr <|> symbol "^" $> OpBitXor <|> symbol "AT" *> symbol "TIME" *> symbol "ZONE" $> OpAtTimeZone orderBy = option [] (symbol "KORDER" *> symbol "BY" *> sepBy1 ord comma) ord = do (,) <$> sqlExpr <*> sqlOrder placeholderExpr :: Parser SqlExpr placeholderExpr = symbol "?" *> pure PlaceHolderSqlExpr sqlOrder :: Parser SqlOrder sqlOrder = do dir <- optional (symbol "ASC" *> pure SqlAsc <|> symbol "DESC" *> pure SqlDesc ) nOrd <- optional (symbol "NULLS" *> symbol "FIRST" *> pure SqlNullsFirst <|> symbol "NULLS" *> symbol "LAST" *> pure SqlNullsLast ) pure (SqlOrder (maybe SqlAsc id dir) (maybe SqlNullsLast id nOrd)) typeExpr :: Parser DBType typeExpr = DBInt2 <$ symbol "SMALLINT" <|> DBInt4 <$ symbol "INT" <|> DBInt8 <$ symbol "BIGINT" <|> DBText <$ symbol "NTEXT" <|> DBDate <$ symbol "DATE" <|> numericType <|> floatType <|> binaryType <|> varbinaryType <|> ncharType <|> nvarcharType <|> timestamptzType <|> timestampType <|> timeType <|> bitType <|> customType where numericType = symbol "NUMERIC" *> ( mkNumericType <$> ( do mv <- optional (openParen *> number) case mv of Just v -> Just . (v, ) <$> optional (comma *> number) <* closeParen Nothing -> pure Nothing ) ) mkNumericType Nothing = DBNumeric 0 0 mkNumericType (Just (v , Nothing)) = DBNumeric (read v) 0 mkNumericType (Just (v, Just v')) = DBNumeric (read v) (read v') typeWithOptParam s d f p = symbol s *> fmap (maybe (f d) f) (optional (parens p)) typeWithOptParamNum s f = typeWithOptParam s 0 f (read <$> number) floatType = typeWithOptParamNum "FLOAT" DBFloat binaryType = typeWithOptParamNum "BINARY" DBBinary timestamptzType = typeWithOptParamNum "DATETIMEOFFSET" DBTimestamptz timestampType = typeWithOptParamNum "DATETIME2" DBTimestamp timeType = typeWithOptParamNum "TIME" DBTime bitType = typeWithOptParamNum "BIT" DBBit ncharType = typeWithOptParamNum "CHAR" DBChar nvarcharType = typeWithOptParam "NVARCHAR" (Right 0) DBVarchar ( Left Type.Max <$ symbol "MAX" <|> Right . read <$> number ) varbinaryType = typeWithOptParam "VARBINARY" (Right 0) DBVarbinary ( Left Type.Max <$ symbol "MAX" <|> Right . read <$> number ) customType = undefined ordDir : : nullOrd : : defaultExpr :: Parser SqlExpr defaultExpr = symbol "DEFAULT" *> pure DefaultSqlExpr lexeme :: Parser a -> Parser a lexeme p = skipSpace *> p symbol :: Text -> Parser Text symbol = lexeme . string identifier :: Parser String identifier = lexeme (many1 (letter <|> char '_')) word : : Parser String number :: Parser String number = lexeme (many1 digit) singleton :: a -> [a] singleton a = [a] openParen :: Parser () openParen = void (lexeme (char '(')) closeParen :: Parser () closeParen = void (lexeme (char ')')) openBracket :: Parser () openBracket = void (lexeme (char '[')) closeBracket :: Parser () closeBracket = void (lexeme (char ']')) doubleQuote :: Parser () doubleQuote = void (lexeme (char '"')) singleQuote :: Parser () singleQuote = void (lexeme (char '\'')) between :: Parser b -> Parser c -> Parser a -> Parser a between open close p = do open *> (p <* close) doubleQuoted :: Parser a -> Parser a doubleQuoted = between doubleQuote doubleQuote quoted :: Parser a -> Parser a quoted = between singleQuote singleQuote parens :: Parser a -> Parser a parens = between openParen closeParen brackets :: Parser a -> Parser a brackets = between openBracket closeBracket void :: Parser a -> Parser () void a = a *> pure () sepByComma :: Parser a -> Parser [a] sepByComma p = p `sepBy` comma comma :: Parser Char comma = lexeme (char ',') literal :: Parser LitSql literal = symbol "NULL" *> pure NullSql <|> symbol "DEFAULT" *> pure DefaultSql <|> boolLit <|> stringLit <|> oidLit <|> where boolLit = ( symbol "TRUE" <|> quoted (symbol "true") ) *> pure (BoolSql True) <|> ( symbol "FALSE" <|> quoted (symbol "false") ) *> pure (BoolSql False) integerLit = (IntegerSql . read . concat) <$> many1 number stringLit = (StringSql . T.pack) <$> ( skipSpace *> char '\'' *> manyTill anyChar (char '\'') ) oidLit = (StringSql . T.pack) <$> quoted (doubleQuoted identifier) data SizeInfo = SizeInfo { szCharacterLength :: Maybe Integer , szNumericPrecision :: Maybe Integer , szNumericScale :: Maybe Integer , szDateTimePrecision :: Maybe Integer , szIntervalPrecision :: Maybe Integer } deriving (Show, Eq) defSizeInfo :: SizeInfo defSizeInfo = SizeInfo Nothing Nothing Nothing Nothing Nothing parseMSSQLType :: String -> Bool -> SizeInfo -> String -> DBType parseMSSQLType scn nullInfo sz = wrapNullable nullInfo . go where go "smallint" = DBInt2 go "int" = DBInt4 go "bigint" = DBInt8 go "numeric" = case (,) <$> szNumericPrecision sz <*> szNumericScale sz of Just (pr, sc) -> DBNumeric pr sc _ -> error "Panic: numeric must specify precision and scale" go "float" = case szNumericPrecision sz of Nothing -> DBFloat 24 Just v -> DBFloat v go "nchar" = case szCharacterLength sz of Just v -> DBChar v _ -> error "Panic: character must specify a size" go "nvarchar (max)" = DBVarchar (Left Type.Max) go "nvarchar" = case szCharacterLength sz of Just v -> DBVarchar (Right v) _ -> error "Panic: varying character must specify a size" go "varchar" = case szCharacterLength sz of Just v -> DBVarchar (Right v) _ -> error "Panic: varying character must specify a size" go "ntext" = DBText Just v -> DBBinary v _ -> error "Panic: Binary type must specify a size or length" go "varbinary (max)" = DBVarbinary (Left Type.Max) go "image" = DBVarbinary (Left Type.Max) go "datetimeoffset" = case szDateTimePrecision sz of Just v -> DBTimestamptz v Nothing -> DBTimestamptz 6 go "datetime2" = case szDateTimePrecision sz of Just v -> DBTimestamp v Nothing -> DBTimestamp 6 go "datetime" = case szDateTimePrecision sz of Just v -> DBTimestamp v Nothing -> DBTimestamp 6 go "smalldatetime" = case szDateTimePrecision sz of Just v -> DBTimestamp v Nothing -> DBTimestamp 6 go "date" = DBDate go "time" = case szDateTimePrecision sz of Just v -> DBTime v Nothing -> DBTime 6 go "bit" = case szCharacterLength sz of Just v -> DBBit v _ -> DBBit 1 go "tinyint" = DBInt2 go "smallmoney" = DBText go "money" = DBText go "xml" = DBText go "uniqueidentifier" = DBUuid go "char" = DBBinary 16 go "decimal" = DBNumeric 0 32 go t = DBCustomType (T.pack scn) (DBTypeName (T.pack t) []) wrapNullable True a = DBNullable a wrapNullable False a = a data ExpWrap = Expr SqlExpr | Op BinOp deriving (Show, Eq) data Assoc = LeftAssoc | RightAssoc deriving Show
667d3258ba2418d79222dce0b73b2d3afcff1dabfd8a9ac5267dda3ed8bf3d9d
SNePS/SNePS2
outnet.lisp
-*- Mode : Lisp ; Syntax : Common - Lisp ; Package : SNEPS ; Base : 10 -*- Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : outnet.lisp , v 1.2 2013/08/28 19:07:25 shapiro Exp $ ;; This file is part of SNePS. $ BEGIN LICENSE$ The contents of this file are subject to the University at Buffalo Public License Version 1.0 ( the " License " ) ; you may ;;; not use this file except in compliance with the License. You ;;; may obtain a copy of the License at ;;; . edu/sneps/Downloads/ubpl.pdf. ;;; Software distributed under the License is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express ;;; or implied. See the License for the specific language gov ;;; erning rights and limitations under the License. ;;; The Original Code is SNePS 2.8 . ;;; The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . ;;; Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :sneps) ; ========================================================================== ; ; outnet ; ------ ; ; arguments : file - <filename> ; ; returns : <nothing> ; ; description : "User function" to be called from SNePS environment. It dumps the current network to the FILE . ; ; side-effects : It prints a message. ; written : jgn 10/10/83 modified : ejm 06/01/84 ; ssc 02/13/87 njm 09/26/88 hc 29/06/93 ; hc 07/18/93 ; (defsnepscom outnet ((file) (top) t) (with-open-file (outunit (cl-user:sneps-translate file) :direction :output :if-does-not-exist :create :if-exists :new-version) (let ((*package* (find-package 'snepsul)) (*print-pretty* nil) (*print-level* nil) (*print-length* nil)) (format outunit "|SNePS network 2.7|~%") (outindices outunit) (outrelations outunit) (outpaths outunit) (outcontexts outunit) (outnodes outunit) (outsysvars outunit))) (format t "~%~%Network dumped to file: ~A~%" file) (values)) (defun outindices (outunit) (format outunit "~%;; Node/Context-ID indices:~%") (dolist (node-name-prefix '(b m v p tm tv tp)) (format outunit "~s " (get 'gennewnode node-name-prefix))) (format outunit "~s~%" (get 'gennewcontext 'c))) ; ; ; ; ========================================================================== ; outrelations ; ------------ ; ; arguments : outunit - <output port> ; ; returns : Sequence of relations ; ; description : Prints a list of the defined relations to ; the output port. ; ; nonlocal-vars : SNePS variable "relations" ; ; side-effects : Additions to output file. ; written : jgn 10/10/83 modified : hc 06/29/93 ; (defun outrelations (outunit) (let ((relations (value.sv 'relations))) (format outunit "~%~d ;; Relation definitions:" (length relations)) (dolist (relation relations) (print.r relation outunit)) (terpri outunit))) (defun outpaths (outunit) (let ((paths (remove-if-not #'(lambda (r) (get r :pathdef)) (value.sv 'relations)))) (format outunit "~%~d ;; Path definitions:" (length paths)) (dolist (path paths) (print-path.r path outunit)) (terpri outunit))) ; ; ; ; ========================================================================== ; ; outcontexts ; ----------- ; ; arguments : outunit - <output port> ; ; returns : Sequence of the current list of contexts ; ; nonlocal-vars : System variable "contexts" ; ; description : Prints a list of the network contexts to output port. ; ; side-effects : Additions to output file. ; written : njm 09/26/88 modified : hc 06/29/93 ; (defun outcontexts (outunit) (let ((contexts (allct))) (format outunit "~%~d ;; Context definitions:" (length contexts)) (dolist (context contexts) (print.ct context outunit)) (terpri outunit))) ; ; ; ; ========================================================================== ; ; outnodes ; -------- ; ; arguments : outunit - <output port> ; ; returns : Sequence of the current list of nodes ; ; nonlocal-vars : System variable "nodes" ; ; description : Prints a list of the network nodes to output port. ; ; side-effects : Additions to output file. ; written : jgn 10/10/83 modified : hc 06/29/93 ; hi 03/24/99 ; modification: Since (isless.n n1 n2) is true in case ; (> (order n1) (order n2)), then need to ; reverse the nodes list before printing it. This is mainly because read.n assigns orders ; according to the position of the node in the infile. HI , 3/24/99 . ; (defun outnodes (outunit) (let ((nodes (value.sv 'nodes))) (format outunit "~%~d ;; Node definitions:" (length nodes)) (dolist (node (reverse nodes)) (print.n node outunit)) (terpri outunit))) ; ; ; ========================================================================== ; ; outsysvars ; ---------- ; ; arguments : outunit - <output port> ; ; returns : Irrelevant, but returns a list of system ; variables. ; ; nonlocal-vars : The system variables ; ; description : Prints the values of the system variables ; to the output port. ; ; side-effects : Additions made to output file ; written : jgn 10/10/83 modified : hc 06/29/93 ; hi 03/28/99 out *nodes ; (defun outsysvars (outunit) (let ((variables (value.sv 'variables)) (excluded-variables '(;; context hashtable is unprintable and gets ;; automatically reconstructed: contexts ;; this is redundant because they get automatically ;; constructed by `inrelations': relations ;; are these any interesting? ;;command lastcommand errorcommand ))) (format outunit "~%~d ;; SNePSUL variable definitions:" (cl:- (length variables) (length excluded-variables))) (dolist (variable variables) (unless (member variable excluded-variables) (print.sv variable outunit))) (terpri outunit)))
null
https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/sneps/fns/outnet.lisp
lisp
Syntax : Common - Lisp ; Package : SNEPS ; Base : 10 -*- This file is part of SNePS. you may not use this file except in compliance with the License. You may obtain a copy of the License at . edu/sneps/Downloads/ubpl.pdf. or implied. See the License for the specific language gov erning rights and limitations under the License. ========================================================================== outnet ------ arguments : file - <filename> returns : <nothing> description : "User function" to be called from SNePS environment. side-effects : It prints a message. ssc 02/13/87 hc 07/18/93 ========================================================================== ------------ arguments : outunit - <output port> returns : Sequence of relations description : Prints a list of the defined relations to the output port. nonlocal-vars : SNePS variable "relations" side-effects : Additions to output file. ========================================================================== outcontexts ----------- arguments : outunit - <output port> returns : Sequence of the current list of contexts nonlocal-vars : System variable "contexts" description : Prints a list of the network contexts to output port. side-effects : Additions to output file. ========================================================================== outnodes -------- arguments : outunit - <output port> returns : Sequence of the current list of nodes nonlocal-vars : System variable "nodes" description : Prints a list of the network nodes to output port. side-effects : Additions to output file. hi 03/24/99 modification: Since (isless.n n1 n2) is true in case (> (order n1) (order n2)), then need to reverse the nodes list before printing it. according to the position of the node in the infile. ========================================================================== outsysvars ---------- arguments : outunit - <output port> returns : Irrelevant, but returns a list of system variables. nonlocal-vars : The system variables description : Prints the values of the system variables to the output port. side-effects : Additions made to output file hi 03/28/99 out *nodes context hashtable is unprintable and gets automatically reconstructed: this is redundant because they get automatically constructed by `inrelations': are these any interesting? command lastcommand errorcommand
Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : outnet.lisp , v 1.2 2013/08/28 19:07:25 shapiro Exp $ $ BEGIN LICENSE$ The contents of this file are subject to the University at Software distributed under the License is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express The Original Code is SNePS 2.8 . The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :sneps) It dumps the current network to the FILE . written : jgn 10/10/83 modified : ejm 06/01/84 njm 09/26/88 hc 29/06/93 (defsnepscom outnet ((file) (top) t) (with-open-file (outunit (cl-user:sneps-translate file) :direction :output :if-does-not-exist :create :if-exists :new-version) (let ((*package* (find-package 'snepsul)) (*print-pretty* nil) (*print-level* nil) (*print-length* nil)) (format outunit "|SNePS network 2.7|~%") (outindices outunit) (outrelations outunit) (outpaths outunit) (outcontexts outunit) (outnodes outunit) (outsysvars outunit))) (format t "~%~%Network dumped to file: ~A~%" file) (values)) (defun outindices (outunit) (format outunit "~%;; Node/Context-ID indices:~%") (dolist (node-name-prefix '(b m v p tm tv tp)) (format outunit "~s " (get 'gennewnode node-name-prefix))) (format outunit "~s~%" (get 'gennewcontext 'c))) outrelations written : jgn 10/10/83 modified : hc 06/29/93 (defun outrelations (outunit) (let ((relations (value.sv 'relations))) (format outunit "~%~d ;; Relation definitions:" (length relations)) (dolist (relation relations) (print.r relation outunit)) (terpri outunit))) (defun outpaths (outunit) (let ((paths (remove-if-not #'(lambda (r) (get r :pathdef)) (value.sv 'relations)))) (format outunit "~%~d ;; Path definitions:" (length paths)) (dolist (path paths) (print-path.r path outunit)) (terpri outunit))) written : njm 09/26/88 modified : hc 06/29/93 (defun outcontexts (outunit) (let ((contexts (allct))) (format outunit "~%~d ;; Context definitions:" (length contexts)) (dolist (context contexts) (print.ct context outunit)) (terpri outunit))) written : jgn 10/10/83 modified : hc 06/29/93 This is mainly because read.n assigns orders HI , 3/24/99 . (defun outnodes (outunit) (let ((nodes (value.sv 'nodes))) (format outunit "~%~d ;; Node definitions:" (length nodes)) (dolist (node (reverse nodes)) (print.n node outunit)) (terpri outunit))) written : jgn 10/10/83 modified : hc 06/29/93 (defun outsysvars (outunit) (let ((variables (value.sv 'variables)) (excluded-variables contexts relations ))) (format outunit "~%~d ;; SNePSUL variable definitions:" (cl:- (length variables) (length excluded-variables))) (dolist (variable variables) (unless (member variable excluded-variables) (print.sv variable outunit))) (terpri outunit)))
98fcf39a6812466eec1732134c9fbbcb01b18fc59bc4c31080346f4aa82d0dc0
gar1t/lambdapad
lpad_cmd.erl
Copyright 2014 < > %%% Licensed under the Apache License , Version 2.0 ( the " License " ) ; %%% you may not use this file except in compliance with the License. %%% You may obtain a copy of the License at %%% %%% -2.0 %%% %%% Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an " AS IS " BASIS , %%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %%% See the License for the specific language governing permissions and %%% limitations under the License. -module(lpad_cmd). -export([run/2, run/3, run/4]). run(Exe, Args) -> run(Exe, Args, [], infinity). run(Exe, Args, Options) -> run(Exe, Args, clean_options(Options), infinity). -define(valid_timeout(T), T == infinity; is_integer(T)). run(Exe, Args, Options, Timeout) when ?valid_timeout(Timeout) -> Self = self(), FullExe = find_exe(Exe), CleanOptions = clean_options(Options), spawn(fun() -> start_port(FullExe, Args, CleanOptions, Timeout, Self) end), receive {N, Out} when is_integer(N) -> {N, Out}; {error, Err} -> error({start_port, {Exe, Args, Options, Timeout}, Err}) end. clean_options(Options) -> clean_env_option(Options). clean_env_option(Options) -> handle_env_option(proplists:get_value(env, Options), Options). handle_env_option(undefined, Options) -> Options; handle_env_option(Env, Options) -> [{env, env_to_strings(Env)}|proplists:delete(env, Options)]. env_to_strings(Env) -> [{to_string(Name), to_string(Val)} || {Name, Val} <- Env]. to_string(L) when is_list(L) -> L; to_string(B) when is_binary(B) -> binary_to_list(B). find_exe(Exe) -> handle_exe_is_file(filelib:is_file(Exe), Exe). handle_exe_is_file(true, Exe) -> Exe; handle_exe_is_file(false, Exe) -> handle_os_find_exe(os:find_executable(Exe), Exe). handle_os_find_exe(false, Exe) -> error({bad_exe, Exe}); handle_os_find_exe(FullExe, _Exe) -> FullExe. start_port(Exe, Args, Options, Timeout, From) -> try open_port({spawn_executable, Exe}, spawn_opts(Args, Options)) of Port -> port_loop(Port, From, Timeout, []) catch error:Err -> send_error(From, Err) end. spawn_opts(Args, Options) -> [{args, Args}, stderr_to_stdout, exit_status | Options]. port_loop(Port, From, Timeout, AccOut) -> TimeoutRef = schedule_next_timeout(Timeout), receive {Port, {data, Data}} -> cancel_timeout(TimeoutRef), port_loop(Port, From, Timeout, [Data|AccOut]); {Port, {exit_status, Exit}} -> cancel_timeout(TimeoutRef), send_result(From, Exit, lists:reverse(AccOut)); timeout -> send_error(From, {timeout, lists:reverse(AccOut)}) end. schedule_next_timeout(infinity) -> undefined; schedule_next_timeout(Timeout) -> erlang:send_after(Timeout, self(), timeout). cancel_timeout(undefined) -> ok; cancel_timeout(TimeoutRef) -> erlang:cancel_timer(TimeoutRef). send_result(Dest, Exit, Out) -> erlang:send(Dest, {Exit, Out}). send_error(Dest, Err) -> erlang:send(Dest, {error, Err}).
null
https://raw.githubusercontent.com/gar1t/lambdapad/483b67694723923a82fc699aa37d580d035bd420/src/lpad_cmd.erl
erlang
you may not use this file except in compliance with the License. You may obtain a copy of the License at -2.0 Unless required by applicable law or agreed to in writing, software WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Copyright 2014 < > Licensed under the Apache License , Version 2.0 ( the " License " ) ; distributed under the License is distributed on an " AS IS " BASIS , -module(lpad_cmd). -export([run/2, run/3, run/4]). run(Exe, Args) -> run(Exe, Args, [], infinity). run(Exe, Args, Options) -> run(Exe, Args, clean_options(Options), infinity). -define(valid_timeout(T), T == infinity; is_integer(T)). run(Exe, Args, Options, Timeout) when ?valid_timeout(Timeout) -> Self = self(), FullExe = find_exe(Exe), CleanOptions = clean_options(Options), spawn(fun() -> start_port(FullExe, Args, CleanOptions, Timeout, Self) end), receive {N, Out} when is_integer(N) -> {N, Out}; {error, Err} -> error({start_port, {Exe, Args, Options, Timeout}, Err}) end. clean_options(Options) -> clean_env_option(Options). clean_env_option(Options) -> handle_env_option(proplists:get_value(env, Options), Options). handle_env_option(undefined, Options) -> Options; handle_env_option(Env, Options) -> [{env, env_to_strings(Env)}|proplists:delete(env, Options)]. env_to_strings(Env) -> [{to_string(Name), to_string(Val)} || {Name, Val} <- Env]. to_string(L) when is_list(L) -> L; to_string(B) when is_binary(B) -> binary_to_list(B). find_exe(Exe) -> handle_exe_is_file(filelib:is_file(Exe), Exe). handle_exe_is_file(true, Exe) -> Exe; handle_exe_is_file(false, Exe) -> handle_os_find_exe(os:find_executable(Exe), Exe). handle_os_find_exe(false, Exe) -> error({bad_exe, Exe}); handle_os_find_exe(FullExe, _Exe) -> FullExe. start_port(Exe, Args, Options, Timeout, From) -> try open_port({spawn_executable, Exe}, spawn_opts(Args, Options)) of Port -> port_loop(Port, From, Timeout, []) catch error:Err -> send_error(From, Err) end. spawn_opts(Args, Options) -> [{args, Args}, stderr_to_stdout, exit_status | Options]. port_loop(Port, From, Timeout, AccOut) -> TimeoutRef = schedule_next_timeout(Timeout), receive {Port, {data, Data}} -> cancel_timeout(TimeoutRef), port_loop(Port, From, Timeout, [Data|AccOut]); {Port, {exit_status, Exit}} -> cancel_timeout(TimeoutRef), send_result(From, Exit, lists:reverse(AccOut)); timeout -> send_error(From, {timeout, lists:reverse(AccOut)}) end. schedule_next_timeout(infinity) -> undefined; schedule_next_timeout(Timeout) -> erlang:send_after(Timeout, self(), timeout). cancel_timeout(undefined) -> ok; cancel_timeout(TimeoutRef) -> erlang:cancel_timer(TimeoutRef). send_result(Dest, Exit, Out) -> erlang:send(Dest, {Exit, Out}). send_error(Dest, Err) -> erlang:send(Dest, {error, Err}).
ef4996c456d921ffde6114d273154cd04c3d6a2a998a6209ef3a35684b475e05
dyoo/whalesong
get-runtime.rkt
#lang racket/base ;; Function to get the runtime library. ;; The resulting Javascript will produce a file that loads : ;; ;; ;; jquery at the the toplevel HashTable at the toplevel ;; jsnums at the toplevel ;; ;; followed by the base library ;; (require racket/contract racket/runtime-path racket/port) (provide/contract [get-runtime (-> string?)]) (define-runtime-path base-path "runtime-src") ;; The order matters here. link needs to come near the top, because ;; the other modules below have some circular dependencies that are resolved ;; by link. (define files '( top.js ;; jquery is special: we need to make sure it's resilient against ;; multiple invokation and inclusion. jquery-protect-header.js jquery.js jquery-protect-footer.js js-numbers.js base64.js baselib.js baselib-dict.js baselib-frames.js baselib-loadscript.js baselib-unionfind.js baselib-equality.js baselib-format.js baselib-constants.js baselib-numbers.js baselib-lists.js baselib-vectors.js baselib-chars.js baselib-symbols.js baselib-paramz.js baselib-strings.js baselib-bytes.js hashes-header.js jshashtable-2.1_src.js llrbtree.js baselib-hashes.js hashes-footer.js baselib-regexps.js baselib-paths.js baselib-boxes.js baselib-placeholders.js baselib-keywords.js baselib-structs.js baselib-srclocs.js baselib-ports.js baselib-functions.js baselib-modules.js baselib-contmarks.js baselib-arity.js baselib-inspectors.js baselib-exceptions.js baselib-readergraph.js ;; baselib-check has to come after the definitions of types, ;; since it uses the type predicates immediately on init time. baselib-check.js baselib-primitives.js runtime.js)) (define (path->string p) (call-with-input-file p (lambda (ip) (port->string ip)))) (define text (apply string-append (map (lambda (n) (path->string (build-path base-path (symbol->string n)))) files))) (define (get-runtime) text)
null
https://raw.githubusercontent.com/dyoo/whalesong/636e0b4e399e4523136ab45ef4cd1f5a84e88cdc/whalesong/js-assembler/get-runtime.rkt
racket
Function to get the runtime library. jquery at the the toplevel jsnums at the toplevel followed by the base library The order matters here. link needs to come near the top, because the other modules below have some circular dependencies that are resolved by link. jquery is special: we need to make sure it's resilient against multiple invokation and inclusion. baselib-check has to come after the definitions of types, since it uses the type predicates immediately on init time.
#lang racket/base The resulting Javascript will produce a file that loads : HashTable at the toplevel (require racket/contract racket/runtime-path racket/port) (provide/contract [get-runtime (-> string?)]) (define-runtime-path base-path "runtime-src") (define files '( top.js jquery-protect-header.js jquery.js jquery-protect-footer.js js-numbers.js base64.js baselib.js baselib-dict.js baselib-frames.js baselib-loadscript.js baselib-unionfind.js baselib-equality.js baselib-format.js baselib-constants.js baselib-numbers.js baselib-lists.js baselib-vectors.js baselib-chars.js baselib-symbols.js baselib-paramz.js baselib-strings.js baselib-bytes.js hashes-header.js jshashtable-2.1_src.js llrbtree.js baselib-hashes.js hashes-footer.js baselib-regexps.js baselib-paths.js baselib-boxes.js baselib-placeholders.js baselib-keywords.js baselib-structs.js baselib-srclocs.js baselib-ports.js baselib-functions.js baselib-modules.js baselib-contmarks.js baselib-arity.js baselib-inspectors.js baselib-exceptions.js baselib-readergraph.js baselib-check.js baselib-primitives.js runtime.js)) (define (path->string p) (call-with-input-file p (lambda (ip) (port->string ip)))) (define text (apply string-append (map (lambda (n) (path->string (build-path base-path (symbol->string n)))) files))) (define (get-runtime) text)
f6c79eac67d22de40953fe23f5375f331525cd1daf9696166932789c3c83252a
IndiscriminateCoding/clarity
validation.ml
module Make (S : Semigroup.S) = struct open Either type 'a t = (S.t, 'a) Either.t include Applicative.Make(struct type nonrec 'a t = 'a t let pure = pure let map = map let ap f x = match f, x () with | Right f, Right x -> Right (f x) | Left a, Left b -> Left (S.append a b) | Left _ as l, _ | _, (Left _ as l) -> l end) let map_errors f = bimap f Fn.id let fail = _Left let fold = fold let maybe_errors = maybe_left let maybe_result = maybe_right external to_either : 'a t -> (S.t, 'a) Either.t = "%identity" external of_either : (S.t, 'a) Either.t -> 'a t = "%identity" end
null
https://raw.githubusercontent.com/IndiscriminateCoding/clarity/163c16249cb3f01c4244b80be39e9aad0b1ca325/lib/types/validation.ml
ocaml
module Make (S : Semigroup.S) = struct open Either type 'a t = (S.t, 'a) Either.t include Applicative.Make(struct type nonrec 'a t = 'a t let pure = pure let map = map let ap f x = match f, x () with | Right f, Right x -> Right (f x) | Left a, Left b -> Left (S.append a b) | Left _ as l, _ | _, (Left _ as l) -> l end) let map_errors f = bimap f Fn.id let fail = _Left let fold = fold let maybe_errors = maybe_left let maybe_result = maybe_right external to_either : 'a t -> (S.t, 'a) Either.t = "%identity" external of_either : (S.t, 'a) Either.t -> 'a t = "%identity" end
429d90feb635fea3af6c9c457a4045d0a97d3c14c93164c55da4f1657d5c4499
Bogdanp/racket-gui-easy
7GUI-7-cells.rkt
#lang racket/base (require (prefix-in p: pict) racket/class racket/format (prefix-in gui: racket/gui) racket/gui/easy racket/gui/easy/operator racket/list racket/match racket/port racket/string) ;; cell ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ") (define index (string->list alphabet)) (define cell-width 100) (define cell-height 30) (struct cell (formula content)) (define (make-cell-name row col) (string->symbol (~cell-name row col))) (define (~cell-name row col) (~a (string-ref alphabet col) row)) (define (~cell c) (cond [(cell-formula c) => (λ (e) (call-with-output-string (lambda (out) (write-char #\= out) (write e out))))] [else (cell-content c)])) (define (cell-pict c) (if (string=? (cell-content c) "") (p:rectangle cell-width cell-height) (p:clip (struct-copy p:pict (p:lc-superimpose (p:rectangle cell-width cell-height) (p:inset (p:text (cell-content c)) 5 0)) [width cell-width])))) (define (table-pict rows) (apply p:vl-append (for/list ([r (in-vector rows)]) (apply p:ht-append (for/list ([c (in-vector r)]) (cell-pict c)))))) ;; formula ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define ops (hasheq '+ + '- - '* * '/ /)) (define (parse-formula s) (with-handlers ([(λ (_) #t) (λ (_) #f)]) (call-with-input-string s read))) (define (formula-deps e) (remove-duplicates (match e [(? symbol? id) #:when (valid-cell-name? id) (list id)] [`(,(? symbol? op) ,e0 ,e1) #:when (hash-has-key? ops op) (append (formula-deps e0) (formula-deps e1))] [_ null]))) (define (eval-formula s e) (number->string (let help ([e e]) (match e [(? number?) e] [(? symbol? id) #:when (valid-cell-name? id) (define-values (row col) (parse-cell-name id)) (state-ref-num s row col)] [`(,(? symbol? op) ,e0 ,e1) #:when (hash-has-key? ops op) ((hash-ref ops op) (help e0) (help e1))] [_ 0])))) ;; state ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; deps: map of cell-name -> dependent cell-name cells : ( vectorof ( vectorof cell ? ) ) (struct state (deps cells)) (define/obs @state (state (hasheq) (for/vector ([_ (in-range 100)]) (for*/vector ([_ (in-range 26)]) (cell #f ""))))) (define (state-ref s row col) (vector-ref (vector-ref (state-cells s) row) col)) (define (state-ref-num s row col) (or (string->number (cell-content (state-ref s row col))) 0)) (define (track-cell-depends s cell-name depends) (define deps-removed (for/hash ([(cell ds) (in-hash (state-deps s))]) (values cell (remq cell-name ds)))) (define deps-added (for/fold ([res deps-removed]) ([d (in-list depends)]) (hash-update res d (λ (ds) (cons cell-name ds)) null))) (struct-copy state s [deps deps-added])) (define (set-cell! s row col the-cell) (vector-set! (vector-ref (state-cells s) row) col the-cell)) (define (change-cell! s row col content) (define cell-name (make-cell-name row col)) (define e (and (string-prefix? content "=") (parse-formula (substring content 1)))) (define c (cell e content)) (define new-s (track-cell-depends s cell-name (if e (formula-deps e) null))) (begin0 new-s (set-cell! new-s row col c) (update-cell! new-s row col))) (define (update-cell! s row col) (define cell-name (make-cell-name row col)) (define the-cell (vector-ref (vector-ref (state-cells s) row) col)) (define new-cell (struct-copy cell the-cell [content (cond [(cell-formula the-cell) => (λ (e) (eval-formula s e))] [else (cell-content the-cell)])])) (set-cell! s row col new-cell) (for ([dep (in-list (reverse (hash-ref (state-deps s) cell-name null)))]) (define-values (dep-row dep-col) (parse-cell-name dep)) (update-cell! s dep-row dep-col))) (define (parse-cell-name id) (match (symbol->string id) [(regexp #rx"^([A-Z])(0|[1-9][0-9]|[1-9])$" `(,_ ,col-name ,row)) (values (string->number row) (index-of index (string-ref col-name 0)))] [_ (values #f #f)])) (define (valid-cell-name? id) (define-values (row col) (parse-cell-name id)) (and row col)) ;; GUI ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define r (render (window #:title "Cells" #:size '(800 600) (pict-canvas (@state . ~> . state-cells) #:style '(hscroll vscroll) #:mixin (λ (%) (class % (inherit get-view-start init-auto-scrollbars) (super-new) (init-auto-scrollbars (* cell-width 26) (* 100 cell-height) 0 0) (define last-click-ts 0) (define/override (on-event e) (define x (send e get-x)) (define y (send e get-y)) (case (send e get-event-type) [(left-up) (when (< (- (send e get-time-stamp) last-click-ts) 250) (define-values (cx cy) (get-view-start)) (define ax (+ cx x)) (define ay (+ cy y)) (define row (quotient ay 30)) (define col (quotient ax 100)) (render-cell-changer r row col)) (set! last-click-ts (send e get-time-stamp))])))) table-pict)))) (define (render-cell-changer parent row col) (render (dialog #:title (~cell-name row col) (input #:min-size '(200 #f) (~cell (state-ref (obs-peek @state) row col)) (λ (event text) (case event [(input) (@state . <~ . (λ (s) (change-cell! s row col text)))] [(return) ((gui:application-quit-handler))])))) parent))
null
https://raw.githubusercontent.com/Bogdanp/racket-gui-easy/1410da641db95df783f2a5be7516414bc8224a61/examples/7GUI-7-cells.rkt
racket
cell ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; formula ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; state ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; deps: map of cell-name -> dependent cell-name GUI ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#lang racket/base (require (prefix-in p: pict) racket/class racket/format (prefix-in gui: racket/gui) racket/gui/easy racket/gui/easy/operator racket/list racket/match racket/port racket/string) (define alphabet "ABCDEFGHIJKLMNOPQRSTUVWXYZ") (define index (string->list alphabet)) (define cell-width 100) (define cell-height 30) (struct cell (formula content)) (define (make-cell-name row col) (string->symbol (~cell-name row col))) (define (~cell-name row col) (~a (string-ref alphabet col) row)) (define (~cell c) (cond [(cell-formula c) => (λ (e) (call-with-output-string (lambda (out) (write-char #\= out) (write e out))))] [else (cell-content c)])) (define (cell-pict c) (if (string=? (cell-content c) "") (p:rectangle cell-width cell-height) (p:clip (struct-copy p:pict (p:lc-superimpose (p:rectangle cell-width cell-height) (p:inset (p:text (cell-content c)) 5 0)) [width cell-width])))) (define (table-pict rows) (apply p:vl-append (for/list ([r (in-vector rows)]) (apply p:ht-append (for/list ([c (in-vector r)]) (cell-pict c)))))) (define ops (hasheq '+ + '- - '* * '/ /)) (define (parse-formula s) (with-handlers ([(λ (_) #t) (λ (_) #f)]) (call-with-input-string s read))) (define (formula-deps e) (remove-duplicates (match e [(? symbol? id) #:when (valid-cell-name? id) (list id)] [`(,(? symbol? op) ,e0 ,e1) #:when (hash-has-key? ops op) (append (formula-deps e0) (formula-deps e1))] [_ null]))) (define (eval-formula s e) (number->string (let help ([e e]) (match e [(? number?) e] [(? symbol? id) #:when (valid-cell-name? id) (define-values (row col) (parse-cell-name id)) (state-ref-num s row col)] [`(,(? symbol? op) ,e0 ,e1) #:when (hash-has-key? ops op) ((hash-ref ops op) (help e0) (help e1))] [_ 0])))) cells : ( vectorof ( vectorof cell ? ) ) (struct state (deps cells)) (define/obs @state (state (hasheq) (for/vector ([_ (in-range 100)]) (for*/vector ([_ (in-range 26)]) (cell #f ""))))) (define (state-ref s row col) (vector-ref (vector-ref (state-cells s) row) col)) (define (state-ref-num s row col) (or (string->number (cell-content (state-ref s row col))) 0)) (define (track-cell-depends s cell-name depends) (define deps-removed (for/hash ([(cell ds) (in-hash (state-deps s))]) (values cell (remq cell-name ds)))) (define deps-added (for/fold ([res deps-removed]) ([d (in-list depends)]) (hash-update res d (λ (ds) (cons cell-name ds)) null))) (struct-copy state s [deps deps-added])) (define (set-cell! s row col the-cell) (vector-set! (vector-ref (state-cells s) row) col the-cell)) (define (change-cell! s row col content) (define cell-name (make-cell-name row col)) (define e (and (string-prefix? content "=") (parse-formula (substring content 1)))) (define c (cell e content)) (define new-s (track-cell-depends s cell-name (if e (formula-deps e) null))) (begin0 new-s (set-cell! new-s row col c) (update-cell! new-s row col))) (define (update-cell! s row col) (define cell-name (make-cell-name row col)) (define the-cell (vector-ref (vector-ref (state-cells s) row) col)) (define new-cell (struct-copy cell the-cell [content (cond [(cell-formula the-cell) => (λ (e) (eval-formula s e))] [else (cell-content the-cell)])])) (set-cell! s row col new-cell) (for ([dep (in-list (reverse (hash-ref (state-deps s) cell-name null)))]) (define-values (dep-row dep-col) (parse-cell-name dep)) (update-cell! s dep-row dep-col))) (define (parse-cell-name id) (match (symbol->string id) [(regexp #rx"^([A-Z])(0|[1-9][0-9]|[1-9])$" `(,_ ,col-name ,row)) (values (string->number row) (index-of index (string-ref col-name 0)))] [_ (values #f #f)])) (define (valid-cell-name? id) (define-values (row col) (parse-cell-name id)) (and row col)) (define r (render (window #:title "Cells" #:size '(800 600) (pict-canvas (@state . ~> . state-cells) #:style '(hscroll vscroll) #:mixin (λ (%) (class % (inherit get-view-start init-auto-scrollbars) (super-new) (init-auto-scrollbars (* cell-width 26) (* 100 cell-height) 0 0) (define last-click-ts 0) (define/override (on-event e) (define x (send e get-x)) (define y (send e get-y)) (case (send e get-event-type) [(left-up) (when (< (- (send e get-time-stamp) last-click-ts) 250) (define-values (cx cy) (get-view-start)) (define ax (+ cx x)) (define ay (+ cy y)) (define row (quotient ay 30)) (define col (quotient ax 100)) (render-cell-changer r row col)) (set! last-click-ts (send e get-time-stamp))])))) table-pict)))) (define (render-cell-changer parent row col) (render (dialog #:title (~cell-name row col) (input #:min-size '(200 #f) (~cell (state-ref (obs-peek @state) row col)) (λ (event text) (case event [(input) (@state . <~ . (λ (s) (change-cell! s row col text)))] [(return) ((gui:application-quit-handler))])))) parent))
29a341e8a9fd4e83693913842b53579f6038eec2c7288531dc13df0940dc0964
ocsigen/js_of_ocaml
ocaml_version.ml
Js_of_ocaml compiler * / * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open! Stdlib type t = int list let split_char ~sep p = let len = String.length p in let rec split beg cur = if cur >= len then if cur - beg > 0 then [ String.sub p ~pos:beg ~len:(cur - beg) ] else [] else if sep p.[cur] then String.sub p ~pos:beg ~len:(cur - beg) :: split (cur + 1) (cur + 1) else split beg (cur + 1) in split 0 0 let split v = match split_char ~sep:(function | '+' | '-' | '~' -> true | _ -> false) v with | [] -> assert false | x :: _ -> List.map (split_char ~sep:(function | '.' -> true | _ -> false) x) ~f:int_of_string let current = split Sys.ocaml_version let compint (a : int) b = compare a b let rec compare v v' = match v, v' with | [ x ], [ y ] -> compint x y | [], [] -> 0 | [], y :: _ -> compint 0 y | x :: _, [] -> compint x 0 | x :: xs, y :: ys -> ( match compint x y with | 0 -> compare xs ys | n -> n) let v = match current with | 4 :: 8 :: _ -> `V4_08 | 4 :: 9 :: _ -> `V4_09 | 4 :: 10 :: _ -> `V4_10 | 4 :: 11 :: _ -> `V4_11 | 4 :: 12 :: _ -> `V4_12 | 4 :: 13 :: _ -> `V4_13 | 4 :: 14 :: _ -> `V4_14 | 5 :: 0 :: _ -> `V5_00 | 5 :: 1 :: _ -> `V5_01 | _ -> if compare current [ 4; 4 ] < 0 then failwith "OCaml version unsupported. Upgrade to OCaml 4.08 or newer." else ( assert (compare current [ 5; 1 ] >= 0); failwith "OCaml version unsupported. Upgrade js_of_ocaml.")
null
https://raw.githubusercontent.com/ocsigen/js_of_ocaml/0fd9c6d715ce5e47ae1bf29f13e33f10c1eeebdd/compiler/lib/ocaml_version.ml
ocaml
Js_of_ocaml compiler * / * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) open! Stdlib type t = int list let split_char ~sep p = let len = String.length p in let rec split beg cur = if cur >= len then if cur - beg > 0 then [ String.sub p ~pos:beg ~len:(cur - beg) ] else [] else if sep p.[cur] then String.sub p ~pos:beg ~len:(cur - beg) :: split (cur + 1) (cur + 1) else split beg (cur + 1) in split 0 0 let split v = match split_char ~sep:(function | '+' | '-' | '~' -> true | _ -> false) v with | [] -> assert false | x :: _ -> List.map (split_char ~sep:(function | '.' -> true | _ -> false) x) ~f:int_of_string let current = split Sys.ocaml_version let compint (a : int) b = compare a b let rec compare v v' = match v, v' with | [ x ], [ y ] -> compint x y | [], [] -> 0 | [], y :: _ -> compint 0 y | x :: _, [] -> compint x 0 | x :: xs, y :: ys -> ( match compint x y with | 0 -> compare xs ys | n -> n) let v = match current with | 4 :: 8 :: _ -> `V4_08 | 4 :: 9 :: _ -> `V4_09 | 4 :: 10 :: _ -> `V4_10 | 4 :: 11 :: _ -> `V4_11 | 4 :: 12 :: _ -> `V4_12 | 4 :: 13 :: _ -> `V4_13 | 4 :: 14 :: _ -> `V4_14 | 5 :: 0 :: _ -> `V5_00 | 5 :: 1 :: _ -> `V5_01 | _ -> if compare current [ 4; 4 ] < 0 then failwith "OCaml version unsupported. Upgrade to OCaml 4.08 or newer." else ( assert (compare current [ 5; 1 ] >= 0); failwith "OCaml version unsupported. Upgrade js_of_ocaml.")
ba53ac3e6d735d7e0f3bff22c2891c82582c5004febb73a7f68029e33dc9ebc3
ericclack/overtone-loops
timing2.clj
(ns overtone-loops.examples.timing2 "Timing tests" (:use [overtone.live] [overtone-loops.loops] [overtone-loops.samples])) (set-up) (defloop hats 1 cymbal-closed [7 5 5]) (defloop kicks 1 bass-soft [7 5 5]) (defloop double-kicks 1/3 bass-soft [7 7 _ 7 7 _ 7 7 _]) (bpm 90) (beats-in-bar 3) (at-bar 1 (hats)) (at-bar 2 (kicks)) (at-bar 4 (silence kicks) (double-kicks)) (at-bar 6 (kicks :first) (silence double-kicks)) (at-bar 9 (silence kicks hats)) ;;(stop)
null
https://raw.githubusercontent.com/ericclack/overtone-loops/54b0c230c1e6bd3d378583af982db4e9ae4bda69/src/overtone_loops/examples/timing2.clj
clojure
(stop)
(ns overtone-loops.examples.timing2 "Timing tests" (:use [overtone.live] [overtone-loops.loops] [overtone-loops.samples])) (set-up) (defloop hats 1 cymbal-closed [7 5 5]) (defloop kicks 1 bass-soft [7 5 5]) (defloop double-kicks 1/3 bass-soft [7 7 _ 7 7 _ 7 7 _]) (bpm 90) (beats-in-bar 3) (at-bar 1 (hats)) (at-bar 2 (kicks)) (at-bar 4 (silence kicks) (double-kicks)) (at-bar 6 (kicks :first) (silence double-kicks)) (at-bar 9 (silence kicks hats))
4ff2809f874338b813411a70c3b04bb9275fcdaef2ae4a8c1da90281eb0bb283
CryptoKami/cryptokami-core
Download.hs
{-# LANGUAGE RankNTypes #-} -- | Logic related to downloading update. module Pos.Update.Download ( installerHash , downloadUpdate ) where import Universum import Control.Exception.Safe (handleAny) import Control.Lens (views) import Control.Monad.Except (ExceptT (..), throwError) import qualified Data.ByteArray as BA import qualified Data.ByteString.Lazy as BSL import qualified Data.HashMap.Strict as HM import Formatting (build, sformat, stext, (%)) import Network.HTTP.Client (Manager, newManager) import Network.HTTP.Client.TLS (tlsManagerSettings) import Network.HTTP.Simple (getResponseBody, getResponseStatus, getResponseStatusCode, httpLBS, parseRequest, setRequestManager) import qualified Serokell.Util.Base16 as B16 import Serokell.Util.Text (listJsonIndent, mapJson) import System.Directory (doesFileExist) import System.Wlog (WithLogger, logDebug, logInfo, logWarning) import Pos.Binary.Class (Raw) import Pos.Binary.Update () import Pos.Core.Update (SoftwareVersion (..), UpdateData (..), UpdateProposal (..)) import Pos.Crypto (Hash, castHash, hash) import Pos.Exception (reportFatalError) import Pos.Reporting (reportOrLogW) import Pos.Update.Configuration (curSoftwareVersion, ourSystemTag) import Pos.Update.Context (UpdateContext (..)) import Pos.Update.DB.Misc (isUpdateInstalled) import Pos.Update.Mode (UpdateMode) import Pos.Update.Params (UpdateParams (..)) import Pos.Update.Poll.Types (ConfirmedProposalState (..)) import Pos.Util.Concurrent (withMVar) import Pos.Util.Util (HasLens (..), (<//>)) | Compute hash of installer , this is hash is ' udPkgHash ' from ' UpdateData ' . -- NB : we compute it by first CBOR - encoding it and then applying hash -- function, which is a bit strange, but it's done for historical -- reasons. installerHash :: LByteString -> Hash Raw installerHash = castHash . hash | Download a software update for given ' ConfirmedProposalState ' and put it into a variable which holds ' ConfirmedProposalState ' of -- downloaded update. Parallel downloads are n't supported , so this function may blocks . -- If we have already downloaded an update successfully, this function won't -- download new updates. -- -- The caller must ensure that: 1 . This update is for our software . 2 . This update is for our system ( according to system tag ) . 3 . This update brings newer software version than our current version . downloadUpdate :: forall ctx m . UpdateMode ctx m => ConfirmedProposalState -> m () downloadUpdate cps = do downloadLock <- ucDownloadLock <$> view (lensOf @UpdateContext) withMVar downloadLock $ \() -> do downloadedUpdateMVar <- ucDownloadedUpdate <$> view (lensOf @UpdateContext) tryReadMVar downloadedUpdateMVar >>= \case Nothing -> do updHash <- getUpdateHash cps installed <- isUpdateInstalled updHash if installed then onAlreadyInstalled else downloadUpdateDo updHash cps Just existingCPS -> onAlreadyDownloaded existingCPS where proposalToDL = cpsUpdateProposal cps onAlreadyDownloaded ConfirmedProposalState {..} = logInfo $ sformat ("We won't download an update for proposal "%build% ", because we have already downloaded another update: "%build% " and we are waiting for it to be applied") proposalToDL cpsUpdateProposal onAlreadyInstalled = logInfo $ sformat ("We won't download an update for proposal "%build% ", because it's already installed") proposalToDL getUpdateHash :: UpdateMode ctx m => ConfirmedProposalState -> m (Hash Raw) getUpdateHash ConfirmedProposalState{..} = do useInstaller <- views (lensOf @UpdateParams) upUpdateWithPkg let data_ = upData cpsUpdateProposal dataHash = if useInstaller then udPkgHash else udAppDiffHash mupdHash = dataHash <$> HM.lookup ourSystemTag data_ logDebug $ sformat ("Proposal's upData: "%mapJson) data_ -- It must be enforced by the caller. maybe (reportFatalError $ sformat ("We are trying to download an update not for our "% "system, update proposal is: "%build) cpsUpdateProposal) pure mupdHash Download and save archive update by given ` ConfirmedProposalState ` downloadUpdateDo :: UpdateMode ctx m => Hash Raw -> ConfirmedProposalState -> m () downloadUpdateDo updHash cps@ConfirmedProposalState {..} = do updateServers <- views (lensOf @UpdateParams) upUpdateServers logInfo $ sformat ("We are going to start downloading an update for "%build) cpsUpdateProposal res <- handleAny handleErr $ runExceptT $ do let updateVersion = upSoftwareVersion cpsUpdateProposal -- It's just a sanity check which must always pass due to the -- outside logic. We take only updates for our software and -- explicitly request only new updates. This invariant must be -- ensure by the caller of 'downloadUpdate'. unless (isVersionAppropriate updateVersion) $ reportFatalError $ sformat ("Update #"%build%" hasn't been downloaded: "% "its version is not newer than current software "% "software version or it's not for our "% "software at all") updHash updPath <- views (lensOf @UpdateParams) upUpdatePath whenM (liftIO $ doesFileExist updPath) $ throwError "There's unapplied update already downloaded" logInfo "Downloading update..." file <- ExceptT $ downloadHash updateServers updHash <&> first (sformat ("Update download (hash "%build% ") has failed: "%stext) updHash) logInfo $ "Update was downloaded, saving to " <> show updPath liftIO $ BSL.writeFile updPath file logInfo $ "Update was downloaded, saved to " <> show updPath downloadedMVar <- views (lensOf @UpdateContext) ucDownloadedUpdate putMVar downloadedMVar cps logInfo "Update MVar filled, wallet is notified" whenLeft res logDownloadError where handleErr e = Left (pretty e) <$ reportOrLogW "Update downloading failed: " e logDownloadError e = logWarning $ sformat ("Failed to download update proposal "%build%": "%stext) cpsUpdateProposal e -- Check that we really should download an update with given -- 'SoftwareVersion'. isVersionAppropriate :: SoftwareVersion -> Bool isVersionAppropriate ver = svAppName ver == svAppName curSoftwareVersion && svNumber ver > svNumber curSoftwareVersion -- Download a file by its hash. -- -- Tries all servers in turn, fails if none of them work. downloadHash :: (MonadIO m, WithLogger m) => [Text] -> Hash Raw -> m (Either Text LByteString) downloadHash updateServers h = do manager <- liftIO $ newManager tlsManagerSettings let -- try all servers in turn until there's a Right go errs (serv:rest) = do let uri = toString serv <//> showHash h logDebug $ "Trying url " <> show uri liftIO (downloadUri manager uri h) >>= \case Left e -> go (e:errs) rest Right r -> return (Right r) -- if there were no servers, that's really weird go [] [] = return . Left $ "no update servers are known" -- if we've tried all servers already, fail go errs [] = return . Left $ sformat ("all update servers failed: "%listJsonIndent 2) (reverse errs) go [] updateServers where showHash :: Hash a -> FilePath showHash = toString . B16.encode . BA.convert -- Download a file and check its hash. downloadUri :: Manager -> String -> Hash Raw -> IO (Either Text LByteString) downloadUri manager uri h = do request <- setRequestManager manager <$> parseRequest uri resp <- httpLBS request let (st, stc) = (getResponseStatus resp, getResponseStatusCode resp) h' = installerHash (getResponseBody resp) return $ if | stc /= 200 -> Left ("error, " <> show st) | h /= h' -> Left "hash mismatch" | otherwise -> Right (getResponseBody resp) {- TODO * check timeouts? * how should we in general deal with e.g. 1B/s download speed? * if we expect updates to be big, use laziness/conduits (httpLBS isn't lazy, despite the “L” in its name) -}
null
https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/update/Pos/Update/Download.hs
haskell
# LANGUAGE RankNTypes # | Logic related to downloading update. function, which is a bit strange, but it's done for historical reasons. downloaded update. If we have already downloaded an update successfully, this function won't download new updates. The caller must ensure that: It must be enforced by the caller. It's just a sanity check which must always pass due to the outside logic. We take only updates for our software and explicitly request only new updates. This invariant must be ensure by the caller of 'downloadUpdate'. Check that we really should download an update with given 'SoftwareVersion'. Download a file by its hash. Tries all servers in turn, fails if none of them work. try all servers in turn until there's a Right if there were no servers, that's really weird if we've tried all servers already, fail Download a file and check its hash. TODO * check timeouts? * how should we in general deal with e.g. 1B/s download speed? * if we expect updates to be big, use laziness/conduits (httpLBS isn't lazy, despite the “L” in its name)
module Pos.Update.Download ( installerHash , downloadUpdate ) where import Universum import Control.Exception.Safe (handleAny) import Control.Lens (views) import Control.Monad.Except (ExceptT (..), throwError) import qualified Data.ByteArray as BA import qualified Data.ByteString.Lazy as BSL import qualified Data.HashMap.Strict as HM import Formatting (build, sformat, stext, (%)) import Network.HTTP.Client (Manager, newManager) import Network.HTTP.Client.TLS (tlsManagerSettings) import Network.HTTP.Simple (getResponseBody, getResponseStatus, getResponseStatusCode, httpLBS, parseRequest, setRequestManager) import qualified Serokell.Util.Base16 as B16 import Serokell.Util.Text (listJsonIndent, mapJson) import System.Directory (doesFileExist) import System.Wlog (WithLogger, logDebug, logInfo, logWarning) import Pos.Binary.Class (Raw) import Pos.Binary.Update () import Pos.Core.Update (SoftwareVersion (..), UpdateData (..), UpdateProposal (..)) import Pos.Crypto (Hash, castHash, hash) import Pos.Exception (reportFatalError) import Pos.Reporting (reportOrLogW) import Pos.Update.Configuration (curSoftwareVersion, ourSystemTag) import Pos.Update.Context (UpdateContext (..)) import Pos.Update.DB.Misc (isUpdateInstalled) import Pos.Update.Mode (UpdateMode) import Pos.Update.Params (UpdateParams (..)) import Pos.Update.Poll.Types (ConfirmedProposalState (..)) import Pos.Util.Concurrent (withMVar) import Pos.Util.Util (HasLens (..), (<//>)) | Compute hash of installer , this is hash is ' udPkgHash ' from ' UpdateData ' . NB : we compute it by first CBOR - encoding it and then applying hash installerHash :: LByteString -> Hash Raw installerHash = castHash . hash | Download a software update for given ' ConfirmedProposalState ' and put it into a variable which holds ' ConfirmedProposalState ' of Parallel downloads are n't supported , so this function may blocks . 1 . This update is for our software . 2 . This update is for our system ( according to system tag ) . 3 . This update brings newer software version than our current version . downloadUpdate :: forall ctx m . UpdateMode ctx m => ConfirmedProposalState -> m () downloadUpdate cps = do downloadLock <- ucDownloadLock <$> view (lensOf @UpdateContext) withMVar downloadLock $ \() -> do downloadedUpdateMVar <- ucDownloadedUpdate <$> view (lensOf @UpdateContext) tryReadMVar downloadedUpdateMVar >>= \case Nothing -> do updHash <- getUpdateHash cps installed <- isUpdateInstalled updHash if installed then onAlreadyInstalled else downloadUpdateDo updHash cps Just existingCPS -> onAlreadyDownloaded existingCPS where proposalToDL = cpsUpdateProposal cps onAlreadyDownloaded ConfirmedProposalState {..} = logInfo $ sformat ("We won't download an update for proposal "%build% ", because we have already downloaded another update: "%build% " and we are waiting for it to be applied") proposalToDL cpsUpdateProposal onAlreadyInstalled = logInfo $ sformat ("We won't download an update for proposal "%build% ", because it's already installed") proposalToDL getUpdateHash :: UpdateMode ctx m => ConfirmedProposalState -> m (Hash Raw) getUpdateHash ConfirmedProposalState{..} = do useInstaller <- views (lensOf @UpdateParams) upUpdateWithPkg let data_ = upData cpsUpdateProposal dataHash = if useInstaller then udPkgHash else udAppDiffHash mupdHash = dataHash <$> HM.lookup ourSystemTag data_ logDebug $ sformat ("Proposal's upData: "%mapJson) data_ maybe (reportFatalError $ sformat ("We are trying to download an update not for our "% "system, update proposal is: "%build) cpsUpdateProposal) pure mupdHash Download and save archive update by given ` ConfirmedProposalState ` downloadUpdateDo :: UpdateMode ctx m => Hash Raw -> ConfirmedProposalState -> m () downloadUpdateDo updHash cps@ConfirmedProposalState {..} = do updateServers <- views (lensOf @UpdateParams) upUpdateServers logInfo $ sformat ("We are going to start downloading an update for "%build) cpsUpdateProposal res <- handleAny handleErr $ runExceptT $ do let updateVersion = upSoftwareVersion cpsUpdateProposal unless (isVersionAppropriate updateVersion) $ reportFatalError $ sformat ("Update #"%build%" hasn't been downloaded: "% "its version is not newer than current software "% "software version or it's not for our "% "software at all") updHash updPath <- views (lensOf @UpdateParams) upUpdatePath whenM (liftIO $ doesFileExist updPath) $ throwError "There's unapplied update already downloaded" logInfo "Downloading update..." file <- ExceptT $ downloadHash updateServers updHash <&> first (sformat ("Update download (hash "%build% ") has failed: "%stext) updHash) logInfo $ "Update was downloaded, saving to " <> show updPath liftIO $ BSL.writeFile updPath file logInfo $ "Update was downloaded, saved to " <> show updPath downloadedMVar <- views (lensOf @UpdateContext) ucDownloadedUpdate putMVar downloadedMVar cps logInfo "Update MVar filled, wallet is notified" whenLeft res logDownloadError where handleErr e = Left (pretty e) <$ reportOrLogW "Update downloading failed: " e logDownloadError e = logWarning $ sformat ("Failed to download update proposal "%build%": "%stext) cpsUpdateProposal e isVersionAppropriate :: SoftwareVersion -> Bool isVersionAppropriate ver = svAppName ver == svAppName curSoftwareVersion && svNumber ver > svNumber curSoftwareVersion downloadHash :: (MonadIO m, WithLogger m) => [Text] -> Hash Raw -> m (Either Text LByteString) downloadHash updateServers h = do manager <- liftIO $ newManager tlsManagerSettings go errs (serv:rest) = do let uri = toString serv <//> showHash h logDebug $ "Trying url " <> show uri liftIO (downloadUri manager uri h) >>= \case Left e -> go (e:errs) rest Right r -> return (Right r) go [] [] = return . Left $ "no update servers are known" go errs [] = return . Left $ sformat ("all update servers failed: "%listJsonIndent 2) (reverse errs) go [] updateServers where showHash :: Hash a -> FilePath showHash = toString . B16.encode . BA.convert downloadUri :: Manager -> String -> Hash Raw -> IO (Either Text LByteString) downloadUri manager uri h = do request <- setRequestManager manager <$> parseRequest uri resp <- httpLBS request let (st, stc) = (getResponseStatus resp, getResponseStatusCode resp) h' = installerHash (getResponseBody resp) return $ if | stc /= 200 -> Left ("error, " <> show st) | h /= h' -> Left "hash mismatch" | otherwise -> Right (getResponseBody resp)
e51d3f910da18b6fb80f989d875d36dcf0e3fddab334f73e4118fe5b68094ee8
VictorNicollet/Ohm-Site
o.ml
Ohm is © 2012 open Ohm open Ohm.Universal open BatPervasives * { 1 Instance role } (** The role of the current instance. This value can be used to only perform some actions in a certain context, such as the web server or the asynchronous bot. *) let role = Util.role () (** {1 Environment and basic configuration} *) (** Available environments. These represent the contexts in which the application may be deployed, such as a production server or the local machine of a developer. *) type environment = [ `Dev | `Prod ] (** The current {!type:environment}. *) let environment = `Dev (** A string representing the current environment, which is then used to construct various environment-dependent names and identifiers. *) let env = match environment with | `Prod -> "prod" | `Dev -> "dev" (** The full absolute path to the log file. *) let logpath = match role with | `Put | `Reset -> None | `Bot | `Web -> Some ("/var/log/ohm/" ^ ConfigProject.lname ^ "-" ^ env ^ ".log") let () = Configure.set `Log (BatOption.default "-" logpath) * { 1 Database management } (** This function returns the full name of a database, constructed from the local name (what the database is called in this project), the project name and the current environment name. *) let db name = Printf.sprintf "%s-%s-%s" ConfigProject.lname env name (** The configuration database. Plug-ins expect to find their configuration in this database. The key for this database is ["config"]. *) module ConfigDB = CouchDB.Convenience.Database(struct let db = db "config" end) (** The {b configuration} for the asynchronous processing database. This is were asynchronous tasks are stored. The key for this database is ["async"]. *) module AsyncDB = CouchDB.Convenience.Config(struct let db = db "async" end) * { 1 Standard execution context } (** The type of internationalization keys available for translation by the standard context. The context provides the infrastructure required to turn keys of this type into actual translated strings. *) type i18n = Asset_AdLib.key * The standard context class . Provides : { ul interaction } { - Async task scheduling } { - AdLib internationalization } } Use the { ! : ctx } function below to create instances of this class . {- CouchDB interaction} {- Async task scheduling} {- AdLib internationalization}} Use the {!val:ctx} function below to create instances of this class. *) class ctx adlib = object inherit CouchDB.init_ctx inherit Async.ctx inherit [i18n] AdLib.ctx adlib end (** Create a new context for a specific language. *) let ctx = function | `EN -> new ctx Asset_AdLib.en (** The type of a pre-emptive thread working in a standard context. *) type 'a run = (ctx,'a) Run.t (** {1 Instances} *) (** The reset module responsible for sending "shut down and reboot" signals to all running instances of the application through the database. *) module Reset = Reset.Make(ConfigDB) (** Run an action when the instance is running in [`Put] mode. *) let put action = if role = `Put then ignore (Ohm.Run.eval (ctx `EN) action) (** {1 Rendering a page} *) * The CSS files used by all the pages rendered using { ! : page } . This should usually include [ Asset.css ] , which is the CSS file generated by the asset pipeline . should usually include [Asset.css], which is the CSS file generated by the asset pipeline. *) let common_css = [ Asset.css ] * The Javascript files used by all the pages rendered using { ! : page } . This should usually include [ Asset.js ] , which is the CSS file generated by the asset pipeline , as well as jQuery . This should usually include [Asset.js], which is the CSS file generated by the asset pipeline, as well as jQuery. *) let common_js = [ "" ; Asset.js ] (** Rendering a page. The caller may provide additional CSS and javascript files to be added. Be aware that many plugins rely on this function being defined. *) let page ?(css=[]) ?(js=[]) ?head ?favicon ?body_classes ~title writer = let css = common_css @ css in let js = common_js @ js in Ohm.Html.print_page ~css ~js ?head ?favicon ?body_classes ~title writer (** {1 Asynchronous tasks} *) * The Async module . Instead of using this module directly , use the { ! : async } object below . {!val:async} object below. *) module Async = Ohm.Async.Make(AsyncDB) (** Asynchronous task manager. Use this object to spawn asynchronous tasks, or register periodic tasks. *) let async : ctx Async.manager = new Async.manager (** This function is used by {!module:Main} to run tasks as part of the [`Bot] role of the application. *) let run_async () = async # run (fun () -> ctx `EN) * { 1 Web configuration } (** The domain on which the server should respond to requests. *) let domain = match environment with | `Prod -> "ohm-framework.com" | `Dev -> "ohm-site.local" (** The domain suffix on which cookies are published. *) let cookies = "." ^ domain (** The snigle-domain server configuration, used to bind request handlers. *) let server = Action.Convenience.single_domain_server ~cookies domain (** Runs an action body within the standard context in the default language. *) let action f req res = Run.with_context (ctx `EN) (f req res) * Defines the 404 error let register_404 f = Action.register_404 (fun server page res -> Run.with_context (ctx `EN) (f server page res)) (** Bind a new action, providing the body to be executed. This returns an endpoint which can be used to generate URLs. *) let register url args body = Action.register server url args (action body) (** Bind a new action, but provide the body later. This returns both an endpoint, and a function to be called on the body. *) let declare url args = let endpoint, define = Action.declare server url args in endpoint, action |- define
null
https://raw.githubusercontent.com/VictorNicollet/Ohm-Site/147fd11df8204180d4b0228d74e7f4ad1ae79191/ocaml/o.ml
ocaml
* The role of the current instance. This value can be used to only perform some actions in a certain context, such as the web server or the asynchronous bot. * {1 Environment and basic configuration} * Available environments. These represent the contexts in which the application may be deployed, such as a production server or the local machine of a developer. * The current {!type:environment}. * A string representing the current environment, which is then used to construct various environment-dependent names and identifiers. * The full absolute path to the log file. * This function returns the full name of a database, constructed from the local name (what the database is called in this project), the project name and the current environment name. * The configuration database. Plug-ins expect to find their configuration in this database. The key for this database is ["config"]. * The {b configuration} for the asynchronous processing database. This is were asynchronous tasks are stored. The key for this database is ["async"]. * The type of internationalization keys available for translation by the standard context. The context provides the infrastructure required to turn keys of this type into actual translated strings. * Create a new context for a specific language. * The type of a pre-emptive thread working in a standard context. * {1 Instances} * The reset module responsible for sending "shut down and reboot" signals to all running instances of the application through the database. * Run an action when the instance is running in [`Put] mode. * {1 Rendering a page} * Rendering a page. The caller may provide additional CSS and javascript files to be added. Be aware that many plugins rely on this function being defined. * {1 Asynchronous tasks} * Asynchronous task manager. Use this object to spawn asynchronous tasks, or register periodic tasks. * This function is used by {!module:Main} to run tasks as part of the [`Bot] role of the application. * The domain on which the server should respond to requests. * The domain suffix on which cookies are published. * The snigle-domain server configuration, used to bind request handlers. * Runs an action body within the standard context in the default language. * Bind a new action, providing the body to be executed. This returns an endpoint which can be used to generate URLs. * Bind a new action, but provide the body later. This returns both an endpoint, and a function to be called on the body.
Ohm is © 2012 open Ohm open Ohm.Universal open BatPervasives * { 1 Instance role } let role = Util.role () type environment = [ `Dev | `Prod ] let environment = `Dev let env = match environment with | `Prod -> "prod" | `Dev -> "dev" let logpath = match role with | `Put | `Reset -> None | `Bot | `Web -> Some ("/var/log/ohm/" ^ ConfigProject.lname ^ "-" ^ env ^ ".log") let () = Configure.set `Log (BatOption.default "-" logpath) * { 1 Database management } let db name = Printf.sprintf "%s-%s-%s" ConfigProject.lname env name module ConfigDB = CouchDB.Convenience.Database(struct let db = db "config" end) module AsyncDB = CouchDB.Convenience.Config(struct let db = db "async" end) * { 1 Standard execution context } type i18n = Asset_AdLib.key * The standard context class . Provides : { ul interaction } { - Async task scheduling } { - AdLib internationalization } } Use the { ! : ctx } function below to create instances of this class . {- CouchDB interaction} {- Async task scheduling} {- AdLib internationalization}} Use the {!val:ctx} function below to create instances of this class. *) class ctx adlib = object inherit CouchDB.init_ctx inherit Async.ctx inherit [i18n] AdLib.ctx adlib end let ctx = function | `EN -> new ctx Asset_AdLib.en type 'a run = (ctx,'a) Run.t module Reset = Reset.Make(ConfigDB) let put action = if role = `Put then ignore (Ohm.Run.eval (ctx `EN) action) * The CSS files used by all the pages rendered using { ! : page } . This should usually include [ Asset.css ] , which is the CSS file generated by the asset pipeline . should usually include [Asset.css], which is the CSS file generated by the asset pipeline. *) let common_css = [ Asset.css ] * The Javascript files used by all the pages rendered using { ! : page } . This should usually include [ Asset.js ] , which is the CSS file generated by the asset pipeline , as well as jQuery . This should usually include [Asset.js], which is the CSS file generated by the asset pipeline, as well as jQuery. *) let common_js = [ "" ; Asset.js ] let page ?(css=[]) ?(js=[]) ?head ?favicon ?body_classes ~title writer = let css = common_css @ css in let js = common_js @ js in Ohm.Html.print_page ~css ~js ?head ?favicon ?body_classes ~title writer * The Async module . Instead of using this module directly , use the { ! : async } object below . {!val:async} object below. *) module Async = Ohm.Async.Make(AsyncDB) let async : ctx Async.manager = new Async.manager let run_async () = async # run (fun () -> ctx `EN) * { 1 Web configuration } let domain = match environment with | `Prod -> "ohm-framework.com" | `Dev -> "ohm-site.local" let cookies = "." ^ domain let server = Action.Convenience.single_domain_server ~cookies domain let action f req res = Run.with_context (ctx `EN) (f req res) * Defines the 404 error let register_404 f = Action.register_404 (fun server page res -> Run.with_context (ctx `EN) (f server page res)) let register url args body = Action.register server url args (action body) let declare url args = let endpoint, define = Action.declare server url args in endpoint, action |- define
9c7f2967946e5f826cb908436d564bd217abba7fa78e3fa5ffd88344b0a76b0b
owainlewis/yaml
reader.clj
(ns yaml.reader (:require [flatland.ordered.set :refer [ordered-set]] [flatland.ordered.map :refer [ordered-map]]) (:refer-clojure :exclude [load]) (:import [org.yaml.snakeyaml Yaml] [org.yaml.snakeyaml.constructor Constructor PassthroughConstructor] [org.yaml.snakeyaml.composer ComposerException])) (def ^:dynamic *keywordize* true) (def ^:dynamic *constructor* (fn [] (Constructor.))) (def passthrough-constructor "Custom constructor that will not barf on unknown YAML tags. This constructor will treat YAML objects with unknown tags with the underlying type (i.e. map, sequence, scalar) " (fn [] (PassthroughConstructor.))) (defprotocol YAMLReader (decode [data])) (defn- decode-key "When *keywordize* is bound to true decode map keys into keywords else leave them as strings. When *keywordize* is a function, calls function on the key." [k] (cond (true? *keywordize*) (keyword k) (fn? *keywordize*) (*keywordize* k) :else k)) (extend-protocol YAMLReader java.util.LinkedHashMap (decode [data] (into (ordered-map) (for [[k v] data] [(decode-key k) (decode v)]))) java.util.LinkedHashSet (decode [data] (into (ordered-set) data)) java.util.ArrayList (decode [data] (into [] (map decode data))) Object (decode [data] data) nil (decode [data] data)) (defn parse-documents "The YAML spec allows for multiple documents. This will take a string containing multiple yaml docs and return a vector containing each document" [^String yaml-documents] (mapv decode (.loadAll (Yaml. (*constructor*)) yaml-documents))) (defn parse-string "Parse a yaml input string. If multiple documents are found it will return a vector of documents When keywords is a true (default), map keys are converted to keywords. When keywords is a function, invokes the function on the map keys. When a custom :constructor is provided, it's used to construct objects. Should be a 0-arity function that returns a constructor. " [^String string & {:keys [keywords constructor] :or {keywords *keywordize* constructor *constructor*}}] (binding [*keywordize* keywords] (try (decode (.load (Yaml. (constructor)) string)) (catch ComposerException e (parse-documents string)))))
null
https://raw.githubusercontent.com/owainlewis/yaml/211303b4844e11dcfbea6ed1c9814dc907d56991/src/yaml/reader.clj
clojure
(ns yaml.reader (:require [flatland.ordered.set :refer [ordered-set]] [flatland.ordered.map :refer [ordered-map]]) (:refer-clojure :exclude [load]) (:import [org.yaml.snakeyaml Yaml] [org.yaml.snakeyaml.constructor Constructor PassthroughConstructor] [org.yaml.snakeyaml.composer ComposerException])) (def ^:dynamic *keywordize* true) (def ^:dynamic *constructor* (fn [] (Constructor.))) (def passthrough-constructor "Custom constructor that will not barf on unknown YAML tags. This constructor will treat YAML objects with unknown tags with the underlying type (i.e. map, sequence, scalar) " (fn [] (PassthroughConstructor.))) (defprotocol YAMLReader (decode [data])) (defn- decode-key "When *keywordize* is bound to true decode map keys into keywords else leave them as strings. When *keywordize* is a function, calls function on the key." [k] (cond (true? *keywordize*) (keyword k) (fn? *keywordize*) (*keywordize* k) :else k)) (extend-protocol YAMLReader java.util.LinkedHashMap (decode [data] (into (ordered-map) (for [[k v] data] [(decode-key k) (decode v)]))) java.util.LinkedHashSet (decode [data] (into (ordered-set) data)) java.util.ArrayList (decode [data] (into [] (map decode data))) Object (decode [data] data) nil (decode [data] data)) (defn parse-documents "The YAML spec allows for multiple documents. This will take a string containing multiple yaml docs and return a vector containing each document" [^String yaml-documents] (mapv decode (.loadAll (Yaml. (*constructor*)) yaml-documents))) (defn parse-string "Parse a yaml input string. If multiple documents are found it will return a vector of documents When keywords is a true (default), map keys are converted to keywords. When keywords is a function, invokes the function on the map keys. When a custom :constructor is provided, it's used to construct objects. Should be a 0-arity function that returns a constructor. " [^String string & {:keys [keywords constructor] :or {keywords *keywordize* constructor *constructor*}}] (binding [*keywordize* keywords] (try (decode (.load (Yaml. (constructor)) string)) (catch ComposerException e (parse-documents string)))))
e891908432d9fc38845f65e9fa46ed7260c66582a48506a60084e67011be7433
hspec/hspec-smallcheck
Types.hs
module Test.Hspec.SmallCheck.Types where import Prelude () import Test.Hspec.SmallCheck.Compat import Data.List import Test.Hspec.Core.Spec (Location(..)) data Result = Failure (Maybe Location) Reason deriving (Eq, Show, Read) data Reason = Reason String | ExpectedActual String String String deriving (Eq, Show, Read) parseResult :: String -> (String, Maybe Result) parseResult xs = case [(x, Just y) | (x, Just y) <- zip (inits xs) (map readMaybe $ tails xs)] of r : _ -> r [] -> (xs, Nothing) concatPrefix :: String -> String -> Maybe String concatPrefix a b = case filter (not . null) $ [a, b] of [] -> Nothing xs -> Just (intercalate "\n" xs)
null
https://raw.githubusercontent.com/hspec/hspec-smallcheck/7963f200a0ed37cde9db4ac6d914b074628f96da/src/Test/Hspec/SmallCheck/Types.hs
haskell
module Test.Hspec.SmallCheck.Types where import Prelude () import Test.Hspec.SmallCheck.Compat import Data.List import Test.Hspec.Core.Spec (Location(..)) data Result = Failure (Maybe Location) Reason deriving (Eq, Show, Read) data Reason = Reason String | ExpectedActual String String String deriving (Eq, Show, Read) parseResult :: String -> (String, Maybe Result) parseResult xs = case [(x, Just y) | (x, Just y) <- zip (inits xs) (map readMaybe $ tails xs)] of r : _ -> r [] -> (xs, Nothing) concatPrefix :: String -> String -> Maybe String concatPrefix a b = case filter (not . null) $ [a, b] of [] -> Nothing xs -> Just (intercalate "\n" xs)
7760317652874f8100869b3ac18c349ecca63d6005badefb8f484990db9b4396
SimulaVR/godot-haskell
Types.hs
# LANGUAGE BangPatterns , FunctionalDependencies , TypeFamilies , TypeInType , LambdaCase , TypeApplications , AllowAmbiguousTypes # module Godot.Gdnative.Internal.Types where import Control.Exception import qualified Data.ByteString as B import qualified Data.ByteString.Unsafe as B import Data.Text (Text) import qualified Data.Text.Encoding as T import Data.Colour import Data.Colour.SRGB import Data.Function ((&)) import Data.Typeable import Data.Coerce import Foreign import Foreign.C import Linear import qualified Data.Vector as V import qualified Data.Map as M import Godot.Gdnative.Internal.Api as I hiding (Rect2,Basis,Transform,Transform2d,Color) import Godot.Gdnative.Internal.Gdnative as I hiding (Rect2,Basis,Transform,Transform2d,Color) import qualified Godot.Gdnative.Internal.Api as G import qualified Godot.Gdnative.Internal.Gdnative as G import Godot.Gdnative.Internal.TH import System.IO.Unsafe data LibType = GodotTy | HaskellTy type family TypeOf (x :: LibType) a -- I'm torn about this instance. Need TH if not using this type instance TypeOf 'GodotTy a = a -- |GodotFFI is a relation between low-level and high-level -- |Godot types, and conversions between them. class GodotFFI low high | low -> high where fromLowLevel :: low -> IO high toLowLevel :: high -> IO low type instance TypeOf 'HaskellTy G.Array = V.Vector GodotVariant instance GodotFFI G.Array (V.Vector GodotVariant) where fromLowLevel arr = do len <- fromIntegral <$> godot_array_size arr V.generateM len (godot_array_get arr . fromIntegral) toLowLevel vec = do arr <- godot_array_new V.mapM_ (godot_array_append arr) vec pure arr type instance TypeOf 'HaskellTy GodotString = Text instance GodotFFI GodotString Text where fromLowLevel str = godot_string_utf8 str >>= \cstr -> T.decodeUtf8 <$> fromCharString cstr where fromCharString cstr = do len <- godot_char_string_length cstr sptr <- godot_char_string_get_data cstr B.packCStringLen (sptr, fromIntegral len) toLowLevel txt = B.unsafeUseAsCStringLen bstr $ \(ptr, len) -> godot_string_chars_to_utf8_with_len ptr (fromIntegral len) where bstr = T.encodeUtf8 txt type instance TypeOf 'HaskellTy Vector2 = V2 Float instance GodotFFI Vector2 (V2 Float) where fromLowLevel v = V2 <$> (realToFrac <$> godot_vector2_get_x v) <*> (realToFrac <$> godot_vector2_get_y v) toLowLevel (V2 x y) = godot_vector2_new (realToFrac x) (realToFrac y) type instance TypeOf 'HaskellTy Vector3 = V3 Float instance GodotFFI Vector3 (V3 Float) where fromLowLevel v = V3 <$> (realToFrac <$> godot_vector3_get_axis v Vector3AxisX) <*> (realToFrac <$> godot_vector3_get_axis v Vector3AxisY) <*> (realToFrac <$> godot_vector3_get_axis v Vector3AxisZ) toLowLevel (V3 x y z) = godot_vector3_new (realToFrac x) (realToFrac y) (realToFrac z) type instance TypeOf 'HaskellTy Quat = Quaternion Float instance GodotFFI Quat (Quaternion Float) where fromLowLevel q = Quaternion <$> (realToFrac <$> godot_quat_get_w q) <*> (V3 <$> (realToFrac <$> godot_quat_get_x q) <*> (realToFrac <$> godot_quat_get_y q) <*> (realToFrac <$> godot_quat_get_z q)) toLowLevel (Quaternion w (V3 x y z)) = godot_quat_new (realToFrac x) (realToFrac y) (realToFrac z) (realToFrac w) type Rect2 = M22 Float type instance TypeOf 'HaskellTy G.Rect2 = Rect2 instance GodotFFI G.Rect2 Rect2 where fromLowLevel r = V2 <$> (fromLowLevel =<< godot_rect2_get_position r) <*> (fromLowLevel =<< godot_rect2_get_size r) toLowLevel (V2 pos size) = do pos' <- toLowLevel pos size' <- toLowLevel size godot_rect2_new_with_position_and_size pos' size' type AABB = M23 Float type instance TypeOf 'HaskellTy Aabb = AABB instance GodotFFI Aabb AABB where fromLowLevel aabb = V2 <$> (fromLowLevel =<< godot_aabb_get_position aabb) <*> (fromLowLevel =<< godot_aabb_get_size aabb) toLowLevel (V2 pos size) = do pos' <- toLowLevel pos size' <- toLowLevel size godot_aabb_new pos' size' Axes X , Y and Z are represented by the int constants 0 , 1 and 2 respectively ( at least for Vector3 ): -- #numeric-constants type Basis = M33 Float type instance TypeOf 'HaskellTy G.Basis = Basis instance GodotFFI G.Basis Basis where fromLowLevel b = V3 <$> (llAxis 0) <*> (llAxis 1) <*> (llAxis 2) where llAxis axis = fromLowLevel =<< godot_basis_get_axis b axis toLowLevel (V3 x y z) = do x' <- toLowLevel x y' <- toLowLevel y z' <- toLowLevel z godot_basis_new_with_rows x' y' z' data Transform = TF { _tfBasis :: Basis, _tfPosition :: V3 Float } type instance TypeOf 'HaskellTy G.Transform = Transform instance GodotFFI G.Transform Transform where fromLowLevel tf = TF <$> (fromLowLevel =<< godot_transform_get_basis tf) <*> (fromLowLevel =<< godot_transform_get_origin tf) toLowLevel (TF basis orig) = do basis' <- toLowLevel basis orig' <- toLowLevel orig godot_transform_new basis' orig' type Basis2d = M22 Float data Transform2d = TF2d { _tf2dX :: V2 Float, _tf2dY :: V2 Float, _tf2dOrigin :: V2 Float } type instance TypeOf 'HaskellTy G.Transform2d = Transform2d instance GodotFFI G.Transform2d Transform2d where fromLowLevel tf = do x <- godot_transform2d_xform_vector2 tf =<< toLowLevel (V2 1 0) y <- godot_transform2d_xform_vector2 tf =<< toLowLevel (V2 0 1) TF2d <$> fromLowLevel x <*> fromLowLevel y <*> (fromLowLevel =<< godot_transform2d_get_origin tf) toLowLevel (TF2d x y o) = do x' <- toLowLevel x y' <- toLowLevel y o' <- toLowLevel o godot_transform2d_new_axis_origin x' o' y' -- This should perhaps be better modeled - FilePath? type instance TypeOf 'HaskellTy G.NodePath = Text instance GodotFFI G.NodePath Text where fromLowLevel np = fromLowLevel =<< godot_node_path_get_name np 0 toLowLevel np = godot_node_path_new =<< toLowLevel np type instance TypeOf 'HaskellTy G.Color = AlphaColour Double instance GodotFFI G.Color (AlphaColour Double) where fromLowLevel c = withOpacity <$> (sRGB <$> (realToFrac <$> godot_color_get_r c) <*> (realToFrac <$> godot_color_get_g c) <*> (realToFrac <$> godot_color_get_b c)) <*> (realToFrac <$> godot_color_get_a c) toLowLevel rgba = toSRGB (rgba `over` black) & \(RGB r g b) -> godot_color_new_rgba (realToFrac r) (realToFrac g) (realToFrac b) (realToFrac $ alphaChannel rgba) type instance TypeOf 'HaskellTy G.PoolStringArray = V.Vector Text instance GodotFFI G.PoolStringArray (V.Vector Text) where fromLowLevel a = do sz <- godot_pool_string_array_size a V.generateM (fromIntegral sz) (\x -> fromLowLevel =<< godot_pool_string_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_string_array_new V.mapM_ (\e -> do s <- toLowLevel e godot_pool_string_array_append p s) v pure p type instance TypeOf 'HaskellTy G.PoolVector2Array = V.Vector (V2 Float) instance GodotFFI G.PoolVector2Array (V.Vector (V2 Float)) where fromLowLevel a = do sz <- godot_pool_vector2_array_size a V.generateM (fromIntegral sz) (\x -> fromLowLevel =<< godot_pool_vector2_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_vector2_array_new V.mapM_ (\e -> do s <- toLowLevel e godot_pool_vector2_array_append p s) v pure p type instance TypeOf 'HaskellTy G.PoolVector3Array = V.Vector (V3 Float) instance GodotFFI G.PoolVector3Array (V.Vector (V3 Float)) where fromLowLevel a = do sz <- godot_pool_vector3_array_size a V.generateM (fromIntegral sz) (\x -> fromLowLevel =<< godot_pool_vector3_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_vector3_array_new V.mapM_ (\e -> do s <- toLowLevel e godot_pool_vector3_array_append p s) v pure p type instance TypeOf 'HaskellTy G.PoolIntArray = V.Vector Int instance GodotFFI G.PoolIntArray (V.Vector Int) where fromLowLevel a = do sz <- godot_pool_int_array_size a V.generateM (fromIntegral sz) (\x -> fromIntegral <$> godot_pool_int_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_int_array_new V.mapM_ (godot_pool_int_array_append p . fromIntegral) v pure p type instance TypeOf 'HaskellTy G.PoolRealArray = V.Vector Float instance GodotFFI G.PoolRealArray (V.Vector Float) where fromLowLevel a = do sz <- godot_pool_real_array_size a V.generateM (fromIntegral sz) (\x -> coerce <$> godot_pool_real_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_real_array_new V.mapM_ (godot_pool_real_array_append p . coerce) v pure p type instance TypeOf 'HaskellTy G.PoolColorArray = V.Vector (AlphaColour Double) instance GodotFFI G.PoolColorArray (V.Vector (AlphaColour Double)) where fromLowLevel a = do sz <- godot_pool_color_array_size a V.generateM (fromIntegral sz) (\x -> fromLowLevel =<< godot_pool_color_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_color_array_new V.mapM_ (\e -> do s <- toLowLevel e godot_pool_color_array_append p s) v pure p type instance TypeOf 'HaskellTy G.Dictionary = V.Vector (GodotVariant, GodotVariant) instance GodotFFI G.Dictionary (V.Vector (GodotVariant, GodotVariant)) where fromLowLevel a = do k <- fromLowLevel =<< godot_dictionary_keys a v <- fromLowLevel =<< godot_dictionary_values a pure $ V.zipWith (,) k v toLowLevel v = do d <- godot_dictionary_new V.mapM_ (\(k,v) -> godot_dictionary_set d k v) v pure d -- Variants data Variant (ty :: LibType) = VariantNil | VariantBool !Bool | VariantInt !Int | VariantReal !Float | VariantString !(TypeOf ty GodotString) | VariantVector2 !(TypeOf ty G.Vector2) | VariantRect2 !(TypeOf ty G.Rect2) | VariantVector3 !(TypeOf ty G.Vector3) | VariantTransform2d !(TypeOf ty G.Transform2d) | VariantPlane !(TypeOf ty G.Plane) | VariantQuat !(TypeOf ty G.Quat) | VariantAabb !(TypeOf ty Aabb) | VariantBasis !(TypeOf ty G.Basis) | VariantTransform !(TypeOf ty G.Transform) | VariantColor !(TypeOf ty G.Color) | VariantNodePath !(TypeOf ty G.NodePath) | VariantRid !(TypeOf ty G.Rid) | VariantObject !(TypeOf ty G.Object) | VariantDictionary !(TypeOf ty G.Dictionary) | VariantArray !(TypeOf ty G.Array) | VariantPoolByteArray !(TypeOf ty G.PoolByteArray) | VariantPoolIntArray !(TypeOf ty G.PoolIntArray) | VariantPoolRealArray !(TypeOf ty G.PoolRealArray) | VariantPoolStringArray !(TypeOf ty G.PoolStringArray) | VariantPoolVector2Array !(TypeOf ty G.PoolVector2Array) | VariantPoolVector3Array !(TypeOf ty G.PoolVector3Array) | VariantPoolColorArray !(TypeOf ty G.PoolColorArray) instance GodotFFI GodotVariant (Variant 'GodotTy) where fromLowLevel var = godot_variant_get_type var >>= \case VariantTypeNil -> return VariantNil VariantTypeBool -> VariantBool . (/= 0) <$> godot_variant_as_bool var VariantTypeInt -> VariantInt . fromIntegral <$> godot_variant_as_int var VariantTypeReal -> VariantReal . realToFrac <$> godot_variant_as_real var VariantTypeString -> VariantString <$> godot_variant_as_string var VariantTypeVector2 -> VariantVector2 <$> godot_variant_as_vector2 var VariantTypeRect2 -> VariantRect2 <$> godot_variant_as_rect2 var VariantTypeVector3 -> VariantVector3 <$> godot_variant_as_vector3 var VariantTypeTransform2d -> VariantTransform2d <$> godot_variant_as_transform2d var VariantTypePlane -> VariantPlane <$> godot_variant_as_plane var VariantTypeQuat -> VariantQuat <$> godot_variant_as_quat var VariantTypeAabb -> VariantAabb <$> godot_variant_as_aabb var VariantTypeBasis -> VariantBasis <$> godot_variant_as_basis var VariantTypeTransform -> VariantTransform <$> godot_variant_as_transform var VariantTypeColor -> VariantColor <$> godot_variant_as_color var VariantTypeNodePath -> VariantNodePath <$> godot_variant_as_node_path var VariantTypeRid -> VariantRid <$> godot_variant_as_rid var VariantTypeObject -> VariantObject <$> godot_variant_as_object var VariantTypeDictionary -> VariantDictionary <$> godot_variant_as_dictionary var VariantTypeArray -> VariantArray <$> godot_variant_as_array var VariantTypePoolByteArray -> VariantPoolByteArray <$> godot_variant_as_pool_byte_array var VariantTypePoolIntArray -> VariantPoolIntArray <$> godot_variant_as_pool_int_array var VariantTypePoolRealArray -> VariantPoolRealArray <$> godot_variant_as_pool_real_array var VariantTypePoolStringArray -> VariantPoolStringArray <$> godot_variant_as_pool_string_array var VariantTypePoolVector2Array -> VariantPoolVector2Array <$> godot_variant_as_pool_vector2_array var VariantTypePoolVector3Array -> VariantPoolVector3Array <$> godot_variant_as_pool_vector3_array var VariantTypePoolColorArray -> VariantPoolColorArray <$> godot_variant_as_pool_color_array var toLowLevel VariantNil = godot_variant_new_nil toLowLevel (VariantBool b) = godot_variant_new_bool . fromIntegral $ fromEnum b toLowLevel (VariantInt i) = godot_variant_new_int (fromIntegral i) toLowLevel (VariantReal r) = godot_variant_new_real (realToFrac r) toLowLevel (VariantString x) = godot_variant_new_string x toLowLevel (VariantVector2 x) = godot_variant_new_vector2 x toLowLevel (VariantRect2 x) = godot_variant_new_rect2 x toLowLevel (VariantVector3 x) = godot_variant_new_vector3 x toLowLevel (VariantTransform2d x) = godot_variant_new_transform2d x toLowLevel (VariantPlane x) = godot_variant_new_plane x toLowLevel (VariantQuat x) = godot_variant_new_quat x toLowLevel (VariantAabb x) = godot_variant_new_aabb x toLowLevel (VariantBasis x) = godot_variant_new_basis x toLowLevel (VariantTransform x) = godot_variant_new_transform x toLowLevel (VariantColor x) = godot_variant_new_color x toLowLevel (VariantNodePath x) = godot_variant_new_node_path x toLowLevel (VariantRid x) = godot_variant_new_rid x toLowLevel (VariantObject x) = godot_variant_new_object x toLowLevel (VariantDictionary x) = godot_variant_new_dictionary x toLowLevel (VariantArray x) = godot_variant_new_array x toLowLevel (VariantPoolByteArray x) = godot_variant_new_pool_byte_array x toLowLevel (VariantPoolIntArray x) = godot_variant_new_pool_int_array x toLowLevel (VariantPoolRealArray x) = godot_variant_new_pool_real_array x toLowLevel (VariantPoolStringArray x) = godot_variant_new_pool_string_array x toLowLevel (VariantPoolVector2Array x) = godot_variant_new_pool_vector2_array x toLowLevel (VariantPoolVector3Array x) = godot_variant_new_pool_vector3_array x toLowLevel (VariantPoolColorArray x) = godot_variant_new_pool_color_array x withVariantArray :: [Variant 'GodotTy] -> ((Ptr (Ptr GodotVariant), CInt) -> IO a) -> IO a withVariantArray vars mtd = allocaArray (length vars) $ \arrPtr -> withVars vars 0 arrPtr mtd where withVars (x:xs) n arrPtr mtd = do vt <- toLowLevel x res <- withGodotVariant vt $ \vtPtr -> do poke (advancePtr arrPtr n) vtPtr withVars xs (n+1) arrPtr mtd godot_variant_destroy vt return res withVars [] n arrPtr mtd = mtd (arrPtr, fromIntegral n) defaultedVariant :: (GodotFFI t high, AsVariant a) => (t -> Variant 'GodotTy) -> high -> Maybe a -> Variant 'GodotTy defaultedVariant ty o = maybe (ty $ unsafePerformIO $ toLowLevel o) toVariant # NOINLINE defaultedVariant # throwIfErr :: VariantCallError -> IO () throwIfErr err = case variantCallErrorError err of CallErrorCallOk -> return () _ -> throwIO err class AsVariant a where toVariant :: a -> Variant 'GodotTy fromVariant :: Variant 'GodotTy -> Maybe a variantType :: a -> VariantType instance AsVariant () where toVariant _ = VariantNil fromVariant VariantNil = Just () fromVariant _ = Nothing variantType _ = VariantTypeNil instance AsVariant GodotVariant where toVariant v = let !res = unsafePerformIO $ fromLowLevel v in res fromVariant v = let !res = unsafePerformIO $ toLowLevel v in Just res variantType v = let !res = unsafePerformIO $ godot_variant_get_type v in res $(generateAsVariantInstances) toGodotVariant :: forall a. (Typeable a, AsVariant a) => a -> IO GodotVariant toGodotVariant = toLowLevel . toVariant fromGodotVariant :: forall a. (Typeable a, AsVariant a) => GodotVariant -> IO a fromGodotVariant var = do res <- fromVariant <$> fromLowLevel var case res of Just x -> x `seq` return x Nothing -> do haveTy <- godot_variant_get_type var let expTy = typeOf (undefined :: a) error $ "Error in API: couldn't fromVariant. have: " ++ show haveTy ++ ", expected: " ++ show expTy
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Gdnative/Internal/Types.hs
haskell
I'm torn about this instance. Need TH if not using this |GodotFFI is a relation between low-level and high-level |Godot types, and conversions between them. #numeric-constants This should perhaps be better modeled - FilePath? Variants
# LANGUAGE BangPatterns , FunctionalDependencies , TypeFamilies , TypeInType , LambdaCase , TypeApplications , AllowAmbiguousTypes # module Godot.Gdnative.Internal.Types where import Control.Exception import qualified Data.ByteString as B import qualified Data.ByteString.Unsafe as B import Data.Text (Text) import qualified Data.Text.Encoding as T import Data.Colour import Data.Colour.SRGB import Data.Function ((&)) import Data.Typeable import Data.Coerce import Foreign import Foreign.C import Linear import qualified Data.Vector as V import qualified Data.Map as M import Godot.Gdnative.Internal.Api as I hiding (Rect2,Basis,Transform,Transform2d,Color) import Godot.Gdnative.Internal.Gdnative as I hiding (Rect2,Basis,Transform,Transform2d,Color) import qualified Godot.Gdnative.Internal.Api as G import qualified Godot.Gdnative.Internal.Gdnative as G import Godot.Gdnative.Internal.TH import System.IO.Unsafe data LibType = GodotTy | HaskellTy type family TypeOf (x :: LibType) a type instance TypeOf 'GodotTy a = a class GodotFFI low high | low -> high where fromLowLevel :: low -> IO high toLowLevel :: high -> IO low type instance TypeOf 'HaskellTy G.Array = V.Vector GodotVariant instance GodotFFI G.Array (V.Vector GodotVariant) where fromLowLevel arr = do len <- fromIntegral <$> godot_array_size arr V.generateM len (godot_array_get arr . fromIntegral) toLowLevel vec = do arr <- godot_array_new V.mapM_ (godot_array_append arr) vec pure arr type instance TypeOf 'HaskellTy GodotString = Text instance GodotFFI GodotString Text where fromLowLevel str = godot_string_utf8 str >>= \cstr -> T.decodeUtf8 <$> fromCharString cstr where fromCharString cstr = do len <- godot_char_string_length cstr sptr <- godot_char_string_get_data cstr B.packCStringLen (sptr, fromIntegral len) toLowLevel txt = B.unsafeUseAsCStringLen bstr $ \(ptr, len) -> godot_string_chars_to_utf8_with_len ptr (fromIntegral len) where bstr = T.encodeUtf8 txt type instance TypeOf 'HaskellTy Vector2 = V2 Float instance GodotFFI Vector2 (V2 Float) where fromLowLevel v = V2 <$> (realToFrac <$> godot_vector2_get_x v) <*> (realToFrac <$> godot_vector2_get_y v) toLowLevel (V2 x y) = godot_vector2_new (realToFrac x) (realToFrac y) type instance TypeOf 'HaskellTy Vector3 = V3 Float instance GodotFFI Vector3 (V3 Float) where fromLowLevel v = V3 <$> (realToFrac <$> godot_vector3_get_axis v Vector3AxisX) <*> (realToFrac <$> godot_vector3_get_axis v Vector3AxisY) <*> (realToFrac <$> godot_vector3_get_axis v Vector3AxisZ) toLowLevel (V3 x y z) = godot_vector3_new (realToFrac x) (realToFrac y) (realToFrac z) type instance TypeOf 'HaskellTy Quat = Quaternion Float instance GodotFFI Quat (Quaternion Float) where fromLowLevel q = Quaternion <$> (realToFrac <$> godot_quat_get_w q) <*> (V3 <$> (realToFrac <$> godot_quat_get_x q) <*> (realToFrac <$> godot_quat_get_y q) <*> (realToFrac <$> godot_quat_get_z q)) toLowLevel (Quaternion w (V3 x y z)) = godot_quat_new (realToFrac x) (realToFrac y) (realToFrac z) (realToFrac w) type Rect2 = M22 Float type instance TypeOf 'HaskellTy G.Rect2 = Rect2 instance GodotFFI G.Rect2 Rect2 where fromLowLevel r = V2 <$> (fromLowLevel =<< godot_rect2_get_position r) <*> (fromLowLevel =<< godot_rect2_get_size r) toLowLevel (V2 pos size) = do pos' <- toLowLevel pos size' <- toLowLevel size godot_rect2_new_with_position_and_size pos' size' type AABB = M23 Float type instance TypeOf 'HaskellTy Aabb = AABB instance GodotFFI Aabb AABB where fromLowLevel aabb = V2 <$> (fromLowLevel =<< godot_aabb_get_position aabb) <*> (fromLowLevel =<< godot_aabb_get_size aabb) toLowLevel (V2 pos size) = do pos' <- toLowLevel pos size' <- toLowLevel size godot_aabb_new pos' size' Axes X , Y and Z are represented by the int constants 0 , 1 and 2 respectively ( at least for Vector3 ): type Basis = M33 Float type instance TypeOf 'HaskellTy G.Basis = Basis instance GodotFFI G.Basis Basis where fromLowLevel b = V3 <$> (llAxis 0) <*> (llAxis 1) <*> (llAxis 2) where llAxis axis = fromLowLevel =<< godot_basis_get_axis b axis toLowLevel (V3 x y z) = do x' <- toLowLevel x y' <- toLowLevel y z' <- toLowLevel z godot_basis_new_with_rows x' y' z' data Transform = TF { _tfBasis :: Basis, _tfPosition :: V3 Float } type instance TypeOf 'HaskellTy G.Transform = Transform instance GodotFFI G.Transform Transform where fromLowLevel tf = TF <$> (fromLowLevel =<< godot_transform_get_basis tf) <*> (fromLowLevel =<< godot_transform_get_origin tf) toLowLevel (TF basis orig) = do basis' <- toLowLevel basis orig' <- toLowLevel orig godot_transform_new basis' orig' type Basis2d = M22 Float data Transform2d = TF2d { _tf2dX :: V2 Float, _tf2dY :: V2 Float, _tf2dOrigin :: V2 Float } type instance TypeOf 'HaskellTy G.Transform2d = Transform2d instance GodotFFI G.Transform2d Transform2d where fromLowLevel tf = do x <- godot_transform2d_xform_vector2 tf =<< toLowLevel (V2 1 0) y <- godot_transform2d_xform_vector2 tf =<< toLowLevel (V2 0 1) TF2d <$> fromLowLevel x <*> fromLowLevel y <*> (fromLowLevel =<< godot_transform2d_get_origin tf) toLowLevel (TF2d x y o) = do x' <- toLowLevel x y' <- toLowLevel y o' <- toLowLevel o godot_transform2d_new_axis_origin x' o' y' type instance TypeOf 'HaskellTy G.NodePath = Text instance GodotFFI G.NodePath Text where fromLowLevel np = fromLowLevel =<< godot_node_path_get_name np 0 toLowLevel np = godot_node_path_new =<< toLowLevel np type instance TypeOf 'HaskellTy G.Color = AlphaColour Double instance GodotFFI G.Color (AlphaColour Double) where fromLowLevel c = withOpacity <$> (sRGB <$> (realToFrac <$> godot_color_get_r c) <*> (realToFrac <$> godot_color_get_g c) <*> (realToFrac <$> godot_color_get_b c)) <*> (realToFrac <$> godot_color_get_a c) toLowLevel rgba = toSRGB (rgba `over` black) & \(RGB r g b) -> godot_color_new_rgba (realToFrac r) (realToFrac g) (realToFrac b) (realToFrac $ alphaChannel rgba) type instance TypeOf 'HaskellTy G.PoolStringArray = V.Vector Text instance GodotFFI G.PoolStringArray (V.Vector Text) where fromLowLevel a = do sz <- godot_pool_string_array_size a V.generateM (fromIntegral sz) (\x -> fromLowLevel =<< godot_pool_string_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_string_array_new V.mapM_ (\e -> do s <- toLowLevel e godot_pool_string_array_append p s) v pure p type instance TypeOf 'HaskellTy G.PoolVector2Array = V.Vector (V2 Float) instance GodotFFI G.PoolVector2Array (V.Vector (V2 Float)) where fromLowLevel a = do sz <- godot_pool_vector2_array_size a V.generateM (fromIntegral sz) (\x -> fromLowLevel =<< godot_pool_vector2_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_vector2_array_new V.mapM_ (\e -> do s <- toLowLevel e godot_pool_vector2_array_append p s) v pure p type instance TypeOf 'HaskellTy G.PoolVector3Array = V.Vector (V3 Float) instance GodotFFI G.PoolVector3Array (V.Vector (V3 Float)) where fromLowLevel a = do sz <- godot_pool_vector3_array_size a V.generateM (fromIntegral sz) (\x -> fromLowLevel =<< godot_pool_vector3_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_vector3_array_new V.mapM_ (\e -> do s <- toLowLevel e godot_pool_vector3_array_append p s) v pure p type instance TypeOf 'HaskellTy G.PoolIntArray = V.Vector Int instance GodotFFI G.PoolIntArray (V.Vector Int) where fromLowLevel a = do sz <- godot_pool_int_array_size a V.generateM (fromIntegral sz) (\x -> fromIntegral <$> godot_pool_int_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_int_array_new V.mapM_ (godot_pool_int_array_append p . fromIntegral) v pure p type instance TypeOf 'HaskellTy G.PoolRealArray = V.Vector Float instance GodotFFI G.PoolRealArray (V.Vector Float) where fromLowLevel a = do sz <- godot_pool_real_array_size a V.generateM (fromIntegral sz) (\x -> coerce <$> godot_pool_real_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_real_array_new V.mapM_ (godot_pool_real_array_append p . coerce) v pure p type instance TypeOf 'HaskellTy G.PoolColorArray = V.Vector (AlphaColour Double) instance GodotFFI G.PoolColorArray (V.Vector (AlphaColour Double)) where fromLowLevel a = do sz <- godot_pool_color_array_size a V.generateM (fromIntegral sz) (\x -> fromLowLevel =<< godot_pool_color_array_get a (fromIntegral x)) toLowLevel v = do p <- godot_pool_color_array_new V.mapM_ (\e -> do s <- toLowLevel e godot_pool_color_array_append p s) v pure p type instance TypeOf 'HaskellTy G.Dictionary = V.Vector (GodotVariant, GodotVariant) instance GodotFFI G.Dictionary (V.Vector (GodotVariant, GodotVariant)) where fromLowLevel a = do k <- fromLowLevel =<< godot_dictionary_keys a v <- fromLowLevel =<< godot_dictionary_values a pure $ V.zipWith (,) k v toLowLevel v = do d <- godot_dictionary_new V.mapM_ (\(k,v) -> godot_dictionary_set d k v) v pure d data Variant (ty :: LibType) = VariantNil | VariantBool !Bool | VariantInt !Int | VariantReal !Float | VariantString !(TypeOf ty GodotString) | VariantVector2 !(TypeOf ty G.Vector2) | VariantRect2 !(TypeOf ty G.Rect2) | VariantVector3 !(TypeOf ty G.Vector3) | VariantTransform2d !(TypeOf ty G.Transform2d) | VariantPlane !(TypeOf ty G.Plane) | VariantQuat !(TypeOf ty G.Quat) | VariantAabb !(TypeOf ty Aabb) | VariantBasis !(TypeOf ty G.Basis) | VariantTransform !(TypeOf ty G.Transform) | VariantColor !(TypeOf ty G.Color) | VariantNodePath !(TypeOf ty G.NodePath) | VariantRid !(TypeOf ty G.Rid) | VariantObject !(TypeOf ty G.Object) | VariantDictionary !(TypeOf ty G.Dictionary) | VariantArray !(TypeOf ty G.Array) | VariantPoolByteArray !(TypeOf ty G.PoolByteArray) | VariantPoolIntArray !(TypeOf ty G.PoolIntArray) | VariantPoolRealArray !(TypeOf ty G.PoolRealArray) | VariantPoolStringArray !(TypeOf ty G.PoolStringArray) | VariantPoolVector2Array !(TypeOf ty G.PoolVector2Array) | VariantPoolVector3Array !(TypeOf ty G.PoolVector3Array) | VariantPoolColorArray !(TypeOf ty G.PoolColorArray) instance GodotFFI GodotVariant (Variant 'GodotTy) where fromLowLevel var = godot_variant_get_type var >>= \case VariantTypeNil -> return VariantNil VariantTypeBool -> VariantBool . (/= 0) <$> godot_variant_as_bool var VariantTypeInt -> VariantInt . fromIntegral <$> godot_variant_as_int var VariantTypeReal -> VariantReal . realToFrac <$> godot_variant_as_real var VariantTypeString -> VariantString <$> godot_variant_as_string var VariantTypeVector2 -> VariantVector2 <$> godot_variant_as_vector2 var VariantTypeRect2 -> VariantRect2 <$> godot_variant_as_rect2 var VariantTypeVector3 -> VariantVector3 <$> godot_variant_as_vector3 var VariantTypeTransform2d -> VariantTransform2d <$> godot_variant_as_transform2d var VariantTypePlane -> VariantPlane <$> godot_variant_as_plane var VariantTypeQuat -> VariantQuat <$> godot_variant_as_quat var VariantTypeAabb -> VariantAabb <$> godot_variant_as_aabb var VariantTypeBasis -> VariantBasis <$> godot_variant_as_basis var VariantTypeTransform -> VariantTransform <$> godot_variant_as_transform var VariantTypeColor -> VariantColor <$> godot_variant_as_color var VariantTypeNodePath -> VariantNodePath <$> godot_variant_as_node_path var VariantTypeRid -> VariantRid <$> godot_variant_as_rid var VariantTypeObject -> VariantObject <$> godot_variant_as_object var VariantTypeDictionary -> VariantDictionary <$> godot_variant_as_dictionary var VariantTypeArray -> VariantArray <$> godot_variant_as_array var VariantTypePoolByteArray -> VariantPoolByteArray <$> godot_variant_as_pool_byte_array var VariantTypePoolIntArray -> VariantPoolIntArray <$> godot_variant_as_pool_int_array var VariantTypePoolRealArray -> VariantPoolRealArray <$> godot_variant_as_pool_real_array var VariantTypePoolStringArray -> VariantPoolStringArray <$> godot_variant_as_pool_string_array var VariantTypePoolVector2Array -> VariantPoolVector2Array <$> godot_variant_as_pool_vector2_array var VariantTypePoolVector3Array -> VariantPoolVector3Array <$> godot_variant_as_pool_vector3_array var VariantTypePoolColorArray -> VariantPoolColorArray <$> godot_variant_as_pool_color_array var toLowLevel VariantNil = godot_variant_new_nil toLowLevel (VariantBool b) = godot_variant_new_bool . fromIntegral $ fromEnum b toLowLevel (VariantInt i) = godot_variant_new_int (fromIntegral i) toLowLevel (VariantReal r) = godot_variant_new_real (realToFrac r) toLowLevel (VariantString x) = godot_variant_new_string x toLowLevel (VariantVector2 x) = godot_variant_new_vector2 x toLowLevel (VariantRect2 x) = godot_variant_new_rect2 x toLowLevel (VariantVector3 x) = godot_variant_new_vector3 x toLowLevel (VariantTransform2d x) = godot_variant_new_transform2d x toLowLevel (VariantPlane x) = godot_variant_new_plane x toLowLevel (VariantQuat x) = godot_variant_new_quat x toLowLevel (VariantAabb x) = godot_variant_new_aabb x toLowLevel (VariantBasis x) = godot_variant_new_basis x toLowLevel (VariantTransform x) = godot_variant_new_transform x toLowLevel (VariantColor x) = godot_variant_new_color x toLowLevel (VariantNodePath x) = godot_variant_new_node_path x toLowLevel (VariantRid x) = godot_variant_new_rid x toLowLevel (VariantObject x) = godot_variant_new_object x toLowLevel (VariantDictionary x) = godot_variant_new_dictionary x toLowLevel (VariantArray x) = godot_variant_new_array x toLowLevel (VariantPoolByteArray x) = godot_variant_new_pool_byte_array x toLowLevel (VariantPoolIntArray x) = godot_variant_new_pool_int_array x toLowLevel (VariantPoolRealArray x) = godot_variant_new_pool_real_array x toLowLevel (VariantPoolStringArray x) = godot_variant_new_pool_string_array x toLowLevel (VariantPoolVector2Array x) = godot_variant_new_pool_vector2_array x toLowLevel (VariantPoolVector3Array x) = godot_variant_new_pool_vector3_array x toLowLevel (VariantPoolColorArray x) = godot_variant_new_pool_color_array x withVariantArray :: [Variant 'GodotTy] -> ((Ptr (Ptr GodotVariant), CInt) -> IO a) -> IO a withVariantArray vars mtd = allocaArray (length vars) $ \arrPtr -> withVars vars 0 arrPtr mtd where withVars (x:xs) n arrPtr mtd = do vt <- toLowLevel x res <- withGodotVariant vt $ \vtPtr -> do poke (advancePtr arrPtr n) vtPtr withVars xs (n+1) arrPtr mtd godot_variant_destroy vt return res withVars [] n arrPtr mtd = mtd (arrPtr, fromIntegral n) defaultedVariant :: (GodotFFI t high, AsVariant a) => (t -> Variant 'GodotTy) -> high -> Maybe a -> Variant 'GodotTy defaultedVariant ty o = maybe (ty $ unsafePerformIO $ toLowLevel o) toVariant # NOINLINE defaultedVariant # throwIfErr :: VariantCallError -> IO () throwIfErr err = case variantCallErrorError err of CallErrorCallOk -> return () _ -> throwIO err class AsVariant a where toVariant :: a -> Variant 'GodotTy fromVariant :: Variant 'GodotTy -> Maybe a variantType :: a -> VariantType instance AsVariant () where toVariant _ = VariantNil fromVariant VariantNil = Just () fromVariant _ = Nothing variantType _ = VariantTypeNil instance AsVariant GodotVariant where toVariant v = let !res = unsafePerformIO $ fromLowLevel v in res fromVariant v = let !res = unsafePerformIO $ toLowLevel v in Just res variantType v = let !res = unsafePerformIO $ godot_variant_get_type v in res $(generateAsVariantInstances) toGodotVariant :: forall a. (Typeable a, AsVariant a) => a -> IO GodotVariant toGodotVariant = toLowLevel . toVariant fromGodotVariant :: forall a. (Typeable a, AsVariant a) => GodotVariant -> IO a fromGodotVariant var = do res <- fromVariant <$> fromLowLevel var case res of Just x -> x `seq` return x Nothing -> do haveTy <- godot_variant_get_type var let expTy = typeOf (undefined :: a) error $ "Error in API: couldn't fromVariant. have: " ++ show haveTy ++ ", expected: " ++ show expTy
574060151cace650679b726aede3892707ce9d55be519916b9321a6fc735553d
rmculpepper/binaryio
info.rkt
#lang info ;; ======================================== ;; pkg info (define collection "binaryio") (define deps '(["base" #:version "6.3"] "binaryio-lib" "rackunit-lib" "math-lib")) (define implies '("binaryio-lib")) (define build-deps '("racket-doc" "scribble-lib")) ;; ======================================== ;; collect info (define name "binaryio") (define scribblings '(["scribblings/binaryio.scrbl" (multi-page)]))
null
https://raw.githubusercontent.com/rmculpepper/binaryio/2802c5b95cb51063f97cabb55a349d472dda5050/binaryio/info.rkt
racket
======================================== pkg info ======================================== collect info
#lang info (define collection "binaryio") (define deps '(["base" #:version "6.3"] "binaryio-lib" "rackunit-lib" "math-lib")) (define implies '("binaryio-lib")) (define build-deps '("racket-doc" "scribble-lib")) (define name "binaryio") (define scribblings '(["scribblings/binaryio.scrbl" (multi-page)]))
746788c402befc0dd1088c69bda4ca07b3f4c63edac7e66c8061cbc730b66601
mirage/index
io_array.ml
module Int63 = Optint.Int63 module IO = Index_unix.Private.IO let ( // ) = Filename.concat let root = "_tests" // "unix.io_array" module Entry = struct module Key = Common.Key module Value = Common.Value type t = Key.t * Value.t let encoded_size = Key.encoded_size + Value.encoded_size let decode string off = let key = Key.decode string off in let value = Value.decode string (off + Key.encoded_size) in (key, value) let append_io io (key, value) = let encoded_key = Key.encode key in let encoded_value = Value.encode value in IO.append io encoded_key; IO.append io encoded_value end module IOArray = Index.Private.Io_array.Make (IO) (Entry) let entry = Alcotest.(pair string string) let fresh_io name = IO.v ~fresh:true ~generation:Int63.zero ~fan_size:Int63.zero (root // name) Append a random sequence of [ size ] keys to an IO instance and return a pair of an IOArray and an equivalent in - memory array . a pair of an IOArray and an equivalent in-memory array. *) let populate_random ~size io = let rec loop acc = function | 0 -> acc | n -> let e = (Common.Key.v (), Common.Value.v ()) in Entry.append_io io e; loop (e :: acc) (n - 1) in let mem_arr = Array.of_list (List.rev (loop [] size)) in let io_arr = IOArray.v io in IO.flush io; (mem_arr, io_arr) (* Tests *) let read_sequential () = let size = 1000 in let io = fresh_io "read_sequential" in let mem_arr, io_arr = populate_random ~size io in for i = 0 to size - 1 do let expected = mem_arr.(i) in let actual = IOArray.get io_arr (Int63.of_int i) in Alcotest.(check entry) (Fmt.str "Inserted key at index %i is accessible" i) expected actual done let read_sequential_prefetch () = let size = 1000 in let io = fresh_io "read_sequential_prefetch" in let mem_arr, io_arr = populate_random ~size io in IOArray.pre_fetch io_arr ~low:Int63.zero ~high:(Int63.of_int 999); (* Read the arrays backwards *) for i = size - 1 to 0 do let expected = mem_arr.(i) in let actual = IOArray.get io_arr (Int63.of_int i) in Alcotest.(check entry) (Fmt.str "Inserted key at index %i is accessible" i) expected actual done let tests = [ ("fresh", `Quick, read_sequential); ("prefetch", `Quick, read_sequential_prefetch); ]
null
https://raw.githubusercontent.com/mirage/index/fe5e962534d192389484ecc63a25e4ab4668a2f0/test/unix/io_array.ml
ocaml
Tests Read the arrays backwards
module Int63 = Optint.Int63 module IO = Index_unix.Private.IO let ( // ) = Filename.concat let root = "_tests" // "unix.io_array" module Entry = struct module Key = Common.Key module Value = Common.Value type t = Key.t * Value.t let encoded_size = Key.encoded_size + Value.encoded_size let decode string off = let key = Key.decode string off in let value = Value.decode string (off + Key.encoded_size) in (key, value) let append_io io (key, value) = let encoded_key = Key.encode key in let encoded_value = Value.encode value in IO.append io encoded_key; IO.append io encoded_value end module IOArray = Index.Private.Io_array.Make (IO) (Entry) let entry = Alcotest.(pair string string) let fresh_io name = IO.v ~fresh:true ~generation:Int63.zero ~fan_size:Int63.zero (root // name) Append a random sequence of [ size ] keys to an IO instance and return a pair of an IOArray and an equivalent in - memory array . a pair of an IOArray and an equivalent in-memory array. *) let populate_random ~size io = let rec loop acc = function | 0 -> acc | n -> let e = (Common.Key.v (), Common.Value.v ()) in Entry.append_io io e; loop (e :: acc) (n - 1) in let mem_arr = Array.of_list (List.rev (loop [] size)) in let io_arr = IOArray.v io in IO.flush io; (mem_arr, io_arr) let read_sequential () = let size = 1000 in let io = fresh_io "read_sequential" in let mem_arr, io_arr = populate_random ~size io in for i = 0 to size - 1 do let expected = mem_arr.(i) in let actual = IOArray.get io_arr (Int63.of_int i) in Alcotest.(check entry) (Fmt.str "Inserted key at index %i is accessible" i) expected actual done let read_sequential_prefetch () = let size = 1000 in let io = fresh_io "read_sequential_prefetch" in let mem_arr, io_arr = populate_random ~size io in IOArray.pre_fetch io_arr ~low:Int63.zero ~high:(Int63.of_int 999); for i = size - 1 to 0 do let expected = mem_arr.(i) in let actual = IOArray.get io_arr (Int63.of_int i) in Alcotest.(check entry) (Fmt.str "Inserted key at index %i is accessible" i) expected actual done let tests = [ ("fresh", `Quick, read_sequential); ("prefetch", `Quick, read_sequential_prefetch); ]
24607aa0326560bb6c9311dab02306b08a56576192c0d9aa3bf69bde3c925fe7
sboehler/beans
Position.hs
module Beans.Position ( Position (Position), deleteLot, ) where import Beans.Account (Account) import Beans.Commodity (Commodity) import Beans.Lot (Lot) import Data.Text.Prettyprint.Doc (Pretty (pretty), (<+>)) data Position = Position Account Commodity (Maybe Lot) deriving (Eq, Ord, Show) instance Pretty Position where pretty (Position a c l) = pretty a <+> pretty c <+> pretty l deleteLot :: Position -> Position deleteLot (Position a c _) = Position a c Nothing
null
https://raw.githubusercontent.com/sboehler/beans/897fc30a602f49906eb952c4fd5c8c0bf05a6beb/src/Beans/Position.hs
haskell
module Beans.Position ( Position (Position), deleteLot, ) where import Beans.Account (Account) import Beans.Commodity (Commodity) import Beans.Lot (Lot) import Data.Text.Prettyprint.Doc (Pretty (pretty), (<+>)) data Position = Position Account Commodity (Maybe Lot) deriving (Eq, Ord, Show) instance Pretty Position where pretty (Position a c l) = pretty a <+> pretty c <+> pretty l deleteLot :: Position -> Position deleteLot (Position a c _) = Position a c Nothing
7338f4b4c96f07f4f24369d4c6a8e3eb72f37735a5aa1b9f8930dc2aebddcd33
hiroshi-unno/coar
let-shift0.ml
external shift0 : (('a (*T*) -> 'b (*C1*)) -> 'c (*C2*)) -> 'a (*T*) = "unknown" external reset : (unit -> 'a (*T*)) -> 'b (*C*) = "unknown" let main () = reset (fun () -> let x = shift0 (fun k -> (k 1) + (k 2)) in x ) [@@@assert "typeof(main) <: unit -> {z: int | z = 3}"] [@@@assert "typeof(main) <: unit -> {z: int | z = 2 || z = 3 || z = 4}"]
null
https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/benchmarks/OCaml/safety/shift0_reset0/simple/let-shift0.ml
ocaml
T C1 C2 T T C
let main () = reset (fun () -> let x = shift0 (fun k -> (k 1) + (k 2)) in x ) [@@@assert "typeof(main) <: unit -> {z: int | z = 3}"] [@@@assert "typeof(main) <: unit -> {z: int | z = 2 || z = 3 || z = 4}"]
f9b0dec64da6ea58903685623a66c8d925d1ab32eece4f29972cbc6c43c7ae78
balint99/sfpl
Instances.hs
# LANGUAGE FlexibleInstances , MultiParamTypeClasses , StandaloneDeriving # -- | Instances for the types describing the core syntax. module SFPL.Syntax.Core.Instances where import SFPL.Base import SFPL.Syntax.Core.Types import SFPL.Syntax.Core.Pretty ---------------------------------------- -- Types -- | @since 1.0.0 instance Num Ty where fromInteger = TyVar . fromInteger (+) = undefined (-) = undefined (*) = undefined negate = undefined abs = undefined signum = undefined deriving instance Eq Ty -- ^ @since 1.0.0 -- | @since 1.0.0 instance Pretty TyPCxt Ty where prettyPrec = prettyTy True deriving instance Show Ty -- ^ @since 1.0.0 ---------------------------------------- -- Patterns -- | @since 1.0.0 instance Pretty PatPCxt Pattern where prettyPrec = prettyPat deriving instance Show Pattern -- ^ @since 1.0.0 ---------------------------------------- -- Terms deriving instance Show UnaryOp -- ^ @since 1.0.0 deriving instance Enum UnaryOp -- ^ @since 1.0.0 deriving instance Bounded UnaryOp -- ^ @since 1.0.0 deriving instance Show BinaryOp -- ^ @since 1.0.0 deriving instance Enum BinaryOp -- ^ @since 1.0.0 deriving instance Bounded BinaryOp -- ^ @since 1.0.0 deriving instance Show NullaryFunc -- ^ @since 1.0.0 deriving instance Enum NullaryFunc -- ^ @since 1.0.0 deriving instance Bounded NullaryFunc -- ^ @since 1.0.0 deriving instance Show UnaryFunc -- ^ @since 1.0.0 deriving instance Enum UnaryFunc -- ^ @since 1.0.0 deriving instance Bounded UnaryFunc -- ^ @since 1.0.0 deriving instance Show BinaryFunc -- ^ @since 1.0.0 deriving instance Enum BinaryFunc -- ^ @since 1.0.0 deriving instance Bounded BinaryFunc -- ^ @since 1.0.0 -- | @since 1.0.0 instance Pretty TmPCxt Tm where prettyPrec = prettyTm True deriving instance Show Tm -- ^ @since 1.0.0 -- | @since 1.0.0 instance Pretty TLPCxt TopLevelDef where prettyPrec = prettyTopLevelDef True deriving instance Show TopLevelDef -- ^ @since 1.0.0 ---------------------------------------- -- Type declarations -- | @since 1.0.0 instance Pretty CtrPCxt Constructor where prettyPrec = prettyConstructor deriving instance Show Constructor -- ^ @since 1.0.0 -- | @since 1.0.0 instance Pretty DDPCxt DataDecl where prettyPrec = prettyDataDecl deriving instance Show DataDecl -- ^ @since 1.0.0 -- | @since 1.0.0 instance Pretty TDPCxt TypeDecl where prettyPrec = prettyTypeDecl deriving instance Show TypeDecl -- ^ @since 1.0.0 ---------------------------------------- -- Programs -- | @since 1.0.0 instance Pretty ProgPCxt Program where prettyPrec = prettyProgram True
null
https://raw.githubusercontent.com/balint99/sfpl/7cf8924e6f436704f578927ce2904e45caa76725/app/SFPL/Syntax/Core/Instances.hs
haskell
| Instances for the types describing the core syntax. -------------------------------------- Types | @since 1.0.0 ^ @since 1.0.0 | @since 1.0.0 ^ @since 1.0.0 -------------------------------------- Patterns | @since 1.0.0 ^ @since 1.0.0 -------------------------------------- Terms ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 ^ @since 1.0.0 | @since 1.0.0 ^ @since 1.0.0 | @since 1.0.0 ^ @since 1.0.0 -------------------------------------- Type declarations | @since 1.0.0 ^ @since 1.0.0 | @since 1.0.0 ^ @since 1.0.0 | @since 1.0.0 ^ @since 1.0.0 -------------------------------------- Programs | @since 1.0.0
# LANGUAGE FlexibleInstances , MultiParamTypeClasses , StandaloneDeriving # module SFPL.Syntax.Core.Instances where import SFPL.Base import SFPL.Syntax.Core.Types import SFPL.Syntax.Core.Pretty instance Num Ty where fromInteger = TyVar . fromInteger (+) = undefined (-) = undefined (*) = undefined negate = undefined abs = undefined signum = undefined instance Pretty TyPCxt Ty where prettyPrec = prettyTy True instance Pretty PatPCxt Pattern where prettyPrec = prettyPat instance Pretty TmPCxt Tm where prettyPrec = prettyTm True instance Pretty TLPCxt TopLevelDef where prettyPrec = prettyTopLevelDef True instance Pretty CtrPCxt Constructor where prettyPrec = prettyConstructor instance Pretty DDPCxt DataDecl where prettyPrec = prettyDataDecl instance Pretty TDPCxt TypeDecl where prettyPrec = prettyTypeDecl instance Pretty ProgPCxt Program where prettyPrec = prettyProgram True
372b33edce19766173a3c257fbe6455ba86a6d3b8748a5e5036484c904151f80
dyoo/whalesong
graphs.rkt
#lang whalesong Modified 2 March 1997 by to add graphs - benchmark and to expand the four macros below . Modified 11 June 1997 by to eliminate assertions ; and to replace a use of "recur" with a named let. Modified 4 May 2010 by to get rid of one - armed ifs ; Performance note : ( graphs - benchmark 7 ) allocates 34509143 pairs 389625 vectors with 2551590 elements 56653504 closures ( not counting top level and known procedures ) ; End of new code. ;;; ==== std.ss ==== ; (define-syntax assert ; (syntax-rules () ; ((assert test info-rest ...) ; #f))) ; ; (define-syntax deny ; (syntax-rules () ; ((deny test info-rest ...) ; #f))) ; ; (define-syntax when ; (syntax-rules () ( ( when test e - first e - rest ... ) ; (if test ; (begin e-first ; e-rest ...))))) ; ; (define-syntax unless ; (syntax-rules () ( ( unless test e - first e - rest ... ) ; (if (not test) ; (begin e-first ; e-rest ...))))) ;;; ==== util.ss ==== Fold over list elements , associating to the left . (define fold (lambda (lst folder state) '(assert (list? lst) lst) '(assert (procedure? folder) folder) (do ((lst lst (cdr lst)) (state state (folder (car lst) state))) ((null? lst) state)))) ; Given the size of a vector and a procedure which ; sends indices to desired vector elements, create ; and return the vector. (define proc->vector (lambda (size f) '(assert (and (integer? size) (exact? size) (>= size 0)) size) '(assert (procedure? f) f) (if (zero? size) (vector) (let ((x (make-vector size (f 0)))) (let loop ((i 1)) [ wdc - was when ] (vector-set! x i (f i)) (loop (+ i 1))) #t)) x)))) (define vector-fold (lambda (vec folder state) '(assert (vector? vec) vec) '(assert (procedure? folder) folder) (let ((len (vector-length vec))) (do ((i 0 (+ i 1)) (state state (folder (vector-ref vec i) state))) ((= i len) state))))) (define vec-map (lambda (vec proc) (proc->vector (vector-length vec) (lambda (i) (proc (vector-ref vec i)))))) Given limit , return the list 0 , 1 , ... , limit-1 . (define giota (lambda (limit) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) (let _-*- ((limit limit) (res '())) (if (zero? limit) res (let ((limit (- limit 1))) (_-*- limit (cons limit res))))))) Fold over the integers [ 0 , limit ) . (define gnatural-fold (lambda (limit folder state) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) '(assert (procedure? folder) folder) (do ((i 0 (+ i 1)) (state state (folder i state))) ((= i limit) state)))) ; Iterate over the integers [0, limit). (define gnatural-for-each (lambda (limit proc!) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) '(assert (procedure? proc!) proc!) (do ((i 0 (+ i 1))) ((= i limit)) (proc! i)))) (define natural-for-all? (lambda (limit ok?) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) '(assert (procedure? ok?) ok?) (let _-*- ((i 0)) (or (= i limit) (and (ok? i) (_-*- (+ i 1))))))) (define natural-there-exists? (lambda (limit ok?) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) '(assert (procedure? ok?) ok?) (let _-*- ((i 0)) (and (not (= i limit)) (or (ok? i) (_-*- (+ i 1))))))) (define there-exists? (lambda (lst ok?) '(assert (list? lst) lst) '(assert (procedure? ok?) ok?) (let _-*- ((lst lst)) (and (not (null? lst)) (or (ok? (car lst)) (_-*- (cdr lst))))))) ;;; ==== ptfold.ss ==== Fold over the tree of permutations of a universe . ; Each branch (from the root) is a permutation of universe. ; Each node at depth d corresponds to all permutations which pick the ; elements spelled out on the branch from the root to that node as the first d elements . Their are two components to the state : ; The b-state is only a function of the branch from the root. ; The t-state is a function of all nodes seen so far. ; At each node, b-folder is called via ; (b-folder elem b-state t-state deeper accross) ; where elem is the next element of the universe picked. ; If b-folder can determine the result of the total tree fold at this stage, ; it should simply return the result. ; If b-folder can determine the result of folding over the sub-tree ; rooted at the resulting node, it should call accross via ; (accross new-t-state) ; where new-t-state is that result. ; Otherwise, b-folder should call deeper via ; (deeper new-b-state new-t-state) ; where new-b-state is the b-state for the new node and new-t-state is ; the new folded t-state. ; At the leaves of the tree, t-folder is called via ; (t-folder b-state t-state accross) ; If t-folder can determine the result of the total tree fold at this stage, ; it should simply return that result. ; If not, it should call accross via ; (accross new-t-state) Note , fold - over - perm - tree always calls b - folder in depth - first order . ; I.e., when b-folder is called at depth d, the branch leading to that node is the most recent calls to b - folder at all the depths less than d. ; This is a gross efficiency hack so that b-folder can use mutation to ; keep the current branch. (define fold-over-perm-tree (lambda (universe b-folder b-state t-folder t-state) '(assert (list? universe) universe) '(assert (procedure? b-folder) b-folder) '(assert (procedure? t-folder) t-folder) (let _-*- ((universe universe) (b-state b-state) (t-state t-state) (accross (lambda (final-t-state) final-t-state))) (if (null? universe) (t-folder b-state t-state accross) (let _-**- ((in universe) (out '()) (t-state t-state)) (let* ((first (car in)) (rest (cdr in)) (accross (if (null? rest) accross (lambda (new-t-state) (_-**- rest (cons first out) new-t-state))))) (b-folder first b-state t-state (lambda (new-b-state new-t-state) (_-*- (fold out cons rest) new-b-state new-t-state accross)) accross))))))) ;;; ==== minimal.ss ==== ; A directed graph is stored as a connection matrix (vector-of-vectors) where the first index is the ` from ' vertex and the second is the ` to ' ; vertex. Each entry is a bool indicating if the edge exists. ; The diagonal of the matrix is never examined. ; Make-minimal? returns a procedure which tests if a labelling ; of the vertices is such that the matrix is minimal. ; If it is, then the procedure returns the result of folding over the elements of the automoriphism group . If not , it returns # f. ; The folding is done by calling folder via ; (folder perm state accross) ; If the folder wants to continue, it should call accross via ; (accross new-state) ; If it just wants the entire minimal? procedure to return something, ; it should return that. ; The ordering used is lexicographic (with #t > #f) and entries ; are examined in the following order: 1->0 , 0->1 ; 2->0 , 0->2 2->1 , 1->2 ; ; 3->0, 0->3 3->1 , 1->3 3->2 , 2->3 ; ... (define make-minimal? (lambda (max-size) '(assert (and (integer? max-size) (exact? max-size) (>= max-size 0)) max-size) (let ((iotas (proc->vector (+ max-size 1) giota)) (perm (make-vector max-size 0))) (lambda (size graph folder state) '(assert (and (integer? size) (exact? size) (<= 0 size max-size)) size max-size) '(assert (vector? graph) graph) '(assert (procedure? folder) folder) (fold-over-perm-tree (vector-ref iotas size) (lambda (perm-x x state deeper accross) (case (cmp-next-vertex graph perm x perm-x) ((less) #f) ((equal) (vector-set! perm x perm-x) (deeper (+ x 1) state)) ((more) (accross state)) ;(else ; (assert #f)) )) 0 (lambda (leaf-depth state accross) '(assert (eqv? leaf-depth size) leaf-depth size) (folder perm state accross)) state))))) ; Given a graph, a partial permutation vector, the next input and the next ; output, return 'less, 'equal or 'more depending on the lexicographic comparison between the permuted and un - permuted graph . (define cmp-next-vertex (lambda (graph perm x perm-x) (let ((from-x (vector-ref graph x)) (from-perm-x (vector-ref graph perm-x))) (let _-*- ((y 0)) (if (= x y) 'equal (let ((x->y? (vector-ref from-x y)) (perm-y (vector-ref perm y))) (cond ((eq? x->y? (vector-ref from-perm-x perm-y)) (let ((y->x? (vector-ref (vector-ref graph y) x))) (cond ((eq? y->x? (vector-ref (vector-ref graph perm-y) perm-x)) (_-*- (+ y 1))) (y->x? 'less) (else 'more)))) (x->y? 'less) (else 'more)))))))) ;;; ==== rdg.ss ==== Fold over rooted directed graphs with bounded out - degree . Size is the number of vertices ( including the root ) . - out is the ; maximum out-degree for any vertex. Folder is called via ; (folder edges state) ; where edges is a list of length size. The ith element of the list is ; a list of the vertices j for which there is an edge from i to j. ; The last vertex is the root. (define fold-over-rdg (lambda (size max-out folder state) '(assert (and (exact? size) (integer? size) (> size 0)) size) '(assert (and (exact? max-out) (integer? max-out) (>= max-out 0)) max-out) '(assert (procedure? folder) folder) (let* ((root (- size 1)) (edge? (proc->vector size (lambda (from) (make-vector size #f)))) (edges (make-vector size '())) (out-degrees (make-vector size 0)) (minimal-folder (make-minimal? root)) (non-root-minimal? (let ((cont (lambda (perm state accross) '(assert (eq? state #t) state) (accross #t)))) (lambda (size) (minimal-folder size edge? cont #t)))) (root-minimal? (let ((cont (lambda (perm state accross) '(assert (eq? state #t) state) (case (cmp-next-vertex edge? perm root root) ((less) #f) ((equal more) (accross #t)) ;(else ; (assert #f)) )))) (lambda () (minimal-folder root edge? cont #t))))) (let _-*- ((vertex 0) (state state)) (cond ((not (non-root-minimal? vertex)) state) ((= vertex root) '(assert (begin (gnatural-for-each root (lambda (v) '(assert (= (vector-ref out-degrees v) (length (vector-ref edges v))) v (vector-ref out-degrees v) (vector-ref edges v)))) #t)) (let ((reach? (make-reach? root edges)) (from-root (vector-ref edge? root))) (let _-*- ((v 0) (outs 0) (efr '()) (efrr '()) (state state)) (cond ((not (or (= v root) (= outs max-out))) (vector-set! from-root v #t) (let ((state (_-*- (+ v 1) (+ outs 1) (cons v efr) (cons (vector-ref reach? v) efrr) state))) (vector-set! from-root v #f) (_-*- (+ v 1) outs efr efrr state))) ((and (natural-for-all? root (lambda (v) (there-exists? efrr (lambda (r) (vector-ref r v))))) (root-minimal?)) (vector-set! edges root efr) (folder (proc->vector size (lambda (i) (vector-ref edges i))) state)) (else state))))) (else (let ((from-vertex (vector-ref edge? vertex))) (let _-**- ((sv 0) (outs 0) (state state)) (if (= sv vertex) (begin (vector-set! out-degrees vertex outs) (_-*- (+ vertex 1) state)) (let* ((state ; no sv->vertex, no vertex->sv (_-**- (+ sv 1) outs state)) (from-sv (vector-ref edge? sv)) (sv-out (vector-ref out-degrees sv)) (state (if (= sv-out max-out) state (begin (vector-set! edges sv (cons vertex (vector-ref edges sv))) (vector-set! from-sv vertex #t) (vector-set! out-degrees sv (+ sv-out 1)) (let* ((state ; sv->vertex, no vertex->sv (_-**- (+ sv 1) outs state)) (state (if (= outs max-out) state (begin (vector-set! from-vertex sv #t) (vector-set! edges vertex (cons sv (vector-ref edges vertex))) (let ((state ; sv->vertex, vertex->sv (_-**- (+ sv 1) (+ outs 1) state))) (vector-set! edges vertex (cdr (vector-ref edges vertex))) (vector-set! from-vertex sv #f) state))))) (vector-set! out-degrees sv sv-out) (vector-set! from-sv vertex #f) (vector-set! edges sv (cdr (vector-ref edges sv))) state))))) (if (= outs max-out) state (begin (vector-set! edges vertex (cons sv (vector-ref edges vertex))) (vector-set! from-vertex sv #t) (let ((state ; no sv->vertex, vertex->sv (_-**- (+ sv 1) (+ outs 1) state))) (vector-set! from-vertex sv #f) (vector-set! edges vertex (cdr (vector-ref edges vertex))) state))))))))))))) ; Given a vector which maps vertex to out-going-edge list, ; return a vector which gives reachability. (define make-reach? (lambda (size vertex->out) (let ((res (proc->vector size (lambda (v) (let ((from-v (make-vector size #f))) (vector-set! from-v v #t) (for-each (lambda (x) (vector-set! from-v x #t)) (vector-ref vertex->out v)) from-v))))) (gnatural-for-each size (lambda (m) (let ((from-m (vector-ref res m))) (gnatural-for-each size (lambda (f) (let ((from-f (vector-ref res f))) [ wdc - was when ] (begin (gnatural-for-each size (lambda (t) (if (vector-ref from-m t) [ wdc - was when ] (vector-set! from-f t #t)) #t)))) #t))))))) res))) ;;; ==== test input ==== ; Produces all directed graphs with N vertices, distinguished root, and out - degree bounded by 2 , upto isomorphism ( there are 44 ) . ;(define go ( let ( ( N 7 ) ) ; (fold-over-rdg N 2 ; cons ; '()))) ( if input 6 1 ) 2 cons '())
null
https://raw.githubusercontent.com/dyoo/whalesong/636e0b4e399e4523136ab45ef4cd1f5a84e88cdc/whalesong/tests/more-tests/graphs.rkt
racket
and to replace a use of "recur" with a named let. End of new code. ==== std.ss ==== (define-syntax assert (syntax-rules () ((assert test info-rest ...) #f))) (define-syntax deny (syntax-rules () ((deny test info-rest ...) #f))) (define-syntax when (syntax-rules () (if test (begin e-first e-rest ...))))) (define-syntax unless (syntax-rules () (if (not test) (begin e-first e-rest ...))))) ==== util.ss ==== Given the size of a vector and a procedure which sends indices to desired vector elements, create and return the vector. Iterate over the integers [0, limit). ==== ptfold.ss ==== Each branch (from the root) is a permutation of universe. Each node at depth d corresponds to all permutations which pick the elements spelled out on the branch from the root to that node as The b-state is only a function of the branch from the root. The t-state is a function of all nodes seen so far. At each node, b-folder is called via (b-folder elem b-state t-state deeper accross) where elem is the next element of the universe picked. If b-folder can determine the result of the total tree fold at this stage, it should simply return the result. If b-folder can determine the result of folding over the sub-tree rooted at the resulting node, it should call accross via (accross new-t-state) where new-t-state is that result. Otherwise, b-folder should call deeper via (deeper new-b-state new-t-state) where new-b-state is the b-state for the new node and new-t-state is the new folded t-state. At the leaves of the tree, t-folder is called via (t-folder b-state t-state accross) If t-folder can determine the result of the total tree fold at this stage, it should simply return that result. If not, it should call accross via (accross new-t-state) I.e., when b-folder is called at depth d, the branch leading to that This is a gross efficiency hack so that b-folder can use mutation to keep the current branch. ==== minimal.ss ==== A directed graph is stored as a connection matrix (vector-of-vectors) vertex. Each entry is a bool indicating if the edge exists. The diagonal of the matrix is never examined. Make-minimal? returns a procedure which tests if a labelling of the vertices is such that the matrix is minimal. If it is, then the procedure returns the result of folding over The folding is done by calling folder via (folder perm state accross) If the folder wants to continue, it should call accross via (accross new-state) If it just wants the entire minimal? procedure to return something, it should return that. The ordering used is lexicographic (with #t > #f) and entries are examined in the following order: 3->0, 0->3 ... (else (assert #f)) Given a graph, a partial permutation vector, the next input and the next output, return 'less, 'equal or 'more depending on the lexicographic ==== rdg.ss ==== maximum out-degree for any vertex. Folder is called via (folder edges state) where edges is a list of length size. The ith element of the list is a list of the vertices j for which there is an edge from i to j. The last vertex is the root. (else (assert #f)) no sv->vertex, no vertex->sv sv->vertex, no vertex->sv sv->vertex, vertex->sv no sv->vertex, vertex->sv Given a vector which maps vertex to out-going-edge list, return a vector which gives reachability. ==== test input ==== Produces all directed graphs with N vertices, distinguished root, (define go (fold-over-rdg N cons '())))
#lang whalesong Modified 2 March 1997 by to add graphs - benchmark and to expand the four macros below . Modified 11 June 1997 by to eliminate assertions Modified 4 May 2010 by to get rid of one - armed ifs Performance note : ( graphs - benchmark 7 ) allocates 34509143 pairs 389625 vectors with 2551590 elements 56653504 closures ( not counting top level and known procedures ) ( ( when test e - first e - rest ... ) ( ( unless test e - first e - rest ... ) Fold over list elements , associating to the left . (define fold (lambda (lst folder state) '(assert (list? lst) lst) '(assert (procedure? folder) folder) (do ((lst lst (cdr lst)) (state state (folder (car lst) state))) ((null? lst) state)))) (define proc->vector (lambda (size f) '(assert (and (integer? size) (exact? size) (>= size 0)) size) '(assert (procedure? f) f) (if (zero? size) (vector) (let ((x (make-vector size (f 0)))) (let loop ((i 1)) [ wdc - was when ] (vector-set! x i (f i)) (loop (+ i 1))) #t)) x)))) (define vector-fold (lambda (vec folder state) '(assert (vector? vec) vec) '(assert (procedure? folder) folder) (let ((len (vector-length vec))) (do ((i 0 (+ i 1)) (state state (folder (vector-ref vec i) state))) ((= i len) state))))) (define vec-map (lambda (vec proc) (proc->vector (vector-length vec) (lambda (i) (proc (vector-ref vec i)))))) Given limit , return the list 0 , 1 , ... , limit-1 . (define giota (lambda (limit) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) (let _-*- ((limit limit) (res '())) (if (zero? limit) res (let ((limit (- limit 1))) (_-*- limit (cons limit res))))))) Fold over the integers [ 0 , limit ) . (define gnatural-fold (lambda (limit folder state) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) '(assert (procedure? folder) folder) (do ((i 0 (+ i 1)) (state state (folder i state))) ((= i limit) state)))) (define gnatural-for-each (lambda (limit proc!) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) '(assert (procedure? proc!) proc!) (do ((i 0 (+ i 1))) ((= i limit)) (proc! i)))) (define natural-for-all? (lambda (limit ok?) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) '(assert (procedure? ok?) ok?) (let _-*- ((i 0)) (or (= i limit) (and (ok? i) (_-*- (+ i 1))))))) (define natural-there-exists? (lambda (limit ok?) '(assert (and (integer? limit) (exact? limit) (>= limit 0)) limit) '(assert (procedure? ok?) ok?) (let _-*- ((i 0)) (and (not (= i limit)) (or (ok? i) (_-*- (+ i 1))))))) (define there-exists? (lambda (lst ok?) '(assert (list? lst) lst) '(assert (procedure? ok?) ok?) (let _-*- ((lst lst)) (and (not (null? lst)) (or (ok? (car lst)) (_-*- (cdr lst))))))) Fold over the tree of permutations of a universe . the first d elements . Their are two components to the state : Note , fold - over - perm - tree always calls b - folder in depth - first order . node is the most recent calls to b - folder at all the depths less than d. (define fold-over-perm-tree (lambda (universe b-folder b-state t-folder t-state) '(assert (list? universe) universe) '(assert (procedure? b-folder) b-folder) '(assert (procedure? t-folder) t-folder) (let _-*- ((universe universe) (b-state b-state) (t-state t-state) (accross (lambda (final-t-state) final-t-state))) (if (null? universe) (t-folder b-state t-state accross) (let _-**- ((in universe) (out '()) (t-state t-state)) (let* ((first (car in)) (rest (cdr in)) (accross (if (null? rest) accross (lambda (new-t-state) (_-**- rest (cons first out) new-t-state))))) (b-folder first b-state t-state (lambda (new-b-state new-t-state) (_-*- (fold out cons rest) new-b-state new-t-state accross)) accross))))))) where the first index is the ` from ' vertex and the second is the ` to ' the elements of the automoriphism group . If not , it returns # f. 1->0 , 0->1 2->0 , 0->2 2->1 , 1->2 3->1 , 1->3 3->2 , 2->3 (define make-minimal? (lambda (max-size) '(assert (and (integer? max-size) (exact? max-size) (>= max-size 0)) max-size) (let ((iotas (proc->vector (+ max-size 1) giota)) (perm (make-vector max-size 0))) (lambda (size graph folder state) '(assert (and (integer? size) (exact? size) (<= 0 size max-size)) size max-size) '(assert (vector? graph) graph) '(assert (procedure? folder) folder) (fold-over-perm-tree (vector-ref iotas size) (lambda (perm-x x state deeper accross) (case (cmp-next-vertex graph perm x perm-x) ((less) #f) ((equal) (vector-set! perm x perm-x) (deeper (+ x 1) state)) ((more) (accross state)) )) 0 (lambda (leaf-depth state accross) '(assert (eqv? leaf-depth size) leaf-depth size) (folder perm state accross)) state))))) comparison between the permuted and un - permuted graph . (define cmp-next-vertex (lambda (graph perm x perm-x) (let ((from-x (vector-ref graph x)) (from-perm-x (vector-ref graph perm-x))) (let _-*- ((y 0)) (if (= x y) 'equal (let ((x->y? (vector-ref from-x y)) (perm-y (vector-ref perm y))) (cond ((eq? x->y? (vector-ref from-perm-x perm-y)) (let ((y->x? (vector-ref (vector-ref graph y) x))) (cond ((eq? y->x? (vector-ref (vector-ref graph perm-y) perm-x)) (_-*- (+ y 1))) (y->x? 'less) (else 'more)))) (x->y? 'less) (else 'more)))))))) Fold over rooted directed graphs with bounded out - degree . Size is the number of vertices ( including the root ) . - out is the (define fold-over-rdg (lambda (size max-out folder state) '(assert (and (exact? size) (integer? size) (> size 0)) size) '(assert (and (exact? max-out) (integer? max-out) (>= max-out 0)) max-out) '(assert (procedure? folder) folder) (let* ((root (- size 1)) (edge? (proc->vector size (lambda (from) (make-vector size #f)))) (edges (make-vector size '())) (out-degrees (make-vector size 0)) (minimal-folder (make-minimal? root)) (non-root-minimal? (let ((cont (lambda (perm state accross) '(assert (eq? state #t) state) (accross #t)))) (lambda (size) (minimal-folder size edge? cont #t)))) (root-minimal? (let ((cont (lambda (perm state accross) '(assert (eq? state #t) state) (case (cmp-next-vertex edge? perm root root) ((less) #f) ((equal more) (accross #t)) )))) (lambda () (minimal-folder root edge? cont #t))))) (let _-*- ((vertex 0) (state state)) (cond ((not (non-root-minimal? vertex)) state) ((= vertex root) '(assert (begin (gnatural-for-each root (lambda (v) '(assert (= (vector-ref out-degrees v) (length (vector-ref edges v))) v (vector-ref out-degrees v) (vector-ref edges v)))) #t)) (let ((reach? (make-reach? root edges)) (from-root (vector-ref edge? root))) (let _-*- ((v 0) (outs 0) (efr '()) (efrr '()) (state state)) (cond ((not (or (= v root) (= outs max-out))) (vector-set! from-root v #t) (let ((state (_-*- (+ v 1) (+ outs 1) (cons v efr) (cons (vector-ref reach? v) efrr) state))) (vector-set! from-root v #f) (_-*- (+ v 1) outs efr efrr state))) ((and (natural-for-all? root (lambda (v) (there-exists? efrr (lambda (r) (vector-ref r v))))) (root-minimal?)) (vector-set! edges root efr) (folder (proc->vector size (lambda (i) (vector-ref edges i))) state)) (else state))))) (else (let ((from-vertex (vector-ref edge? vertex))) (let _-**- ((sv 0) (outs 0) (state state)) (if (= sv vertex) (begin (vector-set! out-degrees vertex outs) (_-*- (+ vertex 1) state)) (let* ((state (_-**- (+ sv 1) outs state)) (from-sv (vector-ref edge? sv)) (sv-out (vector-ref out-degrees sv)) (state (if (= sv-out max-out) state (begin (vector-set! edges sv (cons vertex (vector-ref edges sv))) (vector-set! from-sv vertex #t) (vector-set! out-degrees sv (+ sv-out 1)) (let* ((state (_-**- (+ sv 1) outs state)) (state (if (= outs max-out) state (begin (vector-set! from-vertex sv #t) (vector-set! edges vertex (cons sv (vector-ref edges vertex))) (let ((state (_-**- (+ sv 1) (+ outs 1) state))) (vector-set! edges vertex (cdr (vector-ref edges vertex))) (vector-set! from-vertex sv #f) state))))) (vector-set! out-degrees sv sv-out) (vector-set! from-sv vertex #f) (vector-set! edges sv (cdr (vector-ref edges sv))) state))))) (if (= outs max-out) state (begin (vector-set! edges vertex (cons sv (vector-ref edges vertex))) (vector-set! from-vertex sv #t) (let ((state (_-**- (+ sv 1) (+ outs 1) state))) (vector-set! from-vertex sv #f) (vector-set! edges vertex (cdr (vector-ref edges vertex))) state))))))))))))) (define make-reach? (lambda (size vertex->out) (let ((res (proc->vector size (lambda (v) (let ((from-v (make-vector size #f))) (vector-set! from-v v #t) (for-each (lambda (x) (vector-set! from-v x #t)) (vector-ref vertex->out v)) from-v))))) (gnatural-for-each size (lambda (m) (let ((from-m (vector-ref res m))) (gnatural-for-each size (lambda (f) (let ((from-f (vector-ref res f))) [ wdc - was when ] (begin (gnatural-for-each size (lambda (t) (if (vector-ref from-m t) [ wdc - was when ] (vector-set! from-f t #t)) #t)))) #t))))))) res))) and out - degree bounded by 2 , upto isomorphism ( there are 44 ) . ( let ( ( N 7 ) ) 2 ( if input 6 1 ) 2 cons '())
9988a34bd8b2fbb6e8fd520f39b680b7470dea1ed28b15a0a963ac9c7af88ddc
dybber/fcl
CodeGen.hs
module FCL.IL.CodeGen (codeGen) where import qualified Data.Set as Set import qualified Data.Map as Map import Data.Set (Set) import Data.Map (Map) import CGen hiding (freeVars) import CGen.Syntax (Statement(Decl), CExp(Int32E)) import CGen.OpenCL.HostCode import FCL.IL.Analysis.Liveness import FCL.IL.Analysis.FreeVars import FCL.Compile.Config import FCL.IL.Syntax import FCL.IL.TypeCheck data Kernel = Kernel Int -- number of shared memory arrays [(ILName, ILType)] -- parameters, bound in host-code TopLevel -- kernel declaration -- kernel handle in hostcode data Value = VInt CExp | VBool CExp | VDouble CExp | VString CExp size , elem type and ptr | VHostBuffer ILType ClDeviceBuffer -- size, elem type and opencl memobject deriving Show data Var = VarInt VarName | VarBool VarName | VarDouble VarName | VarString VarName | VarKernelArray ILType VarName | VarHostBuffer ILType ClDeviceBuffer deriving Show type VarEnv = Map.Map ILName Var getVarName :: Var -> VarName getVarName (VarInt x) = x getVarName (VarBool x) = x getVarName (VarDouble x) = x getVarName (VarString x) = x getVarName (VarKernelArray _ x) = x getVarName (VarHostBuffer _ (ClDeviceBuffer x)) = x unInt :: Value -> CExp unInt (VInt i) = i unInt _ = error ("Unexpected value, expecting integer.") unBool :: Value -> CExp unBool (VBool i) = i unBool _ = error ("Unexpected value, expecting bool.") unString :: Value -> CExp unString (VString str) = str unString _ = error ("Unexpected value, expecting string.") convertType :: ILType -> CType convertType ILInt = int32_t convertType ILBool = bool_t convertType ILDouble = double_t convertType ILString = string_t convertType (ILArray ty) = pointer_t [] (convertType ty) hostVarToKernelVar :: VarEnv -> ILName -> CGen a Var hostVarToKernelVar env x = case Map.lookup x env of Just (VarInt _) -> VarInt `fmap` (newVar int32_t (show x)) Just (VarBool _) -> VarBool `fmap` (newVar bool_t (show x)) Just (VarDouble _) -> VarDouble `fmap` (newVar double_t (show x)) Just (VarHostBuffer elemty _) -> VarKernelArray elemty `fmap` (newVar (pointer_t [attrGlobal] (convertType elemty)) (show x)) Just (VarString _) -> error "string" Just (VarKernelArray _ _) -> error "kernel array" Nothing -> error ("not defined: " ++ show x) --------------------------- -- Host generation monad -- --------------------------- -- Host monad type ILHost a = CGen HostState a type KernelMap = Map String Kernel data HostState = HostState { kernels :: KernelMap , deviceAllocations :: Map ClDeviceBuffer (CExp, CType) , hostAllocations :: Set VarName , typeEnv :: TypeEnv } initHostState :: TypeEnv -> HostState initHostState env = HostState { kernels = Map.empty , deviceAllocations = Map.empty , hostAllocations = Set.empty , typeEnv = env } addKernel :: String -> Kernel -> ILHost () addKernel name k = modifyState (\s -> s { kernels = Map.insert name k (kernels s) }) ----------------------------- -- Kernel generation monad -- ----------------------------- type ILKernel a = CGen KernelState a -- sharedMemPtrName :: VarName -- sharedMemPtrName = ("sbase", pointer_t [attrLocal] uint8_t) data KernelState = allocPtrOffset : : CExp -- , sharedMemPointer :: VarName -- , allocations :: [VarName] } initKernelState :: KernelState initKernelState = KernelState { -- allocPtrOffset = constant (0 :: Int) -- , sharedMemPointer = sharedMemPtrName -- , allocations = [] } allocateKernel :: CType -> CExp -> ILKernel VarName allocateKernel cty n = do -- offset <- getsState allocPtrOffset -- sbase <- getsState sharedMemPointer let aty = pointer_t [attrLocal] cty v < - letVar " arr " aty ( cast aty ( var sbase ` addPtr ` offset ) ) -- let bytes = n `muli` (sizeOf cty) -- modifyState (\s -> s { allocPtrOffset = offset `addi` bytes }) v1 <- newVar aty "shared" modifyState (\s -> s { allocations = v1 : allocations s }) return v1 ---------------------------------------------- -- Compiling expressions - both host/kernel -- ---------------------------------------------- compExp :: VarEnv -> ILExp -> Value compExp _ (EInt i) = VInt (constant i) compExp _ (EBool b) = VBool (constant b) compExp _ (EDouble d) = VDouble (constant d) compExp _ (EString s) = VString (string s) compExp env (EIndex x i) = let v1 = compExp env i in case Map.lookup x env of (Just (VarKernelArray ILInt v)) -> VInt (index v (unInt v1)) (Just (VarKernelArray ILDouble v)) -> VDouble (index v (unInt v1)) (Just (VarKernelArray ILBool v)) -> VBool (index v (unInt v1)) _ -> error "not an array" compExp env (EVar x) = case Map.lookup x env of (Just (VarInt v)) -> VInt (var v) (Just (VarBool v)) -> VBool (var v) (Just (VarDouble v)) -> VDouble (var v) (Just (VarString v)) -> VString (var v) (Just (VarKernelArray ty v)) -> VKernelArray ty v (Just (VarHostBuffer ty buf)) -> VHostBuffer ty buf Nothing -> error ("Undefined variable " ++ show x) compExp env (EUnaryOp op e0) = let v0 = compExp env e0 in unop op v0 compExp env (EBinOp op e0 e1) = let v0 = compExp env e0 v1 = compExp env e1 in binop op v0 v1 compExp env (EIf e0 e1 e2) = let v0 = compExp env e0 v1 = compExp env e1 v2 = compExp env e2 in case (v1, v2) of (VInt c1, VInt c2) -> VInt (if_ (unBool v0) c1 c2) (VBool c1, VBool c2) -> VBool (if_ (unBool v0) c1 c2) (VDouble c1, VDouble c2) -> VDouble (if_ (unBool v0) c1 c2) (VString c1, VString c2) -> VString (if_ (unBool v0) c1 c2) (_, _) -> error "cond" unop :: UnaryOp -> Value -> Value unop AbsI (VInt i0) = VInt (absi i0) unop AbsD (VDouble i0) = VDouble (absd i0) unop SignI (VInt i0) = VInt (signi i0) unop CLZ (VInt i0) = VInt (countLeadingZeroes i0) unop B2I (VBool i0) = VInt (b2i i0) unop I2D (VInt i0) = VDouble (i2d i0) unop op _ = error ("operation not implemented yet: " ++ show op) binop :: BinOp -> Value -> Value -> Value binop AddI (VInt i1) (VInt i2) = VInt (addi i1 i2) binop SubI (VInt i1) (VInt i2) = VInt (subi i1 i2) binop MulI (VInt i1) (VInt i2) = VInt (muli i1 i2) binop DivI (VInt i1) (VInt i2) = VInt (divi i1 i2) binop ModI (VInt i1) (VInt i2) = VInt (modi i1 i2) binop AddD (VDouble i1) (VDouble i2) = VDouble (addd i1 i2) binop SubD (VDouble i1) (VDouble i2) = VDouble (subd i1 i2) binop MulD (VDouble i1) (VDouble i2) = VDouble (muld i1 i2) binop DivD (VDouble i1) (VDouble i2) = VDouble (divd i1 i2) binop LtI (VInt i1) (VInt i2) = VBool (lti i1 i2) binop LteI (VInt i1) (VInt i2) = VBool (ltei i1 i2) binop NeqI (VInt i1) (VInt i2) = VBool (neqi i1 i2) binop EqI (VInt i1) (VInt i2) = VBool (eqi i1 i2) binop Sll (VInt i1) (VInt i2) = VInt (sll i1 i2) binop Srl (VInt i1) (VInt i2) = VInt (srl i1 i2) binop Xor (VInt i1) (VInt i2) = VInt (xor i1 i2) binop MinI (VInt i1) (VInt i2) = VInt (mini i1 i2) binop MaxI (VInt i1) (VInt i2) = VInt (maxi i1 i2) binop Land (VInt i1) (VInt i2) = VInt (land i1 i2) binop op _ _ = error ("binary operation not implemented yet: " ++ show op) assignVar :: VarEnv -> ILName -> Value -> CGen a () assignVar env x v = case (Map.lookup x env, v) of (Just (VarInt x'), VInt v') -> assign x' v' (Just (VarDouble x'), VDouble v') -> assign x' v' (Just (VarBool x'), VBool v') -> assign x' v' (Just (VarString x'), VString v') -> assign x' v' (Nothing, _) -> error ("Variable " ++ show x ++ " not defined.") (Just x', v') -> error ("TODO assignvar: " ++ show x' ++ " := " ++ show v') assignSub :: VarEnv -> ILName -> Value -> Value -> CGen a () assignSub env x ix v = case (Map.lookup x env, ix, v) of (Just (VarKernelArray ILInt x'), VInt ix', VInt v') -> assignArray x' v' ix' (Just (VarKernelArray ILDouble x'), VInt ix', VDouble v') -> assignArray x' v' ix' (Just (VarKernelArray ILBool x'), VInt ix', VBool v') -> assignArray x' v' ix' _ -> error "TODO assignsub" ------------------------ -- Thread-level compilation -- ------------------------ compThread :: CompileConfig -> VarEnv -> [Stmt a] -> ILKernel () compThread cfg env stmts = case stmts of [] -> return () (Declare x _z e _ : ss) -> do let v = compExp env e v' <- lett (show x) v compThread cfg (Map.insert x v' env) ss (Alloc x elemty e _ : ss) -> do let size = compExp env e sizeVar <- letVar "size" int32_t (constant (configBlockSize cfg)) --(muli (unInt size) (constant (configBlockSize cfg))) let cty = convertType elemty ptr <- allocateKernel cty (var sizeVar) let offset = addi (var ptr) (muli localID (unInt size)) ptr' <- letVar "threadLocal" (snd ptr) offset v <- lett "arr" (VKernelArray elemty ptr') compThread cfg (Map.insert x v env) ss (SeqFor loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound for (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compThread cfg (Map.insert loopVar i' env) body) compThread cfg env ss (Synchronize _ : ss) -> -- synchronization is a no-op on thread-level compThread cfg env ss (Assign x e _ : ss) -> do let e' = compExp env e assignVar env x e' compThread cfg env ss (AssignSub x ix e _ : ss) -> do let ix' = compExp env ix let e' = compExp env e assignSub env x ix' e' compThread cfg env ss (While stopCond body _ : ss) -> do let v = compExp env stopCond whileLoop (unBool v) (compThread cfg env body) compThread cfg env ss (If cond then_ else_ _ : ss) -> do let cond' = compExp env cond iff (unBool cond') (compThread cfg env then_ ,compThread cfg env else_) compThread cfg env ss (ParFor _ _ _ _ _ : _) -> error "Cannot use parallel constructs on thread-level." (Distribute _ _ _ _ _ : _) -> error "Cannot use parallel constructs on thread-level." (ReadIntCSV _ _ _ _ : _) -> error "Reading input-data is not possible at thread level." (PrintIntArray _ _ _ : _) -> error "Printing not possible at thread level." (PrintDoubleArray _ _ _ : _) -> error "Printing not possible at thread level." (Benchmark _ _ _ : _) -> error "Benchmarking not possible at thread level." ------------------------ -- Kernel compilation -- ------------------------ compKernelBody :: CompileConfig -> VarEnv -> [Stmt a] -> ILKernel () compKernelBody cfg env stmts = case stmts of [] -> return () (Declare x _ e _ : ss) -> do let v = compExp env e v' <- lett (show x) v compKernelBody cfg (Map.insert x v' env) ss -- allocate shared memory (Alloc x elemty e _ : ss) -> do let size = compExp env e sizeVar <- letVar "size" int32_t (unInt size) let cty = convertType elemty ptr <- allocateKernel cty (var sizeVar) v <- lett "arr" (VKernelArray elemty ptr) compKernelBody cfg (Map.insert x v env) ss -- lift a thread-level computation to block level (ParFor _ loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound forAllBlock cfg (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compThread cfg (Map.insert loopVar i' env) body) compKernelBody cfg env ss lift a thread - level computation to block - level ( on this level identical to ) (Distribute _ loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound forAllBlock cfg (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compThread cfg (Map.insert loopVar i' env) body) compKernelBody cfg env ss (Synchronize _ : ss) -> do syncLocal compKernelBody cfg env ss (Assign x e _ : ss) -> do let e' = compExp env e assignVar env x e' compKernelBody cfg env ss (AssignSub x ix e _ : ss) -> do let ix' = compExp env ix let e' = compExp env e assignSub env x ix' e' compKernelBody cfg env ss (While stopCond body _ : ss) -> do let v = compExp env stopCond whileLoop (unBool v) (compKernelBody cfg env body) compKernelBody cfg env ss (If cond then_ else_ _ : ss) -> do let cond' = compExp env cond iff (unBool cond') (compKernelBody cfg env then_ ,compKernelBody cfg env else_) compKernelBody cfg env ss (SeqFor loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound for (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compKernelBody cfg (Map.insert loopVar i' env) body) compKernelBody cfg env ss (ReadIntCSV _ _ _ _ : _) -> error "Reading input-data is not possible at block level" (PrintIntArray _ _ _ : _) -> error "Printing not possible at block level" (PrintDoubleArray _ _ _ : _) -> error "Printing not possible at block level" (Benchmark _ _ _ : _) -> error "Benchmarking not possible at block level" mkKernelBody :: CompileConfig -> VarEnv -> ILName -> ILExp -> [Stmt a] -> ILKernel () mkKernelBody cfg env loopVar loopBound body = let ub = compExp env loopBound in distrParBlock cfg (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compKernelBody cfg (Map.insert loopVar i' env) body) distrParBlock :: CompileConfig -> CExp -> (CExp -> ILKernel ()) -> ILKernel () distrParBlock cfg (Int32E ub) f = do let workgroups = configNumWorkGroups cfg let q = fromIntegral ub `div` workgroups let r = fromIntegral ub `mod` workgroups if q == 1 then do j <- let_ "j" int32_t (workgroupID `muli` constant q) f j else if q > 1 then for (constant q) (\i -> do j <- let_ "j" int32_t ((workgroupID `muli` constant q) `addi` i) f j) else return () if r > 0 then iff (workgroupID `lti` constant r) (do j <- let_ "wid" int32_t ((constant workgroups `muli` constant q) `addi` workgroupID) f j , return ()) else return () distrParBlock cfg ub' f = do let workgroups = constant (configNumWorkGroups cfg) ub <- let_ "ub" int32_t ub' q <- let_ "blocksQ" int32_t (ub `divi` workgroups) for q (\i -> do j <- let_ "j" int32_t ((workgroupID `muli` q) `addi` i) f j) iff (workgroupID `lti` (ub `modi` workgroups)) (do j <- let_ "wid" int32_t ((workgroups `muli` q) `addi` workgroupID) f j , return ()) -- A block-level computation using blockSize threads, to evaluate -- a parallel map -- - evaluating "f j" for every j in [0..n-1] forAllBlock :: CompileConfig -> CExp -> (CExp -> ILKernel ()) -> ILKernel () forAllBlock cfg (Int32E n) f = do let blockSize = configBlockSize cfg let q = fromIntegral n `div` blockSize let r = fromIntegral n `mod` blockSize if q == 1 then do j <- let_ "j" int32_t localID f j else if q > 1 then for (constant q) (\i -> do j <- let_ "j" int32_t ((i `muli` constant blockSize) `addi` localID) f j) else return () if r > 0 then iff (localID `lti` constant r) (do j <- let_ "tid" int32_t ((constant q `muli` constant blockSize) `addi` localID) f j , return ()) else return () syncLocal forAllBlock cfg n f = do let blockSize = constant (configBlockSize cfg) ub <- let_ "ub" int32_t n q <- let_ "q" int32_t (ub `divi` blockSize) for q (\i -> do j <- let_ "j" int32_t ((i `muli` blockSize) `addi` localID) f j) iff (localID `lti` (ub `modi` blockSize)) (do j <- let_ "tid" int32_t ((q `muli` blockSize) `addi` localID) f j , return ()) syncLocal lett :: String -> Value -> CGen a Var lett x (VInt e) = VarInt `fmap` (letVar x int32_t e) lett x (VBool e) = VarBool `fmap` (letVar x bool_t e) lett x (VDouble e) = VarDouble `fmap` (letVar x double_t e) lett _ (VString _) = error "string declarations: not implemented yet" lett _ (VKernelArray ty v) = return (VarKernelArray ty v) lett _ (VHostBuffer ty buf) = return (VarHostBuffer ty buf) --------------------- -- Host compilation --------------------- compHost :: CompileConfig -> ClContext -> VarEnv -> [Stmt a] -> ILHost () compHost cfg ctx env stmts = case stmts of [] -> return () (PrintIntArray size arr _ : ss) -> do let n = compExp env size let arr' = compExp env arr finish ctx printIntArray ctx n arr' compHost cfg ctx env ss (PrintDoubleArray size arr _ : ss) -> do let n = compExp env size let arr' = compExp env arr finish ctx printDoubleArray ctx n arr' compHost cfg ctx env ss (Benchmark iterations ss0 _ : ss) -> do let n = compExp env iterations benchmark ctx n (compHost cfg ctx env ss0) compHost cfg ctx env ss (Declare x ty e _ : ss) -> do let v = compExp env e v' <- lett (show x) v compHost cfg ctx (Map.insert x v' env) ss (Distribute _ x e stmts' _ : ss) -> -- use level for something? Only for type check? do distribute cfg ctx env x e stmts' compHost cfg ctx env ss (ParFor _ _ _ _ _ : _) -> error "parfor<grid>: Not supported yet" (Synchronize _ : ss) -> do finish ctx compHost cfg ctx env ss (ReadIntCSV x xlen e _ : ss) -> do let filename = compExp env e (valuesRead, hostPtr) <- readCSVFile int32_t filename v <- copyToDevice ctx ILInt (var valuesRead) (var hostPtr) compHost cfg ctx (Map.insert xlen (VarInt valuesRead) (Map.insert x v env)) ss (Alloc x elemty e _ : ss) -> do let size = compExp env e v <- allocate ctx elemty size compHost cfg ctx (Map.insert x v env) ss (Assign x e _ : ss) -> do let e' = compExp env e assignVar env x e' compHost cfg ctx env ss (AssignSub x ix e _ : ss) -> do let ix' = compExp env ix e' = compExp env e assignSub env x ix' e' compHost cfg ctx env ss (While stopCond body _ : ss) -> do let v = compExp env stopCond whileLoop (unBool v) (compHost cfg ctx env body) compHost cfg ctx env ss (If cond then_ else_ _ : ss) -> do let cond' = compExp env cond iff (unBool cond') (compHost cfg ctx env then_ ,compHost cfg ctx env else_) compHost cfg ctx env ss (SeqFor loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound for (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compHost cfg ctx (Map.insert loopVar i' env) body) compHost cfg ctx env ss distribute :: CompileConfig -> ClContext -> VarEnv -> ILName -> ILExp -> [Stmt a] -> ILHost () distribute cfg ctx env loopVar loopBound stmts = let createArgument :: (ILName, ILType) -> ILHost KernelArg createArgument (x, ty) = do case Map.lookup x env of Just (VarInt v) -> return (ArgScalar (convertType ty) (var v)) Just (VarBool v) -> return (ArgScalar (convertType ty) (var v)) Just (VarDouble v) -> return (ArgScalar (convertType ty) (var v)) Just (VarHostBuffer _ buf) -> return (ArgBuffer buf) Just (VarKernelArray _ _) -> error "kernel arrays can not occur outside kernels" Just (VarString _) -> error "Can not use strings inside kernels" Nothing -> error "variable not found" callKernel :: String -> Kernel -> ILHost () callKernel kernelName (Kernel i params _) = do -- set shared memory let smarg = replicate i (ArgSharedMemory (constant (configSharedMemory cfg))) -- set input parameters: map over kernel list, lookup allocations in environment args <- mapM createArgument params let kernelHandle = ClKernel (kernelName, kernelCType) invokeKernel ctx kernelHandle (smarg ++ args) (muli (constant (configBlockSize cfg)) (constant (configNumWorkGroups cfg))) (constant (configBlockSize cfg)) profile :: String -> Kernel -> ILHost () profile kernelName (Kernel i params _) = set shared memoryp let smarg = replicate i (ArgSharedMemory (constant (configSharedMemory cfg))) -- set input parameters: map over kernel list, lookup allocations in environment args <- mapM createArgument params let kernelHandle = ClKernel (kernelName, kernelCType) tdiff <- profileKernel ctx kernelHandle (smarg ++ args) (muli (constant (configBlockSize cfg)) (constant (configNumWorkGroups cfg))) (constant (configBlockSize cfg)) let psum = (kernelName ++ "_sum_seconds", CDouble) counter = (kernelName ++ "_counter", CWord64) assign psum (var psum `addi` ((i2d (var tdiff)) `divd` (constant (1000000000.0 :: Double)))) assign counter (var counter `addi` (constant (1 :: Int))) in do kernelName <- newName "kernel" k <- mkKernel cfg env kernelName loopVar loopBound stmts addKernel kernelName k -- save in monad state, to be able to free it in the end if configProfile cfg then profile kernelName k else callKernel kernelName k create parameter list ( newVar ) create VarEnv mapping free variables to the parameter names -- also add the variable used as loop argument to distrPar call with this new VarEnv -- add shared memory argument -- create kernel definition (using distrParBlock) -- create/build kernel on host -- call the kernel using the same order of arguments, as in the parameter list. mkKernel :: CompileConfig -> VarEnv -> String -> ILName -> ILExp -> [Stmt a] -> ILHost Kernel mkKernel cfg env kernelName loopVar loopBound stmts = let params = Set.toList (Set.delete loopVar (freeVars stmts `Set.union` liveInExp loopBound)) mkArgumentList :: [ILName] -> ILHost [Var] mkArgumentList = mapM (hostVarToKernelVar env) in do args <- mkArgumentList params tyenv <- getsState typeEnv let param_tys = map (\k -> maybe (error "not found") id (Map.lookup k tyenv)) params let kernelEnv = Map.fromList (zip params args) (kernelBody, _, finalKernelState) <- embed (mkKernelBody cfg kernelEnv loopVar loopBound stmts) initKernelState let allocs = allocations finalKernelState fndef = kernel kernelName (allocs ++ map getVarName args) kernelBody return (Kernel (length allocs) (zip params param_tys) fndef) allocate :: ClContext -> ILType -> Value -> ILHost Var allocate ctx elemty size = do buf <- allocDevice ctx ReadWrite (unInt size) (convertType elemty) modifyState (\s -> s { deviceAllocations = Map.insert buf (unInt size, convertType elemty) (deviceAllocations s) }) return (VarHostBuffer elemty buf) readCSVFile :: CType -> Value -> ILHost (VarName, VarName) readCSVFile CInt32 filename = do valuesRead <- letVar "valuesRead" int32_t (constant (0 :: Int)) hostPtr <- eval "csvinput" (pointer_t [] int32_t) "readIntVecFile" [addressOf (var valuesRead), unString filename] modifyState (\s -> s { hostAllocations = Set.insert hostPtr (hostAllocations s) }) return (valuesRead, hostPtr) readCSVFile CDouble filename = do valuesRead <- letVar "valuesRead" int32_t (constant (0 :: Int)) hostPtr <- eval "csvinput" (pointer_t [] double_t) "readDoubleVecFile" [addressOf (var valuesRead), unString filename] modifyState (\s -> s { hostAllocations = Set.insert hostPtr (hostAllocations s) }) return (valuesRead, hostPtr) readCSVFile _ _ = error "Can only read CSV files of doubles or integers" copyToDevice :: ClContext -> ILType -> CExp -> CExp -> ILHost Var copyToDevice ctx elemty n hostptr = do buf <- dataToDevice ctx ReadWrite n (convertType elemty) hostptr modifyState (\s -> s { deviceAllocations = Map.insert buf (n, convertType elemty) (deviceAllocations s) }) return (VarHostBuffer elemty buf) printIntArray :: ClContext -> Value -> Value -> ILHost () printIntArray ctx n (VHostBuffer elemty buf) = do hostptr <- mmapToHost ctx buf (convertType elemty) (unInt n) exec void_t "printf" [string "["] let lastElem = subi (unInt n) (constant (1 :: Int)) for lastElem (\i -> exec void_t "printf" [string "%i,", index hostptr i]) exec void_t "printf" [string "%i", index hostptr lastElem] exec void_t "printf" [string "]\\n"] unmmap ctx buf hostptr printIntArray _ _ _ = error "Print array expects array" printDoubleArray :: ClContext -> Value -> Value -> ILHost () printDoubleArray ctx n (VHostBuffer elemty buf) = do hostptr <- mmapToHost ctx buf (convertType elemty) (unInt n) exec void_t "printf" [string "["] let lastElem = subi (unInt n) (constant (1 :: Int)) for lastElem (\i -> exec void_t "printf" [string "%.5f,", index hostptr i]) exec void_t "printf" [string "%.5f", index hostptr lastElem] exec void_t "printf" [string "]\\n"] unmmap ctx buf hostptr printDoubleArray _ _ _ = error "Print array expects array" now :: String -> ILHost CExp now x = do v <- eval x uint64_t "now" [] return (var v) stderr :: CExp stderr = definedConst "stderr" (CCustom "File" Nothing) benchmark :: ClContext -> Value -> ILHost () -> ILHost () benchmark ctx (VInt n) body = do t0 <- now "t0" allocs <- getsState deviceAllocations -- warm up run modifyState (\s -> s { deviceAllocations = Map.empty }) body finish ctx releaseAllDeviceArrays finish ctx -- detect the allocations done in the kernel modifyState (\s -> s { deviceAllocations = Map.empty }) for n (\_ -> do body finish ctx -- deallocate everything before exiting the loop releaseAllDeviceArrays) -- allocsAfter <- getsState deviceAllocations let sizes = map ( \(k , cty ) - > k ` muli ` sizeOf cty ) ( Map.elems allocsAfter ) -- let totalTransferredBytes = foldl addi (constant (0 :: Int)) sizes -- reset allocations modifyState (\s -> s { deviceAllocations = allocs }) t1 <- now "t1" let formatString1 = "Benchmark (%i repetitions): %f ms per run\\n" formatString2 = " Throughput ( % i repetitions ): % .4f / s , data transferred per run : % .4f MiB\\n " milliseconds_per_iter <- let_ "ms" CDouble (divd (i2d (subi t1 t0)) (i2d n)) seconds < - let _ " seconds " CDouble ( milliseconds_per_iter ` divd ` ( constant ( 1000.0 : : Double ) ) ) mebibytes < - let _ " mib " CDouble ( totalTransferredBytes ` divd ` ( constant ( 1024.0 * 1024.0 : : Double ) ) ) gebibytes < - let _ " gib " CDouble ( mebibytes ` divd ` ( constant ( 1024.0 : : Double ) ) ) throughput < - let _ " throughput " CDouble ( gebibytes ` divd ` seconds ) exec void_t "fprintf" [stderr, string formatString1, n, milliseconds_per_iter] -- exec void_t "fprintf" [stderr, string formatString2, n, throughput, mebibytes] benchmark _ _ _ = error "Benchmark expects int as first argument (number of iterations)." --------------------- -- Compile program -- --------------------- initializeCounter :: String -> CGen () () initializeCounter kernelName = do let psum = (kernelName ++ "_sum_seconds", CDouble) counter = (kernelName ++ "_counter", CInt32) addStmt (Decl psum (constant (0 :: Double)) ()) addStmt (Decl counter (constant (0 :: Int)) ()) printCounter :: String -> CGen () () printCounter kernelName = do let formatString = "Kernel %s timing: %f ms per execution (%d executions)\\n" psum = var (kernelName ++ "_sum_seconds", CDouble) counter = var (kernelName ++ "_counter", CInt32) milliseconds <- let_ "ms" CDouble ((psum `muli` (constant (1000.0 :: Double))) `divd` (i2d counter)) exec void_t "fprintf" [stderr, string formatString, string kernelName, milliseconds, counter] compProgram :: CompileConfig -> TypeEnv -> [Stmt a] -> CGen () KernelMap compProgram cfg env program = -- compile body let ctxVar = ClContext ("ctx", contextCType) pVar = ClProgram ("program", programCType) body = compHost cfg ctxVar Map.empty program (stmts, _, _, finalState) = runCGen (initHostState env) body -- collect the generated kernels kernels' = kernels finalState allocs = deviceAllocations finalState in do initializeContext ctxVar (configVerbosity cfg) exec void_t "initializeTimer" [] if configProfile cfg then mapM_ initializeCounter (Map.keys kernels') else return () buildProgram ctxVar pVar (configKernelsFilename cfg) kernelHandles <- mapM (createKernel pVar) (Map.keys kernels') addStmts stmts if configProfile cfg then mapM_ printCounter (Map.keys kernels') else return () mapM_ releaseDeviceData (Map.keys allocs) mapM_ releaseKernel kernelHandles releaseProgram pVar releaseContext ctxVar return kernels' releaseAllDeviceArrays :: ILHost () releaseAllDeviceArrays = do allocs <- getsState deviceAllocations mapM_ releaseDeviceData (Map.keys allocs) prettyKernels :: KernelMap -> String prettyKernels kernelMap = pretty (map (\(Kernel _ _ s) -> s) (Map.elems kernelMap)) createMain :: Statements -> String createMain body = pretty (includes ++ [function int32_t [] "main" body]) includes :: [TopLevel] includes = [includeSys "fcl.h", includeSys "stdio.h", includeSys "sys/time.h", includeSys "mcl.h"] codeGen :: CompileConfig -> TypeEnv -> ILProgram a -> (String, String) codeGen cfg env program = let (mainBody, _, kernels') = evalCGen () (compProgram cfg env program) in (createMain mainBody, prettyKernels kernels')
null
https://raw.githubusercontent.com/dybber/fcl/e794a4b9d3ab6207fbe89fcddaafe97ae0d379dd/src/FCL/IL/CodeGen.hs
haskell
number of shared memory arrays parameters, bound in host-code kernel declaration kernel handle in hostcode size, elem type and opencl memobject ------------------------- Host generation monad -- ------------------------- Host monad --------------------------- Kernel generation monad -- --------------------------- sharedMemPtrName :: VarName sharedMemPtrName = ("sbase", pointer_t [attrLocal] uint8_t) , sharedMemPointer :: VarName , allocPtrOffset = constant (0 :: Int) , sharedMemPointer = sharedMemPtrName , offset <- getsState allocPtrOffset sbase <- getsState sharedMemPointer let bytes = n `muli` (sizeOf cty) modifyState (\s -> s { allocPtrOffset = offset `addi` bytes }) -------------------------------------------- Compiling expressions - both host/kernel -- -------------------------------------------- ---------------------- Thread-level compilation -- ---------------------- (muli (unInt size) (constant (configBlockSize cfg))) synchronization is a no-op on thread-level ---------------------- Kernel compilation -- ---------------------- allocate shared memory lift a thread-level computation to block level A block-level computation using blockSize threads, to evaluate a parallel map - evaluating "f j" for every j in [0..n-1] ------------------- Host compilation ------------------- use level for something? Only for type check? set shared memory set input parameters: map over kernel list, lookup allocations in environment set input parameters: map over kernel list, lookup allocations in environment save in monad state, to be able to free it in the end also add the variable used as loop argument to distrPar add shared memory argument create kernel definition (using distrParBlock) create/build kernel on host call the kernel using the same order of arguments, as in the parameter list. warm up run detect the allocations done in the kernel deallocate everything before exiting the loop allocsAfter <- getsState deviceAllocations let totalTransferredBytes = foldl addi (constant (0 :: Int)) sizes reset allocations exec void_t "fprintf" [stderr, string formatString2, n, throughput, mebibytes] ------------------- Compile program -- ------------------- compile body collect the generated kernels
module FCL.IL.CodeGen (codeGen) where import qualified Data.Set as Set import qualified Data.Map as Map import Data.Set (Set) import Data.Map (Map) import CGen hiding (freeVars) import CGen.Syntax (Statement(Decl), CExp(Int32E)) import CGen.OpenCL.HostCode import FCL.IL.Analysis.Liveness import FCL.IL.Analysis.FreeVars import FCL.Compile.Config import FCL.IL.Syntax import FCL.IL.TypeCheck data Kernel = Kernel data Value = VInt CExp | VBool CExp | VDouble CExp | VString CExp size , elem type and ptr deriving Show data Var = VarInt VarName | VarBool VarName | VarDouble VarName | VarString VarName | VarKernelArray ILType VarName | VarHostBuffer ILType ClDeviceBuffer deriving Show type VarEnv = Map.Map ILName Var getVarName :: Var -> VarName getVarName (VarInt x) = x getVarName (VarBool x) = x getVarName (VarDouble x) = x getVarName (VarString x) = x getVarName (VarKernelArray _ x) = x getVarName (VarHostBuffer _ (ClDeviceBuffer x)) = x unInt :: Value -> CExp unInt (VInt i) = i unInt _ = error ("Unexpected value, expecting integer.") unBool :: Value -> CExp unBool (VBool i) = i unBool _ = error ("Unexpected value, expecting bool.") unString :: Value -> CExp unString (VString str) = str unString _ = error ("Unexpected value, expecting string.") convertType :: ILType -> CType convertType ILInt = int32_t convertType ILBool = bool_t convertType ILDouble = double_t convertType ILString = string_t convertType (ILArray ty) = pointer_t [] (convertType ty) hostVarToKernelVar :: VarEnv -> ILName -> CGen a Var hostVarToKernelVar env x = case Map.lookup x env of Just (VarInt _) -> VarInt `fmap` (newVar int32_t (show x)) Just (VarBool _) -> VarBool `fmap` (newVar bool_t (show x)) Just (VarDouble _) -> VarDouble `fmap` (newVar double_t (show x)) Just (VarHostBuffer elemty _) -> VarKernelArray elemty `fmap` (newVar (pointer_t [attrGlobal] (convertType elemty)) (show x)) Just (VarString _) -> error "string" Just (VarKernelArray _ _) -> error "kernel array" Nothing -> error ("not defined: " ++ show x) type ILHost a = CGen HostState a type KernelMap = Map String Kernel data HostState = HostState { kernels :: KernelMap , deviceAllocations :: Map ClDeviceBuffer (CExp, CType) , hostAllocations :: Set VarName , typeEnv :: TypeEnv } initHostState :: TypeEnv -> HostState initHostState env = HostState { kernels = Map.empty , deviceAllocations = Map.empty , hostAllocations = Set.empty , typeEnv = env } addKernel :: String -> Kernel -> ILHost () addKernel name k = modifyState (\s -> s { kernels = Map.insert name k (kernels s) }) type ILKernel a = CGen KernelState a data KernelState = allocPtrOffset : : CExp allocations :: [VarName] } initKernelState :: KernelState initKernelState = allocations = [] } allocateKernel :: CType -> CExp -> ILKernel VarName allocateKernel cty n = let aty = pointer_t [attrLocal] cty v < - letVar " arr " aty ( cast aty ( var sbase ` addPtr ` offset ) ) v1 <- newVar aty "shared" modifyState (\s -> s { allocations = v1 : allocations s }) return v1 compExp :: VarEnv -> ILExp -> Value compExp _ (EInt i) = VInt (constant i) compExp _ (EBool b) = VBool (constant b) compExp _ (EDouble d) = VDouble (constant d) compExp _ (EString s) = VString (string s) compExp env (EIndex x i) = let v1 = compExp env i in case Map.lookup x env of (Just (VarKernelArray ILInt v)) -> VInt (index v (unInt v1)) (Just (VarKernelArray ILDouble v)) -> VDouble (index v (unInt v1)) (Just (VarKernelArray ILBool v)) -> VBool (index v (unInt v1)) _ -> error "not an array" compExp env (EVar x) = case Map.lookup x env of (Just (VarInt v)) -> VInt (var v) (Just (VarBool v)) -> VBool (var v) (Just (VarDouble v)) -> VDouble (var v) (Just (VarString v)) -> VString (var v) (Just (VarKernelArray ty v)) -> VKernelArray ty v (Just (VarHostBuffer ty buf)) -> VHostBuffer ty buf Nothing -> error ("Undefined variable " ++ show x) compExp env (EUnaryOp op e0) = let v0 = compExp env e0 in unop op v0 compExp env (EBinOp op e0 e1) = let v0 = compExp env e0 v1 = compExp env e1 in binop op v0 v1 compExp env (EIf e0 e1 e2) = let v0 = compExp env e0 v1 = compExp env e1 v2 = compExp env e2 in case (v1, v2) of (VInt c1, VInt c2) -> VInt (if_ (unBool v0) c1 c2) (VBool c1, VBool c2) -> VBool (if_ (unBool v0) c1 c2) (VDouble c1, VDouble c2) -> VDouble (if_ (unBool v0) c1 c2) (VString c1, VString c2) -> VString (if_ (unBool v0) c1 c2) (_, _) -> error "cond" unop :: UnaryOp -> Value -> Value unop AbsI (VInt i0) = VInt (absi i0) unop AbsD (VDouble i0) = VDouble (absd i0) unop SignI (VInt i0) = VInt (signi i0) unop CLZ (VInt i0) = VInt (countLeadingZeroes i0) unop B2I (VBool i0) = VInt (b2i i0) unop I2D (VInt i0) = VDouble (i2d i0) unop op _ = error ("operation not implemented yet: " ++ show op) binop :: BinOp -> Value -> Value -> Value binop AddI (VInt i1) (VInt i2) = VInt (addi i1 i2) binop SubI (VInt i1) (VInt i2) = VInt (subi i1 i2) binop MulI (VInt i1) (VInt i2) = VInt (muli i1 i2) binop DivI (VInt i1) (VInt i2) = VInt (divi i1 i2) binop ModI (VInt i1) (VInt i2) = VInt (modi i1 i2) binop AddD (VDouble i1) (VDouble i2) = VDouble (addd i1 i2) binop SubD (VDouble i1) (VDouble i2) = VDouble (subd i1 i2) binop MulD (VDouble i1) (VDouble i2) = VDouble (muld i1 i2) binop DivD (VDouble i1) (VDouble i2) = VDouble (divd i1 i2) binop LtI (VInt i1) (VInt i2) = VBool (lti i1 i2) binop LteI (VInt i1) (VInt i2) = VBool (ltei i1 i2) binop NeqI (VInt i1) (VInt i2) = VBool (neqi i1 i2) binop EqI (VInt i1) (VInt i2) = VBool (eqi i1 i2) binop Sll (VInt i1) (VInt i2) = VInt (sll i1 i2) binop Srl (VInt i1) (VInt i2) = VInt (srl i1 i2) binop Xor (VInt i1) (VInt i2) = VInt (xor i1 i2) binop MinI (VInt i1) (VInt i2) = VInt (mini i1 i2) binop MaxI (VInt i1) (VInt i2) = VInt (maxi i1 i2) binop Land (VInt i1) (VInt i2) = VInt (land i1 i2) binop op _ _ = error ("binary operation not implemented yet: " ++ show op) assignVar :: VarEnv -> ILName -> Value -> CGen a () assignVar env x v = case (Map.lookup x env, v) of (Just (VarInt x'), VInt v') -> assign x' v' (Just (VarDouble x'), VDouble v') -> assign x' v' (Just (VarBool x'), VBool v') -> assign x' v' (Just (VarString x'), VString v') -> assign x' v' (Nothing, _) -> error ("Variable " ++ show x ++ " not defined.") (Just x', v') -> error ("TODO assignvar: " ++ show x' ++ " := " ++ show v') assignSub :: VarEnv -> ILName -> Value -> Value -> CGen a () assignSub env x ix v = case (Map.lookup x env, ix, v) of (Just (VarKernelArray ILInt x'), VInt ix', VInt v') -> assignArray x' v' ix' (Just (VarKernelArray ILDouble x'), VInt ix', VDouble v') -> assignArray x' v' ix' (Just (VarKernelArray ILBool x'), VInt ix', VBool v') -> assignArray x' v' ix' _ -> error "TODO assignsub" compThread :: CompileConfig -> VarEnv -> [Stmt a] -> ILKernel () compThread cfg env stmts = case stmts of [] -> return () (Declare x _z e _ : ss) -> do let v = compExp env e v' <- lett (show x) v compThread cfg (Map.insert x v' env) ss (Alloc x elemty e _ : ss) -> do let size = compExp env e let cty = convertType elemty ptr <- allocateKernel cty (var sizeVar) let offset = addi (var ptr) (muli localID (unInt size)) ptr' <- letVar "threadLocal" (snd ptr) offset v <- lett "arr" (VKernelArray elemty ptr') compThread cfg (Map.insert x v env) ss (SeqFor loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound for (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compThread cfg (Map.insert loopVar i' env) body) compThread cfg env ss (Synchronize _ : ss) -> compThread cfg env ss (Assign x e _ : ss) -> do let e' = compExp env e assignVar env x e' compThread cfg env ss (AssignSub x ix e _ : ss) -> do let ix' = compExp env ix let e' = compExp env e assignSub env x ix' e' compThread cfg env ss (While stopCond body _ : ss) -> do let v = compExp env stopCond whileLoop (unBool v) (compThread cfg env body) compThread cfg env ss (If cond then_ else_ _ : ss) -> do let cond' = compExp env cond iff (unBool cond') (compThread cfg env then_ ,compThread cfg env else_) compThread cfg env ss (ParFor _ _ _ _ _ : _) -> error "Cannot use parallel constructs on thread-level." (Distribute _ _ _ _ _ : _) -> error "Cannot use parallel constructs on thread-level." (ReadIntCSV _ _ _ _ : _) -> error "Reading input-data is not possible at thread level." (PrintIntArray _ _ _ : _) -> error "Printing not possible at thread level." (PrintDoubleArray _ _ _ : _) -> error "Printing not possible at thread level." (Benchmark _ _ _ : _) -> error "Benchmarking not possible at thread level." compKernelBody :: CompileConfig -> VarEnv -> [Stmt a] -> ILKernel () compKernelBody cfg env stmts = case stmts of [] -> return () (Declare x _ e _ : ss) -> do let v = compExp env e v' <- lett (show x) v compKernelBody cfg (Map.insert x v' env) ss (Alloc x elemty e _ : ss) -> do let size = compExp env e sizeVar <- letVar "size" int32_t (unInt size) let cty = convertType elemty ptr <- allocateKernel cty (var sizeVar) v <- lett "arr" (VKernelArray elemty ptr) compKernelBody cfg (Map.insert x v env) ss (ParFor _ loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound forAllBlock cfg (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compThread cfg (Map.insert loopVar i' env) body) compKernelBody cfg env ss lift a thread - level computation to block - level ( on this level identical to ) (Distribute _ loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound forAllBlock cfg (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compThread cfg (Map.insert loopVar i' env) body) compKernelBody cfg env ss (Synchronize _ : ss) -> do syncLocal compKernelBody cfg env ss (Assign x e _ : ss) -> do let e' = compExp env e assignVar env x e' compKernelBody cfg env ss (AssignSub x ix e _ : ss) -> do let ix' = compExp env ix let e' = compExp env e assignSub env x ix' e' compKernelBody cfg env ss (While stopCond body _ : ss) -> do let v = compExp env stopCond whileLoop (unBool v) (compKernelBody cfg env body) compKernelBody cfg env ss (If cond then_ else_ _ : ss) -> do let cond' = compExp env cond iff (unBool cond') (compKernelBody cfg env then_ ,compKernelBody cfg env else_) compKernelBody cfg env ss (SeqFor loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound for (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compKernelBody cfg (Map.insert loopVar i' env) body) compKernelBody cfg env ss (ReadIntCSV _ _ _ _ : _) -> error "Reading input-data is not possible at block level" (PrintIntArray _ _ _ : _) -> error "Printing not possible at block level" (PrintDoubleArray _ _ _ : _) -> error "Printing not possible at block level" (Benchmark _ _ _ : _) -> error "Benchmarking not possible at block level" mkKernelBody :: CompileConfig -> VarEnv -> ILName -> ILExp -> [Stmt a] -> ILKernel () mkKernelBody cfg env loopVar loopBound body = let ub = compExp env loopBound in distrParBlock cfg (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compKernelBody cfg (Map.insert loopVar i' env) body) distrParBlock :: CompileConfig -> CExp -> (CExp -> ILKernel ()) -> ILKernel () distrParBlock cfg (Int32E ub) f = do let workgroups = configNumWorkGroups cfg let q = fromIntegral ub `div` workgroups let r = fromIntegral ub `mod` workgroups if q == 1 then do j <- let_ "j" int32_t (workgroupID `muli` constant q) f j else if q > 1 then for (constant q) (\i -> do j <- let_ "j" int32_t ((workgroupID `muli` constant q) `addi` i) f j) else return () if r > 0 then iff (workgroupID `lti` constant r) (do j <- let_ "wid" int32_t ((constant workgroups `muli` constant q) `addi` workgroupID) f j , return ()) else return () distrParBlock cfg ub' f = do let workgroups = constant (configNumWorkGroups cfg) ub <- let_ "ub" int32_t ub' q <- let_ "blocksQ" int32_t (ub `divi` workgroups) for q (\i -> do j <- let_ "j" int32_t ((workgroupID `muli` q) `addi` i) f j) iff (workgroupID `lti` (ub `modi` workgroups)) (do j <- let_ "wid" int32_t ((workgroups `muli` q) `addi` workgroupID) f j , return ()) forAllBlock :: CompileConfig -> CExp -> (CExp -> ILKernel ()) -> ILKernel () forAllBlock cfg (Int32E n) f = do let blockSize = configBlockSize cfg let q = fromIntegral n `div` blockSize let r = fromIntegral n `mod` blockSize if q == 1 then do j <- let_ "j" int32_t localID f j else if q > 1 then for (constant q) (\i -> do j <- let_ "j" int32_t ((i `muli` constant blockSize) `addi` localID) f j) else return () if r > 0 then iff (localID `lti` constant r) (do j <- let_ "tid" int32_t ((constant q `muli` constant blockSize) `addi` localID) f j , return ()) else return () syncLocal forAllBlock cfg n f = do let blockSize = constant (configBlockSize cfg) ub <- let_ "ub" int32_t n q <- let_ "q" int32_t (ub `divi` blockSize) for q (\i -> do j <- let_ "j" int32_t ((i `muli` blockSize) `addi` localID) f j) iff (localID `lti` (ub `modi` blockSize)) (do j <- let_ "tid" int32_t ((q `muli` blockSize) `addi` localID) f j , return ()) syncLocal lett :: String -> Value -> CGen a Var lett x (VInt e) = VarInt `fmap` (letVar x int32_t e) lett x (VBool e) = VarBool `fmap` (letVar x bool_t e) lett x (VDouble e) = VarDouble `fmap` (letVar x double_t e) lett _ (VString _) = error "string declarations: not implemented yet" lett _ (VKernelArray ty v) = return (VarKernelArray ty v) lett _ (VHostBuffer ty buf) = return (VarHostBuffer ty buf) compHost :: CompileConfig -> ClContext -> VarEnv -> [Stmt a] -> ILHost () compHost cfg ctx env stmts = case stmts of [] -> return () (PrintIntArray size arr _ : ss) -> do let n = compExp env size let arr' = compExp env arr finish ctx printIntArray ctx n arr' compHost cfg ctx env ss (PrintDoubleArray size arr _ : ss) -> do let n = compExp env size let arr' = compExp env arr finish ctx printDoubleArray ctx n arr' compHost cfg ctx env ss (Benchmark iterations ss0 _ : ss) -> do let n = compExp env iterations benchmark ctx n (compHost cfg ctx env ss0) compHost cfg ctx env ss (Declare x ty e _ : ss) -> do let v = compExp env e v' <- lett (show x) v compHost cfg ctx (Map.insert x v' env) ss do distribute cfg ctx env x e stmts' compHost cfg ctx env ss (ParFor _ _ _ _ _ : _) -> error "parfor<grid>: Not supported yet" (Synchronize _ : ss) -> do finish ctx compHost cfg ctx env ss (ReadIntCSV x xlen e _ : ss) -> do let filename = compExp env e (valuesRead, hostPtr) <- readCSVFile int32_t filename v <- copyToDevice ctx ILInt (var valuesRead) (var hostPtr) compHost cfg ctx (Map.insert xlen (VarInt valuesRead) (Map.insert x v env)) ss (Alloc x elemty e _ : ss) -> do let size = compExp env e v <- allocate ctx elemty size compHost cfg ctx (Map.insert x v env) ss (Assign x e _ : ss) -> do let e' = compExp env e assignVar env x e' compHost cfg ctx env ss (AssignSub x ix e _ : ss) -> do let ix' = compExp env ix e' = compExp env e assignSub env x ix' e' compHost cfg ctx env ss (While stopCond body _ : ss) -> do let v = compExp env stopCond whileLoop (unBool v) (compHost cfg ctx env body) compHost cfg ctx env ss (If cond then_ else_ _ : ss) -> do let cond' = compExp env cond iff (unBool cond') (compHost cfg ctx env then_ ,compHost cfg ctx env else_) compHost cfg ctx env ss (SeqFor loopVar loopBound body _ : ss) -> do let ub = compExp env loopBound for (unInt ub) (\i -> do i' <- lett "ub" (VInt i) compHost cfg ctx (Map.insert loopVar i' env) body) compHost cfg ctx env ss distribute :: CompileConfig -> ClContext -> VarEnv -> ILName -> ILExp -> [Stmt a] -> ILHost () distribute cfg ctx env loopVar loopBound stmts = let createArgument :: (ILName, ILType) -> ILHost KernelArg createArgument (x, ty) = do case Map.lookup x env of Just (VarInt v) -> return (ArgScalar (convertType ty) (var v)) Just (VarBool v) -> return (ArgScalar (convertType ty) (var v)) Just (VarDouble v) -> return (ArgScalar (convertType ty) (var v)) Just (VarHostBuffer _ buf) -> return (ArgBuffer buf) Just (VarKernelArray _ _) -> error "kernel arrays can not occur outside kernels" Just (VarString _) -> error "Can not use strings inside kernels" Nothing -> error "variable not found" callKernel :: String -> Kernel -> ILHost () callKernel kernelName (Kernel i params _) = let smarg = replicate i (ArgSharedMemory (constant (configSharedMemory cfg))) args <- mapM createArgument params let kernelHandle = ClKernel (kernelName, kernelCType) invokeKernel ctx kernelHandle (smarg ++ args) (muli (constant (configBlockSize cfg)) (constant (configNumWorkGroups cfg))) (constant (configBlockSize cfg)) profile :: String -> Kernel -> ILHost () profile kernelName (Kernel i params _) = set shared memoryp let smarg = replicate i (ArgSharedMemory (constant (configSharedMemory cfg))) args <- mapM createArgument params let kernelHandle = ClKernel (kernelName, kernelCType) tdiff <- profileKernel ctx kernelHandle (smarg ++ args) (muli (constant (configBlockSize cfg)) (constant (configNumWorkGroups cfg))) (constant (configBlockSize cfg)) let psum = (kernelName ++ "_sum_seconds", CDouble) counter = (kernelName ++ "_counter", CWord64) assign psum (var psum `addi` ((i2d (var tdiff)) `divd` (constant (1000000000.0 :: Double)))) assign counter (var counter `addi` (constant (1 :: Int))) in do kernelName <- newName "kernel" k <- mkKernel cfg env kernelName loopVar loopBound stmts if configProfile cfg then profile kernelName k else callKernel kernelName k create parameter list ( newVar ) create VarEnv mapping free variables to the parameter names call with this new VarEnv mkKernel :: CompileConfig -> VarEnv -> String -> ILName -> ILExp -> [Stmt a] -> ILHost Kernel mkKernel cfg env kernelName loopVar loopBound stmts = let params = Set.toList (Set.delete loopVar (freeVars stmts `Set.union` liveInExp loopBound)) mkArgumentList :: [ILName] -> ILHost [Var] mkArgumentList = mapM (hostVarToKernelVar env) in do args <- mkArgumentList params tyenv <- getsState typeEnv let param_tys = map (\k -> maybe (error "not found") id (Map.lookup k tyenv)) params let kernelEnv = Map.fromList (zip params args) (kernelBody, _, finalKernelState) <- embed (mkKernelBody cfg kernelEnv loopVar loopBound stmts) initKernelState let allocs = allocations finalKernelState fndef = kernel kernelName (allocs ++ map getVarName args) kernelBody return (Kernel (length allocs) (zip params param_tys) fndef) allocate :: ClContext -> ILType -> Value -> ILHost Var allocate ctx elemty size = do buf <- allocDevice ctx ReadWrite (unInt size) (convertType elemty) modifyState (\s -> s { deviceAllocations = Map.insert buf (unInt size, convertType elemty) (deviceAllocations s) }) return (VarHostBuffer elemty buf) readCSVFile :: CType -> Value -> ILHost (VarName, VarName) readCSVFile CInt32 filename = do valuesRead <- letVar "valuesRead" int32_t (constant (0 :: Int)) hostPtr <- eval "csvinput" (pointer_t [] int32_t) "readIntVecFile" [addressOf (var valuesRead), unString filename] modifyState (\s -> s { hostAllocations = Set.insert hostPtr (hostAllocations s) }) return (valuesRead, hostPtr) readCSVFile CDouble filename = do valuesRead <- letVar "valuesRead" int32_t (constant (0 :: Int)) hostPtr <- eval "csvinput" (pointer_t [] double_t) "readDoubleVecFile" [addressOf (var valuesRead), unString filename] modifyState (\s -> s { hostAllocations = Set.insert hostPtr (hostAllocations s) }) return (valuesRead, hostPtr) readCSVFile _ _ = error "Can only read CSV files of doubles or integers" copyToDevice :: ClContext -> ILType -> CExp -> CExp -> ILHost Var copyToDevice ctx elemty n hostptr = do buf <- dataToDevice ctx ReadWrite n (convertType elemty) hostptr modifyState (\s -> s { deviceAllocations = Map.insert buf (n, convertType elemty) (deviceAllocations s) }) return (VarHostBuffer elemty buf) printIntArray :: ClContext -> Value -> Value -> ILHost () printIntArray ctx n (VHostBuffer elemty buf) = do hostptr <- mmapToHost ctx buf (convertType elemty) (unInt n) exec void_t "printf" [string "["] let lastElem = subi (unInt n) (constant (1 :: Int)) for lastElem (\i -> exec void_t "printf" [string "%i,", index hostptr i]) exec void_t "printf" [string "%i", index hostptr lastElem] exec void_t "printf" [string "]\\n"] unmmap ctx buf hostptr printIntArray _ _ _ = error "Print array expects array" printDoubleArray :: ClContext -> Value -> Value -> ILHost () printDoubleArray ctx n (VHostBuffer elemty buf) = do hostptr <- mmapToHost ctx buf (convertType elemty) (unInt n) exec void_t "printf" [string "["] let lastElem = subi (unInt n) (constant (1 :: Int)) for lastElem (\i -> exec void_t "printf" [string "%.5f,", index hostptr i]) exec void_t "printf" [string "%.5f", index hostptr lastElem] exec void_t "printf" [string "]\\n"] unmmap ctx buf hostptr printDoubleArray _ _ _ = error "Print array expects array" now :: String -> ILHost CExp now x = do v <- eval x uint64_t "now" [] return (var v) stderr :: CExp stderr = definedConst "stderr" (CCustom "File" Nothing) benchmark :: ClContext -> Value -> ILHost () -> ILHost () benchmark ctx (VInt n) body = do t0 <- now "t0" allocs <- getsState deviceAllocations modifyState (\s -> s { deviceAllocations = Map.empty }) body finish ctx releaseAllDeviceArrays finish ctx modifyState (\s -> s { deviceAllocations = Map.empty }) for n (\_ -> do body finish ctx releaseAllDeviceArrays) let sizes = map ( \(k , cty ) - > k ` muli ` sizeOf cty ) ( Map.elems allocsAfter ) modifyState (\s -> s { deviceAllocations = allocs }) t1 <- now "t1" let formatString1 = "Benchmark (%i repetitions): %f ms per run\\n" formatString2 = " Throughput ( % i repetitions ): % .4f / s , data transferred per run : % .4f MiB\\n " milliseconds_per_iter <- let_ "ms" CDouble (divd (i2d (subi t1 t0)) (i2d n)) seconds < - let _ " seconds " CDouble ( milliseconds_per_iter ` divd ` ( constant ( 1000.0 : : Double ) ) ) mebibytes < - let _ " mib " CDouble ( totalTransferredBytes ` divd ` ( constant ( 1024.0 * 1024.0 : : Double ) ) ) gebibytes < - let _ " gib " CDouble ( mebibytes ` divd ` ( constant ( 1024.0 : : Double ) ) ) throughput < - let _ " throughput " CDouble ( gebibytes ` divd ` seconds ) exec void_t "fprintf" [stderr, string formatString1, n, milliseconds_per_iter] benchmark _ _ _ = error "Benchmark expects int as first argument (number of iterations)." initializeCounter :: String -> CGen () () initializeCounter kernelName = do let psum = (kernelName ++ "_sum_seconds", CDouble) counter = (kernelName ++ "_counter", CInt32) addStmt (Decl psum (constant (0 :: Double)) ()) addStmt (Decl counter (constant (0 :: Int)) ()) printCounter :: String -> CGen () () printCounter kernelName = do let formatString = "Kernel %s timing: %f ms per execution (%d executions)\\n" psum = var (kernelName ++ "_sum_seconds", CDouble) counter = var (kernelName ++ "_counter", CInt32) milliseconds <- let_ "ms" CDouble ((psum `muli` (constant (1000.0 :: Double))) `divd` (i2d counter)) exec void_t "fprintf" [stderr, string formatString, string kernelName, milliseconds, counter] compProgram :: CompileConfig -> TypeEnv -> [Stmt a] -> CGen () KernelMap compProgram cfg env program = let ctxVar = ClContext ("ctx", contextCType) pVar = ClProgram ("program", programCType) body = compHost cfg ctxVar Map.empty program (stmts, _, _, finalState) = runCGen (initHostState env) body kernels' = kernels finalState allocs = deviceAllocations finalState in do initializeContext ctxVar (configVerbosity cfg) exec void_t "initializeTimer" [] if configProfile cfg then mapM_ initializeCounter (Map.keys kernels') else return () buildProgram ctxVar pVar (configKernelsFilename cfg) kernelHandles <- mapM (createKernel pVar) (Map.keys kernels') addStmts stmts if configProfile cfg then mapM_ printCounter (Map.keys kernels') else return () mapM_ releaseDeviceData (Map.keys allocs) mapM_ releaseKernel kernelHandles releaseProgram pVar releaseContext ctxVar return kernels' releaseAllDeviceArrays :: ILHost () releaseAllDeviceArrays = do allocs <- getsState deviceAllocations mapM_ releaseDeviceData (Map.keys allocs) prettyKernels :: KernelMap -> String prettyKernels kernelMap = pretty (map (\(Kernel _ _ s) -> s) (Map.elems kernelMap)) createMain :: Statements -> String createMain body = pretty (includes ++ [function int32_t [] "main" body]) includes :: [TopLevel] includes = [includeSys "fcl.h", includeSys "stdio.h", includeSys "sys/time.h", includeSys "mcl.h"] codeGen :: CompileConfig -> TypeEnv -> ILProgram a -> (String, String) codeGen cfg env program = let (mainBody, _, kernels') = evalCGen () (compProgram cfg env program) in (createMain mainBody, prettyKernels kernels')
212cc99a2c81d2ff49ae4f1548255b8fc3c38192b0316ea4b1e9c5308cc53875
morpheusgraphql/morpheus-graphql
Resolver.hs
# LANGUAGE DataKinds # {-# LANGUAGE OverloadedStrings #-} module Domains.Posts.Resolver where import Data.Data (Typeable) import Data.Maybe (catMaybes) import Data.Morpheus (deriveApp) import Data.Morpheus.Types import Domains.Posts.Posts resolvePost :: Monad m => ID -> m (Maybe (Post m)) resolvePost postId = pure $ Just $ Post { Domains.Posts.Posts.id = pure postId, title = pure "Post Tittle", authorID = pure "Post Author" } resolveQuery :: Monad m => Query m resolveQuery = Query { posts = catMaybes <$> traverse resolvePost [ "id1", "id2" ], post = resolvePost . argValue } rootResolver :: Monad m => RootResolver m () Query Undefined Undefined rootResolver = defaultRootResolver {queryResolver = resolveQuery} app :: (Typeable m, Monad m) => App () m app = deriveApp rootResolver
null
https://raw.githubusercontent.com/morpheusgraphql/morpheus-graphql/d2c085efb3ce6d875a5d5d8fe0024c048a089a2c/examples/code-gen/src/Domains/Posts/Resolver.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE DataKinds # module Domains.Posts.Resolver where import Data.Data (Typeable) import Data.Maybe (catMaybes) import Data.Morpheus (deriveApp) import Data.Morpheus.Types import Domains.Posts.Posts resolvePost :: Monad m => ID -> m (Maybe (Post m)) resolvePost postId = pure $ Just $ Post { Domains.Posts.Posts.id = pure postId, title = pure "Post Tittle", authorID = pure "Post Author" } resolveQuery :: Monad m => Query m resolveQuery = Query { posts = catMaybes <$> traverse resolvePost [ "id1", "id2" ], post = resolvePost . argValue } rootResolver :: Monad m => RootResolver m () Query Undefined Undefined rootResolver = defaultRootResolver {queryResolver = resolveQuery} app :: (Typeable m, Monad m) => App () m app = deriveApp rootResolver
fc782254ac50a30956403e245ce9381c86eb3fdb30b0d4671dad67d555e23797
Frozenlock/bacure
obj.clj
(ns bacure.coerce.obj (:require [bacure.coerce :as c :refer [bacnet->clojure clojure->bacnet]] [bacure.coerce.type.primitive :as p] [bacure.coerce.type.enumerated :as e]) (:import com.serotonin.bacnet4j.RemoteObject (com.serotonin.bacnet4j.obj ObjectProperties BACnetObject PropertyTypeDefinition ObjectPropertyTypeDefinition))) ;; we only go to clojure... no need to do a clojure->bacnet method (defmethod bacnet->clojure RemoteObject [^RemoteObject o] {:object-identifier (-> (.getObjectIdentifier o) bacnet->clojure) :object-name (-> (.getObjectName o) bacnet->clojure)}) (defmethod bacnet->clojure PropertyTypeDefinition [^PropertyTypeDefinition o] {:type (-> (re-find #"[A-Za-z0-9]*$" (.toString (.getClazz o))) (c/from-camel) (clojure.string/lower-case) (keyword)) :property-identifier (bacnet->clojure (.getPropertyIdentifier o)) :array (.isArray o) :array-length (.getArrayLength o) :collection (.isCollection o) :list (.isList o)}) (defmethod bacnet->clojure ObjectPropertyTypeDefinition [^ObjectPropertyTypeDefinition o] (let [{:keys [property-identifier type array collection list array-length]} (bacnet->clojure (.getPropertyTypeDefinition o))] [property-identifier {:type type :optional (bacnet->clojure (.isOptional o)) :required (bacnet->clojure (.isRequired o)) :sequence (or array collection list) :array-length array-length}])) (defn property-type-definitions "Given an object type, return the properties it should have, and if they are :required, :optional, or :sequence." [object-type] (->> (ObjectProperties/getObjectPropertyTypeDefinitions (clojure->bacnet :object-type object-type)) (map bacnet->clojure) (into {}))) (defn properties-by-option "Return a list or properties. `option' should be :required, :optional, :sequence or :all." [object-type option] (assert (some #{option} [:required :optional :sequence :all])) (let [profile (property-type-definitions object-type)] (if (= option :all) (keys profile) (for [[k v] profile :when (get v option)] k)))) (defn determine-property-value-type "Given an object-type and a property-identifier, return a map with the :type and if it's a :sequence." [object-type property-identifier] (get (property-type-definitions object-type) (if (keyword? property-identifier) property-identifier (c/int-to-keyword e/property-identifier-map property-identifier)))) (defn get-object-type "Find the object type in an object-map (either from the :object-type, or in the :object-identifier)." [obj-map] (or (:object-type obj-map) (first (:object-identifier obj-map)))) (defn force-type "Associate the value with a specific type. Use only before encoding. Ex: {:some-property (force-type \"some-value\" :character-string)}" [value type-keyword] {::forced-type type-keyword :value value}) (defn encode-property-value "Encode the property value depending on what type it should be given the object. A type can be specified when required (proprietary properties) by using the function `force-type'." [object-type property-identifier value] (let [value-type (determine-property-value-type object-type property-identifier) forced-type (when (map? value) (::forced-type value)) type-keyword (or forced-type (:type value-type)) encode-fn (partial clojure->bacnet type-keyword) naked-value (if forced-type (:value value) value) length (:array-length value-type) pad (fn [coll] (if (> length 0) (take length (concat coll (repeat nil))) coll))] (if-not type-keyword (throw (Exception. (str "Couldn't find the type associated with property '" property-identifier "'. You can try to use the function `bacure.coerce.obj/force-type'.")))) (if (:sequence value-type) (if (not (or (nil? naked-value) (coll? naked-value))) (throw (Exception. (str "The property '"property-identifier "' requires a collection."))) (clojure->bacnet :sequence-of (map encode-fn (pad naked-value)))) (encode-fn naked-value)))) (defn encode-properties-values "Take an object-map (a map of properties and values) and encode the values (not the properties) into their corresponding bacnet4j type. For example, a clojure number \"1\" might be encoded into a real, or into an unisgned integer, depending on the object." [obj-map] (let [o-t (get-object-type obj-map)] (into {} (for [[property value] obj-map] [property (encode-property-value o-t property value)])))) (defn encode-properties "Encode an object map into a sequence of bacnet4j property-values. Remove-keys can be used to remove read-only properties before sending a command." [obj-map & remove-keys] (let [o-t (get-object-type obj-map) encoded-properties-values (for [[k v] (apply dissoc obj-map remove-keys)] (c/clojure->bacnet :property-value* {:property-identifier k :value v :object-type o-t}))] (clojure->bacnet :sequence-of encoded-properties-values))) ;;; (defmethod bacnet->clojure BACnetObject [^BACnetObject o] ;; unfortunately there doesn't appear to be a method retrieve all ;; the object properties at once. While it might be a little ;; wasteful, the most straightforward alternative appears to try to ;; get the value of all the possible properties for the given object ;; type. (let [[object-type object-instance] (c/bacnet->clojure (.getId o)) possible-properties (properties-by-option object-type :all)] (with-meta (->> (for [prop possible-properties :let [value (.get o (c/clojure->bacnet :property-identifier prop))] :when value] [prop (c/bacnet->clojure value)]) (into {})) add the local device as metadata to ease the round - trip from Clojure to BACnet {::local-device (.getLocalDevice o)}))) The local device ' addObject ' method expects a BACnetObject . ;; However, the BACnetObject needs a local device to be initiated. ;; This means that we can't really have a pure 'data' bacnet-object. (defn bacnet-object-with-local-device "Add a local device to the map metadata to allow conversion (and automatic object creation) to BACnet." [object-map local-device-object] (with-meta object-map {::local-device local-device-object})) (defmethod clojure->bacnet :bacnet-object [_ value] (if-let [local-device (::local-device (meta value))] (let [bacnet-object (BACnetObject. local-device (c/clojure->bacnet :object-identifier (:object-identifier value)))] ;; now write the values (doseq [[property value] (encode-properties-values value)] (.writePropertyInternal bacnet-object (c/clojure->bacnet :property-identifier property) value)) bacnet-object) (throw (Exception. (str "Missing local device in the object-map with identfier : " (:object-identifier value) "\nMake sure to use the local device function 'add-object!'")))))
null
https://raw.githubusercontent.com/Frozenlock/bacure/2d743492f7865d8c61313f4d73818c3d1ee462de/src/bacure/coerce/obj.clj
clojure
we only go to clojure... no need to do a clojure->bacnet method unfortunately there doesn't appear to be a method retrieve all the object properties at once. While it might be a little wasteful, the most straightforward alternative appears to try to get the value of all the possible properties for the given object type. However, the BACnetObject needs a local device to be initiated. This means that we can't really have a pure 'data' bacnet-object. now write the values
(ns bacure.coerce.obj (:require [bacure.coerce :as c :refer [bacnet->clojure clojure->bacnet]] [bacure.coerce.type.primitive :as p] [bacure.coerce.type.enumerated :as e]) (:import com.serotonin.bacnet4j.RemoteObject (com.serotonin.bacnet4j.obj ObjectProperties BACnetObject PropertyTypeDefinition ObjectPropertyTypeDefinition))) (defmethod bacnet->clojure RemoteObject [^RemoteObject o] {:object-identifier (-> (.getObjectIdentifier o) bacnet->clojure) :object-name (-> (.getObjectName o) bacnet->clojure)}) (defmethod bacnet->clojure PropertyTypeDefinition [^PropertyTypeDefinition o] {:type (-> (re-find #"[A-Za-z0-9]*$" (.toString (.getClazz o))) (c/from-camel) (clojure.string/lower-case) (keyword)) :property-identifier (bacnet->clojure (.getPropertyIdentifier o)) :array (.isArray o) :array-length (.getArrayLength o) :collection (.isCollection o) :list (.isList o)}) (defmethod bacnet->clojure ObjectPropertyTypeDefinition [^ObjectPropertyTypeDefinition o] (let [{:keys [property-identifier type array collection list array-length]} (bacnet->clojure (.getPropertyTypeDefinition o))] [property-identifier {:type type :optional (bacnet->clojure (.isOptional o)) :required (bacnet->clojure (.isRequired o)) :sequence (or array collection list) :array-length array-length}])) (defn property-type-definitions "Given an object type, return the properties it should have, and if they are :required, :optional, or :sequence." [object-type] (->> (ObjectProperties/getObjectPropertyTypeDefinitions (clojure->bacnet :object-type object-type)) (map bacnet->clojure) (into {}))) (defn properties-by-option "Return a list or properties. `option' should be :required, :optional, :sequence or :all." [object-type option] (assert (some #{option} [:required :optional :sequence :all])) (let [profile (property-type-definitions object-type)] (if (= option :all) (keys profile) (for [[k v] profile :when (get v option)] k)))) (defn determine-property-value-type "Given an object-type and a property-identifier, return a map with the :type and if it's a :sequence." [object-type property-identifier] (get (property-type-definitions object-type) (if (keyword? property-identifier) property-identifier (c/int-to-keyword e/property-identifier-map property-identifier)))) (defn get-object-type "Find the object type in an object-map (either from the :object-type, or in the :object-identifier)." [obj-map] (or (:object-type obj-map) (first (:object-identifier obj-map)))) (defn force-type "Associate the value with a specific type. Use only before encoding. Ex: {:some-property (force-type \"some-value\" :character-string)}" [value type-keyword] {::forced-type type-keyword :value value}) (defn encode-property-value "Encode the property value depending on what type it should be given the object. A type can be specified when required (proprietary properties) by using the function `force-type'." [object-type property-identifier value] (let [value-type (determine-property-value-type object-type property-identifier) forced-type (when (map? value) (::forced-type value)) type-keyword (or forced-type (:type value-type)) encode-fn (partial clojure->bacnet type-keyword) naked-value (if forced-type (:value value) value) length (:array-length value-type) pad (fn [coll] (if (> length 0) (take length (concat coll (repeat nil))) coll))] (if-not type-keyword (throw (Exception. (str "Couldn't find the type associated with property '" property-identifier "'. You can try to use the function `bacure.coerce.obj/force-type'.")))) (if (:sequence value-type) (if (not (or (nil? naked-value) (coll? naked-value))) (throw (Exception. (str "The property '"property-identifier "' requires a collection."))) (clojure->bacnet :sequence-of (map encode-fn (pad naked-value)))) (encode-fn naked-value)))) (defn encode-properties-values "Take an object-map (a map of properties and values) and encode the values (not the properties) into their corresponding bacnet4j type. For example, a clojure number \"1\" might be encoded into a real, or into an unisgned integer, depending on the object." [obj-map] (let [o-t (get-object-type obj-map)] (into {} (for [[property value] obj-map] [property (encode-property-value o-t property value)])))) (defn encode-properties "Encode an object map into a sequence of bacnet4j property-values. Remove-keys can be used to remove read-only properties before sending a command." [obj-map & remove-keys] (let [o-t (get-object-type obj-map) encoded-properties-values (for [[k v] (apply dissoc obj-map remove-keys)] (c/clojure->bacnet :property-value* {:property-identifier k :value v :object-type o-t}))] (clojure->bacnet :sequence-of encoded-properties-values))) (defmethod bacnet->clojure BACnetObject [^BACnetObject o] (let [[object-type object-instance] (c/bacnet->clojure (.getId o)) possible-properties (properties-by-option object-type :all)] (with-meta (->> (for [prop possible-properties :let [value (.get o (c/clojure->bacnet :property-identifier prop))] :when value] [prop (c/bacnet->clojure value)]) (into {})) add the local device as metadata to ease the round - trip from Clojure to BACnet {::local-device (.getLocalDevice o)}))) The local device ' addObject ' method expects a BACnetObject . (defn bacnet-object-with-local-device "Add a local device to the map metadata to allow conversion (and automatic object creation) to BACnet." [object-map local-device-object] (with-meta object-map {::local-device local-device-object})) (defmethod clojure->bacnet :bacnet-object [_ value] (if-let [local-device (::local-device (meta value))] (let [bacnet-object (BACnetObject. local-device (c/clojure->bacnet :object-identifier (:object-identifier value)))] (doseq [[property value] (encode-properties-values value)] (.writePropertyInternal bacnet-object (c/clojure->bacnet :property-identifier property) value)) bacnet-object) (throw (Exception. (str "Missing local device in the object-map with identfier : " (:object-identifier value) "\nMake sure to use the local device function 'add-object!'")))))
5339b95c96839d3af9e053503182b506d8a1ff5516e19633cd64cb19f6488fea
airalab/hs-web3
String.hs
-- | -- Module : Data.Solidity.Prim.String Copyright : 2016 - 2021 -- License : Apache-2.0 -- -- Maintainer : -- Stability : experimental -- Portability : noportable -- - encoded string type . -- module Data.Solidity.Prim.String where import Data.Text (Text) import Data.Text.Encoding (decodeUtf8, encodeUtf8) import Data.Solidity.Abi (AbiGet (..), AbiPut (..), AbiType (..)) import Data.Solidity.Prim.Bytes () instance AbiType Text where isDynamic _ = True instance AbiPut Text where abiPut = abiPut . encodeUtf8 instance AbiGet Text where abiGet = decodeUtf8 <$> abiGet
null
https://raw.githubusercontent.com/airalab/hs-web3/c03b86eb621f963886a78c39ee18bcec753f17ac/packages/solidity/src/Data/Solidity/Prim/String.hs
haskell
| Module : Data.Solidity.Prim.String License : Apache-2.0 Maintainer : Stability : experimental Portability : noportable
Copyright : 2016 - 2021 - encoded string type . module Data.Solidity.Prim.String where import Data.Text (Text) import Data.Text.Encoding (decodeUtf8, encodeUtf8) import Data.Solidity.Abi (AbiGet (..), AbiPut (..), AbiType (..)) import Data.Solidity.Prim.Bytes () instance AbiType Text where isDynamic _ = True instance AbiPut Text where abiPut = abiPut . encodeUtf8 instance AbiGet Text where abiGet = decodeUtf8 <$> abiGet
726c93c4a6e2031bdf7be29f214bae1b438cdb94d78b95116537b1fcb9007b90
JeffreyBenjaminBrown/digraphs-with-text
weird characters.hs
let chars = map (\n -> (show n) ++ " " ++ [toEnum n :: Char]) [1001..1500] mapM_ putStrLn chars 164 ¤ 165 ¥ 166 ¦ 167 § 168 ¨ 169 © 170 ª 172 ¬ 171 « 187 » 191 ¿ 247 ÷ 248 ø 322 ł The next were not readable. 398 Ǝ 399 Ə 404 Ɣ 450 ǂ
null
https://raw.githubusercontent.com/JeffreyBenjaminBrown/digraphs-with-text/34e47a52aa9abb6fd42028deba1623a92e278aae/howto/infreq/weird%20characters.hs
haskell
let chars = map (\n -> (show n) ++ " " ++ [toEnum n :: Char]) [1001..1500] mapM_ putStrLn chars 164 ¤ 165 ¥ 166 ¦ 167 § 168 ¨ 169 © 170 ª 172 ¬ 171 « 187 » 191 ¿ 247 ÷ 248 ø 322 ł The next were not readable. 398 Ǝ 399 Ə 404 Ɣ 450 ǂ
066b46347fa42a0cc62566dae530a38d4e31366a81fbf8c0993a94da7b1ad010
qfpl/reflex-workshop
Counter.hs
| Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation License : : Stability : experimental Portability : non - portable Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecursiveDo # {-# LANGUAGE GADTs #-} module Workshop.Behaviors.Dynamics.Counter ( exCounter ) where import Reflex.Dom import Types.Exercise import Util.Bootstrap import Exercises.Behaviors.Dynamics.Counter import Solutions.Behaviors.Dynamics.Counter mkIn :: MonadWidget t m => m (Event t (), Event t ()) mkIn = divClass "row" $ do eAdd <- divClass "col-6" $ buttonClass "Add" "btn btn-block" eClear <- divClass "col-6" $ buttonClass "Clear" "btn btn-block" pure (eAdd, eClear) mk :: MonadWidget t m => (Event t (Int -> Int) -> m (Dynamic t Int)) -> (Event t (), Event t ()) -> m () mk fn (eAdd, eClear) = mdo let eFn = leftmost [ (+ 1) <$ eAdd, const 0 <$ eClear] d <- fn eFn divClass "row" $ do divClass "col-6" $ text "Count" divClass "col-6" $ display d exCounter :: MonadWidget t m => Exercise m exCounter = let problem = Problem "pages/behaviors/dynamics/counter.html" "src/Exercises/Behaviors/Dynamics/Counter.hs" mempty progress = ProgressSetup True mkIn (mk counterSolution) (mk counterExercise) solution = Solution [ "pages/behaviors/dynamics/counter/solution/0.html" , "pages/behaviors/dynamics/counter/solution/1.html" , "pages/behaviors/dynamics/counter/solution/2.html" , "pages/behaviors/dynamics/counter/solution/3.html" ] in Exercise "counter" "counter" problem progress solution
null
https://raw.githubusercontent.com/qfpl/reflex-workshop/244ef13fb4b2e884f455eccc50072e98d1668c9e/src/Workshop/Behaviors/Dynamics/Counter.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE GADTs #
| Copyright : ( c ) 2018 , Commonwealth Scientific and Industrial Research Organisation License : : Stability : experimental Portability : non - portable Copyright : (c) 2018, Commonwealth Scientific and Industrial Research Organisation License : BSD3 Maintainer : Stability : experimental Portability : non-portable -} # LANGUAGE RecursiveDo # module Workshop.Behaviors.Dynamics.Counter ( exCounter ) where import Reflex.Dom import Types.Exercise import Util.Bootstrap import Exercises.Behaviors.Dynamics.Counter import Solutions.Behaviors.Dynamics.Counter mkIn :: MonadWidget t m => m (Event t (), Event t ()) mkIn = divClass "row" $ do eAdd <- divClass "col-6" $ buttonClass "Add" "btn btn-block" eClear <- divClass "col-6" $ buttonClass "Clear" "btn btn-block" pure (eAdd, eClear) mk :: MonadWidget t m => (Event t (Int -> Int) -> m (Dynamic t Int)) -> (Event t (), Event t ()) -> m () mk fn (eAdd, eClear) = mdo let eFn = leftmost [ (+ 1) <$ eAdd, const 0 <$ eClear] d <- fn eFn divClass "row" $ do divClass "col-6" $ text "Count" divClass "col-6" $ display d exCounter :: MonadWidget t m => Exercise m exCounter = let problem = Problem "pages/behaviors/dynamics/counter.html" "src/Exercises/Behaviors/Dynamics/Counter.hs" mempty progress = ProgressSetup True mkIn (mk counterSolution) (mk counterExercise) solution = Solution [ "pages/behaviors/dynamics/counter/solution/0.html" , "pages/behaviors/dynamics/counter/solution/1.html" , "pages/behaviors/dynamics/counter/solution/2.html" , "pages/behaviors/dynamics/counter/solution/3.html" ] in Exercise "counter" "counter" problem progress solution
c4eda21e2d215c94a4165b7fadf793361df9c618398f9b7969401650f7d625fc
hiredman/clojurebot
stock_quote.clj
(ns hiredman.clojurebot.stock-quote (:require [hiredman.clojurebot.core :as core] [hiredman.utilities :as util] [clojurebot.json :as json])) (def url "=") (defn stock-quote [symbol] (json/decode-from-str (apply str (butlast (drop 4 (util/get-url (.concat url symbol))))))) (defn format-quote [{:keys [l t c cp]}] (format "%s; %s" t c)) (core/defresponder ::stock-quote 0 (core/dfn (and (:addressed? (meta msg)) (re-find #"^ticker [A-Z]+" (core/extract-message bot msg)))) ;; (core/send-out :msg bot msg (try (format-quote (stock-quote (.replaceAll (core/extract-message bot msg) "^ticker " ""))) (catch java.io.IOException e (.toString e))))) ;(core/remove-dispatch-hook ::stock-quote)
null
https://raw.githubusercontent.com/hiredman/clojurebot/1e8bde92f2dd45bb7928d4db17de8ec48557ead1/src/hiredman/clojurebot/stock_quote.clj
clojure
(core/remove-dispatch-hook ::stock-quote)
(ns hiredman.clojurebot.stock-quote (:require [hiredman.clojurebot.core :as core] [hiredman.utilities :as util] [clojurebot.json :as json])) (def url "=") (defn stock-quote [symbol] (json/decode-from-str (apply str (butlast (drop 4 (util/get-url (.concat url symbol))))))) (defn format-quote [{:keys [l t c cp]}] (format "%s; %s" t c)) (core/defresponder ::stock-quote 0 (core/dfn (and (:addressed? (meta msg)) (core/send-out :msg bot msg (try (format-quote (stock-quote (.replaceAll (core/extract-message bot msg) "^ticker " ""))) (catch java.io.IOException e (.toString e)))))
eaab35a2982a1c2fa390155ca6bab2732403632a795c4431979afca395d1057b
GaloisInc/surveyor
StateExplorer.hs
# LANGUAGE DataKinds # {-# LANGUAGE GADTs #-} # LANGUAGE KindSignatures # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # module Surveyor.Brick.Widget.SymbolicExecution.StateExplorer ( StateExplorer, stateExplorer, renderSymbolicExecutionStateExplorer, handleSymbolicExecutionStateExplorerEvent ) where import qualified Brick as B import Control.Lens ( (^.) ) import qualified Control.Lens as L import Control.Monad.IO.Class ( liftIO ) import Data.Maybe ( fromMaybe ) import qualified Data.Parameterized.Classes as PC import qualified Data.Parameterized.Nonce as PN import Data.Proxy ( Proxy(..) ) import qualified Data.Text as T import qualified Lang.Crucible.Backend as CB import qualified Lang.Crucible.CFG.Core as LCCC import qualified Lang.Crucible.Simulator.CallFrame as LCSC import qualified Lang.Crucible.Simulator.ExecutionTree as LCSET import qualified Prettyprinter as PP import qualified Prettyprinter.Render.Text as PPT import qualified What4.Expr.Builder as WEB import Surveyor.Brick.Names ( Names(..) ) import qualified Surveyor.Brick.Panic as SBP import qualified Surveyor.Core as C import qualified Surveyor.Brick.Widget.CallStackViewer as WCSV import qualified Surveyor.Brick.Widget.ModelViewer as WMV | Holds the state of the StateExplorer widget -- -- This includes the selected value state as well as the state for the value -- viewer widget itself, all encapsulated in the 'WCSV.CallStackViewer'. The -- nonce lets us prove that we have the same symbolic backend as the ' C.SymbolicExecutionState ' so that we can move data between the two data StateExplorer arch s e where StateExplorer :: (sym ~ WEB.ExprBuilder s st fs) => PN.Nonce s sym -> WCSV.CallStackViewer arch s sym e -> StateExplorer arch s e -- | Construct the necessary explorer state from a suspended symbolic execution state -- -- This is a little tricky because the values in the 'StateExplorer' capture and -- existentially quantify some types that are also quantified under the ' C.SymbolicExecutionState ' constructor , hence some of the verbose type -- signatures below. -- -- At a high level, this function examines all of the values captured by a breakpoint and builds viewers to inspect them . We use ' Ctx . Assignment 's here -- to provide total indexing, which unfortunately makes the types a bit -- complicated and involves a few wrapper types. -- -- We construct a viewer for each value, as each viewer widget tracks its own -- state about which constituent values are currently selected. We also track -- our own focus widget to determine if we should send events to the value -- selector widget or the value viewer widget. stateExplorer :: forall e arch s . (C.Architecture arch s) => PN.NonceGenerator IO s -> C.SymbolicExecutionState arch s C.Suspend -> IO (StateExplorer arch s e) stateExplorer ng (C.Suspended symNonce suspSt) = do csViewer <- WCSV.callStackViewer (Proxy @arch) ng (C.suspendedReason suspSt) (C.suspendedRegVals suspSt) frames return (StateExplorer symNonce csViewer) where frames = suspSt ^. L.to C.suspendedSimState . LCSET.stateTree . L.to LCSET.activeFrames -- | Render a view of the final state from symbolic execution -- -- Eventually, this should provide some mechanisms for deeply inspecting the -- state (including arch-specific inspection of memory). renderSymbolicExecutionStateExplorer :: forall arch s e . ( C.Architecture arch s , C.CrucibleExtension arch ) => C.SymbolicExecutionState arch s C.Suspend -> StateExplorer arch s e -> C.ValueNameMap s -> B.Widget Names renderSymbolicExecutionStateExplorer (C.Suspended _symNonce1 suspSt) (StateExplorer _symNonce2 csv) valNames = case C.suspendedCallFrame suspSt of { LCSC._frameCFG = fcfg } -> case C.suspendedReason suspSt of C.SuspendedBreakpoint bp -> B.vBox $ [ B.txt "Current Function:" B.<+> B.txt (T.pack (show (LCCC.cfgHandle fcfg))) , B.txt "Current Block:" B.<+> B.txt (T.pack (show (cf ^. LCSC.frameBlockID))) , B.txt "Breakpoint name:" B.<+> B.txt (fromMaybe "<Unnamed Breakpoint>" (C.breakpointName bp)) , WCSV.renderCallStackViewer True valNames csv ] C.SuspendedAssertionFailure mv -> B.vBox $ [ B.txt "Current Function:" B.<+> B.txt (T.pack (show (LCCC.cfgHandle fcfg))) , B.txt "Current Block:" B.<+> B.txt (T.pack (show (cf ^. LCSC.frameBlockID))) , WCSV.renderCallStackViewer True valNames csv , B.txt "Model:" B.<+> WMV.renderModelViewer mv ] C.SuspendedExecutionStep execState -> B.vBox $ [ B.txt "Current Function:" B.<+> B.txt (T.pack (show (LCCC.cfgHandle fcfg))) , B.txt "Current Block:" B.<+> B.txt (T.pack (show (cf ^. LCSC.frameBlockID))) , B.txt "Symbolic State:" B.<+> prettyWidget (ppExecState execState) , WCSV.renderCallStackViewer True valNames csv ] ppExecState :: LCSET.ExecState p sym ext rtp -> PP.Doc ann ppExecState execState = case execState of LCSET.ResultState {} -> "ResultState (returning from function)" LCSET.AbortState rsn _ -> "AbortState " <> PP.parens (CB.ppAbortExecReason rsn) LCSET.UnwindCallState {} -> "UnwindCallState" LCSET.CallState {} -> "CallState" LCSET.TailCallState {} -> "TailCallState" LCSET.ReturnState {} -> "ReturnState" LCSET.RunningState {} -> "RunningState" LCSET.SymbolicBranchState {} -> "SymbolicBranchState" LCSET.ControlTransferState {} -> "ControlTransferState" LCSET.OverrideState {} -> "OverrideState" LCSET.BranchMergeState {} -> "BranchMergeState" LCSET.InitialState {} -> "InitialState" prettyWidget :: PP.Doc ann -> B.Widget n prettyWidget doc = B.txt (PPT.renderStrict (PP.layoutCompact doc)) | Handle events for the ' StateExplorer ' -- This handles changing focus between the two sub - widgets via tab . Beyond -- that, it delegates all events to the currently focused sub-widget. handleSymbolicExecutionStateExplorerEvent :: C.S archEvt u arch s -> B.BrickEvent Names e -> C.SymbolicExecutionState arch s C.Suspend -> StateExplorer arch s e -> B.EventM Names (StateExplorer arch s e) handleSymbolicExecutionStateExplorerEvent s0 evt (C.Suspended symNonce1 suspSt) (StateExplorer symNonce2 csv) = do case PC.testEquality symNonce1 symNonce2 of Nothing -> SBP.panic "handleSymbolicExecutionExplorerEvent" ["Mismatched solver nonce"] Just PC.Refl -> do csv' <- WCSV.handleCallStackViewerEvent evt csv -- Emit an event to update the underlying symbolic execution state (since -- we don't have easy access to it in the event handler, and don't want to -- make keeping everything in sync fragile) let suspSt' = suspSt { C.suspendedCurrentValue = WCSV.selectedValue csv' } let archNonce = s0 ^. C.lNonce let newState = C.Suspended symNonce1 suspSt' let sessionID = C.symbolicSessionID newState liftIO $ C.sEmitEvent s0 (C.SetCurrentSymbolicExecutionValue archNonce symNonce1 sessionID (WCSV.selectedValue csv')) return (StateExplorer symNonce2 csv')
null
https://raw.githubusercontent.com/GaloisInc/surveyor/96b6748d811bc2ab9ef330307a324bd00e04819f/surveyor-brick/src/Surveyor/Brick/Widget/SymbolicExecution/StateExplorer.hs
haskell
# LANGUAGE GADTs # # LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes # This includes the selected value state as well as the state for the value viewer widget itself, all encapsulated in the 'WCSV.CallStackViewer'. The nonce lets us prove that we have the same symbolic backend as the | Construct the necessary explorer state from a suspended symbolic execution state This is a little tricky because the values in the 'StateExplorer' capture and existentially quantify some types that are also quantified under the signatures below. At a high level, this function examines all of the values captured by a to provide total indexing, which unfortunately makes the types a bit complicated and involves a few wrapper types. We construct a viewer for each value, as each viewer widget tracks its own state about which constituent values are currently selected. We also track our own focus widget to determine if we should send events to the value selector widget or the value viewer widget. | Render a view of the final state from symbolic execution Eventually, this should provide some mechanisms for deeply inspecting the state (including arch-specific inspection of memory). that, it delegates all events to the currently focused sub-widget. Emit an event to update the underlying symbolic execution state (since we don't have easy access to it in the event handler, and don't want to make keeping everything in sync fragile)
# LANGUAGE DataKinds # # LANGUAGE KindSignatures # # LANGUAGE ScopedTypeVariables # # LANGUAGE TemplateHaskell # # LANGUAGE TypeApplications # module Surveyor.Brick.Widget.SymbolicExecution.StateExplorer ( StateExplorer, stateExplorer, renderSymbolicExecutionStateExplorer, handleSymbolicExecutionStateExplorerEvent ) where import qualified Brick as B import Control.Lens ( (^.) ) import qualified Control.Lens as L import Control.Monad.IO.Class ( liftIO ) import Data.Maybe ( fromMaybe ) import qualified Data.Parameterized.Classes as PC import qualified Data.Parameterized.Nonce as PN import Data.Proxy ( Proxy(..) ) import qualified Data.Text as T import qualified Lang.Crucible.Backend as CB import qualified Lang.Crucible.CFG.Core as LCCC import qualified Lang.Crucible.Simulator.CallFrame as LCSC import qualified Lang.Crucible.Simulator.ExecutionTree as LCSET import qualified Prettyprinter as PP import qualified Prettyprinter.Render.Text as PPT import qualified What4.Expr.Builder as WEB import Surveyor.Brick.Names ( Names(..) ) import qualified Surveyor.Brick.Panic as SBP import qualified Surveyor.Core as C import qualified Surveyor.Brick.Widget.CallStackViewer as WCSV import qualified Surveyor.Brick.Widget.ModelViewer as WMV | Holds the state of the StateExplorer widget ' C.SymbolicExecutionState ' so that we can move data between the two data StateExplorer arch s e where StateExplorer :: (sym ~ WEB.ExprBuilder s st fs) => PN.Nonce s sym -> WCSV.CallStackViewer arch s sym e -> StateExplorer arch s e ' C.SymbolicExecutionState ' constructor , hence some of the verbose type breakpoint and builds viewers to inspect them . We use ' Ctx . Assignment 's here stateExplorer :: forall e arch s . (C.Architecture arch s) => PN.NonceGenerator IO s -> C.SymbolicExecutionState arch s C.Suspend -> IO (StateExplorer arch s e) stateExplorer ng (C.Suspended symNonce suspSt) = do csViewer <- WCSV.callStackViewer (Proxy @arch) ng (C.suspendedReason suspSt) (C.suspendedRegVals suspSt) frames return (StateExplorer symNonce csViewer) where frames = suspSt ^. L.to C.suspendedSimState . LCSET.stateTree . L.to LCSET.activeFrames renderSymbolicExecutionStateExplorer :: forall arch s e . ( C.Architecture arch s , C.CrucibleExtension arch ) => C.SymbolicExecutionState arch s C.Suspend -> StateExplorer arch s e -> C.ValueNameMap s -> B.Widget Names renderSymbolicExecutionStateExplorer (C.Suspended _symNonce1 suspSt) (StateExplorer _symNonce2 csv) valNames = case C.suspendedCallFrame suspSt of { LCSC._frameCFG = fcfg } -> case C.suspendedReason suspSt of C.SuspendedBreakpoint bp -> B.vBox $ [ B.txt "Current Function:" B.<+> B.txt (T.pack (show (LCCC.cfgHandle fcfg))) , B.txt "Current Block:" B.<+> B.txt (T.pack (show (cf ^. LCSC.frameBlockID))) , B.txt "Breakpoint name:" B.<+> B.txt (fromMaybe "<Unnamed Breakpoint>" (C.breakpointName bp)) , WCSV.renderCallStackViewer True valNames csv ] C.SuspendedAssertionFailure mv -> B.vBox $ [ B.txt "Current Function:" B.<+> B.txt (T.pack (show (LCCC.cfgHandle fcfg))) , B.txt "Current Block:" B.<+> B.txt (T.pack (show (cf ^. LCSC.frameBlockID))) , WCSV.renderCallStackViewer True valNames csv , B.txt "Model:" B.<+> WMV.renderModelViewer mv ] C.SuspendedExecutionStep execState -> B.vBox $ [ B.txt "Current Function:" B.<+> B.txt (T.pack (show (LCCC.cfgHandle fcfg))) , B.txt "Current Block:" B.<+> B.txt (T.pack (show (cf ^. LCSC.frameBlockID))) , B.txt "Symbolic State:" B.<+> prettyWidget (ppExecState execState) , WCSV.renderCallStackViewer True valNames csv ] ppExecState :: LCSET.ExecState p sym ext rtp -> PP.Doc ann ppExecState execState = case execState of LCSET.ResultState {} -> "ResultState (returning from function)" LCSET.AbortState rsn _ -> "AbortState " <> PP.parens (CB.ppAbortExecReason rsn) LCSET.UnwindCallState {} -> "UnwindCallState" LCSET.CallState {} -> "CallState" LCSET.TailCallState {} -> "TailCallState" LCSET.ReturnState {} -> "ReturnState" LCSET.RunningState {} -> "RunningState" LCSET.SymbolicBranchState {} -> "SymbolicBranchState" LCSET.ControlTransferState {} -> "ControlTransferState" LCSET.OverrideState {} -> "OverrideState" LCSET.BranchMergeState {} -> "BranchMergeState" LCSET.InitialState {} -> "InitialState" prettyWidget :: PP.Doc ann -> B.Widget n prettyWidget doc = B.txt (PPT.renderStrict (PP.layoutCompact doc)) | Handle events for the ' StateExplorer ' This handles changing focus between the two sub - widgets via tab . Beyond handleSymbolicExecutionStateExplorerEvent :: C.S archEvt u arch s -> B.BrickEvent Names e -> C.SymbolicExecutionState arch s C.Suspend -> StateExplorer arch s e -> B.EventM Names (StateExplorer arch s e) handleSymbolicExecutionStateExplorerEvent s0 evt (C.Suspended symNonce1 suspSt) (StateExplorer symNonce2 csv) = do case PC.testEquality symNonce1 symNonce2 of Nothing -> SBP.panic "handleSymbolicExecutionExplorerEvent" ["Mismatched solver nonce"] Just PC.Refl -> do csv' <- WCSV.handleCallStackViewerEvent evt csv let suspSt' = suspSt { C.suspendedCurrentValue = WCSV.selectedValue csv' } let archNonce = s0 ^. C.lNonce let newState = C.Suspended symNonce1 suspSt' let sessionID = C.symbolicSessionID newState liftIO $ C.sEmitEvent s0 (C.SetCurrentSymbolicExecutionValue archNonce symNonce1 sessionID (WCSV.selectedValue csv')) return (StateExplorer symNonce2 csv')
d0dd74b3d0b3718a6b3bc82ff031e1cce5ce5207ed430344fe7817f2517fece4
fission-codes/fission
Types.hs
module Fission.CLI.Parser.Quiet.Types (QuietFlag (..)) where import Fission.Prelude newtype QuietFlag = QuietFlag { unFlag :: Bool } deriving newtype (Show, Eq)
null
https://raw.githubusercontent.com/fission-codes/fission/afaae0dc5f83f4e35a3d4fdbdea2608a8d49bef8/fission-cli/library/Fission/CLI/Parser/Quiet/Types.hs
haskell
module Fission.CLI.Parser.Quiet.Types (QuietFlag (..)) where import Fission.Prelude newtype QuietFlag = QuietFlag { unFlag :: Bool } deriving newtype (Show, Eq)
c200b9b5fe57037370a0076f3d9217f414b7cb8a5c0b007101774b12ec4443a3
gelisam/hawk
Uncertain.hs
# LANGUAGE CPP , , RankNTypes # -- | A computation which may raise warnings or fail in error. module Control.Monad.Trans.Uncertain where import Prelude hiding (fail) #if MIN_VERSION_base(4,12,0) import Control.Monad.Fail ( #if !MIN_VERSION_base(4,13,0) MonadFail, #endif fail) #else import Prelude (fail) #endif import "mtl" Control.Monad.Trans import "mtl" Control.Monad.Identity hiding (fail) import "transformers" Control.Monad.Trans.Except import "transformers" Control.Monad.Trans.Writer import System.Exit import System.IO import Text.Printf type Warning = String type Error = String newtype UncertainT m a = UncertainT { unUncertainT :: ExceptT Error (WriterT [Warning] m) a } type Uncertain a = UncertainT Identity a instance Functor m => Functor (UncertainT m) where fmap f = UncertainT . fmap f . unUncertainT instance (Functor m, Monad m) => Applicative (UncertainT m) where pure = UncertainT . pure UncertainT mf <*> UncertainT mx = UncertainT (mf <*> mx) instance Monad m => Monad (UncertainT m) where return = UncertainT . return UncertainT mx >>= f = UncertainT (mx >>= f') where f' = unUncertainT . f #if MIN_VERSION_base(4,12,0) instance Monad m => MonadFail (UncertainT m) where #endif fail s = UncertainT (throwE s) instance MonadTrans UncertainT where lift = UncertainT . lift . lift instance MonadIO m => MonadIO (UncertainT m) where liftIO = lift . liftIO warn :: Monad m => String -> UncertainT m () warn s = UncertainT $ lift $ tell [s] fromRightM :: Monad m => Either String a -> UncertainT m a fromRightM (Left e) = fail e fromRightM (Right x) = return x multilineMsg :: String -> String multilineMsg = concatMap (printf "\n %s") . lines -- | Indent a multiline warning message. -- >>> :{ -- runUncertainIO $ do -- multilineWarn "foo\nbar\n" return 42 -- :} -- warning: -- foo -- bar 42 multilineWarn :: Monad m => String -> UncertainT m () multilineWarn = warn . multilineMsg -- | Indent a multiline error message. -- >>> :{ -- runUncertainIO $ do -- multilineFail "foo\nbar\n" return 42 -- :} -- error: -- foo -- bar * * * Exception : ExitFailure 1 multilineFail :: Monad m => String -> UncertainT m a multilineFail = fail . multilineMsg mapUncertainT :: (forall a. m a -> m' a) -> UncertainT m b -> UncertainT m' b mapUncertainT f = UncertainT . (mapExceptT . mapWriterT) f . unUncertainT runUncertainT :: UncertainT m a -> m (Either Error a, [Warning]) runUncertainT = runWriterT . runExceptT . unUncertainT uncertainT :: Monad m => (Either Error a, [Warning]) -> UncertainT m a uncertainT (Left e, warnings) = mapM_ warn warnings >> fail e uncertainT (Right x, warnings) = mapM_ warn warnings >> return x | A version of ` runWarnings ` which allows you to interleave IO actions -- with uncertain actions. -- Note that the warnings are displayed after the IO 's output . -- -- >>> :{ -- runWarningsIO $ do -- warn "before" -- lift $ putStrLn "IO" -- warn "after" return 42 -- :} -- IO -- warning: before -- warning: after -- Right 42 -- -- >>> :{ -- runWarningsIO $ do -- warn "before" -- lift $ putStrLn "IO" -- fail "fatal" return 42 -- :} -- IO -- warning: before -- Left "fatal" runWarningsIO :: UncertainT IO a -> IO (Either String a) runWarningsIO u = do (r, warnings) <- runUncertainT u mapM_ (hPutStrLn stderr . printf "warning: %s") warnings return r | A version of ` runUncertain ` which only prints the warnings , not the errors . Unlike ` runUncertain ` , it does n't terminate on error . -- -- >>> :{ -- runWarnings $ do -- warn "before" -- warn "after" return 42 -- :} -- warning: before -- warning: after -- Right 42 -- -- >>> :{ -- runWarnings $ do -- warn "before" -- fail "fatal" return 42 -- :} -- warning: before -- Left "fatal" runWarnings :: Uncertain a -> IO (Either String a) runWarnings = runWarningsIO . mapUncertainT (return . runIdentity) | A version of ` runUncertain ` which allows you to interleave IO actions -- with uncertain actions. -- Note that the warnings are displayed after the IO 's output . -- -- >>> :{ -- runUncertainIO $ do -- warn "before" -- lift $ putStrLn "IO" -- warn "after" return 42 -- :} -- IO -- warning: before -- warning: after 42 -- -- >>> :{ -- runUncertainIO $ do -- warn "before" -- lift $ putStrLn "IO" -- fail "fatal" return 42 -- :} -- IO -- warning: before -- error: fatal * * * Exception : ExitFailure 1 runUncertainIO :: UncertainT IO a -> IO a runUncertainIO u = do r <- runWarningsIO u case r of Left e -> do hPutStrLn stderr $ printf "error: %s" e exitFailure Right x -> return x -- | Print warnings and errors, terminating on error. -- -- Note that the warnings are displayed even if there is also an error. -- -- >>> :{ -- runUncertainIO $ do warn " first " warn " second " -- fail "fatal" return 42 -- :} warning : first warning : second -- error: fatal * * * Exception : ExitFailure 1 runUncertain :: Uncertain a -> IO a runUncertain = runUncertainIO . mapUncertainT (return . runIdentity) -- | Upgrade an `IO a -> IO a` wrapping function into a variant which uses -- `UncertainT IO` instead of `IO`. -- -- >>> :{ -- let wrap body = do { putStrLn "before" -- ; r <- body ; putStrLn " after " -- ; return r -- } -- :} -- -- >>> :{ -- wrap $ do { putStrLn "hello" ; return 42 -- } -- :} -- before -- hello -- after 42 -- -- >>> :{ runUncertainIO $ wrapUncertain wrap -- $ do { lift $ putStrLn "hello" -- ; warn "be careful!" ; return 42 -- } -- :} -- before -- hello -- after -- warning: be careful! 42 wrapUncertain :: (Monad m, Monad m') => (forall a. m a -> m' a) -> (UncertainT m b -> UncertainT m' b) wrapUncertain wrap body = wrapUncertainArg wrap' body' where wrap' f = wrap $ f () body' () = body -- | A version of `wrapUncertain` for wrapping functions of type -- `(Handle -> IO a) -> IO a`. -- -- >>> :{ -- let wrap body = do { putStrLn "before" ; r < - body 42 ; putStrLn " after " -- ; return r -- } -- :} -- -- >>> :{ wrap $ \x - > do { putStrLn " hello " -- ; return (x + 1) -- } -- :} -- before -- hello -- after 43 -- -- >>> :{ -- runUncertainIO $ wrapUncertainArg wrap $ \x - > do { lift $ putStrLn " hello " -- ; warn "be careful!" -- ; return (x + 1) -- } -- :} -- before -- hello -- after -- warning: be careful! 43 wrapUncertainArg :: (Monad m, Monad m') => (forall a. (v -> m a) -> m' a) -> ((v -> UncertainT m b) -> UncertainT m' b) wrapUncertainArg wrap body = do (r, ws) <- lift $ wrap $ runUncertainT . body -- repackage the warnings and errors mapM_ warn ws fromRightM r
null
https://raw.githubusercontent.com/gelisam/hawk/55f77ef0f76348865b08fddfc8da063803f88c12/src/Control/Monad/Trans/Uncertain.hs
haskell
| A computation which may raise warnings or fail in error. | Indent a multiline warning message. >>> :{ runUncertainIO $ do multilineWarn "foo\nbar\n" :} warning: foo bar | Indent a multiline error message. >>> :{ runUncertainIO $ do multilineFail "foo\nbar\n" :} error: foo bar with uncertain actions. >>> :{ runWarningsIO $ do warn "before" lift $ putStrLn "IO" warn "after" :} IO warning: before warning: after Right 42 >>> :{ runWarningsIO $ do warn "before" lift $ putStrLn "IO" fail "fatal" :} IO warning: before Left "fatal" >>> :{ runWarnings $ do warn "before" warn "after" :} warning: before warning: after Right 42 >>> :{ runWarnings $ do warn "before" fail "fatal" :} warning: before Left "fatal" with uncertain actions. >>> :{ runUncertainIO $ do warn "before" lift $ putStrLn "IO" warn "after" :} IO warning: before warning: after >>> :{ runUncertainIO $ do warn "before" lift $ putStrLn "IO" fail "fatal" :} IO warning: before error: fatal | Print warnings and errors, terminating on error. Note that the warnings are displayed even if there is also an error. >>> :{ runUncertainIO $ do fail "fatal" :} error: fatal | Upgrade an `IO a -> IO a` wrapping function into a variant which uses `UncertainT IO` instead of `IO`. >>> :{ let wrap body = do { putStrLn "before" ; r <- body ; return r } :} >>> :{ wrap $ do { putStrLn "hello" } :} before hello after >>> :{ $ do { lift $ putStrLn "hello" ; warn "be careful!" } :} before hello after warning: be careful! | A version of `wrapUncertain` for wrapping functions of type `(Handle -> IO a) -> IO a`. >>> :{ let wrap body = do { putStrLn "before" ; return r } :} >>> :{ ; return (x + 1) } :} before hello after >>> :{ runUncertainIO $ wrapUncertainArg wrap ; warn "be careful!" ; return (x + 1) } :} before hello after warning: be careful! repackage the warnings and errors
# LANGUAGE CPP , , RankNTypes # module Control.Monad.Trans.Uncertain where import Prelude hiding (fail) #if MIN_VERSION_base(4,12,0) import Control.Monad.Fail ( #if !MIN_VERSION_base(4,13,0) MonadFail, #endif fail) #else import Prelude (fail) #endif import "mtl" Control.Monad.Trans import "mtl" Control.Monad.Identity hiding (fail) import "transformers" Control.Monad.Trans.Except import "transformers" Control.Monad.Trans.Writer import System.Exit import System.IO import Text.Printf type Warning = String type Error = String newtype UncertainT m a = UncertainT { unUncertainT :: ExceptT Error (WriterT [Warning] m) a } type Uncertain a = UncertainT Identity a instance Functor m => Functor (UncertainT m) where fmap f = UncertainT . fmap f . unUncertainT instance (Functor m, Monad m) => Applicative (UncertainT m) where pure = UncertainT . pure UncertainT mf <*> UncertainT mx = UncertainT (mf <*> mx) instance Monad m => Monad (UncertainT m) where return = UncertainT . return UncertainT mx >>= f = UncertainT (mx >>= f') where f' = unUncertainT . f #if MIN_VERSION_base(4,12,0) instance Monad m => MonadFail (UncertainT m) where #endif fail s = UncertainT (throwE s) instance MonadTrans UncertainT where lift = UncertainT . lift . lift instance MonadIO m => MonadIO (UncertainT m) where liftIO = lift . liftIO warn :: Monad m => String -> UncertainT m () warn s = UncertainT $ lift $ tell [s] fromRightM :: Monad m => Either String a -> UncertainT m a fromRightM (Left e) = fail e fromRightM (Right x) = return x multilineMsg :: String -> String multilineMsg = concatMap (printf "\n %s") . lines return 42 42 multilineWarn :: Monad m => String -> UncertainT m () multilineWarn = warn . multilineMsg return 42 * * * Exception : ExitFailure 1 multilineFail :: Monad m => String -> UncertainT m a multilineFail = fail . multilineMsg mapUncertainT :: (forall a. m a -> m' a) -> UncertainT m b -> UncertainT m' b mapUncertainT f = UncertainT . (mapExceptT . mapWriterT) f . unUncertainT runUncertainT :: UncertainT m a -> m (Either Error a, [Warning]) runUncertainT = runWriterT . runExceptT . unUncertainT uncertainT :: Monad m => (Either Error a, [Warning]) -> UncertainT m a uncertainT (Left e, warnings) = mapM_ warn warnings >> fail e uncertainT (Right x, warnings) = mapM_ warn warnings >> return x | A version of ` runWarnings ` which allows you to interleave IO actions Note that the warnings are displayed after the IO 's output . return 42 return 42 runWarningsIO :: UncertainT IO a -> IO (Either String a) runWarningsIO u = do (r, warnings) <- runUncertainT u mapM_ (hPutStrLn stderr . printf "warning: %s") warnings return r | A version of ` runUncertain ` which only prints the warnings , not the errors . Unlike ` runUncertain ` , it does n't terminate on error . return 42 return 42 runWarnings :: Uncertain a -> IO (Either String a) runWarnings = runWarningsIO . mapUncertainT (return . runIdentity) | A version of ` runUncertain ` which allows you to interleave IO actions Note that the warnings are displayed after the IO 's output . return 42 42 return 42 * * * Exception : ExitFailure 1 runUncertainIO :: UncertainT IO a -> IO a runUncertainIO u = do r <- runWarningsIO u case r of Left e -> do hPutStrLn stderr $ printf "error: %s" e exitFailure Right x -> return x warn " first " warn " second " return 42 warning : first warning : second * * * Exception : ExitFailure 1 runUncertain :: Uncertain a -> IO a runUncertain = runUncertainIO . mapUncertainT (return . runIdentity) ; putStrLn " after " ; return 42 42 runUncertainIO $ wrapUncertain wrap ; return 42 42 wrapUncertain :: (Monad m, Monad m') => (forall a. m a -> m' a) -> (UncertainT m b -> UncertainT m' b) wrapUncertain wrap body = wrapUncertainArg wrap' body' where wrap' f = wrap $ f () body' () = body ; r < - body 42 ; putStrLn " after " wrap $ \x - > do { putStrLn " hello " 43 $ \x - > do { lift $ putStrLn " hello " 43 wrapUncertainArg :: (Monad m, Monad m') => (forall a. (v -> m a) -> m' a) -> ((v -> UncertainT m b) -> UncertainT m' b) wrapUncertainArg wrap body = do (r, ws) <- lift $ wrap $ runUncertainT . body mapM_ warn ws fromRightM r
627c74a840e580d3bb0a8f884c64c42f3c27ec4f7ff67d00bd2ee75932c1d0b6
HumbleUI/HumbleUI
hoverable.clj
(ns io.github.humbleui.ui.hoverable (:require [io.github.humbleui.core :as core] [io.github.humbleui.protocols :as protocols])) (core/deftype+ Hoverable [on-hover on-out ^:mut hovered?] :extends core/AWrapper protocols/IContext (-context [_ ctx] (cond-> ctx hovered? (assoc :hui/hovered? true))) protocols/IComponent (-draw [this ctx rect ^Canvas canvas] (set! child-rect rect) (when-some [ctx' (protocols/-context this ctx)] (core/draw-child child ctx' child-rect canvas))) (-event [this ctx event] (core/eager-or (when-some [ctx' (protocols/-context this ctx)] (core/event-child child ctx' event)) (core/when-every [{:keys [x y]} event] (let [hovered?' (core/rect-contains? child-rect (core/ipoint x y))] (when (not= hovered? hovered?') (set! hovered? hovered?') (if hovered?' (when on-hover (on-hover)) (when on-out (on-out))) true)))))) (defn hoverable "Enable the child element to respond to mouse hover events. If no callback, the event can still effect rendering through use of dynamic context as follows: (ui/dynamic ctx [hovered? (:hui/hovered? ctx)] # here we know the hover state of the object ...) You can also respond to hover events by providing optional :on-hover and/or :on-out callbacks in an options map as the first argument. The callback functions take no arguments and ignore their return value." ([child] (map->Hoverable {:child child :hovered? false})) ([{:keys [on-hover on-out]} child] (map->Hoverable {:on-hover on-hover :on-out on-out :child child :hovered? false})))
null
https://raw.githubusercontent.com/HumbleUI/HumbleUI/b0a596028dac8ebebf178a378e88d1c9f971e9dd/src/io/github/humbleui/ui/hoverable.clj
clojure
(ns io.github.humbleui.ui.hoverable (:require [io.github.humbleui.core :as core] [io.github.humbleui.protocols :as protocols])) (core/deftype+ Hoverable [on-hover on-out ^:mut hovered?] :extends core/AWrapper protocols/IContext (-context [_ ctx] (cond-> ctx hovered? (assoc :hui/hovered? true))) protocols/IComponent (-draw [this ctx rect ^Canvas canvas] (set! child-rect rect) (when-some [ctx' (protocols/-context this ctx)] (core/draw-child child ctx' child-rect canvas))) (-event [this ctx event] (core/eager-or (when-some [ctx' (protocols/-context this ctx)] (core/event-child child ctx' event)) (core/when-every [{:keys [x y]} event] (let [hovered?' (core/rect-contains? child-rect (core/ipoint x y))] (when (not= hovered? hovered?') (set! hovered? hovered?') (if hovered?' (when on-hover (on-hover)) (when on-out (on-out))) true)))))) (defn hoverable "Enable the child element to respond to mouse hover events. If no callback, the event can still effect rendering through use of dynamic context as follows: (ui/dynamic ctx [hovered? (:hui/hovered? ctx)] # here we know the hover state of the object ...) You can also respond to hover events by providing optional :on-hover and/or :on-out callbacks in an options map as the first argument. The callback functions take no arguments and ignore their return value." ([child] (map->Hoverable {:child child :hovered? false})) ([{:keys [on-hover on-out]} child] (map->Hoverable {:on-hover on-hover :on-out on-out :child child :hovered? false})))
c10f019c173f5bd08147154b65d1b5e0ba87f7453569c405a9266dd5a3d904f0
hyperfiddle/electric
hfql13b.clj
(ns dustin.hfql13b "hfql with scope applicative, not monad" (:refer-clojure :exclude [eval]) (:require [dustin.fiddle :refer :all] [dustin.hf-nav :refer :all] [dustin.monad-scope :refer [runScope pure bind fmap]] [meander.epsilon :as m :refer [match rewrite]] [minitest :refer [tests]])) (defn hf-edge->sym [edge] (if (keyword? edge) (symbol edge) edge)) (defn hf-apply [edge a scope] (cond (keyword? edge) (hf-nav edge a #_(get scope '%)) (seq? edge) (let [[f & args] edge] (clojure.core/apply (clojure.core/resolve f) (replace scope args))) () (println "hf-eval unmatched edge: " edge))) (defn hf-eval [edge a] ; name? (fn [scope] (let [b (hf-apply edge a scope)] [{(hf-edge->sym edge) b, '% b} b]))) (defn hf-pull' [pat ma] (match pat {& (m/seqable [?edge ?pat])} (as-> ma ma (bind ma (partial hf-eval ?edge)) (hf-pull' ?pat ma) ; recursive bind (fmap (fn [a] {?edge a}) ma)) ?leaf (as-> ma ma (bind ma (partial hf-eval ?leaf)) (fmap (fn [a] {?leaf a}) ma)) )) (defn hf-pull! [pat v scope] (let [[_ v] (runScope (hf-pull' pat (pure v)) scope)] v)) (defmacro hf-pull [pat v & [scope]] `(hf-pull! (quote ~pat) ~v #_(quote) ~(or scope {}))) (tests (do (def ma (pure :dustingetz/male)) nil) := nil (runScope ma {}) := [{} :dustingetz/male] (runScope (hf-pull' :db/ident ma) {}) := '[{db/ident :dustingetz/male, % :dustingetz/male} #:db{:ident :dustingetz/male}] ; why do we see the ident in scope here ; Tests use hf-pull! runner to test what matters, the result, as I de-bug the scope monad (macroexpand '(hf-pull (hf-nav :db/ident %) :dustingetz/male {% :dustingetz/male})) (hf-pull (hf-nav :db/ident %) :dustingetz/male {'% :dustingetz/male}) := {'(hf-nav :db/ident %) :dustingetz/male} (hf-pull (identity %) :dustingetz/male {'% :dustingetz/male}) := '{(identity %) :dustingetz/male} (hf-pull :dustingetz/gender 17592186045429) := '#:dustingetz{:gender :dustingetz/male} ( hf - pull ' (: / gender % ) { ' % 17592186045441 } ) : = { (: / gender % ) (: / gender 17592186045441 ) } ; ClassCastException (hf-pull {:dustingetz/gender :db/ident} 17592186045429) := '#:dustingetz{:gender #:db{:ident :dustingetz/male}} (hf-pull (gender) nil) := '{(gender) 17592186045418} (hf-pull (submission needle) nil {'needle "alic"}) := '{(submission needle) 17592186045428} (hf-pull {(submission needle) :dustingetz/gender} nil {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender :dustingetz/female}} (hf-pull {(submission needle) :dustingetz/gender} nil {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender :dustingetz/female}} (hf-pull {(submission needle) {:dustingetz/gender :db/ident}} nil {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender #:db{:ident :dustingetz/female}}} (hf-pull {(submission needle) {:dustingetz/gender (shirt-size dustingetz/gender)}} nil {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender {(shirt-size dustingetz/gender) 17592186045425}}} (hf-pull {(submission needle) ; query {:dustingetz/gender {(shirt-size dustingetz/gender) :db/ident}}} nil {'needle "alic"}) ; scope := '{(submission needle) ; result {:dustingetz/gender {(shirt-size dustingetz/gender) {:db/ident :dustingetz/womens-medium}}}} (hf-pull {:db/ident :db/id} 17592186045418) := #:db{:ident #:db{:id 17592186045418}} (hf-pull {:dustingetz/gender {:db/ident :db/id}} 17592186045421) := #:dustingetz{:gender #:db{:ident #:db{:id 17592186045418}}} (hf-pull {:dustingetz/gender {:db/ident {:db/ident :db/ident}}} 17592186045421) := #:dustingetz{:gender #:db{:ident #:db{:ident #:db{:ident :dustingetz/male}}}} (hf-pull {:dustingetz/gender :db/id} 17592186045421) := #:dustingetz{:gender #:db{:id 17592186045418}} (hf-pull {:dustingetz/gender {:db/id :db/id}} 17592186045421) := #:dustingetz{:gender #:db{:id #:db{:id 17592186045418}}} (hf-pull {:dustingetz/gender {:db/id {:db/id {:db/id :db/id}}}} 17592186045421) := #:dustingetz{:gender #:db{:id #:db{:id #:db{:id #:db{:id 17592186045418}}}}} )
null
https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2020/hfql/hfql13b.clj
clojure
name? recursive bind why do we see the ident in scope here Tests use hf-pull! runner to test what matters, the result, as I de-bug the scope monad ClassCastException query scope result
(ns dustin.hfql13b "hfql with scope applicative, not monad" (:refer-clojure :exclude [eval]) (:require [dustin.fiddle :refer :all] [dustin.hf-nav :refer :all] [dustin.monad-scope :refer [runScope pure bind fmap]] [meander.epsilon :as m :refer [match rewrite]] [minitest :refer [tests]])) (defn hf-edge->sym [edge] (if (keyword? edge) (symbol edge) edge)) (defn hf-apply [edge a scope] (cond (keyword? edge) (hf-nav edge a #_(get scope '%)) (seq? edge) (let [[f & args] edge] (clojure.core/apply (clojure.core/resolve f) (replace scope args))) () (println "hf-eval unmatched edge: " edge))) (fn [scope] (let [b (hf-apply edge a scope)] [{(hf-edge->sym edge) b, '% b} b]))) (defn hf-pull' [pat ma] (match pat {& (m/seqable [?edge ?pat])} (as-> ma ma (bind ma (partial hf-eval ?edge)) (fmap (fn [a] {?edge a}) ma)) ?leaf (as-> ma ma (bind ma (partial hf-eval ?leaf)) (fmap (fn [a] {?leaf a}) ma)) )) (defn hf-pull! [pat v scope] (let [[_ v] (runScope (hf-pull' pat (pure v)) scope)] v)) (defmacro hf-pull [pat v & [scope]] `(hf-pull! (quote ~pat) ~v #_(quote) ~(or scope {}))) (tests (do (def ma (pure :dustingetz/male)) nil) := nil (runScope ma {}) := [{} :dustingetz/male] (runScope (hf-pull' :db/ident ma) {}) := '[{db/ident :dustingetz/male, % :dustingetz/male} #:db{:ident :dustingetz/male}] (macroexpand '(hf-pull (hf-nav :db/ident %) :dustingetz/male {% :dustingetz/male})) (hf-pull (hf-nav :db/ident %) :dustingetz/male {'% :dustingetz/male}) := {'(hf-nav :db/ident %) :dustingetz/male} (hf-pull (identity %) :dustingetz/male {'% :dustingetz/male}) := '{(identity %) :dustingetz/male} (hf-pull :dustingetz/gender 17592186045429) := '#:dustingetz{:gender :dustingetz/male} ( hf - pull ' (: / gender % ) { ' % 17592186045441 } ) (hf-pull {:dustingetz/gender :db/ident} 17592186045429) := '#:dustingetz{:gender #:db{:ident :dustingetz/male}} (hf-pull (gender) nil) := '{(gender) 17592186045418} (hf-pull (submission needle) nil {'needle "alic"}) := '{(submission needle) 17592186045428} (hf-pull {(submission needle) :dustingetz/gender} nil {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender :dustingetz/female}} (hf-pull {(submission needle) :dustingetz/gender} nil {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender :dustingetz/female}} (hf-pull {(submission needle) {:dustingetz/gender :db/ident}} nil {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender #:db{:ident :dustingetz/female}}} (hf-pull {(submission needle) {:dustingetz/gender (shirt-size dustingetz/gender)}} nil {'needle "alic"}) := '{(submission needle) #:dustingetz{:gender {(shirt-size dustingetz/gender) 17592186045425}}} (hf-pull {:dustingetz/gender {(shirt-size dustingetz/gender) :db/ident}}} nil {:dustingetz/gender {(shirt-size dustingetz/gender) {:db/ident :dustingetz/womens-medium}}}} (hf-pull {:db/ident :db/id} 17592186045418) := #:db{:ident #:db{:id 17592186045418}} (hf-pull {:dustingetz/gender {:db/ident :db/id}} 17592186045421) := #:dustingetz{:gender #:db{:ident #:db{:id 17592186045418}}} (hf-pull {:dustingetz/gender {:db/ident {:db/ident :db/ident}}} 17592186045421) := #:dustingetz{:gender #:db{:ident #:db{:ident #:db{:ident :dustingetz/male}}}} (hf-pull {:dustingetz/gender :db/id} 17592186045421) := #:dustingetz{:gender #:db{:id 17592186045418}} (hf-pull {:dustingetz/gender {:db/id :db/id}} 17592186045421) := #:dustingetz{:gender #:db{:id #:db{:id 17592186045418}}} (hf-pull {:dustingetz/gender {:db/id {:db/id {:db/id :db/id}}}} 17592186045421) := #:dustingetz{:gender #:db{:id #:db{:id #:db{:id #:db{:id 17592186045418}}}}} )
44f0d268e41e63b45399aa709868787c94fdb4bdfd63847adeb28895e9149cee
efcasado/behaviours2
dummy_gen_server.erl
-module(dummy_gen_server). -compile({parse_transform, bhv2_pt}). -behaviour(gen_server). -export([init/1, handle_info/2]). Only init/1 and handle_info/2 are provided by the user . init([Owner]) -> {ok, Owner}. handle_info(Info, Owner) -> Owner ! lists:reverse(Info), {noreply, Owner}.
null
https://raw.githubusercontent.com/efcasado/behaviours2/95190c212d0c28a89a62b451005e211c71176c7f/tests/dummy_gen_server.erl
erlang
-module(dummy_gen_server). -compile({parse_transform, bhv2_pt}). -behaviour(gen_server). -export([init/1, handle_info/2]). Only init/1 and handle_info/2 are provided by the user . init([Owner]) -> {ok, Owner}. handle_info(Info, Owner) -> Owner ! lists:reverse(Info), {noreply, Owner}.