_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 |
|---|---|---|---|---|---|---|---|---|
6e4e5ce6e479ed732514d8b90b287198f8157afb46ae576dc55448f3e0573068 | geophf/1HaskellADay | Exercise.hs | module Y2018.M02.D02.Exercise where
-
We have been able to download sets of articles and then we 've triaged them ,
but before we do triage , we have to do a bifurcation from before : we do n't
want Associated Press articles showing up in our NEW / UPDATED / REDUNDANT
stacks .
Today 's problem is to remove the AP articles from the downloaded
packets .
Hint : you may have seen this before in a different context .
-
We have been able to download sets of articles and then we've triaged them,
but before we do triage, we have to do a bifurcation from before: we don't
want Associated Press articles showing up in our NEW / UPDATED / REDUNDANT
stacks.
Today's Haskell problem is to remove the AP articles from the downloaded
packets.
Hint: you may have seen this before in a different context.
--}
import Data.Map (Map)
import Database.PostgreSQL.Simple
below imports available via 1HaskellADay git repository
import Data.Logger (Logger)
import Y2017.M12.D27.Exercise (DatedArticle)
import Y2018.M01.D26.Exercise -- for downloading from the endpoint
import Y2018.M01.D29.Exercise -- for determining how far back to go
import Y2018.M01.D30.Exercise -- for triaging from the triage
deAPify :: DatedArticle a -> Maybe (DatedArticle a)
deAPify art = undefined
given a parsed article , remove it ( return Nothing ) if it 's an AP article
-- How many articles did you download?
How many articles were left after you delinted the AP articles ?
- BONUS -----------------------------------------------------------------
Recreate the triage report app that downloads the articles and triages them ,
but this time , first removes the AP articles
-
Recreate the triage report app that downloads the articles and triages them,
but this time, first removes the AP articles
--}
triageSansAP :: Connection
-> Logger IO ([ArticleMetaData], Map Triage [ArticleTriageInformation])
triageSansAP conn = undefined
main' :: [String] -> IO ()
main' args = undefined
| null | https://raw.githubusercontent.com/geophf/1HaskellADay/514792071226cd1e2ba7640af942667b85601006/exercises/HAD/Y2018/M02/D02/Exercise.hs | haskell | }
for downloading from the endpoint
for determining how far back to go
for triaging from the triage
How many articles did you download?
---------------------------------------------------------------
} | module Y2018.M02.D02.Exercise where
-
We have been able to download sets of articles and then we 've triaged them ,
but before we do triage , we have to do a bifurcation from before : we do n't
want Associated Press articles showing up in our NEW / UPDATED / REDUNDANT
stacks .
Today 's problem is to remove the AP articles from the downloaded
packets .
Hint : you may have seen this before in a different context .
-
We have been able to download sets of articles and then we've triaged them,
but before we do triage, we have to do a bifurcation from before: we don't
want Associated Press articles showing up in our NEW / UPDATED / REDUNDANT
stacks.
Today's Haskell problem is to remove the AP articles from the downloaded
packets.
Hint: you may have seen this before in a different context.
import Data.Map (Map)
import Database.PostgreSQL.Simple
below imports available via 1HaskellADay git repository
import Data.Logger (Logger)
import Y2017.M12.D27.Exercise (DatedArticle)
deAPify :: DatedArticle a -> Maybe (DatedArticle a)
deAPify art = undefined
given a parsed article , remove it ( return Nothing ) if it 's an AP article
How many articles were left after you delinted the AP articles ?
Recreate the triage report app that downloads the articles and triages them ,
but this time , first removes the AP articles
-
Recreate the triage report app that downloads the articles and triages them,
but this time, first removes the AP articles
triageSansAP :: Connection
-> Logger IO ([ArticleMetaData], Map Triage [ArticleTriageInformation])
triageSansAP conn = undefined
main' :: [String] -> IO ()
main' args = undefined
|
7020b2bddc5d876f2eac51bc8d1075114332b2cc2e0b6af2e0305b77b35a66cc | acieroid/scala-am | f-7.scm | (letrec ((f (lambda (x) (+ (* x x) (* x x)))) (g (lambda (x) (+ (* x x) (* x x))))) (let ((_tmp1 (f 1))) (let ((_tmp2 (f 2))) (let ((_tmp3 (f 3))) (let ((_tmp4 (f 4))) (let ((_tmp5 (f 5))) (let ((_tmp6 (f 6))) (let ((_tmp7 (g 7))) (let ((_tmp8 (f 8))) (let ((_tmp9 (f 9))) (f 10))))))))))) | null | https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/changesBenevolPaper/f1-tests/f-7.scm | scheme | (letrec ((f (lambda (x) (+ (* x x) (* x x)))) (g (lambda (x) (+ (* x x) (* x x))))) (let ((_tmp1 (f 1))) (let ((_tmp2 (f 2))) (let ((_tmp3 (f 3))) (let ((_tmp4 (f 4))) (let ((_tmp5 (f 5))) (let ((_tmp6 (f 6))) (let ((_tmp7 (g 7))) (let ((_tmp8 (f 8))) (let ((_tmp9 (f 9))) (f 10))))))))))) | |
7fd448ffbdcae9c866b7f609720644c0196457d2d772992e4fb1be38434a9bc8 | samrushing/irken-compiler | t32.scm | ;; -*- Mode: Irken -*-
(include "lib/core.scm")
(define (get-closure)
(%%cexp (-> (irken-closure (string -> int))) "getc"))
(define (thing s)
(let ((closure (get-closure)))
(%%cexp ((irken-closure (string -> int)) int string -> int) "irk" closure 1 s)
))
(print (thing "--- testing ---\n"))
(print (thing "... and testing again!\n"))
| null | https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/vm/tests/t32.scm | scheme | -*- Mode: Irken -*- |
(include "lib/core.scm")
(define (get-closure)
(%%cexp (-> (irken-closure (string -> int))) "getc"))
(define (thing s)
(let ((closure (get-closure)))
(%%cexp ((irken-closure (string -> int)) int string -> int) "irk" closure 1 s)
))
(print (thing "--- testing ---\n"))
(print (thing "... and testing again!\n"))
|
e09b8d010059502b2a74d787db4289be584c7367727011a5e47e6d5374a344c8 | pixlsus/registry.gimp.org_static | lightsaber-effect.130.scm | ; The GIMP -- an image manipulation program
Copyright ( C ) 1995 and
;
; 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. , 675 Mass Ave , Cambridge , , USA .
;
Lightsaber Effect - Creates a lightsaber effect .
; Method taken from /
by < >
;
Updates for streamlining by
;
; Version 1.3.0
;
; This script will, given a layer with a white line on it,
; take the line and apply a "lightsaber" effect to it.
;
; Arguments that must be past are as follows:
; inImage - Gimp image identifier resource.
; inLayer - Gimp layer identifier resource.
of the line which will be converted to a lightsaber .
; inColor - Final color the lightsaber will be.
; inMode - Alpha mode switch.
; "FALSE" for defualt mode (screen), "TRUE" for alpha mode.
; (Alpha mode isn't the normally described method,
; but appears better on lighter backgrounds)
;
(define (script-fu-lightsaber-effect-130 inImage inLayer inWidth inColor inMode)
; This let* encloses the entire script!
(let*
(
(image inImage) ;Image identifier
(blade inLayer) ;Layer identifier
(tightAura inLayer)
(looseAura inLayer)
(width inWidth) ;Blade width
(color inColor) ;Blade color
(mode inMode) ;Alpha mode switch
(imageWidth (car(gimp-image-width image))) ;Width of the image
(imageHeight (car(gimp-image-height image))) ;Height of the image
;This should be changed to gimp-drawable-width eventually (I think)
;drawable should only do what it needs to do - image does the entire thing (Again - I think)
;Regardless, hold off for now - requires finding/passing entirely new arg
(white (list 255 255 255)) ;Lets define white here...
(black (list 0 0 0)) ;...and black as well
(foreground (car(gimp-context-get-foreground))) ;Foreground color - to restore later
(background (car(gimp-context-get-background))) ;Background color - to restore later
)
;start group undo
(gimp-image-undo-group-start image)
;Set FG&BG colors
(gimp-context-set-foreground white)
(gimp-context-set-background black)
create B&W blade from selection in new layer
(set! blade (car(gimp-layer-new image imageWidth imageHeight RGB-IMAGE "blade" 100 NORMAL-MODE)))
(gimp-image-add-layer image blade 0)
(gimp-image-set-active-layer image blade)
(gimp-edit-bucket-fill blade FG-BUCKET-FILL NORMAL 100 100 0 0 0)
; select nothing so it operates on everything
(gimp-selection-none image)
(gimp-drawable-set-name blade "blade")
01 blade : Blur = WIDTH
(blur image blade width)
02 blade : level : value : input : lower : 30 , upper : 50
(level-input blade 30 50)
;03 blade: duplicate layer - new name "loose aura"
(set! looseAura (car (gimp-layer-copy blade FALSE)))
(gimp-image-add-layer image looseAura -1)
(gimp-drawable-set-name looseAura "looseAura")
04 loose aura : blur = WIDTH * 2
(blur image looseAura (* width 2))
05 loose aura : level : value : input : upper : 10
(level-input looseAura 0 10)
06 loose aura : blur = WIDTH * 2
(blur image looseAura (* width 2))
;07 loose aura: level: rgb: output: SABER-COLOR
(level-colorize looseAura color)
08 loose aura : level : value : output : 127
(level-output looseAura 0 128)
09 blade : duplicate layer - new name " tight aura "
(set! tightAura (car (gimp-layer-copy blade FALSE)))
(gimp-image-add-layer image tightAura -1)
(gimp-drawable-set-name tightAura "tightAura")
10 tight aura : blur = WIDTH / 2
(blur image tightAura (/ width 2))
11 tight aura : level : value : input : upper : 10
(level-input tightAura 0 10)
12 tight aura : blur = WIDTH
(blur image tightAura width)
13 tight aura : level : rgb : output : SABER - COLOR
(level-colorize tightAura color)
14 layer - order : blade , tight aura , loose aura
(gimp-image-raise-layer-to-top image looseAura)
(gimp-image-raise-layer-to-top image tightAura)
(gimp-image-raise-layer-to-top image blade)
15 blade : blur = WIDTH / ( 3/8 )
(blur image blade (* 3 (/ width 8)))
; Done rendering, time to merge
(gimp-layer-set-mode blade 4)
; ensure we are visible so merge works fine
(gimp-drawable-set-visible blade 1)
(gimp-drawable-set-visible tightAura 1)
(gimp-drawable-set-visible looseAura 1)
(set! blade (car (gimp-image-merge-down image blade 0)))
(gimp-layer-set-mode blade 4)
(set! blade (car (gimp-image-merge-down image blade 0)))
If Alpha mode is set , then alpha BG instead of screening
(if (= mode TRUE)
(begin
(plug-in-colortoalpha TRUE image blade '(0 0 0))
(gimp-layer-set-mode blade 0)
)
(gimp-layer-set-mode blade 4)
)
(gimp-drawable-set-name blade "LightSaber")
Reset FG / BG colors
(gimp-context-set-foreground foreground)
(gimp-context-set-background background)
End Undo Group
(gimp-image-undo-group-end image)
;Flush Display
(gimp-displays-flush)
)
)
(define (blur image layer width)
(plug-in-gauss TRUE image layer width width 1)
)
(define (level-input layer min max)
(gimp-levels layer 0 min max 1.0 0 255)
)
(define (level-output layer min max)
(gimp-levels layer 0 0 255 1.0 min max)
)
(define (level-colorize layer RGB)
;red
(gimp-levels layer 1 0 255 1.0 0 (car RGB))
;green
(gimp-levels layer 2 0 255 1.0 0 (cadr RGB))
;blue
(gimp-levels layer 3 0 255 1.0 0 (caddr RGB))
)
(script-fu-register
"script-fu-lightsaber-effect-130" ;func name
"<Image>/Script-Fu/Blur/Lightsaber 1.3.0" ;menu pos
"Creates a Lightsaber effect.\
To successfully create the effect,\
simply make a selection around where\
you want the lightsaber!\
(Method taken from\
)" ;description
"Eric Kincl" ;author
"Released under the GNU GPL" ;copyright notice
"September 7, 2009" ;date created
"RGB*" ;image type that the script works on
SF-IMAGE "Gimp Image Resource" 0 ;Image reference identifier
SF-DRAWABLE "Gimp Layer Resource" 0 ;Layer reference identifier
SF-VALUE "Saber width" "10" ;a text variable
SF-COLOR "Saber color" '(0 255 0) ;color variable
SF-TOGGLE "Alpha mode" FALSE ;boolean variable
)
| null | https://raw.githubusercontent.com/pixlsus/registry.gimp.org_static/ffcde7400f402728373ff6579947c6ffe87d1a5e/registry.gimp.org/files/lightsaber-effect.130.scm | scheme | The GIMP -- an image manipulation program
This program is free software; you can redistribute it and/or modify
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.
along with this program; if not, write to the Free Software
Method taken from /
Version 1.3.0
This script will, given a layer with a white line on it,
take the line and apply a "lightsaber" effect to it.
Arguments that must be past are as follows:
inImage - Gimp image identifier resource.
inLayer - Gimp layer identifier resource.
inColor - Final color the lightsaber will be.
inMode - Alpha mode switch.
"FALSE" for defualt mode (screen), "TRUE" for alpha mode.
(Alpha mode isn't the normally described method,
but appears better on lighter backgrounds)
This let* encloses the entire script!
Image identifier
Layer identifier
Blade width
Blade color
Alpha mode switch
Width of the image
Height of the image
This should be changed to gimp-drawable-width eventually (I think)
drawable should only do what it needs to do - image does the entire thing (Again - I think)
Regardless, hold off for now - requires finding/passing entirely new arg
Lets define white here...
...and black as well
Foreground color - to restore later
Background color - to restore later
start group undo
Set FG&BG colors
select nothing so it operates on everything
03 blade: duplicate layer - new name "loose aura"
07 loose aura: level: rgb: output: SABER-COLOR
Done rendering, time to merge
ensure we are visible so merge works fine
Flush Display
red
green
blue
func name
menu pos
description
author
copyright notice
date created
image type that the script works on
Image reference identifier
Layer reference identifier
a text variable
color variable
boolean variable | Copyright ( C ) 1995 and
it under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
Foundation , Inc. , 675 Mass Ave , Cambridge , , USA .
Lightsaber Effect - Creates a lightsaber effect .
by < >
Updates for streamlining by
of the line which will be converted to a lightsaber .
(define (script-fu-lightsaber-effect-130 inImage inLayer inWidth inColor inMode)
(let*
(
(tightAura inLayer)
(looseAura inLayer)
)
(gimp-image-undo-group-start image)
(gimp-context-set-foreground white)
(gimp-context-set-background black)
create B&W blade from selection in new layer
(set! blade (car(gimp-layer-new image imageWidth imageHeight RGB-IMAGE "blade" 100 NORMAL-MODE)))
(gimp-image-add-layer image blade 0)
(gimp-image-set-active-layer image blade)
(gimp-edit-bucket-fill blade FG-BUCKET-FILL NORMAL 100 100 0 0 0)
(gimp-selection-none image)
(gimp-drawable-set-name blade "blade")
01 blade : Blur = WIDTH
(blur image blade width)
02 blade : level : value : input : lower : 30 , upper : 50
(level-input blade 30 50)
(set! looseAura (car (gimp-layer-copy blade FALSE)))
(gimp-image-add-layer image looseAura -1)
(gimp-drawable-set-name looseAura "looseAura")
04 loose aura : blur = WIDTH * 2
(blur image looseAura (* width 2))
05 loose aura : level : value : input : upper : 10
(level-input looseAura 0 10)
06 loose aura : blur = WIDTH * 2
(blur image looseAura (* width 2))
(level-colorize looseAura color)
08 loose aura : level : value : output : 127
(level-output looseAura 0 128)
09 blade : duplicate layer - new name " tight aura "
(set! tightAura (car (gimp-layer-copy blade FALSE)))
(gimp-image-add-layer image tightAura -1)
(gimp-drawable-set-name tightAura "tightAura")
10 tight aura : blur = WIDTH / 2
(blur image tightAura (/ width 2))
11 tight aura : level : value : input : upper : 10
(level-input tightAura 0 10)
12 tight aura : blur = WIDTH
(blur image tightAura width)
13 tight aura : level : rgb : output : SABER - COLOR
(level-colorize tightAura color)
14 layer - order : blade , tight aura , loose aura
(gimp-image-raise-layer-to-top image looseAura)
(gimp-image-raise-layer-to-top image tightAura)
(gimp-image-raise-layer-to-top image blade)
15 blade : blur = WIDTH / ( 3/8 )
(blur image blade (* 3 (/ width 8)))
(gimp-layer-set-mode blade 4)
(gimp-drawable-set-visible blade 1)
(gimp-drawable-set-visible tightAura 1)
(gimp-drawable-set-visible looseAura 1)
(set! blade (car (gimp-image-merge-down image blade 0)))
(gimp-layer-set-mode blade 4)
(set! blade (car (gimp-image-merge-down image blade 0)))
If Alpha mode is set , then alpha BG instead of screening
(if (= mode TRUE)
(begin
(plug-in-colortoalpha TRUE image blade '(0 0 0))
(gimp-layer-set-mode blade 0)
)
(gimp-layer-set-mode blade 4)
)
(gimp-drawable-set-name blade "LightSaber")
Reset FG / BG colors
(gimp-context-set-foreground foreground)
(gimp-context-set-background background)
End Undo Group
(gimp-image-undo-group-end image)
(gimp-displays-flush)
)
)
(define (blur image layer width)
(plug-in-gauss TRUE image layer width width 1)
)
(define (level-input layer min max)
(gimp-levels layer 0 min max 1.0 0 255)
)
(define (level-output layer min max)
(gimp-levels layer 0 0 255 1.0 min max)
)
(define (level-colorize layer RGB)
(gimp-levels layer 1 0 255 1.0 0 (car RGB))
(gimp-levels layer 2 0 255 1.0 0 (cadr RGB))
(gimp-levels layer 3 0 255 1.0 0 (caddr RGB))
)
(script-fu-register
"Creates a Lightsaber effect.\
To successfully create the effect,\
simply make a selection around where\
you want the lightsaber!\
(Method taken from\
)
|
935520da9aafba9d00f338c296cd58832b034385b3e01e793e334e14b911a3bc | NorfairKing/the-notes | Macro.hs | module Computability.Symbols.Macro where
import Types
import Macro.Math
import Macro.MetaMacro
-- * Symbols
-- ** Symbol equality
-- | Symbol equality sign
symEqSign :: Note
symEqSign = underset "s" "="
-- | Symbol equality operation
symEq :: Note -> Note -> Note
symEq = binop symEqSign
-- | Infix symbol equality operator
(=@=) :: Note -> Note -> Note
(=@=) = symEq
-- * Alphabets
-- | Concrete alphabet
alph_ :: Note
alph_ = comm0 "Sigma"
-- | Concrete alphabet and string
alphe_ :: Note
alphe_ = alph_ !: estr
-- * Strings
-- | Empty string
estr :: Note
estr = epsilon
-- | Concrete string
str_ :: Note
str_ = "s"
-- | Strings of alphabet
strsof :: Note -> Note
strsof alphabet = alphabet ^: "*"
-- | Strings of concrete alphabet
strsof_ :: Note
strsof_ = strsof alph_
-- ** Lists of symbols
strlst :: Note -> Note -> Note
strlst s1 sn = s1 <> dotsc <> sn
strlist :: Note -> Note -> Note -> Note
strlist s1 s2 sn = s1 <> s2 <> dotsc <> sn
strof :: [Note] -> Note
strof = mconcat
-- ** Concatenation
-- | String concatenation
strconcat :: [Note] -> Note
strconcat = mconcat
-- | String concatenation infix operator
(<@>) :: Note -> Note -> Note
(<@>) = (<>)
-- ** Reverse String
-- | Reverse of a given string
rstr :: Note -> Note
rstr s = s ^: "R"
| null | https://raw.githubusercontent.com/NorfairKing/the-notes/ff9551b05ec3432d21dd56d43536251bf337be04/src/Computability/Symbols/Macro.hs | haskell | * Symbols
** Symbol equality
| Symbol equality sign
| Symbol equality operation
| Infix symbol equality operator
* Alphabets
| Concrete alphabet
| Concrete alphabet and string
* Strings
| Empty string
| Concrete string
| Strings of alphabet
| Strings of concrete alphabet
** Lists of symbols
** Concatenation
| String concatenation
| String concatenation infix operator
** Reverse String
| Reverse of a given string | module Computability.Symbols.Macro where
import Types
import Macro.Math
import Macro.MetaMacro
symEqSign :: Note
symEqSign = underset "s" "="
symEq :: Note -> Note -> Note
symEq = binop symEqSign
(=@=) :: Note -> Note -> Note
(=@=) = symEq
alph_ :: Note
alph_ = comm0 "Sigma"
alphe_ :: Note
alphe_ = alph_ !: estr
estr :: Note
estr = epsilon
str_ :: Note
str_ = "s"
strsof :: Note -> Note
strsof alphabet = alphabet ^: "*"
strsof_ :: Note
strsof_ = strsof alph_
strlst :: Note -> Note -> Note
strlst s1 sn = s1 <> dotsc <> sn
strlist :: Note -> Note -> Note -> Note
strlist s1 s2 sn = s1 <> s2 <> dotsc <> sn
strof :: [Note] -> Note
strof = mconcat
strconcat :: [Note] -> Note
strconcat = mconcat
(<@>) :: Note -> Note -> Note
(<@>) = (<>)
rstr :: Note -> Note
rstr s = s ^: "R"
|
9cebc39e5e61955841f1672c9aa6ba77ad494dc7846ff4c79dcd3bc7191fa7a2 | clj-easy/graalvm-clojure | main.clj | (ns simple.main
(:require [datascript.core :as d])
(:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(let [schema {:aka {:db/cardinality :db.cardinality/many}}
conn (d/create-conn schema)]
(d/transact! conn [ { :db/id -1
:name "Maksim"
:age 45
:aka ["Max Otto von Stierlitz", "Jack Ryan"] } ])
(println
(d/q '[ :find ?n ?a
:where [?e :aka "Max Otto von Stierlitz"]
[?e :name ?n]
[?e :age ?a] ]
@conn))
;; Destructuring, function call, predicate call, query over collection
(println
(d/q '[ :find ?k ?x
:in [[?k [?min ?max]] ...] ?range
:where [(?range ?min ?max) [?x ...]]
[(even? ?x)] ]
{ :a [1 7], :b [2 4] }
range))
;; Recursive rule
(println
(d/q '[ :find ?u1 ?u2
:in $ %
:where (follows ?u1 ?u2) ]
[ [1 :follows 2]
[2 :follows 3]
[3 :follows 4] ]
'[ [(follows ?e1 ?e2)
[?e1 :follows ?e2]]
[(follows ?e1 ?e2)
[?e1 :follows ?t]
(follows ?t ?e2)] ]))
;; Aggregates
(println
(d/q '[ :find ?color (max ?amount ?x) (min ?amount ?x)
:in [[?color ?x]] ?amount ]
[[:red 10] [:red 20] [:red 30] [:red 40] [:red 50]
[:blue 7] [:blue 8]]
3)))
(println "Hello GraalVM."))
| null | https://raw.githubusercontent.com/clj-easy/graalvm-clojure/5de155ad4f95d5dac97aac1ab3d118400e7d186f/datascript/src/simple/main.clj | clojure | Destructuring, function call, predicate call, query over collection
Recursive rule
Aggregates | (ns simple.main
(:require [datascript.core :as d])
(:gen-class))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(let [schema {:aka {:db/cardinality :db.cardinality/many}}
conn (d/create-conn schema)]
(d/transact! conn [ { :db/id -1
:name "Maksim"
:age 45
:aka ["Max Otto von Stierlitz", "Jack Ryan"] } ])
(println
(d/q '[ :find ?n ?a
:where [?e :aka "Max Otto von Stierlitz"]
[?e :name ?n]
[?e :age ?a] ]
@conn))
(println
(d/q '[ :find ?k ?x
:in [[?k [?min ?max]] ...] ?range
:where [(?range ?min ?max) [?x ...]]
[(even? ?x)] ]
{ :a [1 7], :b [2 4] }
range))
(println
(d/q '[ :find ?u1 ?u2
:in $ %
:where (follows ?u1 ?u2) ]
[ [1 :follows 2]
[2 :follows 3]
[3 :follows 4] ]
'[ [(follows ?e1 ?e2)
[?e1 :follows ?e2]]
[(follows ?e1 ?e2)
[?e1 :follows ?t]
(follows ?t ?e2)] ]))
(println
(d/q '[ :find ?color (max ?amount ?x) (min ?amount ?x)
:in [[?color ?x]] ?amount ]
[[:red 10] [:red 20] [:red 30] [:red 40] [:red 50]
[:blue 7] [:blue 8]]
3)))
(println "Hello GraalVM."))
|
b57980987d136a82ed626e83fa302dc878492a5fbf1534e228ae9f768bfa3eff | kadena-io/chainweb-node | DbCache.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
-- |
Module : Chainweb . Pact . Backend . DbCache
Copyright : Copyright © 2022 Kadena LLC .
-- License: See LICENSE file
--
LRU cache for avoiding expensive JSON deserialization .
--
module Chainweb.Pact.Backend.DbCache
( DbCacheLimitBytes(..)
, DbCache
, checkDbCache
, emptyDbCache
, cacheSize
, cacheCount
, isEmptyCache
, cacheStats
, updateCacheStats
) where
import Control.Lens hiding ((.=))
import Control.Monad.State.Strict
import qualified Crypto.Hash as C (hash)
import Crypto.Hash.Algorithms
import Data.Aeson (FromJSON, ToJSON, Value, object, decodeStrict, (.=))
import qualified Data.ByteArray as BA
import Data.ByteString (ByteString)
import qualified Data.ByteString.Short as BS
import Data.Hashable
import qualified Data.HashMap.Strict as HM
import Data.List (sort)
import Data.Ord
import Database.SQLite3.Direct
import GHC.Compact
import GHC.Stack
import Numeric.Natural
import Pact.Types.Persistence
-- -------------------------------------------------------------------------- --
-- ModuleCacheLimitBytes
newtype DbCacheLimitBytes = DbCacheLimitBytes Natural
deriving (Show, Read, Eq, Ord, ToJSON, FromJSON)
-- -------------------------------------------------------------------------- --
CacheAddress
newtype CacheAddress = CacheAddress BS.ShortByteString
deriving (Show,Eq,Ord,Hashable)
-- -------------------------------------------------------------------------- --
-- CacheEntry
data CacheEntry a = CacheEntry
{ _ceTxId :: !TxId
-- ^ Priority for cache eviction
, _ceAddy :: !CacheAddress
-- ^ Key. Uniquely identifies entries in the cache
, _ceSize :: !Int
-- ^ The size of the entry. Used to keep track of the cache limit
, _ceData :: !a
-- ^ Cached data. This is stored in a compact region.
, _ceHits :: Int
-- ^ Count of cache hits for this entry
}
ceTxId :: Lens' (CacheEntry a) TxId
ceTxId = lens _ceTxId (\a b -> a { _ceTxId = b })
ceHits :: Lens' (CacheEntry a) Int
ceHits = lens _ceHits (\a b -> a { _ceHits = b })
instance Eq (CacheEntry a) where
a == b = _ceAddy a == _ceAddy b && _ceTxId a == _ceTxId b
| Sort by ' _ ceTxId ' so that smaller tx ids are evicted first from the
-- cache. '_ceAddy' is just for stable sort.
--
instance Ord (CacheEntry a) where
a `compare` b = comparing _ceTxId a b <> comparing _ceAddy a b
| Cache entries are stored within a compact regions . The whole region is GCed
-- only when no pointer to any data in the region is live any more.
--
compactCacheEntry :: MonadIO m => FromJSON a => ByteString -> m (Maybe (a, Int))
compactCacheEntry rowdata = do
c <- liftIO $ compact (decodeStrict {- lazy, forced by compact -} rowdata)
case getCompact c of
Nothing -> return Nothing
Just m -> do
s <- liftIO $ compactSize c
return $ Just (m, fromIntegral s)
-- -------------------------------------------------------------------------- --
DbCache
data DbCache a = DbCache
{ _dcStore :: !(HM.HashMap CacheAddress (CacheEntry a))
, _dcSize :: !Int
, _dcLimit :: !Int
-- Telemetry
, _dcMisses :: !Int
, _dcHits :: !Int
}
makeLenses 'DbCache
emptyDbCache :: HasCallStack => DbCacheLimitBytes -> DbCache a
emptyDbCache (DbCacheLimitBytes limit)
| fromIntegral limit > maxBound @Int = error "cache limit is too large"
emptyDbCache (DbCacheLimitBytes limit) = DbCache
{ _dcStore = mempty
, _dcSize = 0
, _dcLimit = fromIntegral limit
, _dcMisses = 0
, _dcHits = 0
}
isEmptyCache :: DbCache a -> Bool
isEmptyCache = HM.null . _dcStore
-- | The total size of all data in the cache.
--
-- Complexity: \(O(1)\)
--
cacheSize :: DbCache a -> Int
cacheSize = _dcSize
-- | Number of entries in the cache.
--
Complexity : \(O(n)\ ) , linear in the number of entries
--
cacheCount :: DbCache a -> Int
cacheCount = HM.size . _dcStore
-- | Provide read-time caching of deserialized JSON values.
-- If cache entry is found, mark it with the current txid and return value.
-- If not, deserialize row data and store in cache, which triggers
-- cache maintenance.
--
checkDbCache
:: FromJSON a
=> Utf8
-- ^ Db key for data
-> ByteString
-- ^ row data that contains the encoded value
-> TxId
^ Current TxId from , used as priority for cache eviction .
Smaller values are evicted first .
-> DbCache a
-> IO (Maybe a, DbCache a)
checkDbCache key rowdata txid = runStateT $ do
readCache txid addy >>= \case
Cache hit
Just x -> do
modify' (dcHits +~ 1)
return $ Just x
-- Cache miss: decode module and insert into cache
Nothing -> compactCacheEntry rowdata >>= \case
Nothing -> return Nothing
Just (m, s) -> do
writeCache txid addy s m
modify' (dcMisses +~ 1)
return $ Just m
where
addy = mkAddress key rowdata
cacheStats :: DbCache a -> Value
cacheStats mc = object
[ "misses" .= _dcMisses mc
, "hits" .= _dcHits mc
, "size" .= cacheSize mc
, "count" .= cacheCount mc
]
updateCacheStats :: DbCache a -> (Value, DbCache a)
updateCacheStats mc = (cacheStats mc, set dcMisses 0 (set dcHits 0 mc))
-- -------------------------------------------------------------------------- --
Internal
mkAddress :: Utf8 -> ByteString -> CacheAddress
mkAddress (Utf8 key) rowdata = CacheAddress . BS.toShort $
key <> ":" <> BA.convert (C.hash @_ @SHA512t_256 rowdata)
readCache
:: TxId
^ Current TxId from checkpointer
-> CacheAddress
-> StateT (DbCache a) IO (Maybe a)
readCache txid ca = do
mc <- use dcStore
forM (HM.lookup ca mc) $ \e -> do
modify'
$ (dcStore . ix ca . ceTxId .~ txid)
. (dcStore . ix ca . ceHits +~ 1)
return $ _ceData e
-- | Add item to module cache
--
writeCache
:: TxId
-> CacheAddress
-> Int
-> a
-> StateT (DbCache a) IO ()
writeCache txid ca sz v = do
modify'
$ (dcStore %~ HM.insert ca (CacheEntry txid ca sz v 0))
. (dcSize +~ sz)
maintainCache
-- | Prune Cache to meet size limit
--
-- Complexity: \(O(n \log(n))\) in the number of entries
--
maintainCache :: Monad m => StateT (DbCache a) m ()
maintainCache = do
sz <- use dcSize
lim <- use dcLimit
unless (sz < lim) $ do
vals <- sort . HM.elems <$> use dcStore
evict sz lim vals
where
evict _ _ [] = return ()
evict sz lim (e:es)
| sz < lim = return ()
| otherwise = do
let sz' = sz - _ceSize e
modify'
$ (dcStore %~ HM.delete (_ceAddy e))
. (dcSize .~ sz')
evict sz' lim es
| null | https://raw.githubusercontent.com/kadena-io/chainweb-node/6ebeb82e7ba05f21da92db6d308352fd40026c38/src/Chainweb/Pact/Backend/DbCache.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE OverloadedStrings #
|
License: See LICENSE file
-------------------------------------------------------------------------- --
ModuleCacheLimitBytes
-------------------------------------------------------------------------- --
-------------------------------------------------------------------------- --
CacheEntry
^ Priority for cache eviction
^ Key. Uniquely identifies entries in the cache
^ The size of the entry. Used to keep track of the cache limit
^ Cached data. This is stored in a compact region.
^ Count of cache hits for this entry
cache. '_ceAddy' is just for stable sort.
only when no pointer to any data in the region is live any more.
lazy, forced by compact
-------------------------------------------------------------------------- --
Telemetry
| The total size of all data in the cache.
Complexity: \(O(1)\)
| Number of entries in the cache.
| Provide read-time caching of deserialized JSON values.
If cache entry is found, mark it with the current txid and return value.
If not, deserialize row data and store in cache, which triggers
cache maintenance.
^ Db key for data
^ row data that contains the encoded value
Cache miss: decode module and insert into cache
-------------------------------------------------------------------------- --
| Add item to module cache
| Prune Cache to meet size limit
Complexity: \(O(n \log(n))\) in the number of entries
| # LANGUAGE FlexibleContexts #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
Module : Chainweb . Pact . Backend . DbCache
Copyright : Copyright © 2022 Kadena LLC .
LRU cache for avoiding expensive JSON deserialization .
module Chainweb.Pact.Backend.DbCache
( DbCacheLimitBytes(..)
, DbCache
, checkDbCache
, emptyDbCache
, cacheSize
, cacheCount
, isEmptyCache
, cacheStats
, updateCacheStats
) where
import Control.Lens hiding ((.=))
import Control.Monad.State.Strict
import qualified Crypto.Hash as C (hash)
import Crypto.Hash.Algorithms
import Data.Aeson (FromJSON, ToJSON, Value, object, decodeStrict, (.=))
import qualified Data.ByteArray as BA
import Data.ByteString (ByteString)
import qualified Data.ByteString.Short as BS
import Data.Hashable
import qualified Data.HashMap.Strict as HM
import Data.List (sort)
import Data.Ord
import Database.SQLite3.Direct
import GHC.Compact
import GHC.Stack
import Numeric.Natural
import Pact.Types.Persistence
newtype DbCacheLimitBytes = DbCacheLimitBytes Natural
deriving (Show, Read, Eq, Ord, ToJSON, FromJSON)
CacheAddress
newtype CacheAddress = CacheAddress BS.ShortByteString
deriving (Show,Eq,Ord,Hashable)
data CacheEntry a = CacheEntry
{ _ceTxId :: !TxId
, _ceAddy :: !CacheAddress
, _ceSize :: !Int
, _ceData :: !a
, _ceHits :: Int
}
ceTxId :: Lens' (CacheEntry a) TxId
ceTxId = lens _ceTxId (\a b -> a { _ceTxId = b })
ceHits :: Lens' (CacheEntry a) Int
ceHits = lens _ceHits (\a b -> a { _ceHits = b })
instance Eq (CacheEntry a) where
a == b = _ceAddy a == _ceAddy b && _ceTxId a == _ceTxId b
| Sort by ' _ ceTxId ' so that smaller tx ids are evicted first from the
instance Ord (CacheEntry a) where
a `compare` b = comparing _ceTxId a b <> comparing _ceAddy a b
| Cache entries are stored within a compact regions . The whole region is GCed
compactCacheEntry :: MonadIO m => FromJSON a => ByteString -> m (Maybe (a, Int))
compactCacheEntry rowdata = do
case getCompact c of
Nothing -> return Nothing
Just m -> do
s <- liftIO $ compactSize c
return $ Just (m, fromIntegral s)
DbCache
data DbCache a = DbCache
{ _dcStore :: !(HM.HashMap CacheAddress (CacheEntry a))
, _dcSize :: !Int
, _dcLimit :: !Int
, _dcMisses :: !Int
, _dcHits :: !Int
}
makeLenses 'DbCache
emptyDbCache :: HasCallStack => DbCacheLimitBytes -> DbCache a
emptyDbCache (DbCacheLimitBytes limit)
| fromIntegral limit > maxBound @Int = error "cache limit is too large"
emptyDbCache (DbCacheLimitBytes limit) = DbCache
{ _dcStore = mempty
, _dcSize = 0
, _dcLimit = fromIntegral limit
, _dcMisses = 0
, _dcHits = 0
}
isEmptyCache :: DbCache a -> Bool
isEmptyCache = HM.null . _dcStore
cacheSize :: DbCache a -> Int
cacheSize = _dcSize
Complexity : \(O(n)\ ) , linear in the number of entries
cacheCount :: DbCache a -> Int
cacheCount = HM.size . _dcStore
checkDbCache
:: FromJSON a
=> Utf8
-> ByteString
-> TxId
^ Current TxId from , used as priority for cache eviction .
Smaller values are evicted first .
-> DbCache a
-> IO (Maybe a, DbCache a)
checkDbCache key rowdata txid = runStateT $ do
readCache txid addy >>= \case
Cache hit
Just x -> do
modify' (dcHits +~ 1)
return $ Just x
Nothing -> compactCacheEntry rowdata >>= \case
Nothing -> return Nothing
Just (m, s) -> do
writeCache txid addy s m
modify' (dcMisses +~ 1)
return $ Just m
where
addy = mkAddress key rowdata
cacheStats :: DbCache a -> Value
cacheStats mc = object
[ "misses" .= _dcMisses mc
, "hits" .= _dcHits mc
, "size" .= cacheSize mc
, "count" .= cacheCount mc
]
updateCacheStats :: DbCache a -> (Value, DbCache a)
updateCacheStats mc = (cacheStats mc, set dcMisses 0 (set dcHits 0 mc))
Internal
mkAddress :: Utf8 -> ByteString -> CacheAddress
mkAddress (Utf8 key) rowdata = CacheAddress . BS.toShort $
key <> ":" <> BA.convert (C.hash @_ @SHA512t_256 rowdata)
readCache
:: TxId
^ Current TxId from checkpointer
-> CacheAddress
-> StateT (DbCache a) IO (Maybe a)
readCache txid ca = do
mc <- use dcStore
forM (HM.lookup ca mc) $ \e -> do
modify'
$ (dcStore . ix ca . ceTxId .~ txid)
. (dcStore . ix ca . ceHits +~ 1)
return $ _ceData e
writeCache
:: TxId
-> CacheAddress
-> Int
-> a
-> StateT (DbCache a) IO ()
writeCache txid ca sz v = do
modify'
$ (dcStore %~ HM.insert ca (CacheEntry txid ca sz v 0))
. (dcSize +~ sz)
maintainCache
maintainCache :: Monad m => StateT (DbCache a) m ()
maintainCache = do
sz <- use dcSize
lim <- use dcLimit
unless (sz < lim) $ do
vals <- sort . HM.elems <$> use dcStore
evict sz lim vals
where
evict _ _ [] = return ()
evict sz lim (e:es)
| sz < lim = return ()
| otherwise = do
let sz' = sz - _ceSize e
modify'
$ (dcStore %~ HM.delete (_ceAddy e))
. (dcSize .~ sz')
evict sz' lim es
|
9250e8153231fb62840788bc7df96a68666d971b4de39e6d28940688bd47b30b | ragkousism/Guix-on-Hurd | adns.scm | ;;; GNU Guix --- Functional package management for GNU
Copyright © 2014 < >
Copyright © 2015 , 2016 < >
;;;
;;; This file is part of GNU Guix.
;;;
GNU is free software ; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;;; GNU General Public License for more details.
;;;
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages adns)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages pkg-config))
(define-public adns
(package
(name "adns")
(version "1.5.1")
(source (origin
(method url-fetch)
(uri (list (string-append "mirror-"
version ".tar.gz")
(string-append
"/~ian/adns/ftp/adns-"
version ".tar.gz")))
(sha256
(base32
"1ssfh94ck6kn98nf2yy6743srpgqgd167va5ja3bwx42igqjc42v"))))
(build-system gnu-build-system)
(arguments
;; Make sure the programs under bin/ fine libadns.so.
'(#:configure-flags (list (string-append "LDFLAGS=-Wl,-rpath -Wl,"
(assoc-ref %outputs "out")
"/lib"))
;; XXX: Tests expect real name resolution to work.
#:tests? #f))
(home-page "/")
(synopsis "Asynchronous DNS client library and utilities")
(description
"GNU adns is a C library that provides easy-to-use DNS resolution
functionality. The library is asynchronous, allowing several concurrent
calls. The package also includes several command-line utilities for use in
scripts.")
(license gpl3+)))
(define-public c-ares
(package
(name "c-ares")
(version "1.12.0")
(source (origin
(method url-fetch)
(uri (string-append
"-ares.haxx.se/download/" name "-" version
".tar.gz"))
(sha256
(base32
"1yv5ygkd813glz8hbagykgp1hlb6450chig061hr7pyw7i0gk4l6"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "-ares.haxx.se/")
(synopsis "C library for asynchronous DNS requests")
(description
"C-ares is a C library that performs DNS requests and name resolution
asynchronously. It is intended for applications which need to perform DNS
queries without blocking, or need to perform multiple DNS queries in parallel.
The primary examples of such applications are servers which communicate with
multiple clients and programs with graphical user interfaces.")
(license (x11-style "-ares.haxx.se/license.html"))))
| null | https://raw.githubusercontent.com/ragkousism/Guix-on-Hurd/e951bb2c0c4961dc6ac2bda8f331b9c4cee0da95/gnu/packages/adns.scm | scheme | GNU Guix --- Functional package management for GNU
This file is part of GNU Guix.
you can redistribute it and/or modify it
either version 3 of the License , or ( at
your option) any later version.
GNU Guix is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Make sure the programs under bin/ fine libadns.so.
XXX: Tests expect real name resolution to work. | Copyright © 2014 < >
Copyright © 2015 , 2016 < >
under the terms of the GNU General Public License as published by
You should have received a copy of the GNU General Public License
along with GNU . If not , see < / > .
(define-module (gnu packages adns)
#:use-module (guix licenses)
#:use-module (guix packages)
#:use-module (guix download)
#:use-module (guix build-system gnu)
#:use-module (gnu packages pkg-config))
(define-public adns
(package
(name "adns")
(version "1.5.1")
(source (origin
(method url-fetch)
(uri (list (string-append "mirror-"
version ".tar.gz")
(string-append
"/~ian/adns/ftp/adns-"
version ".tar.gz")))
(sha256
(base32
"1ssfh94ck6kn98nf2yy6743srpgqgd167va5ja3bwx42igqjc42v"))))
(build-system gnu-build-system)
(arguments
'(#:configure-flags (list (string-append "LDFLAGS=-Wl,-rpath -Wl,"
(assoc-ref %outputs "out")
"/lib"))
#:tests? #f))
(home-page "/")
(synopsis "Asynchronous DNS client library and utilities")
(description
"GNU adns is a C library that provides easy-to-use DNS resolution
functionality. The library is asynchronous, allowing several concurrent
calls. The package also includes several command-line utilities for use in
scripts.")
(license gpl3+)))
(define-public c-ares
(package
(name "c-ares")
(version "1.12.0")
(source (origin
(method url-fetch)
(uri (string-append
"-ares.haxx.se/download/" name "-" version
".tar.gz"))
(sha256
(base32
"1yv5ygkd813glz8hbagykgp1hlb6450chig061hr7pyw7i0gk4l6"))))
(build-system gnu-build-system)
(native-inputs
`(("pkg-config" ,pkg-config)))
(home-page "-ares.haxx.se/")
(synopsis "C library for asynchronous DNS requests")
(description
"C-ares is a C library that performs DNS requests and name resolution
asynchronously. It is intended for applications which need to perform DNS
queries without blocking, or need to perform multiple DNS queries in parallel.
The primary examples of such applications are servers which communicate with
multiple clients and programs with graphical user interfaces.")
(license (x11-style "-ares.haxx.se/license.html"))))
|
209673a7221c0f86cd0609812c73ef4cb2ebe8ecbde94cb2e2055143a4cc49d9 | kmicinski/cmsc330examples | cek.ml | module L = List
module CekMachine = struct
type var = string
type term =
| Var of var (* Variables *)
| Lam of string * term (* Lambda abstractions *)
| App of term * term (* Applications *)
let rec string_of_term = function
| Var x -> x
| Lam (x,t) -> "(\\" ^ x ^ ". " ^ (string_of_term t) ^ ")"
| App (t1,t2) -> "(" ^ (string_of_term t1) ^ " " ^ (string_of_term t2) ^ ")"
type control = term
type machine_value =
| Clo of term * environment
and environment =
(var * machine_value) list
and continuation =
| Done
| EvalArg of term * environment * continuation
| Call of term * environment * continuation
let add var value environment = (var,value)::environment
let rec lookup var = function
| [] -> failwith ("variable " ^ var ^ " undefined")
| (k,(v:machine_value))::tl -> if (k = var) then v else lookup var tl
type machine =
control * environment * continuation
(* Pretty printing... *)
let rec string_of_environment env =
(L.fold_left (fun acc (k,v) -> acc ^ k ^ " |-> " ^ (string_of_machine_value v))
"[ " env) ^ " ]"
and string_of_machine_value = function
| Clo (t,environment) -> "{ " ^ (string_of_term t) ^ " w/ environment "
^ string_of_environment environment ^ " }"
let rec string_of_continuation = function
| Done -> "[]"
| EvalArg(t,e,k) -> "Arg[" ^ string_of_term t ^ "," ^ string_of_environment e
^ "," ^ (string_of_continuation k) ^ "]"
| Call(t,e,k) -> "Call[" ^ string_of_term t ^ "," ^ string_of_environment e
^ "," ^ (string_of_continuation k) ^ "]"
let string_of_machine (c,e,k) = "< " ^ string_of_term c ^ ", "
^ string_of_environment e ^ ", "
^ string_of_continuation k ^ " >"
let step state = match state with
(* How do we evaluate a variable? *)
| (Var x, e, k) ->
(match (lookup x e) with
| Clo (lambda,e') -> (lambda,e',k))
(* How do we evaluate an application? *)
| (App (t1,t2), e, k) ->
(t1, e, EvalArg(t2,e,k))
(* What do we do when we have a lambda and need to evaluate the argument? *)
| (Lam (x,t), e, EvalArg(t',e',k)) ->
(t',e',Call(Lam(x,t),e,k))
(* What do we do when we need to call the function we just computed? *)
| (Lam (x,t), e, Call(Lam(x',t'),e',k)) ->
let extended_env = add x' (Clo(Lam (x,t),e)) e' in
(t',extended_env,k)
(* What do we do when there are no steps left? *)
| (_,_,Done) -> state
(* Fail on all other cases. *)
| _ -> failwith "no step defined..."
let inject t = (t,[],Done)
end
open CekMachine
let example = App(Lam("x",Var "x"),Lam("y",Var "y"))
| null | https://raw.githubusercontent.com/kmicinski/cmsc330examples/78f5acaaae25f11a39817673433efcf33271df6d/lambda-calculus/cek.ml | ocaml | Variables
Lambda abstractions
Applications
Pretty printing...
How do we evaluate a variable?
How do we evaluate an application?
What do we do when we have a lambda and need to evaluate the argument?
What do we do when we need to call the function we just computed?
What do we do when there are no steps left?
Fail on all other cases. | module L = List
module CekMachine = struct
type var = string
type term =
let rec string_of_term = function
| Var x -> x
| Lam (x,t) -> "(\\" ^ x ^ ". " ^ (string_of_term t) ^ ")"
| App (t1,t2) -> "(" ^ (string_of_term t1) ^ " " ^ (string_of_term t2) ^ ")"
type control = term
type machine_value =
| Clo of term * environment
and environment =
(var * machine_value) list
and continuation =
| Done
| EvalArg of term * environment * continuation
| Call of term * environment * continuation
let add var value environment = (var,value)::environment
let rec lookup var = function
| [] -> failwith ("variable " ^ var ^ " undefined")
| (k,(v:machine_value))::tl -> if (k = var) then v else lookup var tl
type machine =
control * environment * continuation
let rec string_of_environment env =
(L.fold_left (fun acc (k,v) -> acc ^ k ^ " |-> " ^ (string_of_machine_value v))
"[ " env) ^ " ]"
and string_of_machine_value = function
| Clo (t,environment) -> "{ " ^ (string_of_term t) ^ " w/ environment "
^ string_of_environment environment ^ " }"
let rec string_of_continuation = function
| Done -> "[]"
| EvalArg(t,e,k) -> "Arg[" ^ string_of_term t ^ "," ^ string_of_environment e
^ "," ^ (string_of_continuation k) ^ "]"
| Call(t,e,k) -> "Call[" ^ string_of_term t ^ "," ^ string_of_environment e
^ "," ^ (string_of_continuation k) ^ "]"
let string_of_machine (c,e,k) = "< " ^ string_of_term c ^ ", "
^ string_of_environment e ^ ", "
^ string_of_continuation k ^ " >"
let step state = match state with
| (Var x, e, k) ->
(match (lookup x e) with
| Clo (lambda,e') -> (lambda,e',k))
| (App (t1,t2), e, k) ->
(t1, e, EvalArg(t2,e,k))
| (Lam (x,t), e, EvalArg(t',e',k)) ->
(t',e',Call(Lam(x,t),e,k))
| (Lam (x,t), e, Call(Lam(x',t'),e',k)) ->
let extended_env = add x' (Clo(Lam (x,t),e)) e' in
(t',extended_env,k)
| (_,_,Done) -> state
| _ -> failwith "no step defined..."
let inject t = (t,[],Done)
end
open CekMachine
let example = App(Lam("x",Var "x"),Lam("y",Var "y"))
|
3693c6bd46129f631c99fec84ea5b265a73e824e95958b4cb5bc007bcad9c6a6 | nyampass/conceit | commons.clj | (ns conceit.commons
(require conceit.commons.ns))
(def ^{:private true} sub-namespaces '#{type assert boolean class fn map number string char byte coll date flow http meta multimethod regex ns named})
(doseq [sub-ns sub-namespaces]
(let [sub-ns-full (symbol (str (name (ns-name *ns*)) "." (name sub-ns)))]
(require sub-ns-full)
(conceit.commons.ns/intern-publics *ns* sub-ns-full)))
| null | https://raw.githubusercontent.com/nyampass/conceit/2b8ba8cc3d732fe2f58d320e2aa4ecdd6f3f3be5/conceit-commons/src/conceit/commons.clj | clojure | (ns conceit.commons
(require conceit.commons.ns))
(def ^{:private true} sub-namespaces '#{type assert boolean class fn map number string char byte coll date flow http meta multimethod regex ns named})
(doseq [sub-ns sub-namespaces]
(let [sub-ns-full (symbol (str (name (ns-name *ns*)) "." (name sub-ns)))]
(require sub-ns-full)
(conceit.commons.ns/intern-publics *ns* sub-ns-full)))
| |
ba85321e53aba8035b0fab279585a4c1e7ec2568f892db884d241307fb833363 | ocaml-sf/learn-ocaml-corpus | discr_ONat.ml | let pigeonhole_sort (bound : int) (kvs : (int * 'v) list) : 'v list =
(* Create an array of buckets, each of which is initially empty. *)
assert (0 <= bound);
let bucket : 'v list array = Array.make bound [] in
(* Place every value into an appropriate bucket, according to its key. *)
List.iter (fun (k, v) ->
assert (0 <= k && k < bound);
bucket.(k) <- v :: bucket.(k)
) kvs;
(* Reverse the list stored in every bucket, so as to have a stable sort. *)
for k = 0 to bound - 1 do
bucket.(k) <- List.rev bucket.(k)
done;
(* Concatenate all buckets. *)
List.flatten (Array.to_list bucket)
let rec cmp : type a . a order -> a -> a -> result =
fun o x y ->
match o with
| OTrue ->
Eq
| ONat _bound ->
if x < y then Lt
else if x = y then Eq
else Gt
| OSum (o1, o2) ->
begin match x, y with
| Inl x, Inl y ->
cmp o1 x y
| Inr x, Inr y ->
cmp o2 x y
| Inl _, Inr _ ->
Lt
| Inr _, Inl _ ->
Gt
end
| OProd (o1, o2) ->
let (x1, x2) = x
and (y1, y2) = y in
begin match cmp o1 x1 y1 with
| Eq ->
cmp o2 x2 y2
| Lt | Gt as result ->
result
end
| OMap (f, o) ->
cmp o (f x) (f y)
let rec partition (kvs : (('a, 'b) either * 'v) list) : ('a * 'v) list * ('b * 'v) list =
match kvs with
| [] ->
[], []
| (Inl l, v) :: kvs ->
let lvs, rvs = partition kvs in
(l, v) :: lvs, rvs
| (Inr r, v) :: kvs ->
let lvs, rvs = partition kvs in
lvs, (r, v) :: rvs
let curryl ((k1, k2), v) =
(k1, (k2, v))
let curryr ((k1, k2), v) =
(k2, (k1, v))
let rec sort : type k v . k order -> (k * v) list -> v list =
fun o kvs ->
match o, kvs with
| _, [] ->
(* The input list is empty. Return an empty output list. *)
[]
| _, [(_k, v)] ->
(* The input list is a singleton. Return a singleton output list.
This is just an optimization (this case could be removed), but
it seems worthwhile, as it allows us to avoid the case analysis
on [o], and the deconstruction of the value [v] that would come
with it. *)
[v]
| OTrue, _ ->
(* All keys are equivalent. Return just the values. *)
List.map snd kvs
| ONat bound, _ ->
(* The keys are integers. Use pigeonhole sort. *)
pigeonhole_sort bound kvs
| OSum (o1, o2), _ ->
Split the key - value list in two sublists : those whose key is
[ Inl _ ] , and those whose key is [ Inr _ ] . Sort each of them ,
and concatenate them , as [ Inl _ ] is less than [ Inr _ ] .
[Inl _], and those whose key is [Inr _]. Sort each of them,
and concatenate them, as [Inl _] is less than [Inr _]. *)
let lvs, rvs = partition kvs in
sort o1 lvs @ sort o2 rvs
| OProd (o1, o2), _ ->
To sort lexicographically with respect to keys which are pairs ,
sort with respect to the least significant pair component first ,
then sort with respect to the most significant pair component .
The fact that this is a stable sort is crucial .
sort with respect to the least significant pair component first,
then sort with respect to the most significant pair component.
The fact that this is a stable sort is crucial. *)
kvs
|> List.map curryr
|> sort o2
|> sort o1
| OMap (f, o), _ ->
(* Apply [f] to every key and sort. *)
sort o (List.map (fun (k, v) -> (f k, v)) kvs)
let simple_sort (o : 'v order) (vs : 'v list) : 'v list =
sort o (List.map (fun v -> (v, v)) vs)
let bool : bool order =
OMap ((fun b -> if b then 1 else 0), ONat 2)
In this solution , [ bool ] is mapped into the integer interval [ 0 .. 1 ] .
Another approach would be to map it to the sum type [ 1 + 1 ] .
Another approach would be to map it to the sum type [1 + 1]. *)
let unfold (xs : 'a list) : (unit, 'a * 'a list) either =
match xs with
| [] ->
Inl ()
| x :: xs ->
Inr (x, xs)
let list (o : 'a order) : 'a list order =
(* A recursive value definition. *)
let rec lexico = OMap (unfold, OSum (OTrue, OProd (o, lexico))) in
lexico
let char : char order =
OMap (Char.code, ONat 255)
(* A string is converted to a list of characters as follows. *)
(* One could arrange for the conversion to take place on demand,
so the conversion is carried out only so far as required by
the comparison. For the sake of simplicity, this is not done
here. *)
let chars (s : string) : char list =
let n = String.length s in
let c = Array.init n (String.get s) in
Array.to_list c
let string : string order =
OMap (chars, list char)
A 32 - bit unsigned integer is split into a pair of 16 - bit unsigned
integers as follows .
integers as follows. *)
let split32 i =
i lsr 16, i land 0xFFFF
A 16 - bit unsigned integer is split into a pair of 8 - bit unsigned
integers as follows .
integers as follows. *)
let split16 i =
i lsr 8, i land 0xFF
(* This leads to the following definitions. *)
let int8 =
ONat 256
let int16 =
OMap (split16, OProd (int8, int8))
let int32 =
OMap (split32, OProd (int16, int16))
(* A discriminator returns a list of nonempty lists of values,
where the inner lists group values whose keys are equivalent. *)
This is top - down discrimination ( Henglein , 2012 ) .
let nonempty = function [] -> false | _ :: _ -> true
let pigeonhole_discr (bound : int) (kvs : (int * 'v) list) : 'v list list =
(* Create an array of buckets, each of which is initially empty. *)
assert (0 <= bound);
let bucket : 'v list array = Array.make bound [] in
(* Place every value into an appropriate bucket, according to its key. *)
List.iter (fun (k, v) ->
assert (0 <= k && k < bound);
bucket.(k) <- v :: bucket.(k)
) kvs;
(* Reverse the list stored in every bucket, so as to have a stable sort. *)
for k = 0 to bound - 1 do
bucket.(k) <- List.rev bucket.(k)
done;
(* Concatenate all nonempty buckets. *)
(* wrong: keep empty buckets. *)
Array.to_list bucket
let rec discr : type k v . k order -> (k * v) list -> v list list =
fun o kvs ->
match o, kvs with
| _, [] ->
[]
| _, [(_k, v)] ->
[[v]]
| OTrue, _ ->
[List.map snd kvs]
| ONat bound, _ ->
pigeonhole_discr bound kvs
| OSum (o1, o2), _ ->
let lvs, rvs = partition kvs in
discr o1 lvs @ discr o2 rvs
| OProd (o1, o2), _ ->
Discriminate with respect to the most significant pair component
first , then ( within each group ) discriminate with respect to the
least significant pair component . Finally , collapse the outer two
layers of list structure . This should in fact be intuitive ; what
is not intuitive is the fact that sorting proceeds the other way
around . This is because sorting does not have group boundaries .
first, then (within each group) discriminate with respect to the
least significant pair component. Finally, collapse the outer two
layers of list structure. This should in fact be intuitive; what
is not intuitive is the fact that sorting proceeds the other way
around. This is because sorting does not have group boundaries. *)
kvs
|> List.map curryl
|> discr o1
|> List.map (discr o2)
|> List.flatten
| OMap (f, o), _ ->
discr o (List.map (fun (k, v) -> (f k, v)) kvs)
| null | https://raw.githubusercontent.com/ocaml-sf/learn-ocaml-corpus/7dcf4d72b49863a3e37e41b3c3097aa4c6101a69/exercises/fpottier/generic_sorting/wrong/discr_ONat.ml | ocaml | Create an array of buckets, each of which is initially empty.
Place every value into an appropriate bucket, according to its key.
Reverse the list stored in every bucket, so as to have a stable sort.
Concatenate all buckets.
The input list is empty. Return an empty output list.
The input list is a singleton. Return a singleton output list.
This is just an optimization (this case could be removed), but
it seems worthwhile, as it allows us to avoid the case analysis
on [o], and the deconstruction of the value [v] that would come
with it.
All keys are equivalent. Return just the values.
The keys are integers. Use pigeonhole sort.
Apply [f] to every key and sort.
A recursive value definition.
A string is converted to a list of characters as follows.
One could arrange for the conversion to take place on demand,
so the conversion is carried out only so far as required by
the comparison. For the sake of simplicity, this is not done
here.
This leads to the following definitions.
A discriminator returns a list of nonempty lists of values,
where the inner lists group values whose keys are equivalent.
Create an array of buckets, each of which is initially empty.
Place every value into an appropriate bucket, according to its key.
Reverse the list stored in every bucket, so as to have a stable sort.
Concatenate all nonempty buckets.
wrong: keep empty buckets. | let pigeonhole_sort (bound : int) (kvs : (int * 'v) list) : 'v list =
assert (0 <= bound);
let bucket : 'v list array = Array.make bound [] in
List.iter (fun (k, v) ->
assert (0 <= k && k < bound);
bucket.(k) <- v :: bucket.(k)
) kvs;
for k = 0 to bound - 1 do
bucket.(k) <- List.rev bucket.(k)
done;
List.flatten (Array.to_list bucket)
let rec cmp : type a . a order -> a -> a -> result =
fun o x y ->
match o with
| OTrue ->
Eq
| ONat _bound ->
if x < y then Lt
else if x = y then Eq
else Gt
| OSum (o1, o2) ->
begin match x, y with
| Inl x, Inl y ->
cmp o1 x y
| Inr x, Inr y ->
cmp o2 x y
| Inl _, Inr _ ->
Lt
| Inr _, Inl _ ->
Gt
end
| OProd (o1, o2) ->
let (x1, x2) = x
and (y1, y2) = y in
begin match cmp o1 x1 y1 with
| Eq ->
cmp o2 x2 y2
| Lt | Gt as result ->
result
end
| OMap (f, o) ->
cmp o (f x) (f y)
let rec partition (kvs : (('a, 'b) either * 'v) list) : ('a * 'v) list * ('b * 'v) list =
match kvs with
| [] ->
[], []
| (Inl l, v) :: kvs ->
let lvs, rvs = partition kvs in
(l, v) :: lvs, rvs
| (Inr r, v) :: kvs ->
let lvs, rvs = partition kvs in
lvs, (r, v) :: rvs
let curryl ((k1, k2), v) =
(k1, (k2, v))
let curryr ((k1, k2), v) =
(k2, (k1, v))
let rec sort : type k v . k order -> (k * v) list -> v list =
fun o kvs ->
match o, kvs with
| _, [] ->
[]
| _, [(_k, v)] ->
[v]
| OTrue, _ ->
List.map snd kvs
| ONat bound, _ ->
pigeonhole_sort bound kvs
| OSum (o1, o2), _ ->
Split the key - value list in two sublists : those whose key is
[ Inl _ ] , and those whose key is [ Inr _ ] . Sort each of them ,
and concatenate them , as [ Inl _ ] is less than [ Inr _ ] .
[Inl _], and those whose key is [Inr _]. Sort each of them,
and concatenate them, as [Inl _] is less than [Inr _]. *)
let lvs, rvs = partition kvs in
sort o1 lvs @ sort o2 rvs
| OProd (o1, o2), _ ->
To sort lexicographically with respect to keys which are pairs ,
sort with respect to the least significant pair component first ,
then sort with respect to the most significant pair component .
The fact that this is a stable sort is crucial .
sort with respect to the least significant pair component first,
then sort with respect to the most significant pair component.
The fact that this is a stable sort is crucial. *)
kvs
|> List.map curryr
|> sort o2
|> sort o1
| OMap (f, o), _ ->
sort o (List.map (fun (k, v) -> (f k, v)) kvs)
let simple_sort (o : 'v order) (vs : 'v list) : 'v list =
sort o (List.map (fun v -> (v, v)) vs)
let bool : bool order =
OMap ((fun b -> if b then 1 else 0), ONat 2)
In this solution , [ bool ] is mapped into the integer interval [ 0 .. 1 ] .
Another approach would be to map it to the sum type [ 1 + 1 ] .
Another approach would be to map it to the sum type [1 + 1]. *)
let unfold (xs : 'a list) : (unit, 'a * 'a list) either =
match xs with
| [] ->
Inl ()
| x :: xs ->
Inr (x, xs)
let list (o : 'a order) : 'a list order =
let rec lexico = OMap (unfold, OSum (OTrue, OProd (o, lexico))) in
lexico
let char : char order =
OMap (Char.code, ONat 255)
let chars (s : string) : char list =
let n = String.length s in
let c = Array.init n (String.get s) in
Array.to_list c
let string : string order =
OMap (chars, list char)
A 32 - bit unsigned integer is split into a pair of 16 - bit unsigned
integers as follows .
integers as follows. *)
let split32 i =
i lsr 16, i land 0xFFFF
A 16 - bit unsigned integer is split into a pair of 8 - bit unsigned
integers as follows .
integers as follows. *)
let split16 i =
i lsr 8, i land 0xFF
let int8 =
ONat 256
let int16 =
OMap (split16, OProd (int8, int8))
let int32 =
OMap (split32, OProd (int16, int16))
This is top - down discrimination ( Henglein , 2012 ) .
let nonempty = function [] -> false | _ :: _ -> true
let pigeonhole_discr (bound : int) (kvs : (int * 'v) list) : 'v list list =
assert (0 <= bound);
let bucket : 'v list array = Array.make bound [] in
List.iter (fun (k, v) ->
assert (0 <= k && k < bound);
bucket.(k) <- v :: bucket.(k)
) kvs;
for k = 0 to bound - 1 do
bucket.(k) <- List.rev bucket.(k)
done;
Array.to_list bucket
let rec discr : type k v . k order -> (k * v) list -> v list list =
fun o kvs ->
match o, kvs with
| _, [] ->
[]
| _, [(_k, v)] ->
[[v]]
| OTrue, _ ->
[List.map snd kvs]
| ONat bound, _ ->
pigeonhole_discr bound kvs
| OSum (o1, o2), _ ->
let lvs, rvs = partition kvs in
discr o1 lvs @ discr o2 rvs
| OProd (o1, o2), _ ->
Discriminate with respect to the most significant pair component
first , then ( within each group ) discriminate with respect to the
least significant pair component . Finally , collapse the outer two
layers of list structure . This should in fact be intuitive ; what
is not intuitive is the fact that sorting proceeds the other way
around . This is because sorting does not have group boundaries .
first, then (within each group) discriminate with respect to the
least significant pair component. Finally, collapse the outer two
layers of list structure. This should in fact be intuitive; what
is not intuitive is the fact that sorting proceeds the other way
around. This is because sorting does not have group boundaries. *)
kvs
|> List.map curryl
|> discr o1
|> List.map (discr o2)
|> List.flatten
| OMap (f, o), _ ->
discr o (List.map (fun (k, v) -> (f k, v)) kvs)
|
9450031b13afa5d183163550e3bc03f993ff4f10d9d2cb4fdc96ba03e87f1041 | ocaml-multicore/ocaml-tsan | odoc_latex.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 2001 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Generation of LaTeX documentation. *)
open Odoc_info
open Value
open Type
open Extension
open Exception
open Class
open Module
let separate_files = ref false
let latex_titles = ref [
0, "section" ;
1, "section" ;
2, "subsection" ;
3, "subsubsection" ;
4, "paragraph" ;
5, "subparagraph" ;
]
let latex_value_prefix = ref Odoc_messages.default_latex_value_prefix
let latex_type_prefix = ref Odoc_messages.default_latex_type_prefix
let latex_type_elt_prefix = ref Odoc_messages.default_latex_type_elt_prefix
let latex_extension_prefix = ref Odoc_messages.default_latex_extension_prefix
let latex_exception_prefix = ref Odoc_messages.default_latex_exception_prefix
let latex_module_prefix = ref Odoc_messages.default_latex_module_prefix
let latex_module_type_prefix = ref Odoc_messages.default_latex_module_type_prefix
let latex_class_prefix = ref Odoc_messages.default_latex_class_prefix
let latex_class_type_prefix = ref Odoc_messages.default_latex_class_type_prefix
let latex_attribute_prefix = ref Odoc_messages.default_latex_attribute_prefix
let latex_method_prefix = ref Odoc_messages.default_latex_method_prefix
let new_buf () = Buffer.create 1024
let new_fmt () =
let b = new_buf () in
let fmt = Format.formatter_of_buffer b in
(fmt,
fun () ->
Format.pp_print_flush fmt ();
let s = Buffer.contents b in
Buffer.reset b;
s
)
let p = Format.fprintf
let ps f s = Format.fprintf f "%s" s
let rec merge_codepre = function
[] -> []
| [e] -> [e]
| (CodePre s1) :: (CodePre s2) :: q ->
merge_codepre ((CodePre (s1^"\n"^s2)) :: q)
| e :: q ->
e :: (merge_codepre q)
let print_concat fmt sep f =
let rec iter = function
[] -> ()
| [c] -> f c
| c :: q ->
f c;
ps fmt sep;
iter q
in
iter
(** Generation of LaTeX code from text structures. *)
class text =
object (self)
(** Return latex code to make a section according to the given level,
and with the given latex code. *)
method section_style level s =
try
let sec = List.assoc level !latex_titles in
"\\"^sec^"{"^s^"}\n"
with Not_found -> s
(** Associations of strings to substitute in latex code. *)
val subst_strings = List.map (fun (x, y) -> (Str.regexp x, y))
[
"\001", "\001\002";
"\\\\", "\001b";
"{", "\\\\{";
"}", "\\\\}";
"\\$", "\\\\$";
"\\^", "{\\\\textasciicircum}";
"%", "\\\\%";
"_", "\\\\_";
"~", "\\\\~{}";
"#", "{\\char35}";
"->", "$\\\\rightarrow$";
"<-", "$\\\\leftarrow$";
">=", "$\\\\geq$";
"<=", "$\\\\leq$";
">", "$>$";
"<", "$<$";
"=", "$=$";
"|", "{\\\\textbar}";
"\\.\\.\\.", "$\\\\ldots$";
"&", "\\\\&";
"\001b", "{\\\\char92}";
"\001\002", "\001";
]
val subst_strings_simple = List.map (fun (x, y) -> (Str.regexp x, y))
[
"\001", "\001\002";
"\\\\", "\001b";
"{", "\001l";
"}", "{\\\\char125}";
"'", "{\\\\textquotesingle}";
"`", "{\\\\textasciigrave}";
"\001b", "{\\\\char92}";
"\001l", "{\\\\char123}";
"\001\002", "\001";
]
val subst_strings_code = List.map (fun (x, y) -> (Str.regexp x, y))
[
"\001", "\001\002";
"\\\\", "\001b";
"{", "\001l";
"}", "{\\\\char125}";
"'", "{\\\\textquotesingle}";
"`", "{\\\\textasciigrave}";
"%", "\\\\%";
"_", "\\\\_";
"~", "{\\\\char126}";
"#", "{\\\\char35}";
"&", "\\\\&";
"\\$", "\\\\$";
"\\^", "{\\\\char94}";
"\001b", "{\\\\char92}";
"\001l", "{\\\\char123}";
"\001\002", "\001";
]
method subst l s =
List.fold_left (fun acc (re, st) -> Str.global_replace re st acc) s l
* Escape the strings which would clash with LaTeX syntax .
method escape s = self#subst subst_strings s
(** Escape the ['\'], ['{'] and ['}'] characters. *)
method escape_simple s = self#subst subst_strings_simple s
(** Escape some characters for the code style. *)
method escape_code s = self#subst subst_strings_code s
(** Make a correct latex label from a name. *)
The following characters are forbidden in LaTeX :
\ { } $ & # ^ _ % ~ ! " @ | ( " to close the double quote )
The following characters are forbidden in LaTeX :
\ { } $ & # ^ _ % ~
So we will use characters not forbidden in if no _ = true .
\ { } $ & # ^ _ % ~ ! " @ | (" to close the double quote)
The following characters are forbidden in LaTeX \label:
\ { } $ & # ^ _ % ~
So we will use characters not forbidden in \index if no_ = true.
*)
method label ?(no_=true) name =
let len = String.length name in
let buf = Buffer.create len in
for i = 0 to len - 1 do
let (s_no_, s) =
match name.[i] with
'_' -> ("-underscore", "_")
| '~' -> ("-tilde", "~")
| '%' -> ("-percent", "%")
| '@' -> ("-at", "\"@")
| '!' -> ("-bang", "\"!")
| '|' -> ("-pipe", "\"|")
| '<' -> ("-lt", "<")
| '>' -> ("-gt", ">")
| '^' -> ("-exp", "^")
| '&' -> ("-ampersand", "&")
| '+' -> ("-plus", "+")
| '-' -> ("-minus", "-")
| '*' -> ("-star", "*")
| '/' -> ("-slash", "/")
| '$' -> ("-dollar", "$")
| '=' -> ("-equal", "=")
| ':' -> ("-colon", ":")
| c -> (String.make 1 c, String.make 1 c)
in
Buffer.add_string buf (if no_ then s_no_ else s)
done;
Buffer.contents buf
(** Make a correct label from a value name. *)
method value_label ?no_ name = !latex_value_prefix^(self#label ?no_ name)
(** Make a correct label from an attribute name. *)
method attribute_label ?no_ name = !latex_attribute_prefix^(self#label ?no_ name)
(** Make a correct label from a method name. *)
method method_label ?no_ name = !latex_method_prefix^(self#label ?no_ name)
(** Make a correct label from a class name. *)
method class_label ?no_ name = !latex_class_prefix^(self#label ?no_ name)
(** Make a correct label from a class type name. *)
method class_type_label ?no_ name = !latex_class_type_prefix^(self#label ?no_ name)
(** Make a correct label from a module name. *)
method module_label ?no_ name = !latex_module_prefix^(self#label ?no_ name)
(** Make a correct label from a module type name. *)
method module_type_label ?no_ name = !latex_module_type_prefix^(self#label ?no_ name)
(** Make a correct label from an extension name. *)
method extension_label ?no_ name = !latex_extension_prefix^(self#label ?no_ name)
(** Make a correct label from an exception name. *)
method exception_label ?no_ name = !latex_exception_prefix^(self#label ?no_ name)
(** Make a correct label from a type name. *)
method type_label ?no_ name = !latex_type_prefix^(self#label ?no_ name)
(** Make a correct label from a record field. *)
method recfield_label ?no_ name = !latex_type_elt_prefix^(self#label ?no_ name)
(** Make a correct label from a variant constructor. *)
method const_label ?no_ name = !latex_type_elt_prefix^(self#label ?no_ name)
(** Return latex code for the label of a given label. *)
method make_label label = "\\label{"^label^"}"
(** Return latex code for the ref to a given label. *)
method make_ref label = "\\ref{"^label^"}"
* Print the LaTeX code corresponding to the [ text ] parameter .
method latex_of_text fmt t =
List.iter (self#latex_of_text_element fmt) t
* Print the LaTeX code for the [ text_element ] in parameter .
method latex_of_text_element fmt txt =
match txt with
| Odoc_info.Raw s -> self#latex_of_Raw fmt s
| Odoc_info.Code s -> self#latex_of_Code fmt s
| Odoc_info.CodePre s -> self#latex_of_CodePre fmt s
| Odoc_info.Verbatim s -> self#latex_of_Verbatim fmt s
| Odoc_info.Bold t -> self#latex_of_Bold fmt t
| Odoc_info.Italic t -> self#latex_of_Italic fmt t
| Odoc_info.Emphasize t -> self#latex_of_Emphasize fmt t
| Odoc_info.Center t -> self#latex_of_Center fmt t
| Odoc_info.Left t -> self#latex_of_Left fmt t
| Odoc_info.Right t -> self#latex_of_Right fmt t
| Odoc_info.List tl -> self#latex_of_List fmt tl
| Odoc_info.Enum tl -> self#latex_of_Enum fmt tl
| Odoc_info.Newline -> self#latex_of_Newline fmt
| Odoc_info.Block t -> self#latex_of_Block fmt t
| Odoc_info.Title (n, l_opt, t) -> self#latex_of_Title fmt n l_opt t
| Odoc_info.Latex s -> self#latex_of_Latex fmt s
| Odoc_info.Link (s, t) -> self#latex_of_Link fmt s t
| Odoc_info.Ref (name, ref_opt, text_opt) ->
self#latex_of_Ref fmt name ref_opt text_opt
| Odoc_info.Superscript t -> self#latex_of_Superscript fmt t
| Odoc_info.Subscript t -> self#latex_of_Subscript fmt t
| Odoc_info.Module_list _ -> ()
| Odoc_info.Index_list -> ()
| Odoc_info.Custom (s,t) -> self#latex_of_custom_text fmt s t
| Odoc_info.Target (target, code) -> self#latex_of_Target fmt ~target ~code
method latex_of_custom_text _ _ _ = ()
method latex_of_Target fmt ~target ~code =
if String.lowercase_ascii target = "latex" then
self#latex_of_Latex fmt code
else
()
method latex_of_Raw fmt s =
ps fmt (self#escape s)
method latex_of_Code fmt s =
let s2 = self#escape_code s in
let s3 = Str.global_replace (Str.regexp "\n") ("\\\\\n") s2 in
p fmt "{\\tt{%s}}" s3
method latex_of_CodePre fmt s =
ps fmt "\\begin{ocamldoccode}\n";
ps fmt (self#escape_simple s);
ps fmt "\n\\end{ocamldoccode}\n"
method latex_of_Verbatim fmt s =
ps fmt "\n\\begin{verbatim}\n";
ps fmt s;
ps fmt "\n\\end{verbatim}\n"
method latex_of_Bold fmt t =
ps fmt "{\\bf ";
self#latex_of_text fmt t;
ps fmt "}"
method latex_of_Italic fmt t =
ps fmt "{\\it ";
self#latex_of_text fmt t;
ps fmt "}"
method latex_of_Emphasize fmt t =
ps fmt "{\\em ";
self#latex_of_text fmt t;
ps fmt "}"
method latex_of_Center fmt t =
ps fmt "\\begin{center}\n";
self#latex_of_text fmt t;
ps fmt "\\end{center}\n"
method latex_of_Left fmt t =
ps fmt "\\begin{flushleft}\n";
self#latex_of_text fmt t;
ps fmt "\\end{flushleft}\n"
method latex_of_Right fmt t =
ps fmt "\\begin{flushright}\n";
self#latex_of_text fmt t;
ps fmt "\\end{flushright}\n"
method latex_of_List fmt tl =
ps fmt "\\begin{itemize}\n";
List.iter
(fun t ->
ps fmt "\\item ";
self#latex_of_text fmt t;
ps fmt "\n"
)
tl;
ps fmt "\\end{itemize}\n"
method latex_of_Enum fmt tl =
ps fmt "\\begin{enumerate}\n";
List.iter
(fun t ->
ps fmt "\\item ";
self#latex_of_text fmt t;
ps fmt "\n"
)
tl;
ps fmt "\\end{enumerate}\n"
method latex_of_Newline fmt = ps fmt "\n\n"
method latex_of_Block fmt t =
ps fmt "\\begin{ocamldocdescription}\n";
self#latex_of_text fmt t;
ps fmt "\n\\end{ocamldocdescription}\n"
method latex_of_Title fmt n label_opt t =
let (fmt2, flush) = new_fmt () in
self#latex_of_text fmt2 t;
let s_title2 = self#section_style n (flush ()) in
ps fmt s_title2;
(
match label_opt with
None -> ()
| Some l ->
ps fmt (self#make_label (self#label ~no_: false l))
)
method latex_of_Latex fmt s = ps fmt s
method latex_of_Link fmt s t =
self#latex_of_text fmt t ;
ps fmt "[\\url{";
ps fmt s ;
ps fmt "}]"
method latex_of_Ref fmt name ref_opt text_opt =
match ref_opt with
None ->
self#latex_of_text fmt
(match text_opt with
None ->
[Odoc_info.Code (Odoc_info.use_hidden_modules name)]
| Some t -> t
)
| Some (RK_section _) ->
let text = match text_opt with
| None -> []
| Some x -> x in
let label= self#make_ref (self#label ~no_:false (Name.simple name)) in
self#latex_of_text fmt
(text @ [Latex ("["^label^"]")] )
| Some kind ->
let f_label =
match kind with
Odoc_info.RK_module -> self#module_label
| Odoc_info.RK_module_type -> self#module_type_label
| Odoc_info.RK_class -> self#class_label
| Odoc_info.RK_class_type -> self#class_type_label
| Odoc_info.RK_value -> self#value_label
| Odoc_info.RK_type -> self#type_label
| Odoc_info.RK_extension -> self#extension_label
| Odoc_info.RK_exception -> self#exception_label
| Odoc_info.RK_attribute -> self#attribute_label
| Odoc_info.RK_method -> self#method_label
| Odoc_info.RK_section _ -> assert false
| Odoc_info.RK_recfield -> self#recfield_label
| Odoc_info.RK_const -> self#const_label
in
let text =
match text_opt with
None -> [Odoc_info.Code (Odoc_info.use_hidden_modules name)]
| Some t -> t
in
self#latex_of_text fmt
(text @ [Latex ("["^(self#make_ref (f_label name))^"]")])
method latex_of_Superscript fmt t =
ps fmt "$^{";
self#latex_of_text fmt t;
ps fmt "}$"
method latex_of_Subscript fmt t =
ps fmt "$_{";
self#latex_of_text fmt t;
ps fmt "}$"
end
* A class used to generate LaTeX code for info structures .
class virtual info =
object (self)
* The method used to get LaTeX code from a [ text ] .
method virtual latex_of_text : Format.formatter -> Odoc_info.text -> unit
(** The method used to get a [text] from an optional info structure. *)
method virtual text_of_info : ?block: bool -> Odoc_info.info option -> Odoc_info.text
(** Print LaTeX code for a description, except for the [i_params] field. *)
method latex_of_info fmt ?(block=false) info_opt =
self#latex_of_text fmt
(self#text_of_info ~block info_opt)
end
module Generator =
struct
* This class is used to create objects which can generate a simple LaTeX documentation .
class latex =
object (self)
inherit text
inherit Odoc_to_text.to_text as to_text
inherit info
* Get the first sentence and the rest of a description ,
from an optional [ info ] structure . The first sentence
can be empty if it would not appear right in a title .
In the first sentence , the titles and lists has been removed ,
since it is used in LaTeX titles and would make LaTeX complain
if we has two nested \section commands .
from an optional [info] structure. The first sentence
can be empty if it would not appear right in a title.
In the first sentence, the titles and lists has been removed,
since it is used in LaTeX titles and would make LaTeX complain
if we has two nested \section commands.
*)
method first_and_rest_of_info i_opt =
match i_opt with
None -> ([], [])
| Some i ->
match i.Odoc_info.i_desc with
None -> ([], self#text_of_info ~block: true i_opt)
| Some t ->
let (first,_) = Odoc_info.first_sentence_and_rest_of_text t in
let (_, rest) = Odoc_info.first_sentence_and_rest_of_text (self#text_of_info ~block: false i_opt) in
(Odoc_info.text_no_title_no_list first, rest)
(** Print LaTeX code for a value. *)
method latex_of_value fmt v =
Odoc_info.reset_type_names () ;
let label = self#value_label v.val_name in
let latex = self#make_label label in
self#latex_of_text fmt
((Latex latex) ::
(to_text#text_of_value v))
(** Print LaTeX code for a class attribute. *)
method latex_of_attribute fmt a =
self#latex_of_text fmt
((Latex (self#make_label (self#attribute_label a.att_value.val_name))) ::
(to_text#text_of_attribute a))
(** Print LaTeX code for a class method. *)
method latex_of_method fmt m =
self#latex_of_text fmt
((Latex (self#make_label (self#method_label m.met_value.val_name))) ::
(to_text#text_of_method m))
(** Print LaTeX code for the parameters of a type. *)
method latex_of_type_params fmt m_name t =
let print_one (p, co, cn) =
ps fmt (Odoc_info.string_of_variance t (co,cn));
ps fmt (self#normal_type m_name p)
in
match t.ty_parameters with
[] -> ()
| [(p,co,cn)] -> print_one (p, co, cn)
| _ ->
ps fmt "(";
print_concat fmt ", " print_one t.ty_parameters;
ps fmt ")"
method latex_of_class_parameter_list fmt father c =
self#latex_of_text fmt
(self#text_of_class_params father c)
method entry_comment (fmt,flush) = function
| None -> []
| Some t ->
let s =
ps fmt "\\begin{ocamldoccomment}\n";
self#latex_of_info fmt (Some t);
ps fmt "\n\\end{ocamldoccomment}\n";
flush ()
in
[ Latex s]
(** record printing method *)
method latex_of_record ( (fmt,flush) as f) mod_name l =
p fmt "{";
let fields =
List.map (fun r ->
let s_field =
p fmt
"@[<h 6> %s%s :@ %s ;"
(if r.rf_mutable then "mutable " else "")
r.rf_name
(self#normal_type mod_name r.rf_type);
flush ()
in
[ CodePre s_field ] @ (self#entry_comment f r.rf_text)
) l in
List.flatten fields @ [ CodePre "}" ]
method latex_of_cstr_args ( (fmt,flush) as f) mod_name (args, ret) =
match args, ret with
| Cstr_tuple [], None -> [CodePre(flush())]
| Cstr_tuple _ as l, None ->
p fmt " of@ %s"
(self#normal_cstr_args ~par:false mod_name l);
[CodePre (flush())]
| Cstr_tuple t as l, Some r ->
let res = self#normal_type mod_name r in
if t = [] then
p fmt " :@ %s" res
else
p fmt " :@ %s -> %s" (self#normal_cstr_args ~par:false mod_name l) res
;
[CodePre (flush())]
| Cstr_record l, None ->
p fmt " of@ ";
self#latex_of_record f mod_name l
| Cstr_record r, Some res ->
let l =
p fmt " :@ ";
self#latex_of_record f mod_name r in
let l2 =
p fmt "@ %s@ %s" "->"
(self#normal_type mod_name res);
[CodePre (flush())] in
l @ l2
(** Print LaTeX code for a type. *)
method latex_of_type fmt t =
let s_name = Name.simple t.ty_name in
let text =
let ( (fmt2, flush2) as f) = new_fmt () in
Odoc_info.reset_type_names () ;
let mod_name = Name.father t.ty_name in
Format.fprintf fmt2 "@[<h 2>type ";
self#latex_of_type_params fmt2 mod_name t;
(match t.ty_parameters with [] -> () | _ -> ps fmt2 " ");
ps fmt2 s_name;
let priv = t.ty_private = Asttypes.Private in
(
match t.ty_manifest with
| Some (Other typ) ->
p fmt2 " = %s%s" (if priv then "private " else "") (self#normal_type mod_name typ)
| _ -> ()
);
let s_type3 =
p fmt2
" %s"
(
match t.ty_kind with
Type_abstract ->
begin match t.ty_manifest with
| Some (Object_type _) ->
"= " ^ (if priv then "private" else "") ^ " <"
| _ -> ""
end
| Type_variant _ -> "="^(if priv then " private" else "")
| Type_record _ -> "= "^(if priv then "private " else "")
| Type_open -> "= .."
) ;
flush2 ()
in
let defs =
match t.ty_kind with
| Type_abstract ->
begin match t.ty_manifest with
| Some (Object_type l) ->
let fields =
List.map (fun r ->
let s_field =
p fmt2
"@[<h 6> %s :@ %s ;"
r.of_name
(self#normal_type mod_name r.of_type);
flush2 ()
in
[ CodePre s_field ] @ (self#entry_comment f r.of_text)
) l
in
List.flatten fields @ [ CodePre ">" ]
| None | Some (Other _) -> []
end
| Type_variant l ->
if l = [] then (p fmt2 "@[<h 6> |"; [CodePre (flush2())]) else (
let constructors =
List.map (fun {vc_name; vc_args; vc_ret; vc_text} ->
p fmt2 "@[<h 6> | %s" vc_name ;
let l = self#latex_of_cstr_args f mod_name (vc_args,vc_ret) in
l @ (self#entry_comment f vc_text) ) l
in
List.flatten constructors)
| Type_record l ->
self#latex_of_record f mod_name l
| Type_open ->
(* FIXME ? *)
[]
in
let defs2 = (CodePre s_type3) :: defs in
(merge_codepre defs2) @
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @
(self#text_of_info t.ty_info)
in
self#latex_of_text fmt
((Latex (self#make_label (self#type_label t.ty_name))) :: text)
(** Print LaTeX code for a type extension. *)
method latex_of_type_extension mod_name fmt te =
let text =
let (fmt2, flush2) as f = new_fmt () in
Odoc_info.reset_type_names () ;
Format.fprintf fmt2 "@[<h 2>type ";
(
match te.te_type_parameters with
[] -> ()
| [p] ->
ps fmt2 (self#normal_type mod_name p);
ps fmt2 " "
| l ->
ps fmt2 "(";
print_concat fmt2 ", " (fun p -> ps fmt2 (self#normal_type mod_name p)) l;
ps fmt2 ") "
);
ps fmt2 (self#relative_idents mod_name te.te_type_name);
p fmt2 " +=%s" (if te.te_private = Asttypes.Private then " private" else "") ;
let s_type3 = flush2 () in
let defs =
(List.flatten
(List.map
(fun x ->
let father = Name.father x.xt_name in
p fmt2 "@[<h 6> | %s" (Name.simple x.xt_name);
let l = self#latex_of_cstr_args f father (x.xt_args, x.xt_ret) in
let c =
match x.xt_alias with
| None -> []
| Some xa ->
p fmt2 " = %s"
(
match xa.xa_xt with
| None -> xa.xa_name
| Some x -> x.xt_name
);
[CodePre (flush2 ())]
in
Latex (self#make_label (self#extension_label x.xt_name)) :: l @ c
@ (match x.xt_text with
None -> []
| Some t ->
let s =
ps fmt2 "\\begin{ocamldoccomment}\n";
self#latex_of_info fmt2 (Some t);
ps fmt2 "\n\\end{ocamldoccomment}\n";
flush2 ()
in
[ Latex s]
)
)
te.te_constructors
)
)
in
let defs2 = (CodePre s_type3) :: defs in
(merge_codepre defs2) @
(self#text_of_info te.te_info)
in
self#latex_of_text fmt text
(** Print LaTeX code for an exception. *)
method latex_of_exception fmt e =
let text =
let (fmt2, flush2) as f = new_fmt() in
Odoc_info.reset_type_names () ;
let s_name = Name.simple e.ex_name in
let father = Name.father e.ex_name in
p fmt2 "@[<hov 2>exception %s" s_name;
let l = self#latex_of_cstr_args f father (e.ex_args, e.ex_ret) in
let s =
match e.ex_alias with
None -> []
| Some ea ->
Format.fprintf fmt " = %s"
(
match ea.ea_ex with
None -> ea.ea_name
| Some e -> e.ex_name
);
[CodePre (flush2 ())]
in
Latex ( self#make_label (self#exception_label e.ex_name) ) ::
merge_codepre (l @ s ) @
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")]
@ (self#text_of_info e.ex_info) in
self#latex_of_text fmt text
method latex_of_module_parameter fmt m_name p =
self#latex_of_text fmt
[
Code "functor (";
Code p.mp_name ;
Code " : ";
] ;
self#latex_of_module_type_kind fmt m_name p.mp_kind;
self#latex_of_text fmt [ Code ") -> "]
method latex_of_module_type_kind fmt father kind =
match kind with
Module_type_struct eles ->
self#latex_of_text fmt [Latex "\\begin{ocamldocsigend}\n"];
List.iter (self#latex_of_module_element fmt father) eles;
self#latex_of_text fmt [Latex "\\end{ocamldocsigend}\n"]
| Module_type_functor (p, k) ->
self#latex_of_module_parameter fmt father p;
self#latex_of_module_type_kind fmt father k
| Module_type_alias a ->
self#latex_of_text fmt
[Code (self#relative_module_idents father a.mta_name)]
| Module_type_with (k, s) ->
self#latex_of_module_type_kind fmt father k;
self#latex_of_text fmt
[ Code " ";
Code (self#relative_idents father s);
]
| Module_type_typeof s ->
self#latex_of_text fmt
[ Code "module type of ";
Code (self#relative_idents father s);
]
method latex_of_module_kind fmt father kind =
match kind with
Module_struct eles ->
self#latex_of_text fmt [Latex "\\begin{ocamldocsigend}\n"];
List.iter (self#latex_of_module_element fmt father) eles;
self#latex_of_text fmt [Latex "\\end{ocamldocsigend}\n"]
| Module_alias a ->
self#latex_of_text fmt
[Code (self#relative_module_idents father a.ma_name)]
| Module_functor (p, k) ->
self#latex_of_module_parameter fmt father p;
self#latex_of_module_kind fmt father k
| Module_apply (k1, k2) ->
TODO : application is not correct in a .mli .
Fix ? - > print the typedtree module_type
Fix? -> print the typedtree module_type *)
self#latex_of_module_kind fmt father k1;
self#latex_of_text fmt [Code "("];
self#latex_of_module_kind fmt father k2;
self#latex_of_text fmt [Code ")"]
| Module_with (k, s) ->
(* TODO: modify when Module_with will be more detailed *)
self#latex_of_module_type_kind fmt father k;
self#latex_of_text fmt
[ Code " ";
Code (self#relative_idents father s) ;
]
| Module_constraint (k, _tk) ->
(* TODO: what should we print? *)
self#latex_of_module_kind fmt father k
| Module_typeof s ->
self#latex_of_text fmt
[ Code "module type of ";
Code (self#relative_idents father s);
]
| Module_unpack (s, _) ->
self#latex_of_text fmt
[
Code (self#relative_idents father s);
]
method latex_of_class_kind fmt father kind =
match kind with
Class_structure (inh, eles) ->
self#latex_of_text fmt [Latex "\\begin{ocamldocobjectend}\n"];
self#generate_inheritance_info fmt inh;
List.iter (self#latex_of_class_element fmt father) eles;
self#latex_of_text fmt [Latex "\\end{ocamldocobjectend}\n"]
| Class_apply _ ->
(* TODO: print final type from typedtree *)
self#latex_of_text fmt [Raw "class application not handled yet"]
| Class_constr cco ->
(
match cco.cco_type_parameters with
[] -> ()
| l ->
self#latex_of_text fmt
(
Code "[" ::
(self#text_of_class_type_param_expr_list father l) @
[Code "] "]
)
);
self#latex_of_text fmt
[Code (self#relative_idents father cco.cco_name)]
| Class_constraint (ck, ctk) ->
self#latex_of_text fmt [Code "( "] ;
self#latex_of_class_kind fmt father ck;
self#latex_of_text fmt [Code " : "] ;
self#latex_of_class_type_kind fmt father ctk;
self#latex_of_text fmt [Code " )"]
method latex_of_class_type_kind fmt father kind =
match kind with
Class_type cta ->
(
match cta.cta_type_parameters with
[] -> ()
| l ->
self#latex_of_text fmt
(Code "[" ::
(self#text_of_class_type_param_expr_list father l) @
[Code "] "]
)
);
self#latex_of_text fmt
[Code (self#relative_idents father cta.cta_name)]
| Class_signature (inh, eles) ->
self#latex_of_text fmt [Latex "\\begin{ocamldocobjectend}\n"];
self#generate_inheritance_info fmt inh;
List.iter (self#latex_of_class_element fmt father) eles;
self#latex_of_text fmt [Latex "\\end{ocamldocobjectend}\n"]
method latex_for_module_index fmt m =
let s_name = Name.simple m.m_name in
self#latex_of_text fmt
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
(self#label ~no_:false s_name)^"`}\n"
)
]
method latex_for_module_type_index fmt mt =
let s_name = Name.simple mt.mt_name in
self#latex_of_text fmt
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
(self#label ~no_:false (Name.simple s_name))^"`}\n"
)
]
method latex_for_module_label fmt m =
ps fmt (self#make_label (self#module_label m.m_name))
method latex_for_module_type_label fmt mt =
ps fmt (self#make_label (self#module_type_label mt.mt_name))
method latex_for_class_index fmt c =
let s_name = Name.simple c.cl_name in
self#latex_of_text fmt
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
(self#label ~no_:false s_name)^"`}\n"
)
]
method latex_for_class_type_index fmt ct =
let s_name = Name.simple ct.clt_name in
self#latex_of_text fmt
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
(self#label ~no_:false s_name)^"`}\n"
)
]
method latex_for_class_label fmt c =
ps fmt (self#make_label (self#class_label c.cl_name))
method latex_for_class_type_label fmt ct =
ps fmt (self#make_label (self#class_type_label ct.clt_name))
* Print the LaTeX code for the given module .
method latex_of_module fmt m =
let father = Name.father m.m_name in
let t =
[
Latex "\\begin{ocamldoccode}\n" ;
Code "module ";
Code (Name.simple m.m_name);
Code " : ";
]
in
self#latex_of_text fmt t;
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_module_label fmt m;
self#latex_for_module_index fmt m;
p fmt "@[<h 4>";
self#latex_of_module_kind fmt father m.m_kind;
(
match Module.module_is_functor m with
false -> ()
| true ->
self#latex_of_text fmt [Newline];
(
match List.filter (fun (_,d) -> d <> None)
(module_parameters ~trans: false m)
with
[] -> ()
| l ->
let t =
[ Bold [Raw "Parameters: "];
List
(List.map
(fun (p,text_opt) ->
let t = match text_opt with None -> [] | Some t -> t in
( Raw p.mp_name :: Raw ": " :: t)
)
l
)
]
in
self#latex_of_text fmt t
);
);
self#latex_of_text fmt [Newline];
self#latex_of_info fmt ~block: true m.m_info;
p fmt "@]";
* Print the LaTeX code for the given module type .
method latex_of_module_type fmt mt =
let father = Name.father mt.mt_name in
let t =
[
Latex "\\begin{ocamldoccode}\n" ;
Code "module type " ;
Code (Name.simple mt.mt_name);
]
in
self#latex_of_text fmt t;
(
match mt.mt_type, mt.mt_kind with
| Some _, Some kind ->
self#latex_of_text fmt [ Code " = " ];
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_module_type_label fmt mt;
self#latex_for_module_type_index fmt mt;
p fmt "@[<h 4>";
self#latex_of_module_type_kind fmt father kind
| _ ->
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_module_type_index fmt mt;
p fmt "@[<h 4>";
);
(
match Module.module_type_is_functor mt with
false -> ()
| true ->
self#latex_of_text fmt [Newline];
(
match List.filter (fun (_,d) -> d <> None)
(module_type_parameters ~trans: false mt)
with
[] -> ()
| l ->
let t =
[ Bold [Raw "Parameters: "];
List
(List.map
(fun (p,text_opt) ->
let t = match text_opt with None -> [] | Some t -> t in
( Raw p.mp_name :: Raw ": " :: t)
)
l
)
]
in
self#latex_of_text fmt t
);
);
self#latex_of_text fmt [Newline];
self#latex_of_info fmt ~block: true mt.mt_info;
p fmt "@]";
* Print the LaTeX code for the given included module .
method latex_of_included_module fmt im =
self#latex_of_text fmt
((Code "include ") ::
(Code
(match im.im_module with
None -> im.im_name
| Some (Mod m) -> m.m_name
| Some (Modtype mt) -> mt.mt_name)
) ::
(self#text_of_info im.im_info)
)
* Print the LaTeX code for the given class .
method latex_of_class fmt c =
Odoc_info.reset_type_names () ;
let father = Name.father c.cl_name in
let type_params =
match c.cl_type_parameters with
[] -> ""
| l -> (self#normal_class_type_param_list father l)^" "
in
let t =
[
Latex "\\begin{ocamldoccode}\n" ;
Code (Printf.sprintf
"class %s%s%s : "
(if c.cl_virtual then "virtual " else "")
type_params
(Name.simple c.cl_name)
)
]
in
self#latex_of_text fmt t;
self#latex_of_class_parameter_list fmt father c;
(* avoid a big gap if the kind is a constr *)
(
match c.cl_kind with
Class.Class_constr _ ->
self#latex_of_class_kind fmt father c.cl_kind
| _ ->
()
);
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_class_label fmt c;
self#latex_for_class_index fmt c;
p fmt "@[<h 4>";
(match c.cl_kind with
Class.Class_constr _ -> ()
| _ -> self#latex_of_class_kind fmt father c.cl_kind
);
self#latex_of_text fmt [Newline];
self#latex_of_info fmt ~block: true c.cl_info;
p fmt "@]"
* Print the LaTeX code for the given class type .
method latex_of_class_type fmt ct =
Odoc_info.reset_type_names () ;
let father = Name.father ct.clt_name in
let type_params =
match ct.clt_type_parameters with
[] -> ""
| l -> (self#normal_class_type_param_list father l)^" "
in
let t =
[
Latex "\\begin{ocamldoccode}\n" ;
Code (Printf.sprintf
"class type %s%s%s = "
(if ct.clt_virtual then "virtual " else "")
type_params
(Name.simple ct.clt_name)
)
]
in
self#latex_of_text fmt t;
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_class_type_label fmt ct;
self#latex_for_class_type_index fmt ct;
p fmt "@[<h 4>";
self#latex_of_class_type_kind fmt father ct.clt_kind;
self#latex_of_text fmt [Newline];
self#latex_of_info fmt ~block: true ct.clt_info;
p fmt "@]"
* Print the LaTeX code for the given class element .
method latex_of_class_element fmt class_name class_ele =
self#latex_of_text fmt [Newline];
match class_ele with
Class_attribute att -> self#latex_of_attribute fmt att
| Class_method met -> self#latex_of_method fmt met
| Class_comment t ->
match t with
| [] -> ()
| (Title (_,_,_)) :: _ -> self#latex_of_text fmt t
| _ -> self#latex_of_text fmt [ Title ((Name.depth class_name) + 2, None, t) ]
* Print the LaTeX code for the given module element .
method latex_of_module_element fmt module_name module_ele =
self#latex_of_text fmt [Newline];
match module_ele with
Element_module m -> self#latex_of_module fmt m
| Element_module_type mt -> self#latex_of_module_type fmt mt
| Element_included_module im -> self#latex_of_included_module fmt im
| Element_class c -> self#latex_of_class fmt c
| Element_class_type ct -> self#latex_of_class_type fmt ct
| Element_value v -> self#latex_of_value fmt v
| Element_type_extension te -> self#latex_of_type_extension module_name fmt te
| Element_exception e -> self#latex_of_exception fmt e
| Element_type t -> self#latex_of_type fmt t
| Element_module_comment t -> self#latex_of_text fmt t
* Generate the LaTeX code for the given list of inherited classes .
method generate_inheritance_info fmt inher_l =
let f inh =
match inh.ic_class with
None -> (* we can't make the reference *)
Newline ::
Code ("inherit "^inh.ic_name) ::
(match inh.ic_text with
None -> []
| Some t -> Newline :: t
)
| Some cct ->
let label =
match cct with
Cl _ -> self#class_label inh.ic_name
| Cltype _ -> self#class_type_label inh.ic_name
in
(* we can create the reference *)
Newline ::
Odoc_info.Code ("inherit "^inh.ic_name) ::
(Odoc_info.Latex (" ["^(self#make_ref label)^"]")) ::
(match inh.ic_text with
None -> []
| Some t -> Newline :: t
)
in
List.iter (self#latex_of_text fmt) (List.map f inher_l)
* Generate the LaTeX code for the inherited classes of the given class .
method generate_class_inheritance_info fmt cl =
let rec iter_kind k =
match k with
Class_structure ([], _) ->
()
| Class_structure (l, _) ->
self#generate_inheritance_info fmt l
| Class_constraint (k, _) ->
iter_kind k
| Class_apply _
| Class_constr _ ->
()
in
iter_kind cl.cl_kind
* Generate the LaTeX code for the inherited classes of the given class type .
method generate_class_type_inheritance_info fmt clt =
match clt.clt_kind with
Class_signature ([], _) ->
()
| Class_signature (l, _) ->
self#generate_inheritance_info fmt l
| Class_type _ ->
()
* Generate the LaTeX code for the given top module , in the given buffer .
method generate_for_top_module fmt m =
let (first_t, rest_t) = self#first_and_rest_of_info m.m_info in
let text =
let title =
if m.m_text_only then [Raw m.m_name]
else [ Raw (Odoc_messages.modul^" ") ; Code m.m_name ] in
let subtitle = match first_t with
| [] -> []
| t -> (Raw " : ") :: t in
[ Title (0, None, title @ subtitle ) ]
in
self#latex_of_text fmt text;
self#latex_for_module_label fmt m;
self#latex_for_module_index fmt m;
self#latex_of_text fmt rest_t ;
self#latex_of_text fmt [ Newline ] ;
if not m.m_text_only then ps fmt "\\ocamldocvspace{0.5cm}\n\n";
List.iter
(fun ele ->
self#latex_of_module_element fmt m.m_name ele;
ps fmt "\n\n"
)
(Module.module_elements ~trans: false m)
* Print the header of the TeX document .
method latex_header fmt module_list =
ps fmt "\\documentclass[11pt]{article} \n";
ps fmt "\\usepackage[latin1]{inputenc} \n";
ps fmt "\\usepackage[T1]{fontenc} \n";
ps fmt "\\usepackage{textcomp}\n";
ps fmt "\\usepackage{fullpage} \n";
ps fmt "\\usepackage{url} \n";
ps fmt "\\usepackage{ocamldoc}\n";
(
match !Global.title with
None -> ()
| Some s ->
ps fmt "\\title{";
ps fmt (self#escape s);
ps fmt "}\n"
);
ps fmt "\\begin{document}\n";
(match !Global.title with
None -> () |
Some _ -> ps fmt "\\maketitle\n"
);
if !Global.with_toc then ps fmt "\\tableofcontents\n";
(
let info = Odoc_info.apply_opt
(Odoc_info.info_of_comment_file module_list)
!Odoc_info.Global.intro_file
in
(match info with None -> () | Some _ -> ps fmt "\\vspace{0.2cm}");
self#latex_of_info fmt info;
(match info with None -> () | Some _ -> ps fmt "\n\n")
)
(** Generate the LaTeX style file, if it does not exist. *)
method generate_style_file =
try
let dir = Filename.dirname !Global.out_file in
let file = Filename.concat dir "ocamldoc.sty" in
if Sys.file_exists file then
Odoc_info.verbose (Odoc_messages.file_exists_dont_generate file)
else
(
let chanout = open_out file in
output_string chanout Odoc_latex_style.content ;
flush chanout ;
close_out chanout;
Odoc_info.verbose (Odoc_messages.file_generated file)
)
with
Sys_error s ->
prerr_endline s ;
incr Odoc_info.errors ;
* Generate the LaTeX file from a module list , in the { ! Odoc_info . Global.out_file } file .
method generate module_list =
self#generate_style_file ;
let main_file = !Global.out_file in
let dir = Filename.dirname main_file in
if !separate_files then
(
let f m =
try
let chanout =
open_out ((Filename.concat dir (Name.simple m.m_name))^".tex")
in
let fmt = Format.formatter_of_out_channel chanout in
self#generate_for_top_module fmt m ;
Format.pp_print_flush fmt ();
close_out chanout
with
Failure s
| Sys_error s ->
prerr_endline s ;
incr Odoc_info.errors
in
List.iter f module_list
);
try
let chanout = open_out main_file in
let fmt = Format.formatter_of_out_channel chanout in
if !Global.with_header then self#latex_header fmt module_list;
List.iter
(fun m ->
if !separate_files then
ps fmt ("\\input{"^((Name.simple m.m_name))^".tex}\n")
else
self#generate_for_top_module fmt m
)
module_list ;
if !Global.with_trailer then ps fmt "\\end{document}\n";
Format.pp_print_flush fmt ();
close_out chanout
with
Failure s
| Sys_error s ->
prerr_endline s ;
incr Odoc_info.errors
end
end
module type Latex_generator = module type of Generator
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/f54002470cc6ab780963cc81b11a85a820a40819/ocamldoc/odoc_latex.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Generation of LaTeX documentation.
* Generation of LaTeX code from text structures.
* Return latex code to make a section according to the given level,
and with the given latex code.
* Associations of strings to substitute in latex code.
* Escape the ['\'], ['{'] and ['}'] characters.
* Escape some characters for the code style.
* Make a correct latex label from a name.
* Make a correct label from a value name.
* Make a correct label from an attribute name.
* Make a correct label from a method name.
* Make a correct label from a class name.
* Make a correct label from a class type name.
* Make a correct label from a module name.
* Make a correct label from a module type name.
* Make a correct label from an extension name.
* Make a correct label from an exception name.
* Make a correct label from a type name.
* Make a correct label from a record field.
* Make a correct label from a variant constructor.
* Return latex code for the label of a given label.
* Return latex code for the ref to a given label.
* The method used to get a [text] from an optional info structure.
* Print LaTeX code for a description, except for the [i_params] field.
* Print LaTeX code for a value.
* Print LaTeX code for a class attribute.
* Print LaTeX code for a class method.
* Print LaTeX code for the parameters of a type.
* record printing method
* Print LaTeX code for a type.
FIXME ?
* Print LaTeX code for a type extension.
* Print LaTeX code for an exception.
TODO: modify when Module_with will be more detailed
TODO: what should we print?
TODO: print final type from typedtree
avoid a big gap if the kind is a constr
we can't make the reference
we can create the reference
* Generate the LaTeX style file, if it does not exist. | , projet Cristal , INRIA Rocquencourt
Copyright 2001 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Odoc_info
open Value
open Type
open Extension
open Exception
open Class
open Module
let separate_files = ref false
let latex_titles = ref [
0, "section" ;
1, "section" ;
2, "subsection" ;
3, "subsubsection" ;
4, "paragraph" ;
5, "subparagraph" ;
]
let latex_value_prefix = ref Odoc_messages.default_latex_value_prefix
let latex_type_prefix = ref Odoc_messages.default_latex_type_prefix
let latex_type_elt_prefix = ref Odoc_messages.default_latex_type_elt_prefix
let latex_extension_prefix = ref Odoc_messages.default_latex_extension_prefix
let latex_exception_prefix = ref Odoc_messages.default_latex_exception_prefix
let latex_module_prefix = ref Odoc_messages.default_latex_module_prefix
let latex_module_type_prefix = ref Odoc_messages.default_latex_module_type_prefix
let latex_class_prefix = ref Odoc_messages.default_latex_class_prefix
let latex_class_type_prefix = ref Odoc_messages.default_latex_class_type_prefix
let latex_attribute_prefix = ref Odoc_messages.default_latex_attribute_prefix
let latex_method_prefix = ref Odoc_messages.default_latex_method_prefix
let new_buf () = Buffer.create 1024
let new_fmt () =
let b = new_buf () in
let fmt = Format.formatter_of_buffer b in
(fmt,
fun () ->
Format.pp_print_flush fmt ();
let s = Buffer.contents b in
Buffer.reset b;
s
)
let p = Format.fprintf
let ps f s = Format.fprintf f "%s" s
let rec merge_codepre = function
[] -> []
| [e] -> [e]
| (CodePre s1) :: (CodePre s2) :: q ->
merge_codepre ((CodePre (s1^"\n"^s2)) :: q)
| e :: q ->
e :: (merge_codepre q)
let print_concat fmt sep f =
let rec iter = function
[] -> ()
| [c] -> f c
| c :: q ->
f c;
ps fmt sep;
iter q
in
iter
class text =
object (self)
method section_style level s =
try
let sec = List.assoc level !latex_titles in
"\\"^sec^"{"^s^"}\n"
with Not_found -> s
val subst_strings = List.map (fun (x, y) -> (Str.regexp x, y))
[
"\001", "\001\002";
"\\\\", "\001b";
"{", "\\\\{";
"}", "\\\\}";
"\\$", "\\\\$";
"\\^", "{\\\\textasciicircum}";
"%", "\\\\%";
"_", "\\\\_";
"~", "\\\\~{}";
"#", "{\\char35}";
"->", "$\\\\rightarrow$";
"<-", "$\\\\leftarrow$";
">=", "$\\\\geq$";
"<=", "$\\\\leq$";
">", "$>$";
"<", "$<$";
"=", "$=$";
"|", "{\\\\textbar}";
"\\.\\.\\.", "$\\\\ldots$";
"&", "\\\\&";
"\001b", "{\\\\char92}";
"\001\002", "\001";
]
val subst_strings_simple = List.map (fun (x, y) -> (Str.regexp x, y))
[
"\001", "\001\002";
"\\\\", "\001b";
"{", "\001l";
"}", "{\\\\char125}";
"'", "{\\\\textquotesingle}";
"`", "{\\\\textasciigrave}";
"\001b", "{\\\\char92}";
"\001l", "{\\\\char123}";
"\001\002", "\001";
]
val subst_strings_code = List.map (fun (x, y) -> (Str.regexp x, y))
[
"\001", "\001\002";
"\\\\", "\001b";
"{", "\001l";
"}", "{\\\\char125}";
"'", "{\\\\textquotesingle}";
"`", "{\\\\textasciigrave}";
"%", "\\\\%";
"_", "\\\\_";
"~", "{\\\\char126}";
"#", "{\\\\char35}";
"&", "\\\\&";
"\\$", "\\\\$";
"\\^", "{\\\\char94}";
"\001b", "{\\\\char92}";
"\001l", "{\\\\char123}";
"\001\002", "\001";
]
method subst l s =
List.fold_left (fun acc (re, st) -> Str.global_replace re st acc) s l
* Escape the strings which would clash with LaTeX syntax .
method escape s = self#subst subst_strings s
method escape_simple s = self#subst subst_strings_simple s
method escape_code s = self#subst subst_strings_code s
The following characters are forbidden in LaTeX :
\ { } $ & # ^ _ % ~ ! " @ | ( " to close the double quote )
The following characters are forbidden in LaTeX :
\ { } $ & # ^ _ % ~
So we will use characters not forbidden in if no _ = true .
\ { } $ & # ^ _ % ~ ! " @ | (" to close the double quote)
The following characters are forbidden in LaTeX \label:
\ { } $ & # ^ _ % ~
So we will use characters not forbidden in \index if no_ = true.
*)
method label ?(no_=true) name =
let len = String.length name in
let buf = Buffer.create len in
for i = 0 to len - 1 do
let (s_no_, s) =
match name.[i] with
'_' -> ("-underscore", "_")
| '~' -> ("-tilde", "~")
| '%' -> ("-percent", "%")
| '@' -> ("-at", "\"@")
| '!' -> ("-bang", "\"!")
| '|' -> ("-pipe", "\"|")
| '<' -> ("-lt", "<")
| '>' -> ("-gt", ">")
| '^' -> ("-exp", "^")
| '&' -> ("-ampersand", "&")
| '+' -> ("-plus", "+")
| '-' -> ("-minus", "-")
| '*' -> ("-star", "*")
| '/' -> ("-slash", "/")
| '$' -> ("-dollar", "$")
| '=' -> ("-equal", "=")
| ':' -> ("-colon", ":")
| c -> (String.make 1 c, String.make 1 c)
in
Buffer.add_string buf (if no_ then s_no_ else s)
done;
Buffer.contents buf
method value_label ?no_ name = !latex_value_prefix^(self#label ?no_ name)
method attribute_label ?no_ name = !latex_attribute_prefix^(self#label ?no_ name)
method method_label ?no_ name = !latex_method_prefix^(self#label ?no_ name)
method class_label ?no_ name = !latex_class_prefix^(self#label ?no_ name)
method class_type_label ?no_ name = !latex_class_type_prefix^(self#label ?no_ name)
method module_label ?no_ name = !latex_module_prefix^(self#label ?no_ name)
method module_type_label ?no_ name = !latex_module_type_prefix^(self#label ?no_ name)
method extension_label ?no_ name = !latex_extension_prefix^(self#label ?no_ name)
method exception_label ?no_ name = !latex_exception_prefix^(self#label ?no_ name)
method type_label ?no_ name = !latex_type_prefix^(self#label ?no_ name)
method recfield_label ?no_ name = !latex_type_elt_prefix^(self#label ?no_ name)
method const_label ?no_ name = !latex_type_elt_prefix^(self#label ?no_ name)
method make_label label = "\\label{"^label^"}"
method make_ref label = "\\ref{"^label^"}"
* Print the LaTeX code corresponding to the [ text ] parameter .
method latex_of_text fmt t =
List.iter (self#latex_of_text_element fmt) t
* Print the LaTeX code for the [ text_element ] in parameter .
method latex_of_text_element fmt txt =
match txt with
| Odoc_info.Raw s -> self#latex_of_Raw fmt s
| Odoc_info.Code s -> self#latex_of_Code fmt s
| Odoc_info.CodePre s -> self#latex_of_CodePre fmt s
| Odoc_info.Verbatim s -> self#latex_of_Verbatim fmt s
| Odoc_info.Bold t -> self#latex_of_Bold fmt t
| Odoc_info.Italic t -> self#latex_of_Italic fmt t
| Odoc_info.Emphasize t -> self#latex_of_Emphasize fmt t
| Odoc_info.Center t -> self#latex_of_Center fmt t
| Odoc_info.Left t -> self#latex_of_Left fmt t
| Odoc_info.Right t -> self#latex_of_Right fmt t
| Odoc_info.List tl -> self#latex_of_List fmt tl
| Odoc_info.Enum tl -> self#latex_of_Enum fmt tl
| Odoc_info.Newline -> self#latex_of_Newline fmt
| Odoc_info.Block t -> self#latex_of_Block fmt t
| Odoc_info.Title (n, l_opt, t) -> self#latex_of_Title fmt n l_opt t
| Odoc_info.Latex s -> self#latex_of_Latex fmt s
| Odoc_info.Link (s, t) -> self#latex_of_Link fmt s t
| Odoc_info.Ref (name, ref_opt, text_opt) ->
self#latex_of_Ref fmt name ref_opt text_opt
| Odoc_info.Superscript t -> self#latex_of_Superscript fmt t
| Odoc_info.Subscript t -> self#latex_of_Subscript fmt t
| Odoc_info.Module_list _ -> ()
| Odoc_info.Index_list -> ()
| Odoc_info.Custom (s,t) -> self#latex_of_custom_text fmt s t
| Odoc_info.Target (target, code) -> self#latex_of_Target fmt ~target ~code
method latex_of_custom_text _ _ _ = ()
method latex_of_Target fmt ~target ~code =
if String.lowercase_ascii target = "latex" then
self#latex_of_Latex fmt code
else
()
method latex_of_Raw fmt s =
ps fmt (self#escape s)
method latex_of_Code fmt s =
let s2 = self#escape_code s in
let s3 = Str.global_replace (Str.regexp "\n") ("\\\\\n") s2 in
p fmt "{\\tt{%s}}" s3
method latex_of_CodePre fmt s =
ps fmt "\\begin{ocamldoccode}\n";
ps fmt (self#escape_simple s);
ps fmt "\n\\end{ocamldoccode}\n"
method latex_of_Verbatim fmt s =
ps fmt "\n\\begin{verbatim}\n";
ps fmt s;
ps fmt "\n\\end{verbatim}\n"
method latex_of_Bold fmt t =
ps fmt "{\\bf ";
self#latex_of_text fmt t;
ps fmt "}"
method latex_of_Italic fmt t =
ps fmt "{\\it ";
self#latex_of_text fmt t;
ps fmt "}"
method latex_of_Emphasize fmt t =
ps fmt "{\\em ";
self#latex_of_text fmt t;
ps fmt "}"
method latex_of_Center fmt t =
ps fmt "\\begin{center}\n";
self#latex_of_text fmt t;
ps fmt "\\end{center}\n"
method latex_of_Left fmt t =
ps fmt "\\begin{flushleft}\n";
self#latex_of_text fmt t;
ps fmt "\\end{flushleft}\n"
method latex_of_Right fmt t =
ps fmt "\\begin{flushright}\n";
self#latex_of_text fmt t;
ps fmt "\\end{flushright}\n"
method latex_of_List fmt tl =
ps fmt "\\begin{itemize}\n";
List.iter
(fun t ->
ps fmt "\\item ";
self#latex_of_text fmt t;
ps fmt "\n"
)
tl;
ps fmt "\\end{itemize}\n"
method latex_of_Enum fmt tl =
ps fmt "\\begin{enumerate}\n";
List.iter
(fun t ->
ps fmt "\\item ";
self#latex_of_text fmt t;
ps fmt "\n"
)
tl;
ps fmt "\\end{enumerate}\n"
method latex_of_Newline fmt = ps fmt "\n\n"
method latex_of_Block fmt t =
ps fmt "\\begin{ocamldocdescription}\n";
self#latex_of_text fmt t;
ps fmt "\n\\end{ocamldocdescription}\n"
method latex_of_Title fmt n label_opt t =
let (fmt2, flush) = new_fmt () in
self#latex_of_text fmt2 t;
let s_title2 = self#section_style n (flush ()) in
ps fmt s_title2;
(
match label_opt with
None -> ()
| Some l ->
ps fmt (self#make_label (self#label ~no_: false l))
)
method latex_of_Latex fmt s = ps fmt s
method latex_of_Link fmt s t =
self#latex_of_text fmt t ;
ps fmt "[\\url{";
ps fmt s ;
ps fmt "}]"
method latex_of_Ref fmt name ref_opt text_opt =
match ref_opt with
None ->
self#latex_of_text fmt
(match text_opt with
None ->
[Odoc_info.Code (Odoc_info.use_hidden_modules name)]
| Some t -> t
)
| Some (RK_section _) ->
let text = match text_opt with
| None -> []
| Some x -> x in
let label= self#make_ref (self#label ~no_:false (Name.simple name)) in
self#latex_of_text fmt
(text @ [Latex ("["^label^"]")] )
| Some kind ->
let f_label =
match kind with
Odoc_info.RK_module -> self#module_label
| Odoc_info.RK_module_type -> self#module_type_label
| Odoc_info.RK_class -> self#class_label
| Odoc_info.RK_class_type -> self#class_type_label
| Odoc_info.RK_value -> self#value_label
| Odoc_info.RK_type -> self#type_label
| Odoc_info.RK_extension -> self#extension_label
| Odoc_info.RK_exception -> self#exception_label
| Odoc_info.RK_attribute -> self#attribute_label
| Odoc_info.RK_method -> self#method_label
| Odoc_info.RK_section _ -> assert false
| Odoc_info.RK_recfield -> self#recfield_label
| Odoc_info.RK_const -> self#const_label
in
let text =
match text_opt with
None -> [Odoc_info.Code (Odoc_info.use_hidden_modules name)]
| Some t -> t
in
self#latex_of_text fmt
(text @ [Latex ("["^(self#make_ref (f_label name))^"]")])
method latex_of_Superscript fmt t =
ps fmt "$^{";
self#latex_of_text fmt t;
ps fmt "}$"
method latex_of_Subscript fmt t =
ps fmt "$_{";
self#latex_of_text fmt t;
ps fmt "}$"
end
* A class used to generate LaTeX code for info structures .
class virtual info =
object (self)
* The method used to get LaTeX code from a [ text ] .
method virtual latex_of_text : Format.formatter -> Odoc_info.text -> unit
method virtual text_of_info : ?block: bool -> Odoc_info.info option -> Odoc_info.text
method latex_of_info fmt ?(block=false) info_opt =
self#latex_of_text fmt
(self#text_of_info ~block info_opt)
end
module Generator =
struct
* This class is used to create objects which can generate a simple LaTeX documentation .
class latex =
object (self)
inherit text
inherit Odoc_to_text.to_text as to_text
inherit info
* Get the first sentence and the rest of a description ,
from an optional [ info ] structure . The first sentence
can be empty if it would not appear right in a title .
In the first sentence , the titles and lists has been removed ,
since it is used in LaTeX titles and would make LaTeX complain
if we has two nested \section commands .
from an optional [info] structure. The first sentence
can be empty if it would not appear right in a title.
In the first sentence, the titles and lists has been removed,
since it is used in LaTeX titles and would make LaTeX complain
if we has two nested \section commands.
*)
method first_and_rest_of_info i_opt =
match i_opt with
None -> ([], [])
| Some i ->
match i.Odoc_info.i_desc with
None -> ([], self#text_of_info ~block: true i_opt)
| Some t ->
let (first,_) = Odoc_info.first_sentence_and_rest_of_text t in
let (_, rest) = Odoc_info.first_sentence_and_rest_of_text (self#text_of_info ~block: false i_opt) in
(Odoc_info.text_no_title_no_list first, rest)
method latex_of_value fmt v =
Odoc_info.reset_type_names () ;
let label = self#value_label v.val_name in
let latex = self#make_label label in
self#latex_of_text fmt
((Latex latex) ::
(to_text#text_of_value v))
method latex_of_attribute fmt a =
self#latex_of_text fmt
((Latex (self#make_label (self#attribute_label a.att_value.val_name))) ::
(to_text#text_of_attribute a))
method latex_of_method fmt m =
self#latex_of_text fmt
((Latex (self#make_label (self#method_label m.met_value.val_name))) ::
(to_text#text_of_method m))
method latex_of_type_params fmt m_name t =
let print_one (p, co, cn) =
ps fmt (Odoc_info.string_of_variance t (co,cn));
ps fmt (self#normal_type m_name p)
in
match t.ty_parameters with
[] -> ()
| [(p,co,cn)] -> print_one (p, co, cn)
| _ ->
ps fmt "(";
print_concat fmt ", " print_one t.ty_parameters;
ps fmt ")"
method latex_of_class_parameter_list fmt father c =
self#latex_of_text fmt
(self#text_of_class_params father c)
method entry_comment (fmt,flush) = function
| None -> []
| Some t ->
let s =
ps fmt "\\begin{ocamldoccomment}\n";
self#latex_of_info fmt (Some t);
ps fmt "\n\\end{ocamldoccomment}\n";
flush ()
in
[ Latex s]
method latex_of_record ( (fmt,flush) as f) mod_name l =
p fmt "{";
let fields =
List.map (fun r ->
let s_field =
p fmt
"@[<h 6> %s%s :@ %s ;"
(if r.rf_mutable then "mutable " else "")
r.rf_name
(self#normal_type mod_name r.rf_type);
flush ()
in
[ CodePre s_field ] @ (self#entry_comment f r.rf_text)
) l in
List.flatten fields @ [ CodePre "}" ]
method latex_of_cstr_args ( (fmt,flush) as f) mod_name (args, ret) =
match args, ret with
| Cstr_tuple [], None -> [CodePre(flush())]
| Cstr_tuple _ as l, None ->
p fmt " of@ %s"
(self#normal_cstr_args ~par:false mod_name l);
[CodePre (flush())]
| Cstr_tuple t as l, Some r ->
let res = self#normal_type mod_name r in
if t = [] then
p fmt " :@ %s" res
else
p fmt " :@ %s -> %s" (self#normal_cstr_args ~par:false mod_name l) res
;
[CodePre (flush())]
| Cstr_record l, None ->
p fmt " of@ ";
self#latex_of_record f mod_name l
| Cstr_record r, Some res ->
let l =
p fmt " :@ ";
self#latex_of_record f mod_name r in
let l2 =
p fmt "@ %s@ %s" "->"
(self#normal_type mod_name res);
[CodePre (flush())] in
l @ l2
method latex_of_type fmt t =
let s_name = Name.simple t.ty_name in
let text =
let ( (fmt2, flush2) as f) = new_fmt () in
Odoc_info.reset_type_names () ;
let mod_name = Name.father t.ty_name in
Format.fprintf fmt2 "@[<h 2>type ";
self#latex_of_type_params fmt2 mod_name t;
(match t.ty_parameters with [] -> () | _ -> ps fmt2 " ");
ps fmt2 s_name;
let priv = t.ty_private = Asttypes.Private in
(
match t.ty_manifest with
| Some (Other typ) ->
p fmt2 " = %s%s" (if priv then "private " else "") (self#normal_type mod_name typ)
| _ -> ()
);
let s_type3 =
p fmt2
" %s"
(
match t.ty_kind with
Type_abstract ->
begin match t.ty_manifest with
| Some (Object_type _) ->
"= " ^ (if priv then "private" else "") ^ " <"
| _ -> ""
end
| Type_variant _ -> "="^(if priv then " private" else "")
| Type_record _ -> "= "^(if priv then "private " else "")
| Type_open -> "= .."
) ;
flush2 ()
in
let defs =
match t.ty_kind with
| Type_abstract ->
begin match t.ty_manifest with
| Some (Object_type l) ->
let fields =
List.map (fun r ->
let s_field =
p fmt2
"@[<h 6> %s :@ %s ;"
r.of_name
(self#normal_type mod_name r.of_type);
flush2 ()
in
[ CodePre s_field ] @ (self#entry_comment f r.of_text)
) l
in
List.flatten fields @ [ CodePre ">" ]
| None | Some (Other _) -> []
end
| Type_variant l ->
if l = [] then (p fmt2 "@[<h 6> |"; [CodePre (flush2())]) else (
let constructors =
List.map (fun {vc_name; vc_args; vc_ret; vc_text} ->
p fmt2 "@[<h 6> | %s" vc_name ;
let l = self#latex_of_cstr_args f mod_name (vc_args,vc_ret) in
l @ (self#entry_comment f vc_text) ) l
in
List.flatten constructors)
| Type_record l ->
self#latex_of_record f mod_name l
| Type_open ->
[]
in
let defs2 = (CodePre s_type3) :: defs in
(merge_codepre defs2) @
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")] @
(self#text_of_info t.ty_info)
in
self#latex_of_text fmt
((Latex (self#make_label (self#type_label t.ty_name))) :: text)
method latex_of_type_extension mod_name fmt te =
let text =
let (fmt2, flush2) as f = new_fmt () in
Odoc_info.reset_type_names () ;
Format.fprintf fmt2 "@[<h 2>type ";
(
match te.te_type_parameters with
[] -> ()
| [p] ->
ps fmt2 (self#normal_type mod_name p);
ps fmt2 " "
| l ->
ps fmt2 "(";
print_concat fmt2 ", " (fun p -> ps fmt2 (self#normal_type mod_name p)) l;
ps fmt2 ") "
);
ps fmt2 (self#relative_idents mod_name te.te_type_name);
p fmt2 " +=%s" (if te.te_private = Asttypes.Private then " private" else "") ;
let s_type3 = flush2 () in
let defs =
(List.flatten
(List.map
(fun x ->
let father = Name.father x.xt_name in
p fmt2 "@[<h 6> | %s" (Name.simple x.xt_name);
let l = self#latex_of_cstr_args f father (x.xt_args, x.xt_ret) in
let c =
match x.xt_alias with
| None -> []
| Some xa ->
p fmt2 " = %s"
(
match xa.xa_xt with
| None -> xa.xa_name
| Some x -> x.xt_name
);
[CodePre (flush2 ())]
in
Latex (self#make_label (self#extension_label x.xt_name)) :: l @ c
@ (match x.xt_text with
None -> []
| Some t ->
let s =
ps fmt2 "\\begin{ocamldoccomment}\n";
self#latex_of_info fmt2 (Some t);
ps fmt2 "\n\\end{ocamldoccomment}\n";
flush2 ()
in
[ Latex s]
)
)
te.te_constructors
)
)
in
let defs2 = (CodePre s_type3) :: defs in
(merge_codepre defs2) @
(self#text_of_info te.te_info)
in
self#latex_of_text fmt text
method latex_of_exception fmt e =
let text =
let (fmt2, flush2) as f = new_fmt() in
Odoc_info.reset_type_names () ;
let s_name = Name.simple e.ex_name in
let father = Name.father e.ex_name in
p fmt2 "@[<hov 2>exception %s" s_name;
let l = self#latex_of_cstr_args f father (e.ex_args, e.ex_ret) in
let s =
match e.ex_alias with
None -> []
| Some ea ->
Format.fprintf fmt " = %s"
(
match ea.ea_ex with
None -> ea.ea_name
| Some e -> e.ex_name
);
[CodePre (flush2 ())]
in
Latex ( self#make_label (self#exception_label e.ex_name) ) ::
merge_codepre (l @ s ) @
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^(self#label ~no_:false s_name)^"`}\n")]
@ (self#text_of_info e.ex_info) in
self#latex_of_text fmt text
method latex_of_module_parameter fmt m_name p =
self#latex_of_text fmt
[
Code "functor (";
Code p.mp_name ;
Code " : ";
] ;
self#latex_of_module_type_kind fmt m_name p.mp_kind;
self#latex_of_text fmt [ Code ") -> "]
method latex_of_module_type_kind fmt father kind =
match kind with
Module_type_struct eles ->
self#latex_of_text fmt [Latex "\\begin{ocamldocsigend}\n"];
List.iter (self#latex_of_module_element fmt father) eles;
self#latex_of_text fmt [Latex "\\end{ocamldocsigend}\n"]
| Module_type_functor (p, k) ->
self#latex_of_module_parameter fmt father p;
self#latex_of_module_type_kind fmt father k
| Module_type_alias a ->
self#latex_of_text fmt
[Code (self#relative_module_idents father a.mta_name)]
| Module_type_with (k, s) ->
self#latex_of_module_type_kind fmt father k;
self#latex_of_text fmt
[ Code " ";
Code (self#relative_idents father s);
]
| Module_type_typeof s ->
self#latex_of_text fmt
[ Code "module type of ";
Code (self#relative_idents father s);
]
method latex_of_module_kind fmt father kind =
match kind with
Module_struct eles ->
self#latex_of_text fmt [Latex "\\begin{ocamldocsigend}\n"];
List.iter (self#latex_of_module_element fmt father) eles;
self#latex_of_text fmt [Latex "\\end{ocamldocsigend}\n"]
| Module_alias a ->
self#latex_of_text fmt
[Code (self#relative_module_idents father a.ma_name)]
| Module_functor (p, k) ->
self#latex_of_module_parameter fmt father p;
self#latex_of_module_kind fmt father k
| Module_apply (k1, k2) ->
TODO : application is not correct in a .mli .
Fix ? - > print the typedtree module_type
Fix? -> print the typedtree module_type *)
self#latex_of_module_kind fmt father k1;
self#latex_of_text fmt [Code "("];
self#latex_of_module_kind fmt father k2;
self#latex_of_text fmt [Code ")"]
| Module_with (k, s) ->
self#latex_of_module_type_kind fmt father k;
self#latex_of_text fmt
[ Code " ";
Code (self#relative_idents father s) ;
]
| Module_constraint (k, _tk) ->
self#latex_of_module_kind fmt father k
| Module_typeof s ->
self#latex_of_text fmt
[ Code "module type of ";
Code (self#relative_idents father s);
]
| Module_unpack (s, _) ->
self#latex_of_text fmt
[
Code (self#relative_idents father s);
]
method latex_of_class_kind fmt father kind =
match kind with
Class_structure (inh, eles) ->
self#latex_of_text fmt [Latex "\\begin{ocamldocobjectend}\n"];
self#generate_inheritance_info fmt inh;
List.iter (self#latex_of_class_element fmt father) eles;
self#latex_of_text fmt [Latex "\\end{ocamldocobjectend}\n"]
| Class_apply _ ->
self#latex_of_text fmt [Raw "class application not handled yet"]
| Class_constr cco ->
(
match cco.cco_type_parameters with
[] -> ()
| l ->
self#latex_of_text fmt
(
Code "[" ::
(self#text_of_class_type_param_expr_list father l) @
[Code "] "]
)
);
self#latex_of_text fmt
[Code (self#relative_idents father cco.cco_name)]
| Class_constraint (ck, ctk) ->
self#latex_of_text fmt [Code "( "] ;
self#latex_of_class_kind fmt father ck;
self#latex_of_text fmt [Code " : "] ;
self#latex_of_class_type_kind fmt father ctk;
self#latex_of_text fmt [Code " )"]
method latex_of_class_type_kind fmt father kind =
match kind with
Class_type cta ->
(
match cta.cta_type_parameters with
[] -> ()
| l ->
self#latex_of_text fmt
(Code "[" ::
(self#text_of_class_type_param_expr_list father l) @
[Code "] "]
)
);
self#latex_of_text fmt
[Code (self#relative_idents father cta.cta_name)]
| Class_signature (inh, eles) ->
self#latex_of_text fmt [Latex "\\begin{ocamldocobjectend}\n"];
self#generate_inheritance_info fmt inh;
List.iter (self#latex_of_class_element fmt father) eles;
self#latex_of_text fmt [Latex "\\end{ocamldocobjectend}\n"]
method latex_for_module_index fmt m =
let s_name = Name.simple m.m_name in
self#latex_of_text fmt
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
(self#label ~no_:false s_name)^"`}\n"
)
]
method latex_for_module_type_index fmt mt =
let s_name = Name.simple mt.mt_name in
self#latex_of_text fmt
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
(self#label ~no_:false (Name.simple s_name))^"`}\n"
)
]
method latex_for_module_label fmt m =
ps fmt (self#make_label (self#module_label m.m_name))
method latex_for_module_type_label fmt mt =
ps fmt (self#make_label (self#module_type_label mt.mt_name))
method latex_for_class_index fmt c =
let s_name = Name.simple c.cl_name in
self#latex_of_text fmt
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
(self#label ~no_:false s_name)^"`}\n"
)
]
method latex_for_class_type_index fmt ct =
let s_name = Name.simple ct.clt_name in
self#latex_of_text fmt
[Latex ("\\index{"^(self#label s_name)^"@\\verb`"^
(self#label ~no_:false s_name)^"`}\n"
)
]
method latex_for_class_label fmt c =
ps fmt (self#make_label (self#class_label c.cl_name))
method latex_for_class_type_label fmt ct =
ps fmt (self#make_label (self#class_type_label ct.clt_name))
* Print the LaTeX code for the given module .
method latex_of_module fmt m =
let father = Name.father m.m_name in
let t =
[
Latex "\\begin{ocamldoccode}\n" ;
Code "module ";
Code (Name.simple m.m_name);
Code " : ";
]
in
self#latex_of_text fmt t;
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_module_label fmt m;
self#latex_for_module_index fmt m;
p fmt "@[<h 4>";
self#latex_of_module_kind fmt father m.m_kind;
(
match Module.module_is_functor m with
false -> ()
| true ->
self#latex_of_text fmt [Newline];
(
match List.filter (fun (_,d) -> d <> None)
(module_parameters ~trans: false m)
with
[] -> ()
| l ->
let t =
[ Bold [Raw "Parameters: "];
List
(List.map
(fun (p,text_opt) ->
let t = match text_opt with None -> [] | Some t -> t in
( Raw p.mp_name :: Raw ": " :: t)
)
l
)
]
in
self#latex_of_text fmt t
);
);
self#latex_of_text fmt [Newline];
self#latex_of_info fmt ~block: true m.m_info;
p fmt "@]";
* Print the LaTeX code for the given module type .
method latex_of_module_type fmt mt =
let father = Name.father mt.mt_name in
let t =
[
Latex "\\begin{ocamldoccode}\n" ;
Code "module type " ;
Code (Name.simple mt.mt_name);
]
in
self#latex_of_text fmt t;
(
match mt.mt_type, mt.mt_kind with
| Some _, Some kind ->
self#latex_of_text fmt [ Code " = " ];
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_module_type_label fmt mt;
self#latex_for_module_type_index fmt mt;
p fmt "@[<h 4>";
self#latex_of_module_type_kind fmt father kind
| _ ->
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_module_type_index fmt mt;
p fmt "@[<h 4>";
);
(
match Module.module_type_is_functor mt with
false -> ()
| true ->
self#latex_of_text fmt [Newline];
(
match List.filter (fun (_,d) -> d <> None)
(module_type_parameters ~trans: false mt)
with
[] -> ()
| l ->
let t =
[ Bold [Raw "Parameters: "];
List
(List.map
(fun (p,text_opt) ->
let t = match text_opt with None -> [] | Some t -> t in
( Raw p.mp_name :: Raw ": " :: t)
)
l
)
]
in
self#latex_of_text fmt t
);
);
self#latex_of_text fmt [Newline];
self#latex_of_info fmt ~block: true mt.mt_info;
p fmt "@]";
* Print the LaTeX code for the given included module .
method latex_of_included_module fmt im =
self#latex_of_text fmt
((Code "include ") ::
(Code
(match im.im_module with
None -> im.im_name
| Some (Mod m) -> m.m_name
| Some (Modtype mt) -> mt.mt_name)
) ::
(self#text_of_info im.im_info)
)
* Print the LaTeX code for the given class .
method latex_of_class fmt c =
Odoc_info.reset_type_names () ;
let father = Name.father c.cl_name in
let type_params =
match c.cl_type_parameters with
[] -> ""
| l -> (self#normal_class_type_param_list father l)^" "
in
let t =
[
Latex "\\begin{ocamldoccode}\n" ;
Code (Printf.sprintf
"class %s%s%s : "
(if c.cl_virtual then "virtual " else "")
type_params
(Name.simple c.cl_name)
)
]
in
self#latex_of_text fmt t;
self#latex_of_class_parameter_list fmt father c;
(
match c.cl_kind with
Class.Class_constr _ ->
self#latex_of_class_kind fmt father c.cl_kind
| _ ->
()
);
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_class_label fmt c;
self#latex_for_class_index fmt c;
p fmt "@[<h 4>";
(match c.cl_kind with
Class.Class_constr _ -> ()
| _ -> self#latex_of_class_kind fmt father c.cl_kind
);
self#latex_of_text fmt [Newline];
self#latex_of_info fmt ~block: true c.cl_info;
p fmt "@]"
* Print the LaTeX code for the given class type .
method latex_of_class_type fmt ct =
Odoc_info.reset_type_names () ;
let father = Name.father ct.clt_name in
let type_params =
match ct.clt_type_parameters with
[] -> ""
| l -> (self#normal_class_type_param_list father l)^" "
in
let t =
[
Latex "\\begin{ocamldoccode}\n" ;
Code (Printf.sprintf
"class type %s%s%s = "
(if ct.clt_virtual then "virtual " else "")
type_params
(Name.simple ct.clt_name)
)
]
in
self#latex_of_text fmt t;
self#latex_of_text fmt [ Latex "\\end{ocamldoccode}\n" ];
self#latex_for_class_type_label fmt ct;
self#latex_for_class_type_index fmt ct;
p fmt "@[<h 4>";
self#latex_of_class_type_kind fmt father ct.clt_kind;
self#latex_of_text fmt [Newline];
self#latex_of_info fmt ~block: true ct.clt_info;
p fmt "@]"
* Print the LaTeX code for the given class element .
method latex_of_class_element fmt class_name class_ele =
self#latex_of_text fmt [Newline];
match class_ele with
Class_attribute att -> self#latex_of_attribute fmt att
| Class_method met -> self#latex_of_method fmt met
| Class_comment t ->
match t with
| [] -> ()
| (Title (_,_,_)) :: _ -> self#latex_of_text fmt t
| _ -> self#latex_of_text fmt [ Title ((Name.depth class_name) + 2, None, t) ]
* Print the LaTeX code for the given module element .
method latex_of_module_element fmt module_name module_ele =
self#latex_of_text fmt [Newline];
match module_ele with
Element_module m -> self#latex_of_module fmt m
| Element_module_type mt -> self#latex_of_module_type fmt mt
| Element_included_module im -> self#latex_of_included_module fmt im
| Element_class c -> self#latex_of_class fmt c
| Element_class_type ct -> self#latex_of_class_type fmt ct
| Element_value v -> self#latex_of_value fmt v
| Element_type_extension te -> self#latex_of_type_extension module_name fmt te
| Element_exception e -> self#latex_of_exception fmt e
| Element_type t -> self#latex_of_type fmt t
| Element_module_comment t -> self#latex_of_text fmt t
* Generate the LaTeX code for the given list of inherited classes .
method generate_inheritance_info fmt inher_l =
let f inh =
match inh.ic_class with
Newline ::
Code ("inherit "^inh.ic_name) ::
(match inh.ic_text with
None -> []
| Some t -> Newline :: t
)
| Some cct ->
let label =
match cct with
Cl _ -> self#class_label inh.ic_name
| Cltype _ -> self#class_type_label inh.ic_name
in
Newline ::
Odoc_info.Code ("inherit "^inh.ic_name) ::
(Odoc_info.Latex (" ["^(self#make_ref label)^"]")) ::
(match inh.ic_text with
None -> []
| Some t -> Newline :: t
)
in
List.iter (self#latex_of_text fmt) (List.map f inher_l)
* Generate the LaTeX code for the inherited classes of the given class .
method generate_class_inheritance_info fmt cl =
let rec iter_kind k =
match k with
Class_structure ([], _) ->
()
| Class_structure (l, _) ->
self#generate_inheritance_info fmt l
| Class_constraint (k, _) ->
iter_kind k
| Class_apply _
| Class_constr _ ->
()
in
iter_kind cl.cl_kind
* Generate the LaTeX code for the inherited classes of the given class type .
method generate_class_type_inheritance_info fmt clt =
match clt.clt_kind with
Class_signature ([], _) ->
()
| Class_signature (l, _) ->
self#generate_inheritance_info fmt l
| Class_type _ ->
()
* Generate the LaTeX code for the given top module , in the given buffer .
method generate_for_top_module fmt m =
let (first_t, rest_t) = self#first_and_rest_of_info m.m_info in
let text =
let title =
if m.m_text_only then [Raw m.m_name]
else [ Raw (Odoc_messages.modul^" ") ; Code m.m_name ] in
let subtitle = match first_t with
| [] -> []
| t -> (Raw " : ") :: t in
[ Title (0, None, title @ subtitle ) ]
in
self#latex_of_text fmt text;
self#latex_for_module_label fmt m;
self#latex_for_module_index fmt m;
self#latex_of_text fmt rest_t ;
self#latex_of_text fmt [ Newline ] ;
if not m.m_text_only then ps fmt "\\ocamldocvspace{0.5cm}\n\n";
List.iter
(fun ele ->
self#latex_of_module_element fmt m.m_name ele;
ps fmt "\n\n"
)
(Module.module_elements ~trans: false m)
* Print the header of the TeX document .
method latex_header fmt module_list =
ps fmt "\\documentclass[11pt]{article} \n";
ps fmt "\\usepackage[latin1]{inputenc} \n";
ps fmt "\\usepackage[T1]{fontenc} \n";
ps fmt "\\usepackage{textcomp}\n";
ps fmt "\\usepackage{fullpage} \n";
ps fmt "\\usepackage{url} \n";
ps fmt "\\usepackage{ocamldoc}\n";
(
match !Global.title with
None -> ()
| Some s ->
ps fmt "\\title{";
ps fmt (self#escape s);
ps fmt "}\n"
);
ps fmt "\\begin{document}\n";
(match !Global.title with
None -> () |
Some _ -> ps fmt "\\maketitle\n"
);
if !Global.with_toc then ps fmt "\\tableofcontents\n";
(
let info = Odoc_info.apply_opt
(Odoc_info.info_of_comment_file module_list)
!Odoc_info.Global.intro_file
in
(match info with None -> () | Some _ -> ps fmt "\\vspace{0.2cm}");
self#latex_of_info fmt info;
(match info with None -> () | Some _ -> ps fmt "\n\n")
)
method generate_style_file =
try
let dir = Filename.dirname !Global.out_file in
let file = Filename.concat dir "ocamldoc.sty" in
if Sys.file_exists file then
Odoc_info.verbose (Odoc_messages.file_exists_dont_generate file)
else
(
let chanout = open_out file in
output_string chanout Odoc_latex_style.content ;
flush chanout ;
close_out chanout;
Odoc_info.verbose (Odoc_messages.file_generated file)
)
with
Sys_error s ->
prerr_endline s ;
incr Odoc_info.errors ;
* Generate the LaTeX file from a module list , in the { ! Odoc_info . Global.out_file } file .
method generate module_list =
self#generate_style_file ;
let main_file = !Global.out_file in
let dir = Filename.dirname main_file in
if !separate_files then
(
let f m =
try
let chanout =
open_out ((Filename.concat dir (Name.simple m.m_name))^".tex")
in
let fmt = Format.formatter_of_out_channel chanout in
self#generate_for_top_module fmt m ;
Format.pp_print_flush fmt ();
close_out chanout
with
Failure s
| Sys_error s ->
prerr_endline s ;
incr Odoc_info.errors
in
List.iter f module_list
);
try
let chanout = open_out main_file in
let fmt = Format.formatter_of_out_channel chanout in
if !Global.with_header then self#latex_header fmt module_list;
List.iter
(fun m ->
if !separate_files then
ps fmt ("\\input{"^((Name.simple m.m_name))^".tex}\n")
else
self#generate_for_top_module fmt m
)
module_list ;
if !Global.with_trailer then ps fmt "\\end{document}\n";
Format.pp_print_flush fmt ();
close_out chanout
with
Failure s
| Sys_error s ->
prerr_endline s ;
incr Odoc_info.errors
end
end
module type Latex_generator = module type of Generator
|
6d8e0f51724ed473034f2fe4b91b75b2963cc6c33ab7e467b06e891e6ebe7737 | imandra-ai/ocaml-opentelemetry | logs_types.mli | (** logs.proto Types *)
(** {2 Types} *)
type severity_number =
| Severity_number_unspecified
| Severity_number_trace
| Severity_number_trace2
| Severity_number_trace3
| Severity_number_trace4
| Severity_number_debug
| Severity_number_debug2
| Severity_number_debug3
| Severity_number_debug4
| Severity_number_info
| Severity_number_info2
| Severity_number_info3
| Severity_number_info4
| Severity_number_warn
| Severity_number_warn2
| Severity_number_warn3
| Severity_number_warn4
| Severity_number_error
| Severity_number_error2
| Severity_number_error3
| Severity_number_error4
| Severity_number_fatal
| Severity_number_fatal2
| Severity_number_fatal3
| Severity_number_fatal4
type log_record = {
time_unix_nano : int64;
observed_time_unix_nano : int64;
severity_number : severity_number;
severity_text : string;
body : Common_types.any_value option;
attributes : Common_types.key_value list;
dropped_attributes_count : int32;
flags : int32;
trace_id : bytes;
span_id : bytes;
}
type scope_logs = {
scope : Common_types.instrumentation_scope option;
log_records : log_record list;
schema_url : string;
}
type resource_logs = {
resource : Resource_types.resource option;
scope_logs : scope_logs list;
schema_url : string;
}
type logs_data = {
resource_logs : resource_logs list;
}
type log_record_flags =
| Log_record_flag_unspecified
| Log_record_flag_trace_flags_mask
* { 2 Default values }
val default_severity_number : unit -> severity_number
(** [default_severity_number ()] is the default value for type [severity_number] *)
val default_log_record :
?time_unix_nano:int64 ->
?observed_time_unix_nano:int64 ->
?severity_number:severity_number ->
?severity_text:string ->
?body:Common_types.any_value option ->
?attributes:Common_types.key_value list ->
?dropped_attributes_count:int32 ->
?flags:int32 ->
?trace_id:bytes ->
?span_id:bytes ->
unit ->
log_record
(** [default_log_record ()] is the default value for type [log_record] *)
val default_scope_logs :
?scope:Common_types.instrumentation_scope option ->
?log_records:log_record list ->
?schema_url:string ->
unit ->
scope_logs
(** [default_scope_logs ()] is the default value for type [scope_logs] *)
val default_resource_logs :
?resource:Resource_types.resource option ->
?scope_logs:scope_logs list ->
?schema_url:string ->
unit ->
resource_logs
(** [default_resource_logs ()] is the default value for type [resource_logs] *)
val default_logs_data :
?resource_logs:resource_logs list ->
unit ->
logs_data
(** [default_logs_data ()] is the default value for type [logs_data] *)
val default_log_record_flags : unit -> log_record_flags
(** [default_log_record_flags ()] is the default value for type [log_record_flags] *)
| null | https://raw.githubusercontent.com/imandra-ai/ocaml-opentelemetry/3dc7d63c7d2c345ba13e50b67b56aff878b6d0bb/src/logs_types.mli | ocaml | * logs.proto Types
* {2 Types}
* [default_severity_number ()] is the default value for type [severity_number]
* [default_log_record ()] is the default value for type [log_record]
* [default_scope_logs ()] is the default value for type [scope_logs]
* [default_resource_logs ()] is the default value for type [resource_logs]
* [default_logs_data ()] is the default value for type [logs_data]
* [default_log_record_flags ()] is the default value for type [log_record_flags] |
type severity_number =
| Severity_number_unspecified
| Severity_number_trace
| Severity_number_trace2
| Severity_number_trace3
| Severity_number_trace4
| Severity_number_debug
| Severity_number_debug2
| Severity_number_debug3
| Severity_number_debug4
| Severity_number_info
| Severity_number_info2
| Severity_number_info3
| Severity_number_info4
| Severity_number_warn
| Severity_number_warn2
| Severity_number_warn3
| Severity_number_warn4
| Severity_number_error
| Severity_number_error2
| Severity_number_error3
| Severity_number_error4
| Severity_number_fatal
| Severity_number_fatal2
| Severity_number_fatal3
| Severity_number_fatal4
type log_record = {
time_unix_nano : int64;
observed_time_unix_nano : int64;
severity_number : severity_number;
severity_text : string;
body : Common_types.any_value option;
attributes : Common_types.key_value list;
dropped_attributes_count : int32;
flags : int32;
trace_id : bytes;
span_id : bytes;
}
type scope_logs = {
scope : Common_types.instrumentation_scope option;
log_records : log_record list;
schema_url : string;
}
type resource_logs = {
resource : Resource_types.resource option;
scope_logs : scope_logs list;
schema_url : string;
}
type logs_data = {
resource_logs : resource_logs list;
}
type log_record_flags =
| Log_record_flag_unspecified
| Log_record_flag_trace_flags_mask
* { 2 Default values }
val default_severity_number : unit -> severity_number
val default_log_record :
?time_unix_nano:int64 ->
?observed_time_unix_nano:int64 ->
?severity_number:severity_number ->
?severity_text:string ->
?body:Common_types.any_value option ->
?attributes:Common_types.key_value list ->
?dropped_attributes_count:int32 ->
?flags:int32 ->
?trace_id:bytes ->
?span_id:bytes ->
unit ->
log_record
val default_scope_logs :
?scope:Common_types.instrumentation_scope option ->
?log_records:log_record list ->
?schema_url:string ->
unit ->
scope_logs
val default_resource_logs :
?resource:Resource_types.resource option ->
?scope_logs:scope_logs list ->
?schema_url:string ->
unit ->
resource_logs
val default_logs_data :
?resource_logs:resource_logs list ->
unit ->
logs_data
val default_log_record_flags : unit -> log_record_flags
|
11d777cc6c401cb081e7b75f0d8f6562ec7797e131ab172b8775f4b396c6785a | returntocorp/semgrep | metavar_equality_var.ml | let foo =
(* ERROR: *)
let myfile = open_file "file" in
close myfile
| null | https://raw.githubusercontent.com/returntocorp/semgrep/8c379c2c73b4ece1b1316655b00e21a8af3f00bb/tests/patterns/ocaml/metavar_equality_var.ml | ocaml | ERROR: | let foo =
let myfile = open_file "file" in
close myfile
|
861ba1b616702933c4d5a1fae08c0198e72fc8aa67001fe99d48783e7f1e70d0 | hpdeifel/hledger-iadd | ConfigParserSpec.hs | {-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - orphans #
module ConfigParserSpec (spec) where
import Test.Hspec
import Test.QuickCheck
import Data.Text (Text)
import qualified Data.Text as T
import ConfigParser
spec :: Spec
spec = do
fullTest
defaultTest
syntaxTests
valueTests
commentTests
exampleTests
data TestData = TestData
{ someInt :: Int
, someInteger :: Integer
, someString :: String
, someText :: Text
} deriving (Eq, Show)
testParser :: OptParser TestData
testParser = TestData
<$> option "someInt" 42 "Help for this"
<*> option "someInteger" 23 "Help for that"
<*> option "someString" "foobar" "Help with\nMultiple lines"
<*> option "someText" "barfoo" "And another help"
defaultData :: TestData
defaultData = parserDefault testParser
fullTest :: Spec
fullTest = it "parses a complete example" $ do
let inputTxt = T.unlines [ "someInt = 1"
, "someInteger = 2"
, "someString = a"
, "someText = \"b\""]
output = TestData 1 2 "a" "b"
parseConfig "" inputTxt testParser `shouldBe` Right output
defaultTest :: Spec
defaultTest = do
it "fills in the default values" $
parseConfig "" "" testParser `shouldBe` Right (TestData 42 23 "foobar" "barfoo")
it "fills in the default values for random data" $
property defaultWorksProp
defaultWorksProp :: TestData -> Property
defaultWorksProp testData =
let parser = TestData
<$> option "someInt" (someInt testData) "Help for this"
<*> option "someInteger" (someInteger testData) "Help for that"
<*> option "someString" (someString testData) "Help with\nMultiple lines"
<*> option "someText" (someText testData) "And another help"
in parseConfig "" "" parser === Right testData
syntaxTests :: Spec
syntaxTests = do
context "given whitespace" whitespaceTests
context "given escaped strings" escapingTests
context "given bare strings" bareStringTests
optionNameTests
whitespaceTests :: Spec
whitespaceTests = do
it "parses just whitespace" $
parseConfig "" "" testParser
`shouldBe` Right (TestData 42 23 "foobar" "barfoo")
it "parses beginning whitespace" $
parseConfig "" "\n\n\n someInt = 13" testParser
`shouldBe` Right (TestData 13 23 "foobar" "barfoo")
it "parses trailing whitespace" $
parseConfig "" "someInt = 13 \n\n\n" testParser
`shouldBe` Right (TestData 13 23 "foobar" "barfoo")
it "parses middle whitespace" $
parseConfig "" "someInt = 13 \n\n\n someInteger = 14" testParser
`shouldBe` Right (TestData 13 14 "foobar" "barfoo")
it "parses whitespace everywhere" $
parseConfig "" " \n \n someInt = 13 \n \n \n someInteger = 14 \n \n " testParser
`shouldBe` Right (TestData 13 14 "foobar" "barfoo")
escapingTests :: Spec
escapingTests = do
it "parses simple escaped strings" $
parseConfig "" "someText = \"test\" " testParser
`shouldBe` Right (defaultData { someText = "test" })
it "parses escaped strings with quotes in them" $
parseConfig "" "someText = \"te\\\"st\" " testParser
`shouldBe` Right (defaultData { someText = "te\"st" })
it "parses escaped strings with backslashes in them" $
parseConfig "" "someText = \"te\\\\st\" " testParser
`shouldBe` Right (defaultData { someText = "te\\st" })
it "parses escaped strings with newlines in them" $
parseConfig "" "someText = \"te\nst\" " testParser
`shouldBe` Right (defaultData { someText = "te\nst" })
it "fails to parse non-terminated escaped strings" $
parseConfig "" "someText = \"test " testParser
`shouldSatisfy` isLeft
bareStringTests :: Spec
bareStringTests = do
it "parses a bare string correctly" $
parseConfig "" "someText =test" testParser
`shouldBe` Right (defaultData { someText = "test" })
it "correctly trims bare strings" $
parseConfig "" "someText = foo test " testParser
`shouldBe` Right (defaultData { someText = "foo test" })
it "fails to parse empty bare strings" $
parseConfig "" "someText = " testParser `shouldSatisfy` isLeft
optionNameTests :: Spec
optionNameTests = do
it "allows dashes in option names" $ do
let parser = (\x -> defaultData { someInt = x }) <$> option "test-name" 10 ""
parseConfig "" "test-name = 10" parser `shouldBe` Right defaultData { someInt = 10 }
it "allows underscores in option names" $ do
let parser = (\x -> defaultData { someInt = x }) <$> option "test_name" 10 ""
parseConfig "" "test_name = 10" parser `shouldBe` Right defaultData { someInt = 10 }
it "doesn't allow spaces in option names" $ do
let parser = (\x -> defaultData { someInt = x }) <$> option "test name" 10 ""
parseConfig "" "test name = 10" parser `shouldSatisfy` isLeft
it "doesn't allow equal signs in option names" $ do
let parser = (\x -> defaultData { someInt = x }) <$> option "test=foo" 10 ""
parseConfig "" "test=foo = 10" parser `shouldSatisfy` isLeft
valueTests :: Spec
valueTests = do
context "given integers" $ do
it "parses zero" $
parseConfig "" "someInt = 0" testParser `shouldBe` Right defaultData { someInt = 0 }
it "parses negative zero" $
parseConfig "" "someInt = -0" testParser `shouldBe` Right defaultData { someInt = 0 }
it "fails to parse integer with trailing stuff" $
parseConfig "" "someInt = 10foo" testParser `shouldSatisfy` isLeft
it "fails to parse empty string as integer" $
parseConfig "" "someInt = \"\"" testParser `shouldSatisfy` isLeft
it "fails to parse letters as integer" $
parseConfig "" "someInt = foo" testParser `shouldSatisfy` isLeft
context "given strings" $
it "parses the empty string quoted" $
parseConfig "" "someString = \"\"" testParser `shouldBe` Right defaultData { someString = "" }
commentTests :: Spec
commentTests = do
it "handles a file with just comments" $
parseConfig "" "# a comment \n #another comment " testParser
`shouldBe` Right defaultData
it "handles comments and whitespace in front" $
parseConfig "" " \n\n#another comment " testParser
`shouldBe` Right defaultData
it "handles comments and whitespace in front" $
parseConfig "" " \n\n#another comment " testParser
`shouldBe` Right defaultData
it "handles comments and whitespace after" $
parseConfig "" "#another comment\n\n " testParser
`shouldBe` Right defaultData
it "handles comments with whitespace between" $
parseConfig "" "\n \n # comment \n #another comment\n\n " testParser
`shouldBe` Right defaultData
it "handles comments after assignments" $ do
parseConfig "" "someInt = 4# a comment" testParser
`shouldBe` Right defaultData { someInt = 4 }
parseConfig "" "someInt = 4# a comment\n" testParser
`shouldBe` Right defaultData { someInt = 4 }
parseConfig "" "someInt = 4 # a comment" testParser
`shouldBe` Right defaultData { someInt = 4 }
it "handles comments around assignments" $ do
parseConfig "" "someInt = 4# a comment\n # a comment\nsomeString = foo # bar" testParser
`shouldBe` Right defaultData { someInt = 4, someString = "foo" }
exampleTests :: Spec
exampleTests = describe "parserExample" $ do
it "works for one example" $
let output = T.strip $ T.unlines
[ "# Help for this"
, "someInt = 42"
, ""
, "# Help for that"
, "someInteger = 23"
, ""
, "# Help with"
, "# Multiple lines"
, "someString = \"foobar\""
, ""
, "# And another help"
, "someText = \"barfoo\""
]
in parserExample testParser `shouldBe` output
it "can parse it's own example output" $
property exampleParseableProp
exampleParseableProp :: TestData -> Property
exampleParseableProp testData =
let parser = TestData <$> option "someInt" (someInt testData) "help"
<*> option "someInteger" (someInteger testData) "help"
<*> option "someString" (someString testData) "help"
<*> option "someText" (someText testData) "help"
in parseConfig "" (parserExample parser) parser === Right testData
isLeft :: Either a b -> Bool
isLeft = either (const True) (const False)
instance Arbitrary TestData where
arbitrary = TestData <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary Text where
arbitrary = T.pack <$> arbitrary
| null | https://raw.githubusercontent.com/hpdeifel/hledger-iadd/782239929d411bce4714e65dd5c7bb97b2ba4e75/tests/ConfigParserSpec.hs | haskell | # LANGUAGE OverloadedStrings # | # OPTIONS_GHC -fno - warn - orphans #
module ConfigParserSpec (spec) where
import Test.Hspec
import Test.QuickCheck
import Data.Text (Text)
import qualified Data.Text as T
import ConfigParser
spec :: Spec
spec = do
fullTest
defaultTest
syntaxTests
valueTests
commentTests
exampleTests
data TestData = TestData
{ someInt :: Int
, someInteger :: Integer
, someString :: String
, someText :: Text
} deriving (Eq, Show)
testParser :: OptParser TestData
testParser = TestData
<$> option "someInt" 42 "Help for this"
<*> option "someInteger" 23 "Help for that"
<*> option "someString" "foobar" "Help with\nMultiple lines"
<*> option "someText" "barfoo" "And another help"
defaultData :: TestData
defaultData = parserDefault testParser
fullTest :: Spec
fullTest = it "parses a complete example" $ do
let inputTxt = T.unlines [ "someInt = 1"
, "someInteger = 2"
, "someString = a"
, "someText = \"b\""]
output = TestData 1 2 "a" "b"
parseConfig "" inputTxt testParser `shouldBe` Right output
defaultTest :: Spec
defaultTest = do
it "fills in the default values" $
parseConfig "" "" testParser `shouldBe` Right (TestData 42 23 "foobar" "barfoo")
it "fills in the default values for random data" $
property defaultWorksProp
defaultWorksProp :: TestData -> Property
defaultWorksProp testData =
let parser = TestData
<$> option "someInt" (someInt testData) "Help for this"
<*> option "someInteger" (someInteger testData) "Help for that"
<*> option "someString" (someString testData) "Help with\nMultiple lines"
<*> option "someText" (someText testData) "And another help"
in parseConfig "" "" parser === Right testData
syntaxTests :: Spec
syntaxTests = do
context "given whitespace" whitespaceTests
context "given escaped strings" escapingTests
context "given bare strings" bareStringTests
optionNameTests
whitespaceTests :: Spec
whitespaceTests = do
it "parses just whitespace" $
parseConfig "" "" testParser
`shouldBe` Right (TestData 42 23 "foobar" "barfoo")
it "parses beginning whitespace" $
parseConfig "" "\n\n\n someInt = 13" testParser
`shouldBe` Right (TestData 13 23 "foobar" "barfoo")
it "parses trailing whitespace" $
parseConfig "" "someInt = 13 \n\n\n" testParser
`shouldBe` Right (TestData 13 23 "foobar" "barfoo")
it "parses middle whitespace" $
parseConfig "" "someInt = 13 \n\n\n someInteger = 14" testParser
`shouldBe` Right (TestData 13 14 "foobar" "barfoo")
it "parses whitespace everywhere" $
parseConfig "" " \n \n someInt = 13 \n \n \n someInteger = 14 \n \n " testParser
`shouldBe` Right (TestData 13 14 "foobar" "barfoo")
escapingTests :: Spec
escapingTests = do
it "parses simple escaped strings" $
parseConfig "" "someText = \"test\" " testParser
`shouldBe` Right (defaultData { someText = "test" })
it "parses escaped strings with quotes in them" $
parseConfig "" "someText = \"te\\\"st\" " testParser
`shouldBe` Right (defaultData { someText = "te\"st" })
it "parses escaped strings with backslashes in them" $
parseConfig "" "someText = \"te\\\\st\" " testParser
`shouldBe` Right (defaultData { someText = "te\\st" })
it "parses escaped strings with newlines in them" $
parseConfig "" "someText = \"te\nst\" " testParser
`shouldBe` Right (defaultData { someText = "te\nst" })
it "fails to parse non-terminated escaped strings" $
parseConfig "" "someText = \"test " testParser
`shouldSatisfy` isLeft
bareStringTests :: Spec
bareStringTests = do
it "parses a bare string correctly" $
parseConfig "" "someText =test" testParser
`shouldBe` Right (defaultData { someText = "test" })
it "correctly trims bare strings" $
parseConfig "" "someText = foo test " testParser
`shouldBe` Right (defaultData { someText = "foo test" })
it "fails to parse empty bare strings" $
parseConfig "" "someText = " testParser `shouldSatisfy` isLeft
optionNameTests :: Spec
optionNameTests = do
it "allows dashes in option names" $ do
let parser = (\x -> defaultData { someInt = x }) <$> option "test-name" 10 ""
parseConfig "" "test-name = 10" parser `shouldBe` Right defaultData { someInt = 10 }
it "allows underscores in option names" $ do
let parser = (\x -> defaultData { someInt = x }) <$> option "test_name" 10 ""
parseConfig "" "test_name = 10" parser `shouldBe` Right defaultData { someInt = 10 }
it "doesn't allow spaces in option names" $ do
let parser = (\x -> defaultData { someInt = x }) <$> option "test name" 10 ""
parseConfig "" "test name = 10" parser `shouldSatisfy` isLeft
it "doesn't allow equal signs in option names" $ do
let parser = (\x -> defaultData { someInt = x }) <$> option "test=foo" 10 ""
parseConfig "" "test=foo = 10" parser `shouldSatisfy` isLeft
valueTests :: Spec
valueTests = do
context "given integers" $ do
it "parses zero" $
parseConfig "" "someInt = 0" testParser `shouldBe` Right defaultData { someInt = 0 }
it "parses negative zero" $
parseConfig "" "someInt = -0" testParser `shouldBe` Right defaultData { someInt = 0 }
it "fails to parse integer with trailing stuff" $
parseConfig "" "someInt = 10foo" testParser `shouldSatisfy` isLeft
it "fails to parse empty string as integer" $
parseConfig "" "someInt = \"\"" testParser `shouldSatisfy` isLeft
it "fails to parse letters as integer" $
parseConfig "" "someInt = foo" testParser `shouldSatisfy` isLeft
context "given strings" $
it "parses the empty string quoted" $
parseConfig "" "someString = \"\"" testParser `shouldBe` Right defaultData { someString = "" }
commentTests :: Spec
commentTests = do
it "handles a file with just comments" $
parseConfig "" "# a comment \n #another comment " testParser
`shouldBe` Right defaultData
it "handles comments and whitespace in front" $
parseConfig "" " \n\n#another comment " testParser
`shouldBe` Right defaultData
it "handles comments and whitespace in front" $
parseConfig "" " \n\n#another comment " testParser
`shouldBe` Right defaultData
it "handles comments and whitespace after" $
parseConfig "" "#another comment\n\n " testParser
`shouldBe` Right defaultData
it "handles comments with whitespace between" $
parseConfig "" "\n \n # comment \n #another comment\n\n " testParser
`shouldBe` Right defaultData
it "handles comments after assignments" $ do
parseConfig "" "someInt = 4# a comment" testParser
`shouldBe` Right defaultData { someInt = 4 }
parseConfig "" "someInt = 4# a comment\n" testParser
`shouldBe` Right defaultData { someInt = 4 }
parseConfig "" "someInt = 4 # a comment" testParser
`shouldBe` Right defaultData { someInt = 4 }
it "handles comments around assignments" $ do
parseConfig "" "someInt = 4# a comment\n # a comment\nsomeString = foo # bar" testParser
`shouldBe` Right defaultData { someInt = 4, someString = "foo" }
exampleTests :: Spec
exampleTests = describe "parserExample" $ do
it "works for one example" $
let output = T.strip $ T.unlines
[ "# Help for this"
, "someInt = 42"
, ""
, "# Help for that"
, "someInteger = 23"
, ""
, "# Help with"
, "# Multiple lines"
, "someString = \"foobar\""
, ""
, "# And another help"
, "someText = \"barfoo\""
]
in parserExample testParser `shouldBe` output
it "can parse it's own example output" $
property exampleParseableProp
exampleParseableProp :: TestData -> Property
exampleParseableProp testData =
let parser = TestData <$> option "someInt" (someInt testData) "help"
<*> option "someInteger" (someInteger testData) "help"
<*> option "someString" (someString testData) "help"
<*> option "someText" (someText testData) "help"
in parseConfig "" (parserExample parser) parser === Right testData
isLeft :: Either a b -> Bool
isLeft = either (const True) (const False)
instance Arbitrary TestData where
arbitrary = TestData <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
instance Arbitrary Text where
arbitrary = T.pack <$> arbitrary
|
dcfbe623333176273cc4f6a29ee1a4e8729fcd48c258d72731e0b3532eb436d9 | haskellari/strict | These.hs | {-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Safe #-}
#if MIN_VERSION_base(4,9,0)
#define LIFTED_FUNCTOR_CLASSES 1
#else
#if MIN_VERSION_transformers(0,5,0)
#define LIFTED_FUNCTOR_CLASSES 1
#else
#if MIN_VERSION_transformers_compat(0,5,0) && !MIN_VERSION_transformers(0,4,0)
#define LIFTED_FUNCTOR_CLASSES 1
#endif
#endif
#endif
module Data.Strict.These (
These(..)
-- * Functions to get rid of 'These'
, these
, fromThese
, mergeThese
, mergeTheseWith
-- * Partition
, partitionThese
, partitionHereThere
, partitionEithersNE
-- * Distributivity
--
-- | This distributivity combinators aren't isomorphisms!
, distrThesePair
, undistrThesePair
, distrPairThese
, undistrPairThese
) where
import Control.Applicative (Applicative (..), (<$>))
import Control.DeepSeq (NFData (..))
import Data.Bifoldable (Bifoldable (..))
import Data.Bifunctor (Bifunctor (..))
import Data.Binary (Binary (..))
import Data.Bitraversable (Bitraversable (..))
import Data.Data (Data, Typeable)
import Data.Either (partitionEithers)
import Data.Foldable (Foldable (..))
import Data.Hashable (Hashable (..))
import Data.Hashable.Lifted (Hashable1 (..), Hashable2 (..))
import Data.List.NonEmpty (NonEmpty (..))
import Data.Monoid (Monoid (..))
import Data.Semigroup (Semigroup (..))
import Data.Traversable (Traversable (..))
import GHC.Generics (Generic)
import Prelude
(Bool (..), Either (..), Eq (..), Functor (..), Int, Monad (..),
Ord (..), Ordering (..), Read (..), Show (..), id, lex, readParen,
seq, showParen, showString, ($), (&&), (.))
import qualified Data.These as L
#if MIN_VERSION_deepseq(1,4,3)
import Control.DeepSeq (NFData1 (..), NFData2 (..))
#endif
#if __GLASGOW_HASKELL__ >= 706
import GHC.Generics (Generic1)
#endif
#ifdef MIN_VERSION_assoc
import Data.Bifunctor.Assoc (Assoc (..))
import Data.Bifunctor.Swap (Swap (..))
#endif
#ifdef LIFTED_FUNCTOR_CLASSES
import Data.Functor.Classes
(Eq1 (..), Eq2 (..), Ord1 (..), Ord2 (..), Read1 (..), Read2 (..),
Show1 (..), Show2 (..))
#else
import Data.Functor.Classes (Eq1 (..), Ord1 (..), Read1 (..), Show1 (..))
#endif
-- $setup
> > > import Prelude ( map )
-- | The strict these type.
data These a b = This !a | That !b | These !a !b
deriving (Eq, Ord, Read, Show, Typeable, Data, Generic
#if __GLASGOW_HASKELL__ >= 706
, Generic1
#endif
)
toStrict :: L.These a b -> These a b
toStrict (L.This x) = This x
toStrict (L.That y) = That y
toStrict (L.These x y) = These x y
toLazy :: These a b -> L.These a b
toLazy (This x) = L.This x
toLazy (That y) = L.That y
toLazy (These x y) = L.These x y
-------------------------------------------------------------------------------
-- Eliminators
-------------------------------------------------------------------------------
-- | Case analysis for the 'These' type.
these :: (a -> c) -> (b -> c) -> (a -> b -> c) -> These a b -> c
these l _ _ (This a) = l a
these _ r _ (That x) = r x
these _ _ lr (These a x) = lr a x
| Takes two default values and produces a tuple .
fromThese :: a -> b -> These a b -> (a, b)
fromThese x y = these (`pair` y) (x `pair`) pair where
pair = (,)
-- | Coalesce with the provided operation.
mergeThese :: (a -> a -> a) -> These a a -> a
mergeThese = these id id
-- | 'bimap' and coalesce results with the provided operation.
mergeTheseWith :: (a -> c) -> (b -> c) -> (c -> c -> c) -> These a b -> c
mergeTheseWith f g op t = mergeThese op $ bimap f g t
-------------------------------------------------------------------------------
-- Partitioning
-------------------------------------------------------------------------------
-- | Select each constructor and partition them into separate lists.
partitionThese :: [These a b] -> ([a], [b], [(a, b)])
partitionThese [] = ([], [], [])
partitionThese (t:ts) = case t of
This x -> (x : xs, ys, xys)
That y -> ( xs, y : ys, xys)
These x y -> ( xs, ys, (x,y) : xys)
where
~(xs,ys,xys) = partitionThese ts
-- | Select 'here' and 'there' elements and partition them into separate lists.
--
partitionHereThere :: [These a b] -> ([a], [b])
partitionHereThere [] = ([], [])
partitionHereThere (t:ts) = case t of
This x -> (x : xs, ys)
That y -> ( xs, y : ys)
These x y -> (x : xs, y : ys)
where
~(xs,ys) = partitionHereThere ts
| Like ' partitionEithers ' but for ' NonEmpty ' types .
--
-- * either all are 'Left'
-- * either all are 'Right'
-- * or there is both 'Left' and 'Right' stuff
--
-- /Note:/ this is not online algorithm. In the worst case it will traverse
-- the whole list before deciding the result constructor.
--
-- >>> partitionEithersNE $ Left 'x' :| [Right 'y']
-- These ('x' :| "") ('y' :| "")
--
-- >>> partitionEithersNE $ Left 'x' :| map Left "yz"
-- This ('x' :| "yz")
--
partitionEithersNE :: NonEmpty (Either a b) -> These (NonEmpty a) (NonEmpty b)
partitionEithersNE (x :| xs) = case (x, ls, rs) of
(Left y, ys, []) -> This (y :| ys)
(Left y, ys, z:zs) -> These (y :| ys) (z :| zs)
(Right z, [], zs) -> That (z :| zs)
(Right z, y:ys, zs) -> These (y :| ys) (z :| zs)
where
(ls, rs) = partitionEithers xs
-------------------------------------------------------------------------------
-- Distributivity
-------------------------------------------------------------------------------
distrThesePair :: These (a, b) c -> (These a c, These b c)
distrThesePair (This (a, b)) = (This a, This b)
distrThesePair (That c) = (That c, That c)
distrThesePair (These (a, b) c) = (These a c, These b c)
undistrThesePair :: (These a c, These b c) -> These (a, b) c
undistrThesePair (This a, This b) = This (a, b)
undistrThesePair (That c, That _) = That c
undistrThesePair (These a c, These b _) = These (a, b) c
undistrThesePair (This _, That c) = That c
undistrThesePair (This a, These b c) = These (a, b) c
undistrThesePair (That c, This _) = That c
undistrThesePair (That c, These _ _) = That c
undistrThesePair (These a c, This b) = These (a, b) c
undistrThesePair (These _ c, That _) = That c
distrPairThese :: (These a b, c) -> These (a, c) (b, c)
distrPairThese (This a, c) = This (a, c)
distrPairThese (That b, c) = That (b, c)
distrPairThese (These a b, c) = These (a, c) (b, c)
undistrPairThese :: These (a, c) (b, c) -> (These a b, c)
undistrPairThese (This (a, c)) = (This a, c)
undistrPairThese (That (b, c)) = (That b, c)
undistrPairThese (These (a, c) (b, _)) = (These a b, c)
-------------------------------------------------------------------------------
-- Instances
-------------------------------------------------------------------------------
instance (Semigroup a, Semigroup b) => Semigroup (These a b) where
This a <> This b = This (a <> b)
This a <> That y = These a y
This a <> These b y = These (a <> b) y
That x <> This b = These b x
That x <> That y = That (x <> y)
That x <> These b y = These b (x <> y)
These a x <> This b = These (a <> b) x
These a x <> That y = These a (x <> y)
These a x <> These b y = These (a <> b) (x <> y)
instance Functor (These a) where
fmap _ (This x) = This x
fmap f (That y) = That (f y)
fmap f (These x y) = These x (f y)
instance Foldable (These a) where
foldr _ z (This _) = z
foldr f z (That x) = f x z
foldr f z (These _ x) = f x z
instance Traversable (These a) where
traverse _ (This a) = pure $ This a
traverse f (That x) = That <$> f x
traverse f (These a x) = These a <$> f x
sequenceA (This a) = pure $ This a
sequenceA (That x) = That <$> x
sequenceA (These a x) = These a <$> x
instance Bifunctor These where
bimap f _ (This a ) = This (f a)
bimap _ g (That x) = That (g x)
bimap f g (These a x) = These (f a) (g x)
instance Bifoldable These where
bifold = these id id mappend
bifoldr f g z = these (`f` z) (`g` z) (\x y -> x `f` (y `g` z))
bifoldl f g z = these (z `f`) (z `g`) (\x y -> (z `f` x) `g` y)
instance Bitraversable These where
bitraverse f _ (This x) = This <$> f x
bitraverse _ g (That x) = That <$> g x
bitraverse f g (These x y) = These <$> f x <*> g y
instance (Semigroup a) => Applicative (These a) where
pure = That
This a <*> _ = This a
That _ <*> This b = This b
That f <*> That x = That (f x)
That f <*> These b x = These b (f x)
These a _ <*> This b = This (a <> b)
These a f <*> That x = These a (f x)
These a f <*> These b x = These (a <> b) (f x)
instance (Semigroup a) => Monad (These a) where
return = pure
This a >>= _ = This a
That x >>= k = k x
These a x >>= k = case k x of
This b -> This (a <> b)
That y -> These a y
These b y -> These (a <> b) y
-------------------------------------------------------------------------------
-- Data.Functor.Classes
-------------------------------------------------------------------------------
#ifdef LIFTED_FUNCTOR_CLASSES
instance Eq2 These where
liftEq2 f _ (This a) (This a') = f a a'
liftEq2 _ g (That b) (That b') = g b b'
liftEq2 f g (These a b) (These a' b') = f a a' && g b b'
liftEq2 _ _ _ _ = False
instance Eq a => Eq1 (These a) where
liftEq = liftEq2 (==)
instance Ord2 These where
liftCompare2 f _ (This a) (This a') = f a a'
liftCompare2 _ _ (This _) _ = LT
liftCompare2 _ _ _ (This _) = GT
liftCompare2 _ g (That b) (That b') = g b b'
liftCompare2 _ _ (That _) _ = LT
liftCompare2 _ _ _ (That _) = GT
liftCompare2 f g (These a b) (These a' b') = f a a' `mappend` g b b'
instance Ord a => Ord1 (These a) where
liftCompare = liftCompare2 compare
instance Show a => Show1 (These a) where
liftShowsPrec = liftShowsPrec2 showsPrec showList
instance Show2 These where
liftShowsPrec2 sa _ _sb _ d (This a) = showParen (d > 10)
$ showString "This "
. sa 11 a
liftShowsPrec2 _sa _ sb _ d (That b) = showParen (d > 10)
$ showString "That "
. sb 11 b
liftShowsPrec2 sa _ sb _ d (These a b) = showParen (d > 10)
$ showString "These "
. sa 11 a
. showString " "
. sb 11 b
instance Read2 These where
liftReadsPrec2 ra _ rb _ d = readParen (d > 10) $ \s -> cons s
where
cons s0 = do
(ident, s1) <- lex s0
case ident of
"This" -> do
(a, s2) <- ra 11 s1
return (This a, s2)
"That" -> do
(b, s2) <- rb 11 s1
return (That b, s2)
"These" -> do
(a, s2) <- ra 11 s1
(b, s3) <- rb 11 s2
return (These a b, s3)
_ -> []
instance Read a => Read1 (These a) where
liftReadsPrec = liftReadsPrec2 readsPrec readList
#else
instance Eq a => Eq1 (These a) where eq1 = (==)
instance Ord a => Ord1 (These a) where compare1 = compare
instance Show a => Show1 (These a) where showsPrec1 = showsPrec
instance Read a => Read1 (These a) where readsPrec1 = readsPrec
#endif
-------------------------------------------------------------------------------
-- assoc
-------------------------------------------------------------------------------
#ifdef MIN_VERSION_assoc
instance Swap These where
swap (This a) = That a
swap (That b) = This b
swap (These a b) = These b a
instance Assoc These where
assoc (This (This a)) = This a
assoc (This (That b)) = That (This b)
assoc (That c) = That (That c)
assoc (These (That b) c) = That (These b c)
assoc (This (These a b)) = These a (This b)
assoc (These (This a) c) = These a (That c)
assoc (These (These a b) c) = These a (These b c)
unassoc (This a) = This (This a)
unassoc (That (This b)) = This (That b)
unassoc (That (That c)) = That c
unassoc (That (These b c)) = These (That b) c
unassoc (These a (This b)) = This (These a b)
unassoc (These a (That c)) = These (This a) c
unassoc (These a (These b c)) = These (These a b) c
#endif
-------------------------------------------------------------------------------
deepseq
-------------------------------------------------------------------------------
instance (NFData a, NFData b) => NFData (These a b) where
rnf (This a) = rnf a
rnf (That b) = rnf b
rnf (These a b) = rnf a `seq` rnf b
#if MIN_VERSION_deepseq(1,4,3)
instance NFData a => NFData1 (These a) where
liftRnf _rnfB (This a) = rnf a
liftRnf rnfB (That b) = rnfB b
liftRnf rnfB (These a b) = rnf a `seq` rnfB b
instance NFData2 These where
liftRnf2 rnfA _rnfB (This a) = rnfA a
liftRnf2 _rnfA rnfB (That b) = rnfB b
liftRnf2 rnfA rnfB (These a b) = rnfA a `seq` rnfB b
#endif
-------------------------------------------------------------------------------
-- binary
-------------------------------------------------------------------------------
instance (Binary a, Binary b) => Binary (These a b) where
put = put . toLazy
get = toStrict <$> get
-------------------------------------------------------------------------------
-- hashable
-------------------------------------------------------------------------------
instance (Hashable a, Hashable b) => Hashable (These a b) where
hashWithSalt salt (This a) =
salt `hashWithSalt` (0 :: Int) `hashWithSalt` a
hashWithSalt salt (That b) =
salt `hashWithSalt` (1 :: Int) `hashWithSalt` b
hashWithSalt salt (These a b) =
salt `hashWithSalt` (2 :: Int) `hashWithSalt` a `hashWithSalt` b
instance Hashable a => Hashable1 (These a) where
liftHashWithSalt _hashB salt (This a) =
salt `hashWithSalt` (0 :: Int) `hashWithSalt` a
liftHashWithSalt hashB salt (That b) =
(salt `hashWithSalt` (1 :: Int)) `hashB` b
liftHashWithSalt hashB salt (These a b) =
(salt `hashWithSalt` (2 :: Int) `hashWithSalt` a) `hashB` b
instance Hashable2 These where
liftHashWithSalt2 hashA _hashB salt (This a) =
(salt `hashWithSalt` (0 :: Int)) `hashA` a
liftHashWithSalt2 _hashA hashB salt (That b) =
(salt `hashWithSalt` (1 :: Int)) `hashB` b
liftHashWithSalt2 hashA hashB salt (These a b) =
(salt `hashWithSalt` (2 :: Int)) `hashA` a `hashB` b
| null | https://raw.githubusercontent.com/haskellari/strict/4691acdfbe95dcd49725baec09127fa0077d93ba/strict/src/Data/Strict/These.hs | haskell | # LANGUAGE CPP #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE OverloadedStrings #
# LANGUAGE Safe #
* Functions to get rid of 'These'
* Partition
* Distributivity
| This distributivity combinators aren't isomorphisms!
$setup
| The strict these type.
-----------------------------------------------------------------------------
Eliminators
-----------------------------------------------------------------------------
| Case analysis for the 'These' type.
| Coalesce with the provided operation.
| 'bimap' and coalesce results with the provided operation.
-----------------------------------------------------------------------------
Partitioning
-----------------------------------------------------------------------------
| Select each constructor and partition them into separate lists.
| Select 'here' and 'there' elements and partition them into separate lists.
* either all are 'Left'
* either all are 'Right'
* or there is both 'Left' and 'Right' stuff
/Note:/ this is not online algorithm. In the worst case it will traverse
the whole list before deciding the result constructor.
>>> partitionEithersNE $ Left 'x' :| [Right 'y']
These ('x' :| "") ('y' :| "")
>>> partitionEithersNE $ Left 'x' :| map Left "yz"
This ('x' :| "yz")
-----------------------------------------------------------------------------
Distributivity
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Instances
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
Data.Functor.Classes
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
assoc
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
binary
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
hashable
----------------------------------------------------------------------------- | # LANGUAGE DeriveGeneric #
#if MIN_VERSION_base(4,9,0)
#define LIFTED_FUNCTOR_CLASSES 1
#else
#if MIN_VERSION_transformers(0,5,0)
#define LIFTED_FUNCTOR_CLASSES 1
#else
#if MIN_VERSION_transformers_compat(0,5,0) && !MIN_VERSION_transformers(0,4,0)
#define LIFTED_FUNCTOR_CLASSES 1
#endif
#endif
#endif
module Data.Strict.These (
These(..)
, these
, fromThese
, mergeThese
, mergeTheseWith
, partitionThese
, partitionHereThere
, partitionEithersNE
, distrThesePair
, undistrThesePair
, distrPairThese
, undistrPairThese
) where
import Control.Applicative (Applicative (..), (<$>))
import Control.DeepSeq (NFData (..))
import Data.Bifoldable (Bifoldable (..))
import Data.Bifunctor (Bifunctor (..))
import Data.Binary (Binary (..))
import Data.Bitraversable (Bitraversable (..))
import Data.Data (Data, Typeable)
import Data.Either (partitionEithers)
import Data.Foldable (Foldable (..))
import Data.Hashable (Hashable (..))
import Data.Hashable.Lifted (Hashable1 (..), Hashable2 (..))
import Data.List.NonEmpty (NonEmpty (..))
import Data.Monoid (Monoid (..))
import Data.Semigroup (Semigroup (..))
import Data.Traversable (Traversable (..))
import GHC.Generics (Generic)
import Prelude
(Bool (..), Either (..), Eq (..), Functor (..), Int, Monad (..),
Ord (..), Ordering (..), Read (..), Show (..), id, lex, readParen,
seq, showParen, showString, ($), (&&), (.))
import qualified Data.These as L
#if MIN_VERSION_deepseq(1,4,3)
import Control.DeepSeq (NFData1 (..), NFData2 (..))
#endif
#if __GLASGOW_HASKELL__ >= 706
import GHC.Generics (Generic1)
#endif
#ifdef MIN_VERSION_assoc
import Data.Bifunctor.Assoc (Assoc (..))
import Data.Bifunctor.Swap (Swap (..))
#endif
#ifdef LIFTED_FUNCTOR_CLASSES
import Data.Functor.Classes
(Eq1 (..), Eq2 (..), Ord1 (..), Ord2 (..), Read1 (..), Read2 (..),
Show1 (..), Show2 (..))
#else
import Data.Functor.Classes (Eq1 (..), Ord1 (..), Read1 (..), Show1 (..))
#endif
> > > import Prelude ( map )
data These a b = This !a | That !b | These !a !b
deriving (Eq, Ord, Read, Show, Typeable, Data, Generic
#if __GLASGOW_HASKELL__ >= 706
, Generic1
#endif
)
toStrict :: L.These a b -> These a b
toStrict (L.This x) = This x
toStrict (L.That y) = That y
toStrict (L.These x y) = These x y
toLazy :: These a b -> L.These a b
toLazy (This x) = L.This x
toLazy (That y) = L.That y
toLazy (These x y) = L.These x y
these :: (a -> c) -> (b -> c) -> (a -> b -> c) -> These a b -> c
these l _ _ (This a) = l a
these _ r _ (That x) = r x
these _ _ lr (These a x) = lr a x
| Takes two default values and produces a tuple .
fromThese :: a -> b -> These a b -> (a, b)
fromThese x y = these (`pair` y) (x `pair`) pair where
pair = (,)
mergeThese :: (a -> a -> a) -> These a a -> a
mergeThese = these id id
mergeTheseWith :: (a -> c) -> (b -> c) -> (c -> c -> c) -> These a b -> c
mergeTheseWith f g op t = mergeThese op $ bimap f g t
partitionThese :: [These a b] -> ([a], [b], [(a, b)])
partitionThese [] = ([], [], [])
partitionThese (t:ts) = case t of
This x -> (x : xs, ys, xys)
That y -> ( xs, y : ys, xys)
These x y -> ( xs, ys, (x,y) : xys)
where
~(xs,ys,xys) = partitionThese ts
partitionHereThere :: [These a b] -> ([a], [b])
partitionHereThere [] = ([], [])
partitionHereThere (t:ts) = case t of
This x -> (x : xs, ys)
That y -> ( xs, y : ys)
These x y -> (x : xs, y : ys)
where
~(xs,ys) = partitionHereThere ts
| Like ' partitionEithers ' but for ' NonEmpty ' types .
partitionEithersNE :: NonEmpty (Either a b) -> These (NonEmpty a) (NonEmpty b)
partitionEithersNE (x :| xs) = case (x, ls, rs) of
(Left y, ys, []) -> This (y :| ys)
(Left y, ys, z:zs) -> These (y :| ys) (z :| zs)
(Right z, [], zs) -> That (z :| zs)
(Right z, y:ys, zs) -> These (y :| ys) (z :| zs)
where
(ls, rs) = partitionEithers xs
distrThesePair :: These (a, b) c -> (These a c, These b c)
distrThesePair (This (a, b)) = (This a, This b)
distrThesePair (That c) = (That c, That c)
distrThesePair (These (a, b) c) = (These a c, These b c)
undistrThesePair :: (These a c, These b c) -> These (a, b) c
undistrThesePair (This a, This b) = This (a, b)
undistrThesePair (That c, That _) = That c
undistrThesePair (These a c, These b _) = These (a, b) c
undistrThesePair (This _, That c) = That c
undistrThesePair (This a, These b c) = These (a, b) c
undistrThesePair (That c, This _) = That c
undistrThesePair (That c, These _ _) = That c
undistrThesePair (These a c, This b) = These (a, b) c
undistrThesePair (These _ c, That _) = That c
distrPairThese :: (These a b, c) -> These (a, c) (b, c)
distrPairThese (This a, c) = This (a, c)
distrPairThese (That b, c) = That (b, c)
distrPairThese (These a b, c) = These (a, c) (b, c)
undistrPairThese :: These (a, c) (b, c) -> (These a b, c)
undistrPairThese (This (a, c)) = (This a, c)
undistrPairThese (That (b, c)) = (That b, c)
undistrPairThese (These (a, c) (b, _)) = (These a b, c)
instance (Semigroup a, Semigroup b) => Semigroup (These a b) where
This a <> This b = This (a <> b)
This a <> That y = These a y
This a <> These b y = These (a <> b) y
That x <> This b = These b x
That x <> That y = That (x <> y)
That x <> These b y = These b (x <> y)
These a x <> This b = These (a <> b) x
These a x <> That y = These a (x <> y)
These a x <> These b y = These (a <> b) (x <> y)
instance Functor (These a) where
fmap _ (This x) = This x
fmap f (That y) = That (f y)
fmap f (These x y) = These x (f y)
instance Foldable (These a) where
foldr _ z (This _) = z
foldr f z (That x) = f x z
foldr f z (These _ x) = f x z
instance Traversable (These a) where
traverse _ (This a) = pure $ This a
traverse f (That x) = That <$> f x
traverse f (These a x) = These a <$> f x
sequenceA (This a) = pure $ This a
sequenceA (That x) = That <$> x
sequenceA (These a x) = These a <$> x
instance Bifunctor These where
bimap f _ (This a ) = This (f a)
bimap _ g (That x) = That (g x)
bimap f g (These a x) = These (f a) (g x)
instance Bifoldable These where
bifold = these id id mappend
bifoldr f g z = these (`f` z) (`g` z) (\x y -> x `f` (y `g` z))
bifoldl f g z = these (z `f`) (z `g`) (\x y -> (z `f` x) `g` y)
instance Bitraversable These where
bitraverse f _ (This x) = This <$> f x
bitraverse _ g (That x) = That <$> g x
bitraverse f g (These x y) = These <$> f x <*> g y
instance (Semigroup a) => Applicative (These a) where
pure = That
This a <*> _ = This a
That _ <*> This b = This b
That f <*> That x = That (f x)
That f <*> These b x = These b (f x)
These a _ <*> This b = This (a <> b)
These a f <*> That x = These a (f x)
These a f <*> These b x = These (a <> b) (f x)
instance (Semigroup a) => Monad (These a) where
return = pure
This a >>= _ = This a
That x >>= k = k x
These a x >>= k = case k x of
This b -> This (a <> b)
That y -> These a y
These b y -> These (a <> b) y
#ifdef LIFTED_FUNCTOR_CLASSES
instance Eq2 These where
liftEq2 f _ (This a) (This a') = f a a'
liftEq2 _ g (That b) (That b') = g b b'
liftEq2 f g (These a b) (These a' b') = f a a' && g b b'
liftEq2 _ _ _ _ = False
instance Eq a => Eq1 (These a) where
liftEq = liftEq2 (==)
instance Ord2 These where
liftCompare2 f _ (This a) (This a') = f a a'
liftCompare2 _ _ (This _) _ = LT
liftCompare2 _ _ _ (This _) = GT
liftCompare2 _ g (That b) (That b') = g b b'
liftCompare2 _ _ (That _) _ = LT
liftCompare2 _ _ _ (That _) = GT
liftCompare2 f g (These a b) (These a' b') = f a a' `mappend` g b b'
instance Ord a => Ord1 (These a) where
liftCompare = liftCompare2 compare
instance Show a => Show1 (These a) where
liftShowsPrec = liftShowsPrec2 showsPrec showList
instance Show2 These where
liftShowsPrec2 sa _ _sb _ d (This a) = showParen (d > 10)
$ showString "This "
. sa 11 a
liftShowsPrec2 _sa _ sb _ d (That b) = showParen (d > 10)
$ showString "That "
. sb 11 b
liftShowsPrec2 sa _ sb _ d (These a b) = showParen (d > 10)
$ showString "These "
. sa 11 a
. showString " "
. sb 11 b
instance Read2 These where
liftReadsPrec2 ra _ rb _ d = readParen (d > 10) $ \s -> cons s
where
cons s0 = do
(ident, s1) <- lex s0
case ident of
"This" -> do
(a, s2) <- ra 11 s1
return (This a, s2)
"That" -> do
(b, s2) <- rb 11 s1
return (That b, s2)
"These" -> do
(a, s2) <- ra 11 s1
(b, s3) <- rb 11 s2
return (These a b, s3)
_ -> []
instance Read a => Read1 (These a) where
liftReadsPrec = liftReadsPrec2 readsPrec readList
#else
instance Eq a => Eq1 (These a) where eq1 = (==)
instance Ord a => Ord1 (These a) where compare1 = compare
instance Show a => Show1 (These a) where showsPrec1 = showsPrec
instance Read a => Read1 (These a) where readsPrec1 = readsPrec
#endif
#ifdef MIN_VERSION_assoc
instance Swap These where
swap (This a) = That a
swap (That b) = This b
swap (These a b) = These b a
instance Assoc These where
assoc (This (This a)) = This a
assoc (This (That b)) = That (This b)
assoc (That c) = That (That c)
assoc (These (That b) c) = That (These b c)
assoc (This (These a b)) = These a (This b)
assoc (These (This a) c) = These a (That c)
assoc (These (These a b) c) = These a (These b c)
unassoc (This a) = This (This a)
unassoc (That (This b)) = This (That b)
unassoc (That (That c)) = That c
unassoc (That (These b c)) = These (That b) c
unassoc (These a (This b)) = This (These a b)
unassoc (These a (That c)) = These (This a) c
unassoc (These a (These b c)) = These (These a b) c
#endif
deepseq
instance (NFData a, NFData b) => NFData (These a b) where
rnf (This a) = rnf a
rnf (That b) = rnf b
rnf (These a b) = rnf a `seq` rnf b
#if MIN_VERSION_deepseq(1,4,3)
instance NFData a => NFData1 (These a) where
liftRnf _rnfB (This a) = rnf a
liftRnf rnfB (That b) = rnfB b
liftRnf rnfB (These a b) = rnf a `seq` rnfB b
instance NFData2 These where
liftRnf2 rnfA _rnfB (This a) = rnfA a
liftRnf2 _rnfA rnfB (That b) = rnfB b
liftRnf2 rnfA rnfB (These a b) = rnfA a `seq` rnfB b
#endif
instance (Binary a, Binary b) => Binary (These a b) where
put = put . toLazy
get = toStrict <$> get
instance (Hashable a, Hashable b) => Hashable (These a b) where
hashWithSalt salt (This a) =
salt `hashWithSalt` (0 :: Int) `hashWithSalt` a
hashWithSalt salt (That b) =
salt `hashWithSalt` (1 :: Int) `hashWithSalt` b
hashWithSalt salt (These a b) =
salt `hashWithSalt` (2 :: Int) `hashWithSalt` a `hashWithSalt` b
instance Hashable a => Hashable1 (These a) where
liftHashWithSalt _hashB salt (This a) =
salt `hashWithSalt` (0 :: Int) `hashWithSalt` a
liftHashWithSalt hashB salt (That b) =
(salt `hashWithSalt` (1 :: Int)) `hashB` b
liftHashWithSalt hashB salt (These a b) =
(salt `hashWithSalt` (2 :: Int) `hashWithSalt` a) `hashB` b
instance Hashable2 These where
liftHashWithSalt2 hashA _hashB salt (This a) =
(salt `hashWithSalt` (0 :: Int)) `hashA` a
liftHashWithSalt2 _hashA hashB salt (That b) =
(salt `hashWithSalt` (1 :: Int)) `hashB` b
liftHashWithSalt2 hashA hashB salt (These a b) =
(salt `hashWithSalt` (2 :: Int)) `hashA` a `hashB` b
|
8c353b113ffe24a98612b44049303f3800b5856ed3ec7a6a65a75f8c6e647148 | dzaporozhets/clojure-web-application | helpers.clj | (ns sample.features.helpers
(:require [sample.handler :refer [app]]
[sample.models.user :as db]
[sample.crypt :as crypt]
[kerodon.core :refer :all]
[kerodon.test :refer :all]
[clojure.test :refer :all]))
(def foo-email "")
(defn create-user []
(if-not (db/get-user-by-email foo-email)
(db/create-user {:name "Foo"
:email foo-email
:encrypted_password (crypt/encrypt "123456")})))
(defn remove-users []
(db/delete-user-by-email foo-email)
(db/delete-user-by-email ""))
| null | https://raw.githubusercontent.com/dzaporozhets/clojure-web-application/8d813fc95080a8ebc9532c0a4067f540f7f91553/test/sample/features/helpers.clj | clojure | (ns sample.features.helpers
(:require [sample.handler :refer [app]]
[sample.models.user :as db]
[sample.crypt :as crypt]
[kerodon.core :refer :all]
[kerodon.test :refer :all]
[clojure.test :refer :all]))
(def foo-email "")
(defn create-user []
(if-not (db/get-user-by-email foo-email)
(db/create-user {:name "Foo"
:email foo-email
:encrypted_password (crypt/encrypt "123456")})))
(defn remove-users []
(db/delete-user-by-email foo-email)
(db/delete-user-by-email ""))
| |
b10ed2d730c32c0b5cf3c5f5cecb9004f448e37b0332a1b4504fb3192813ecfc | slipstream/SlipStreamServer | quota.clj | (ns com.sixsq.slipstream.ssclj.resources.quota
"
The collection of Quota resources defines the overall resource utilization
policy for the SlipStream server. Each Quota resource defines a limit on an
identified resource. For new resource requests, SlipStream will verify that the
request will not exceed the defined quotas before executing the request.
Currently, SlipStream only checks quotas when deploying new workloads.
The Quota resource follows the standard CIMI SCRUD patterns. It is **not** a
templated resource and uses the simple CIMI add pattern.
> NOTE: Because quotas can potentially impact a large number of users, only
administrators can create Quota resources.
An abbreviated example of a Quota resource that sets a limit (116) on the
total number (count:id) of VirtualMachine resources for the given credential
for the MYORG organization.
```json
{
\"id\": \"quota/a6d547cd-3855-4b24-aae2-73ad0707d828\",
\"resourceURI\": \"\",
\"name\": \"max_instances in connector/exoscale-ch-dk\",
\"description\": \"limits regarding max_instances, for credential credential/45765716-33f0-46bb-b3de-7bef04a58998 in connector/exoscale-ch-dk\",
\"updated\": \"2018-10-18T05:17:21.162Z\",
\"created\": \"2018-08-06T05:30:03.214Z\",
\"resource\": \"VirtualMachine\",
\"selection\": \"credentials/href='credential/45765716-33f0-46bb-b3de-7bef04a58998'\"
\"aggregation\": \"count:id\",
\"limit\": 116,
\"acl\": {
\"owner\": {
\"type\": \"ROLE\",
\"principal\": \"ADMIN\"
},
\"rules\": [
{
\"right\": \"VIEW\",
\"type\": \"ROLE\",
\"principal\": \"MYORG:can_deploy\"
}
]
},
\"operations\": [
{
\"rel\": \"\",
\"href\": \"quota/a6d547cd-3855-4b24-aae2-73ad0707d828/collect\"
}
]
}
```
## Quota Attributes
| Attribute | Description |
| :---- | :---- |
| `resource` | Identifies the resource to which the quota applies. Current examples include 'VirtualMachine' and 'NuvlaBoxRecord', the source of the current debate. |
| `selection` | A CIMI filter expression that identifies the resources to include in the calculation of the current resource utilization. |
| `aggregation` | A CIMI aggregation expression that calculates the values for the current resource utilization. One number is calculated with the access rights of the user and another, with the access rights of 'super'. |
| `limit` | The value to compare the calculated resource utilization against. |
| `acl` | Defines to whom a given quota resource applies. If a quota resource is visible to an entity (user, group, role, etc.), it applies to that entity. |
### Collect Action
The 'collect' action (shown in the operations section) can be executed
by sending an HTTP POST request to the given URL.
This action will calculate the Quota's aggregation by running the
defined selection filter against the specified resource collection.
This will be done twice: once as the user and once with as the
administrator.
The Quota resource will be returned with two attributes added:
`current` and `currentAll`. These are described below.
| | |
| :---- | :---- |
| `current` | Aggregation result when run as the user. |
| `currentAll` | Aggregation result when run as the administrator. |
The enforcement algorithm for the resource will then accept or reject
a request by comparing the `current` or `currentAll` values to the
defined `limit`. How the comparison is done and how multiple
quotas are combined are defined by the enforcement algorithm itself.
"
(:require
[com.sixsq.slipstream.auth.acl :as a]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.schema :as c]
[com.sixsq.slipstream.ssclj.resources.common.std-crud :as std-crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.quota.utils :as quota-utils]
[com.sixsq.slipstream.ssclj.resources.spec.quota :as quota]
[com.sixsq.slipstream.util.response :as sr]
[superstring.core :as str]))
(def ^:const resource-name "Quota")
(def ^:const resource-tag (keyword (str (str/camel-case resource-name) "s")))
(def ^:const resource-url (u/de-camelcase resource-name))
(def ^:const collection-name "QuotaCollection")
(def ^:const resource-uri (str c/slipstream-schema-uri resource-name))
(def ^:const collection-uri (str c/slipstream-schema-uri collection-name))
(def collection-acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "USER"
:type "ROLE"
:right "VIEW"}]})
;;
;; multimethods for validation and operations
;;
(def validate-fn (u/create-spec-validation-fn ::quota/quota))
(defmethod crud/validate resource-uri
[resource]
(validate-fn resource))
;;
;; use default ACL method
;;
(defmethod crud/add-acl resource-uri
[resource request]
(a/add-acl resource request))
;;
;; CRUD operations
;;
(def add-impl (std-crud/add-fn resource-name collection-acl resource-uri))
(defmethod crud/add resource-name
[request]
(add-impl request))
(def retrieve-impl (std-crud/retrieve-fn resource-name))
(defmethod crud/retrieve resource-name
[request]
(retrieve-impl request))
(def edit-impl (std-crud/edit-fn resource-name))
(defmethod crud/edit resource-name
[request]
(edit-impl request))
(def delete-impl (std-crud/delete-fn resource-name))
(defmethod crud/delete resource-name
[request]
(delete-impl request))
(def query-impl (std-crud/query-fn resource-name collection-acl collection-uri resource-tag))
(defmethod crud/query resource-name
[request]
(query-impl request))
;;
;; provide an action that allows the quota to be evaluated
;; returns the quota resource augmented with the keys
: ( for all usage of the quota ) and : currentUser
;; (for all usage of the quota by that user).
;;
(defmethod crud/set-operations resource-uri
[{:keys [id resourceURI username] :as resource} request]
(let [href (str id "/collect")
collect-op {:rel (:collect c/action-uri) :href href}]
(-> (crud/set-standard-operations resource request)
(update-in [:operations] conj collect-op))))
(defmethod crud/do-action [resource-url "collect"]
[{{uuid :uuid} :params :as request}]
(try
(let [id (str resource-url "/" uuid)]
(-> (crud/retrieve-by-id-as-admin id)
(quota-utils/collect request)
sr/json-response))
(catch Exception e
(or (ex-data e) (throw e)))))
;;
;; initialization
;;
(defn initialize
[]
(std-crud/initialize resource-url ::quota/quota))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/cimi-resources/src/com/sixsq/slipstream/ssclj/resources/quota.clj | clojure | | Description |
multimethods for validation and operations
use default ACL method
CRUD operations
provide an action that allows the quota to be evaluated
returns the quota resource augmented with the keys
(for all usage of the quota by that user).
initialization
| (ns com.sixsq.slipstream.ssclj.resources.quota
"
The collection of Quota resources defines the overall resource utilization
policy for the SlipStream server. Each Quota resource defines a limit on an
identified resource. For new resource requests, SlipStream will verify that the
request will not exceed the defined quotas before executing the request.
Currently, SlipStream only checks quotas when deploying new workloads.
The Quota resource follows the standard CIMI SCRUD patterns. It is **not** a
templated resource and uses the simple CIMI add pattern.
> NOTE: Because quotas can potentially impact a large number of users, only
administrators can create Quota resources.
An abbreviated example of a Quota resource that sets a limit (116) on the
total number (count:id) of VirtualMachine resources for the given credential
for the MYORG organization.
```json
{
\"id\": \"quota/a6d547cd-3855-4b24-aae2-73ad0707d828\",
\"resourceURI\": \"\",
\"name\": \"max_instances in connector/exoscale-ch-dk\",
\"description\": \"limits regarding max_instances, for credential credential/45765716-33f0-46bb-b3de-7bef04a58998 in connector/exoscale-ch-dk\",
\"updated\": \"2018-10-18T05:17:21.162Z\",
\"created\": \"2018-08-06T05:30:03.214Z\",
\"resource\": \"VirtualMachine\",
\"selection\": \"credentials/href='credential/45765716-33f0-46bb-b3de-7bef04a58998'\"
\"aggregation\": \"count:id\",
\"limit\": 116,
\"acl\": {
\"owner\": {
\"type\": \"ROLE\",
\"principal\": \"ADMIN\"
},
\"rules\": [
{
\"right\": \"VIEW\",
\"type\": \"ROLE\",
\"principal\": \"MYORG:can_deploy\"
}
]
},
\"operations\": [
{
\"rel\": \"\",
\"href\": \"quota/a6d547cd-3855-4b24-aae2-73ad0707d828/collect\"
}
]
}
```
## Quota Attributes
| :---- | :---- |
| `resource` | Identifies the resource to which the quota applies. Current examples include 'VirtualMachine' and 'NuvlaBoxRecord', the source of the current debate. |
| `selection` | A CIMI filter expression that identifies the resources to include in the calculation of the current resource utilization. |
| `aggregation` | A CIMI aggregation expression that calculates the values for the current resource utilization. One number is calculated with the access rights of the user and another, with the access rights of 'super'. |
| `limit` | The value to compare the calculated resource utilization against. |
| `acl` | Defines to whom a given quota resource applies. If a quota resource is visible to an entity (user, group, role, etc.), it applies to that entity. |
### Collect Action
The 'collect' action (shown in the operations section) can be executed
by sending an HTTP POST request to the given URL.
This action will calculate the Quota's aggregation by running the
defined selection filter against the specified resource collection.
This will be done twice: once as the user and once with as the
administrator.
The Quota resource will be returned with two attributes added:
`current` and `currentAll`. These are described below.
| | |
| :---- | :---- |
| `current` | Aggregation result when run as the user. |
| `currentAll` | Aggregation result when run as the administrator. |
The enforcement algorithm for the resource will then accept or reject
a request by comparing the `current` or `currentAll` values to the
defined `limit`. How the comparison is done and how multiple
quotas are combined are defined by the enforcement algorithm itself.
"
(:require
[com.sixsq.slipstream.auth.acl :as a]
[com.sixsq.slipstream.ssclj.resources.common.crud :as crud]
[com.sixsq.slipstream.ssclj.resources.common.schema :as c]
[com.sixsq.slipstream.ssclj.resources.common.std-crud :as std-crud]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.quota.utils :as quota-utils]
[com.sixsq.slipstream.ssclj.resources.spec.quota :as quota]
[com.sixsq.slipstream.util.response :as sr]
[superstring.core :as str]))
(def ^:const resource-name "Quota")
(def ^:const resource-tag (keyword (str (str/camel-case resource-name) "s")))
(def ^:const resource-url (u/de-camelcase resource-name))
(def ^:const collection-name "QuotaCollection")
(def ^:const resource-uri (str c/slipstream-schema-uri resource-name))
(def ^:const collection-uri (str c/slipstream-schema-uri collection-name))
(def collection-acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "USER"
:type "ROLE"
:right "VIEW"}]})
(def validate-fn (u/create-spec-validation-fn ::quota/quota))
(defmethod crud/validate resource-uri
[resource]
(validate-fn resource))
(defmethod crud/add-acl resource-uri
[resource request]
(a/add-acl resource request))
(def add-impl (std-crud/add-fn resource-name collection-acl resource-uri))
(defmethod crud/add resource-name
[request]
(add-impl request))
(def retrieve-impl (std-crud/retrieve-fn resource-name))
(defmethod crud/retrieve resource-name
[request]
(retrieve-impl request))
(def edit-impl (std-crud/edit-fn resource-name))
(defmethod crud/edit resource-name
[request]
(edit-impl request))
(def delete-impl (std-crud/delete-fn resource-name))
(defmethod crud/delete resource-name
[request]
(delete-impl request))
(def query-impl (std-crud/query-fn resource-name collection-acl collection-uri resource-tag))
(defmethod crud/query resource-name
[request]
(query-impl request))
: ( for all usage of the quota ) and : currentUser
(defmethod crud/set-operations resource-uri
[{:keys [id resourceURI username] :as resource} request]
(let [href (str id "/collect")
collect-op {:rel (:collect c/action-uri) :href href}]
(-> (crud/set-standard-operations resource request)
(update-in [:operations] conj collect-op))))
(defmethod crud/do-action [resource-url "collect"]
[{{uuid :uuid} :params :as request}]
(try
(let [id (str resource-url "/" uuid)]
(-> (crud/retrieve-by-id-as-admin id)
(quota-utils/collect request)
sr/json-response))
(catch Exception e
(or (ex-data e) (throw e)))))
(defn initialize
[]
(std-crud/initialize resource-url ::quota/quota))
|
0ba01f49e23e8cf571cdc30a71acaa261614c6b3526a9c3be16d5b67256c3c59 | prepor/ocaml-edn | edn_cconv.mli | type t = Edn.t
val source : t CConv.Decode.source
val output : t CConv.Encode.output
val encode : 'a CConv.Encode.encoder -> 'a -> t
val decode : 'a CConv.Decode.decoder -> t -> 'a CConv.or_error
val decode_exn : 'a CConv.Decode.decoder -> t -> 'a
val to_string : t CConv.Encode.encoder -> t -> string
val of_string : 'a CConv.Decode.decoder -> string -> 'a CConv.or_error
val of_string_exn : 'a CConv.Decode.decoder -> string -> 'a
| null | https://raw.githubusercontent.com/prepor/ocaml-edn/3cc3c02dd24d5954aa3265cc743ada1fdd03c82c/cconv/edn_cconv.mli | ocaml | type t = Edn.t
val source : t CConv.Decode.source
val output : t CConv.Encode.output
val encode : 'a CConv.Encode.encoder -> 'a -> t
val decode : 'a CConv.Decode.decoder -> t -> 'a CConv.or_error
val decode_exn : 'a CConv.Decode.decoder -> t -> 'a
val to_string : t CConv.Encode.encoder -> t -> string
val of_string : 'a CConv.Decode.decoder -> string -> 'a CConv.or_error
val of_string_exn : 'a CConv.Decode.decoder -> string -> 'a
| |
5d867e52cae7dcd507711258ab5c1d1b864c05c4a5dc76a15a2f8a419dfecf0a | quil-lang/quilc | analysis-tests.lisp | ;;;; analysis-tests.lisp
;;;;
Author :
(in-package #:cl-quil-tests)
(defun same-list-p (a b)
(and (= (length a)
(length b))
(every #'=
(sort (copy-seq a) #'<)
(sort (copy-seq b) #'<))))
(a:define-constant +identity-defgate+ "
DEFGATE I:
1, 0, 0, 0
0, 1, 0, 0
0, 0, 1, 0
0, 0, 0, 1"
:test #'string=)
(deftest test-compress-qubits ()
"Test that qubits get compressed correctly."
(let ((p1 (with-output-to-quil
(write-line "H 0")
(write-line "RX(1.0) 1")
(write-line "MEASURE 1")
(write-line "RESET 1")
(write-line "CNOT 6 0")))
(p2 (with-output-to-quil
(write-line "RESET")
(write-line "NOP"))))
(is (= 7 (quil::qubits-needed p1)))
(is (= 0 (quil::qubits-needed p2)))
(is (same-list-p
'(0 1 6)
(quil::qubits-used p1)))
(is (null (quil::qubits-used p2)))
(quil::transform 'quil::compress-qubits p1)
(quil::transform 'quil::compress-qubits p2)
(is (= 3 (quil::qubits-needed p1)))
(is (= 0 (quil::qubits-needed p2)))
(is (same-list-p
'(0 1 2)
(quil::qubits-used p1)))
(is (null (quil::qubits-used p2)))))
(deftest test-repeat-labels ()
"Test that repeat labels are detected."
(let ((pp (with-output-to-quil
"LABEL @a"
"LABEL @a")))
(signals simple-error
(quil::transform 'quil::patch-labels pp))))
(defun identity-test-program (quil-instr)
(with-output-to-string (s)
(write-string +identity-defgate+ s)
(terpri s)
(write-string quil-instr s)
(terpri s)))
(deftest test-repeat-qubits ()
"Test that repeated qubits on a gate are detected."
(signals simple-error
(cl-quil:parse-quil
(identity-test-program "I 1 1"))))
(deftest test-too-few-qubits ()
"Test that a gate applied to too few qubits is detected."
(signals simple-error
(cl-quil:parse-quil
(identity-test-program "I 0"))))
(deftest test-too-many-qubits ()
"Test that a gate applied to too many qubits is detected."
(signals simple-error
(cl-quil:parse-quil "I 1 2 3")))
(deftest test-standard-gate-resolution ()
"Test that all standard gates resolve."
(let ((quil (with-output-to-quil
"I 0"
"X 0"
"Y 0"
"Z 0"
"H 0"
"RX(0.0) 0"
"RY(0.0) 0"
"RZ(0.0) 0"
"CNOT 0 1"
"CCNOT 0 1 2"
"S 0"
"T 0"
"PHASE(0.0) 0"
"CPHASE00(0.0) 0 1"
"CPHASE01(0.0) 0 1"
"CPHASE10(0.0) 0 1"
"CPHASE(0.0) 0 1"
"CZ 0 1"
"SWAP 0 1"
"CSWAP 0 1 2"
"ISWAP 0 1"
"PSWAP(0.0) 0 1")))
(is (every (lambda (isn)
(typep isn 'quil:gate-application))
(quil:parsed-program-executable-code quil)))))
(deftest test-qubit-relabeler ()
"Test that qubit relabeling seems to be sane."
(let ((r1 (cl-quil.frontend::qubit-relabeler #(0 1 2)))
(r2 (cl-quil.frontend::qubit-relabeler #(2 1 0)))
(r3 (cl-quil.frontend::qubit-relabeler #(5)))
(r4 (cl-quil.frontend::qubit-relabeler #())))
(flet ((test-success (relabeler qubit-input qubit-output)
(let ((q (quil:qubit qubit-input)))
(is (eq t (funcall relabeler q)))
(is (= qubit-output (quil:qubit-index q)))))
(test-choke (relabeler bad-input)
(signals simple-error (funcall relabeler (quil:qubit bad-input))))
(test-dont-choke (relabeler bad-input)
(let ((q (quil:qubit bad-input)))
(is (eq nil (funcall relabeler q :dont-choke t)))
(is (= bad-input (quil:qubit-index q))))))
;; Identity map
(test-success r1 0 0)
(test-success r1 1 1)
(test-success r1 2 2)
(test-choke r1 3)
(test-dont-choke r1 3)
;; Reverse map
(test-success r2 0 2)
(test-success r2 1 1)
(test-success r2 2 0)
(test-choke r2 3)
(test-dont-choke r2 3)
;; Partial map
(test-success r3 5 0)
(test-choke r3 4)
(test-dont-choke r3 4)
;; Empty map
(test-choke r4 0)
(test-dont-choke r4 0))))
(deftest test-kraus-stuff-rewritten-properly ()
"Test that COMPRESS-QUBITS acts correctly on Kraus/POVM PRAGMAs."
(let ((p (quil:parse-quil "
DECLARE ro BIT[6]
PRAGMA ADD-KRAUS X 0 \"(0 0 0 0)\"
PRAGMA ADD-KRAUS X 5 \"(5 0 0 0)\"
PRAGMA READOUT-POVM 0 \"(0 0 0 0)\"
PRAGMA READOUT-POVM 5 \"(5 0 0 0)\"
X 5
MEASURE 5 ro[5]
")))
(setf p (quil::compress-qubits p))
(let ((code (quil:parsed-program-executable-code p)))
(is (typep (aref code 0) 'quil:no-operation))
(is (typep (aref code 1) 'quil::pragma-add-kraus))
(is (typep (aref code 2) 'quil:no-operation))
(is (typep (aref code 3) 'quil::pragma-readout-povm))
(is (equal '(0) (quil:pragma-qubit-arguments (aref code 1))))
(is (zerop (quil:pragma-qubit-index (aref code 3)))))))
(deftest test-parameter-arithmetic-rewriting ()
"Test rewriting arithmetic for gates with and without parameters."
(let ((in-p (let ((quil:*allow-unresolved-applications* t))
(quil:parse-quil "
DECLARE a REAL
DECLARE b REAL[2]
A(1, 1 + 1, a, 1 + a)
B(a) 0
C(2) 0 1
D(2 * a) 0 1 2
E(a + 3 * b[1]) 0 1 2 3
"))))
(multiple-value-bind (p mem-descriptors recalc-table)
(rewrite-arithmetic in-p)
(let ((__p (find-if (lambda (name) (eql 0 (search "__P" name)))
(quil:parsed-program-memory-definitions p)
:key #'quil::memory-descriptor-name)))
;; Do we have the memory descriptor?
(is (not (null __p)))
;; Is it the right length?
(is (= 3 (quil::memory-descriptor-length __p)))
;; Is the recalc table of equal size?
(is (= 3 (hash-table-count recalc-table)))
;; Are the members of the table correct?
(let ((__p-name (memory-descriptor-name __p)))
(dotimes (i 3)
(is (not (null (gethash (mref __p-name i) recalc-table)))))
;; Are the actual expressions correct?
(labels ((cleanse-mrefs (expr)
delete the descriptors from any mrefs present in
;; expr
(cond
((typep expr 'quil::memory-ref)
(setf (quil::memory-ref-descriptor expr) nil)
expr)
((atom expr)
expr)
(t (cons (cleanse-mrefs (car expr))
(cleanse-mrefs (cdr expr))))))
(get-mref (i)
(cleanse-mrefs
(quil::delayed-expression-expression
(gethash (mref __p-name i) recalc-table)))))
(let ((A (get-mref 0))
(D (get-mref 1))
(E (get-mref 2)))
A should be 1 + a[0 ]
(is (equalp A `(+ 1.0d0 ,(mref "a" 0))))
D should be 2 * a[0 ]
(is (equalp D `(* 2.0d0 ,(mref "a" 0))))
;; E should be a[0] + 3 * b[1]
(is (equalp E `(+ ,(mref "a" 0) (* 3.0d0 ,(mref "b" 1))))))))
;; Now we go through the program to make sure that is correct.
(let ((old-code (quil:parsed-program-executable-code in-p))
(new-code (quil:parsed-program-executable-code p)))
;; Is it the same length as the old one?
(is (= (length old-code) (length new-code)))
;; Are the untouched instructions' parameters the same?
(is (equalp (application-parameters (aref old-code 1))
(application-parameters (aref new-code 1))))
(is (equalp (application-parameters (aref old-code 2))
(application-parameters (aref new-code 2))))
;; Do the new instructions have rewritten parameters?
(flet ((checkem (program-index parameter-index mref-index)
(let ((rewritten-param
(nth parameter-index
(application-parameters (aref new-code program-index)))))
(is (typep rewritten-param 'quil::delayed-expression))
(let ((new-mref (quil::delayed-expression-expression rewritten-param)))
(is (typep new-mref 'quil::memory-ref))
(is (zerop (search "__P" (quil::memory-ref-name new-mref))))
(is (= mref-index (quil::memory-ref-position new-mref)))))))
(checkem 0 3 0)
(checkem 3 0 1)
(checkem 4 0 2))
;; Are our returned memory descriptors the same as the old ones?
(let ((old-defs (quil:parsed-program-memory-definitions in-p)))
(is (and (subsetp old-defs mem-descriptors)
(subsetp mem-descriptors old-defs)))))))))
(deftest test-plain-arithmetic-rewriting ()
"Test rewriting arithmetic for a program without any parameters to rewrite."
(let ((in-p (let ((quil:*allow-unresolved-applications* t))
(quil:parse-quil "
DECLARE a REAL
DECLARE b REAL[2]
A(1, 1 + 1, a)
B(b) 0 1
"))))
(multiple-value-bind (p mem-descriptors recalc-table)
(rewrite-arithmetic in-p)
;; Is the recalc table empty?
(is (= 0 (hash-table-count recalc-table)))
(let ((old-code (quil:parsed-program-executable-code in-p))
(new-code (quil:parsed-program-executable-code p)))
;; Is the old program the same length as the new one?
(is (= (length old-code) (length new-code))))
(let ((old-defs (quil:parsed-program-memory-definitions in-p)))
;; Are our returned memory descriptors the same as the old ones?
(is (and (subsetp old-defs mem-descriptors)
(subsetp mem-descriptors old-defs)))
;; Are there no new memory descriptors (no __P)?
(is (= (length old-defs) (length mem-descriptors)))))))
;;; Fusion tests
(deftest test-grid-node ()
"Tests on the grid node data structure and associated functions."
(let ((q0 (cl-quil.frontend::make-grid-node 'q0 0))
(q1 (cl-quil.frontend::make-grid-node 'q1 1))
(q2 (cl-quil.frontend::make-grid-node 'q2 2))
(q01 (cl-quil.frontend::make-grid-node 'q01 0 1))
(q12 (cl-quil.frontend::make-grid-node 'q12 1 2))
(q02 (cl-quil.frontend::make-grid-node 'q02 0 2)))
;; All nodes start as root nodes.
(is (every #'cl-quil.frontend::root-node-p (list q0 q1 q2 q01 q12 q02)))
;; Set succeeding, check preceding.
(setf (cl-quil.frontend::succeeding-node-on-qubit q0 0) q01)
(is (eq q01 (cl-quil.frontend::succeeding-node-on-qubit q0 0)))
;; Set preceding, check succeeding
(setf (cl-quil.frontend::preceding-node-on-qubit q12 2) q2)
(is (eq q2 (cl-quil.frontend::preceding-node-on-qubit q12 2)))
;; Check that we can't set a preceding or succeeding node on
;; invalid qubits.
(signals error (setf (cl-quil.frontend::succeeding-node-on-qubit q2 0) q02))
(signals error (setf (cl-quil.frontend::preceding-node-on-qubit q02 1) q1))
;; Check trailer dealios.
(is (cl-quil.frontend::trailer-node-on-qubit-p q01 0))
(is (not (cl-quil.frontend::trailer-node-on-qubit-p q0 0)))))
(defclass dummy-node ()
((value :initarg :value
:accessor dummy-node-value)))
(defun dummy-node (x)
(make-instance 'dummy-node :value (a:ensure-list x)))
(defmethod quil::fuse-objects ((a dummy-node) (b dummy-node))
(make-instance 'dummy-node
:value (append
(a:ensure-list (dummy-node-value a))
(a:ensure-list (dummy-node-value b)))))
(deftest test-fuse-dummy-objects ()
"Test that FUSE-OBJECTS behaves properly in MERGE-GRID-NODES."
(is (equal '(a b)
(dummy-node-value
(cl-quil.frontend::grid-node-tag
(cl-quil.frontend::merge-grid-nodes
(cl-quil.frontend::make-grid-node (dummy-node 'a) 1)
(cl-quil.frontend::make-grid-node (dummy-node 'b) 1)))))))
(defun build-grid (&rest proto-nodes)
(loop :with pg := (make-instance 'cl-quil.frontend::program-grid)
:for (x . qs) :in proto-nodes
:for gn := (apply #'cl-quil.frontend::make-grid-node
(dummy-node x)
qs)
:do (cl-quil.frontend::append-node pg gn)
:finally (return pg)))
(deftest test-trivial-fusion ()
"Test that a bunch of trivially fuseable gates can be fused."
(flet ((test-it (&rest proto-nodes)
(let ((output-pg (cl-quil.frontend::fuse-trivially (apply #'build-grid proto-nodes))))
(is (= 1 (length (cl-quil.frontend::roots output-pg))))
(let ((root (first (cl-quil.frontend::roots output-pg))))
(is (cl-quil.frontend::root-node-p root))
(is (every (a:curry #'eq root) (cl-quil.frontend::trailers output-pg)))
(is (every #'null (cl-quil.frontend::grid-node-back root)))
(is (every #'null (cl-quil.frontend::grid-node-forward root)))
(is (equalp (mapcar #'first proto-nodes)
(dummy-node-value (cl-quil.frontend::grid-node-tag root))))))))
(test-it '(a 0)
'(b 0 1)
'(c 0 1 2)
'(d 0 1 2 3))
(test-it '(a 0 1 2 3)
'(b 0 1 2)
'(c 0 1)
'(d 0))
(test-it '(a 0 1 2 3)
'(b 0 1 2 3)
'(c 0 1 2 3)
'(d 0 1 2 3))
(test-it '(a 0)
'(b 0 1)
'(c 0 1 2)
'(d 0 1 2 3)
'(e 0 1 2)
'(f 0 1)
'(g 0))))
;;; Simplify arithmetic tests
(deftest test-simplify-arithmetic-linear ()
"Test that a linear expression can simplified"
(let ((in-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(2.0+3.0*theta[0]-3.0*theta[0]/4.0-2.0) 0
"))
(out-p (quil::parse-quil "
DECLARE theta REAL[1]
RX(2.25*theta[0]) 0
")))
(setf in-p (quil::simplify-arithmetic in-p))
(is (equalp (quil::application-parameters (quil::nth-instr 0 in-p))
(quil::application-parameters (quil::nth-instr 0 out-p))))))
(deftest test-simplify-arithmetic-non-linear ()
"Test that a non-linear expression is left alone"
(let ((in-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(2.0+3.0*cos(theta[0])-3.0*theta[0]-2.0) 0
"))
(out-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(2.0+3.0*cos(theta[0])-3.0*theta[0]-2.0) 0
")))
(setf in-p (quil::simplify-arithmetic in-p))
(is (equalp (quil::application-parameters (quil::nth-instr 0 in-p))
(quil::application-parameters (quil::nth-instr 0 out-p))))))
(deftest test-simplify-arithmetic-negative-references ()
"Test that simplification works on negative-prefixed memory references e.g. RX(-theta[0] + 2.0*theta[0] + 2.0) 0 -> RX(2.0 + 1.0*theta[0]) 0"
(let ((in-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(-theta[0]+2.0*theta[0]+2.0) 0
"))
(out-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(2.0+theta[0]) 0
")))
(setf in-p (quil::simplify-arithmetic in-p))
(is (equalp (quil::application-parameters (quil::nth-instr 0 in-p))
(quil::application-parameters (quil::nth-instr 0 out-p))))))
| null | https://raw.githubusercontent.com/quil-lang/quilc/44442079373f8033c7ccc7f95854fcd2ea185dba/tests/analysis-tests.lisp | lisp | analysis-tests.lisp
Identity map
Reverse map
Partial map
Empty map
Do we have the memory descriptor?
Is it the right length?
Is the recalc table of equal size?
Are the members of the table correct?
Are the actual expressions correct?
expr
E should be a[0] + 3 * b[1]
Now we go through the program to make sure that is correct.
Is it the same length as the old one?
Are the untouched instructions' parameters the same?
Do the new instructions have rewritten parameters?
Are our returned memory descriptors the same as the old ones?
Is the recalc table empty?
Is the old program the same length as the new one?
Are our returned memory descriptors the same as the old ones?
Are there no new memory descriptors (no __P)?
Fusion tests
All nodes start as root nodes.
Set succeeding, check preceding.
Set preceding, check succeeding
Check that we can't set a preceding or succeeding node on
invalid qubits.
Check trailer dealios.
Simplify arithmetic tests | Author :
(in-package #:cl-quil-tests)
(defun same-list-p (a b)
(and (= (length a)
(length b))
(every #'=
(sort (copy-seq a) #'<)
(sort (copy-seq b) #'<))))
(a:define-constant +identity-defgate+ "
DEFGATE I:
1, 0, 0, 0
0, 1, 0, 0
0, 0, 1, 0
0, 0, 0, 1"
:test #'string=)
(deftest test-compress-qubits ()
"Test that qubits get compressed correctly."
(let ((p1 (with-output-to-quil
(write-line "H 0")
(write-line "RX(1.0) 1")
(write-line "MEASURE 1")
(write-line "RESET 1")
(write-line "CNOT 6 0")))
(p2 (with-output-to-quil
(write-line "RESET")
(write-line "NOP"))))
(is (= 7 (quil::qubits-needed p1)))
(is (= 0 (quil::qubits-needed p2)))
(is (same-list-p
'(0 1 6)
(quil::qubits-used p1)))
(is (null (quil::qubits-used p2)))
(quil::transform 'quil::compress-qubits p1)
(quil::transform 'quil::compress-qubits p2)
(is (= 3 (quil::qubits-needed p1)))
(is (= 0 (quil::qubits-needed p2)))
(is (same-list-p
'(0 1 2)
(quil::qubits-used p1)))
(is (null (quil::qubits-used p2)))))
(deftest test-repeat-labels ()
"Test that repeat labels are detected."
(let ((pp (with-output-to-quil
"LABEL @a"
"LABEL @a")))
(signals simple-error
(quil::transform 'quil::patch-labels pp))))
(defun identity-test-program (quil-instr)
(with-output-to-string (s)
(write-string +identity-defgate+ s)
(terpri s)
(write-string quil-instr s)
(terpri s)))
(deftest test-repeat-qubits ()
"Test that repeated qubits on a gate are detected."
(signals simple-error
(cl-quil:parse-quil
(identity-test-program "I 1 1"))))
(deftest test-too-few-qubits ()
"Test that a gate applied to too few qubits is detected."
(signals simple-error
(cl-quil:parse-quil
(identity-test-program "I 0"))))
(deftest test-too-many-qubits ()
"Test that a gate applied to too many qubits is detected."
(signals simple-error
(cl-quil:parse-quil "I 1 2 3")))
(deftest test-standard-gate-resolution ()
"Test that all standard gates resolve."
(let ((quil (with-output-to-quil
"I 0"
"X 0"
"Y 0"
"Z 0"
"H 0"
"RX(0.0) 0"
"RY(0.0) 0"
"RZ(0.0) 0"
"CNOT 0 1"
"CCNOT 0 1 2"
"S 0"
"T 0"
"PHASE(0.0) 0"
"CPHASE00(0.0) 0 1"
"CPHASE01(0.0) 0 1"
"CPHASE10(0.0) 0 1"
"CPHASE(0.0) 0 1"
"CZ 0 1"
"SWAP 0 1"
"CSWAP 0 1 2"
"ISWAP 0 1"
"PSWAP(0.0) 0 1")))
(is (every (lambda (isn)
(typep isn 'quil:gate-application))
(quil:parsed-program-executable-code quil)))))
(deftest test-qubit-relabeler ()
"Test that qubit relabeling seems to be sane."
(let ((r1 (cl-quil.frontend::qubit-relabeler #(0 1 2)))
(r2 (cl-quil.frontend::qubit-relabeler #(2 1 0)))
(r3 (cl-quil.frontend::qubit-relabeler #(5)))
(r4 (cl-quil.frontend::qubit-relabeler #())))
(flet ((test-success (relabeler qubit-input qubit-output)
(let ((q (quil:qubit qubit-input)))
(is (eq t (funcall relabeler q)))
(is (= qubit-output (quil:qubit-index q)))))
(test-choke (relabeler bad-input)
(signals simple-error (funcall relabeler (quil:qubit bad-input))))
(test-dont-choke (relabeler bad-input)
(let ((q (quil:qubit bad-input)))
(is (eq nil (funcall relabeler q :dont-choke t)))
(is (= bad-input (quil:qubit-index q))))))
(test-success r1 0 0)
(test-success r1 1 1)
(test-success r1 2 2)
(test-choke r1 3)
(test-dont-choke r1 3)
(test-success r2 0 2)
(test-success r2 1 1)
(test-success r2 2 0)
(test-choke r2 3)
(test-dont-choke r2 3)
(test-success r3 5 0)
(test-choke r3 4)
(test-dont-choke r3 4)
(test-choke r4 0)
(test-dont-choke r4 0))))
(deftest test-kraus-stuff-rewritten-properly ()
"Test that COMPRESS-QUBITS acts correctly on Kraus/POVM PRAGMAs."
(let ((p (quil:parse-quil "
DECLARE ro BIT[6]
PRAGMA ADD-KRAUS X 0 \"(0 0 0 0)\"
PRAGMA ADD-KRAUS X 5 \"(5 0 0 0)\"
PRAGMA READOUT-POVM 0 \"(0 0 0 0)\"
PRAGMA READOUT-POVM 5 \"(5 0 0 0)\"
X 5
MEASURE 5 ro[5]
")))
(setf p (quil::compress-qubits p))
(let ((code (quil:parsed-program-executable-code p)))
(is (typep (aref code 0) 'quil:no-operation))
(is (typep (aref code 1) 'quil::pragma-add-kraus))
(is (typep (aref code 2) 'quil:no-operation))
(is (typep (aref code 3) 'quil::pragma-readout-povm))
(is (equal '(0) (quil:pragma-qubit-arguments (aref code 1))))
(is (zerop (quil:pragma-qubit-index (aref code 3)))))))
(deftest test-parameter-arithmetic-rewriting ()
"Test rewriting arithmetic for gates with and without parameters."
(let ((in-p (let ((quil:*allow-unresolved-applications* t))
(quil:parse-quil "
DECLARE a REAL
DECLARE b REAL[2]
A(1, 1 + 1, a, 1 + a)
B(a) 0
C(2) 0 1
D(2 * a) 0 1 2
E(a + 3 * b[1]) 0 1 2 3
"))))
(multiple-value-bind (p mem-descriptors recalc-table)
(rewrite-arithmetic in-p)
(let ((__p (find-if (lambda (name) (eql 0 (search "__P" name)))
(quil:parsed-program-memory-definitions p)
:key #'quil::memory-descriptor-name)))
(is (not (null __p)))
(is (= 3 (quil::memory-descriptor-length __p)))
(is (= 3 (hash-table-count recalc-table)))
(let ((__p-name (memory-descriptor-name __p)))
(dotimes (i 3)
(is (not (null (gethash (mref __p-name i) recalc-table)))))
(labels ((cleanse-mrefs (expr)
delete the descriptors from any mrefs present in
(cond
((typep expr 'quil::memory-ref)
(setf (quil::memory-ref-descriptor expr) nil)
expr)
((atom expr)
expr)
(t (cons (cleanse-mrefs (car expr))
(cleanse-mrefs (cdr expr))))))
(get-mref (i)
(cleanse-mrefs
(quil::delayed-expression-expression
(gethash (mref __p-name i) recalc-table)))))
(let ((A (get-mref 0))
(D (get-mref 1))
(E (get-mref 2)))
A should be 1 + a[0 ]
(is (equalp A `(+ 1.0d0 ,(mref "a" 0))))
D should be 2 * a[0 ]
(is (equalp D `(* 2.0d0 ,(mref "a" 0))))
(is (equalp E `(+ ,(mref "a" 0) (* 3.0d0 ,(mref "b" 1))))))))
(let ((old-code (quil:parsed-program-executable-code in-p))
(new-code (quil:parsed-program-executable-code p)))
(is (= (length old-code) (length new-code)))
(is (equalp (application-parameters (aref old-code 1))
(application-parameters (aref new-code 1))))
(is (equalp (application-parameters (aref old-code 2))
(application-parameters (aref new-code 2))))
(flet ((checkem (program-index parameter-index mref-index)
(let ((rewritten-param
(nth parameter-index
(application-parameters (aref new-code program-index)))))
(is (typep rewritten-param 'quil::delayed-expression))
(let ((new-mref (quil::delayed-expression-expression rewritten-param)))
(is (typep new-mref 'quil::memory-ref))
(is (zerop (search "__P" (quil::memory-ref-name new-mref))))
(is (= mref-index (quil::memory-ref-position new-mref)))))))
(checkem 0 3 0)
(checkem 3 0 1)
(checkem 4 0 2))
(let ((old-defs (quil:parsed-program-memory-definitions in-p)))
(is (and (subsetp old-defs mem-descriptors)
(subsetp mem-descriptors old-defs)))))))))
(deftest test-plain-arithmetic-rewriting ()
"Test rewriting arithmetic for a program without any parameters to rewrite."
(let ((in-p (let ((quil:*allow-unresolved-applications* t))
(quil:parse-quil "
DECLARE a REAL
DECLARE b REAL[2]
A(1, 1 + 1, a)
B(b) 0 1
"))))
(multiple-value-bind (p mem-descriptors recalc-table)
(rewrite-arithmetic in-p)
(is (= 0 (hash-table-count recalc-table)))
(let ((old-code (quil:parsed-program-executable-code in-p))
(new-code (quil:parsed-program-executable-code p)))
(is (= (length old-code) (length new-code))))
(let ((old-defs (quil:parsed-program-memory-definitions in-p)))
(is (and (subsetp old-defs mem-descriptors)
(subsetp mem-descriptors old-defs)))
(is (= (length old-defs) (length mem-descriptors)))))))
(deftest test-grid-node ()
"Tests on the grid node data structure and associated functions."
(let ((q0 (cl-quil.frontend::make-grid-node 'q0 0))
(q1 (cl-quil.frontend::make-grid-node 'q1 1))
(q2 (cl-quil.frontend::make-grid-node 'q2 2))
(q01 (cl-quil.frontend::make-grid-node 'q01 0 1))
(q12 (cl-quil.frontend::make-grid-node 'q12 1 2))
(q02 (cl-quil.frontend::make-grid-node 'q02 0 2)))
(is (every #'cl-quil.frontend::root-node-p (list q0 q1 q2 q01 q12 q02)))
(setf (cl-quil.frontend::succeeding-node-on-qubit q0 0) q01)
(is (eq q01 (cl-quil.frontend::succeeding-node-on-qubit q0 0)))
(setf (cl-quil.frontend::preceding-node-on-qubit q12 2) q2)
(is (eq q2 (cl-quil.frontend::preceding-node-on-qubit q12 2)))
(signals error (setf (cl-quil.frontend::succeeding-node-on-qubit q2 0) q02))
(signals error (setf (cl-quil.frontend::preceding-node-on-qubit q02 1) q1))
(is (cl-quil.frontend::trailer-node-on-qubit-p q01 0))
(is (not (cl-quil.frontend::trailer-node-on-qubit-p q0 0)))))
(defclass dummy-node ()
((value :initarg :value
:accessor dummy-node-value)))
(defun dummy-node (x)
(make-instance 'dummy-node :value (a:ensure-list x)))
(defmethod quil::fuse-objects ((a dummy-node) (b dummy-node))
(make-instance 'dummy-node
:value (append
(a:ensure-list (dummy-node-value a))
(a:ensure-list (dummy-node-value b)))))
(deftest test-fuse-dummy-objects ()
"Test that FUSE-OBJECTS behaves properly in MERGE-GRID-NODES."
(is (equal '(a b)
(dummy-node-value
(cl-quil.frontend::grid-node-tag
(cl-quil.frontend::merge-grid-nodes
(cl-quil.frontend::make-grid-node (dummy-node 'a) 1)
(cl-quil.frontend::make-grid-node (dummy-node 'b) 1)))))))
(defun build-grid (&rest proto-nodes)
(loop :with pg := (make-instance 'cl-quil.frontend::program-grid)
:for (x . qs) :in proto-nodes
:for gn := (apply #'cl-quil.frontend::make-grid-node
(dummy-node x)
qs)
:do (cl-quil.frontend::append-node pg gn)
:finally (return pg)))
(deftest test-trivial-fusion ()
"Test that a bunch of trivially fuseable gates can be fused."
(flet ((test-it (&rest proto-nodes)
(let ((output-pg (cl-quil.frontend::fuse-trivially (apply #'build-grid proto-nodes))))
(is (= 1 (length (cl-quil.frontend::roots output-pg))))
(let ((root (first (cl-quil.frontend::roots output-pg))))
(is (cl-quil.frontend::root-node-p root))
(is (every (a:curry #'eq root) (cl-quil.frontend::trailers output-pg)))
(is (every #'null (cl-quil.frontend::grid-node-back root)))
(is (every #'null (cl-quil.frontend::grid-node-forward root)))
(is (equalp (mapcar #'first proto-nodes)
(dummy-node-value (cl-quil.frontend::grid-node-tag root))))))))
(test-it '(a 0)
'(b 0 1)
'(c 0 1 2)
'(d 0 1 2 3))
(test-it '(a 0 1 2 3)
'(b 0 1 2)
'(c 0 1)
'(d 0))
(test-it '(a 0 1 2 3)
'(b 0 1 2 3)
'(c 0 1 2 3)
'(d 0 1 2 3))
(test-it '(a 0)
'(b 0 1)
'(c 0 1 2)
'(d 0 1 2 3)
'(e 0 1 2)
'(f 0 1)
'(g 0))))
(deftest test-simplify-arithmetic-linear ()
"Test that a linear expression can simplified"
(let ((in-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(2.0+3.0*theta[0]-3.0*theta[0]/4.0-2.0) 0
"))
(out-p (quil::parse-quil "
DECLARE theta REAL[1]
RX(2.25*theta[0]) 0
")))
(setf in-p (quil::simplify-arithmetic in-p))
(is (equalp (quil::application-parameters (quil::nth-instr 0 in-p))
(quil::application-parameters (quil::nth-instr 0 out-p))))))
(deftest test-simplify-arithmetic-non-linear ()
"Test that a non-linear expression is left alone"
(let ((in-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(2.0+3.0*cos(theta[0])-3.0*theta[0]-2.0) 0
"))
(out-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(2.0+3.0*cos(theta[0])-3.0*theta[0]-2.0) 0
")))
(setf in-p (quil::simplify-arithmetic in-p))
(is (equalp (quil::application-parameters (quil::nth-instr 0 in-p))
(quil::application-parameters (quil::nth-instr 0 out-p))))))
(deftest test-simplify-arithmetic-negative-references ()
"Test that simplification works on negative-prefixed memory references e.g. RX(-theta[0] + 2.0*theta[0] + 2.0) 0 -> RX(2.0 + 1.0*theta[0]) 0"
(let ((in-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(-theta[0]+2.0*theta[0]+2.0) 0
"))
(out-p (quil:parse-quil "
DECLARE theta REAL[1]
RX(2.0+theta[0]) 0
")))
(setf in-p (quil::simplify-arithmetic in-p))
(is (equalp (quil::application-parameters (quil::nth-instr 0 in-p))
(quil::application-parameters (quil::nth-instr 0 out-p))))))
|
05d3a7a165741cad28852670f739a8fa32c6d8331d58cfe61d7892c51c8864be | lspector/Clojush | uball5d.clj | ;; uball5d.clj
an example problem for clojush , a Push / PushGP system written in Clojure
, , 2017
(ns clojush.problems.regression.uball5d
(:use [clojush.pushgp.pushgp]
[clojush.pushstate]
[clojush.random]
[clojush.interpreter]
[clojure.math.numeric-tower]))
;;;;;;;;;;;;
Floating point symbolic regression of the Vladislavleva 2009 UBall5D problem .
;; Each training case will be in the form [[x1 x2 x3 x4 x5] y], where the xs are
;; inputs and y is the output.
(def uball5d-training-cases
(for [xseq (repeatedly 1024
(fn [] (repeatedly 5
#(+ 0.05 (lrand 6.05)))))]
[xseq
(->> (map (fn [x] (#(* % %) (- x 3)))
xseq)
(reduce +)
(+ 5)
(/ 10.0))]))
(def argmap
{:error-function (fn [individual]
(assoc individual
:errors
(doall
(for [[[x1 x2 x3 x4 x5] y] uball5d-training-cases]
(let [result (->> (run-push (:program individual)
(->> (make-push-state)
(push-item x1 :input)
(push-item x2 :input)
(push-item x3 :input)
(push-item x4 :input)
(push-item x5 :input)))
(top-item :float))]
(if (number? result)
(Math/abs (- result y))
1000000))))))
:atom-generators (conj '[float_div float_mult float_sub float_add
float_rot float_swap float_dup float_pop
in1 in2 in3 in4 in5]
lrand)
:error-threshold 0.01
:epigenetic-markers []
:parent-selection :epsilon-lexicase
:genetic-operator-probabilities {:alternation 0.5
:uniform-mutation 0.5}})
| null | https://raw.githubusercontent.com/lspector/Clojush/685b991535607cf942ae1500557171a0739982c3/src/clojush/problems/regression/uball5d.clj | clojure | uball5d.clj
Each training case will be in the form [[x1 x2 x3 x4 x5] y], where the xs are
inputs and y is the output. | an example problem for clojush , a Push / PushGP system written in Clojure
, , 2017
(ns clojush.problems.regression.uball5d
(:use [clojush.pushgp.pushgp]
[clojush.pushstate]
[clojush.random]
[clojush.interpreter]
[clojure.math.numeric-tower]))
Floating point symbolic regression of the Vladislavleva 2009 UBall5D problem .
(def uball5d-training-cases
(for [xseq (repeatedly 1024
(fn [] (repeatedly 5
#(+ 0.05 (lrand 6.05)))))]
[xseq
(->> (map (fn [x] (#(* % %) (- x 3)))
xseq)
(reduce +)
(+ 5)
(/ 10.0))]))
(def argmap
{:error-function (fn [individual]
(assoc individual
:errors
(doall
(for [[[x1 x2 x3 x4 x5] y] uball5d-training-cases]
(let [result (->> (run-push (:program individual)
(->> (make-push-state)
(push-item x1 :input)
(push-item x2 :input)
(push-item x3 :input)
(push-item x4 :input)
(push-item x5 :input)))
(top-item :float))]
(if (number? result)
(Math/abs (- result y))
1000000))))))
:atom-generators (conj '[float_div float_mult float_sub float_add
float_rot float_swap float_dup float_pop
in1 in2 in3 in4 in5]
lrand)
:error-threshold 0.01
:epigenetic-markers []
:parent-selection :epsilon-lexicase
:genetic-operator-probabilities {:alternation 0.5
:uniform-mutation 0.5}})
|
3dddb23a865f95353fea772741282eb61efc02a2b4542feba16f5efb83603fe8 | swaywm/cl-wlroots | surface.lisp | (in-package #:wlr/types/surface)
(export '(subsurface
subsurface-create
subsurface-state
surface
surface-create
surface-for-each-surface
surface-from-resource
surface-get-extends
surface-get-root-surface
surface-get-texture
surface-has-buffer
surface-point-accepts-input
surface-role
surface-send-enter
surface-send-frame-done
surface-send-leave
surface-set-role
surface-state
surface-state-field
surface-surface-at))
(cffi:defcfun ("wlr_surface_create" surface-create) :pointer
(client :pointer)
(version :uint32)
(id :uint32)
(renderer :pointer)
(resource-list :pointer))
(cffi:defcfun ("wlr_surface_set_role" surface-set-role) :pointer
(surface :pointer)
(role :pointer)
(role-data :pointer)
(error-resource :pointer)
(error-code :uint32))
(cffi:defcfun ("wlr_surface_has_buffer" surface-has-buffer) :pointer
(surface :pointer))
(cffi:defcfun ("wlr_surface_get_texture" surface-get-texture) :pointer
(surface :pointer))
(cffi:defcfun ("wlr_subsurface_create" subsurface-create) :pointer
(surface :pointer)
(parent :pointer)
(version :uint32)
(id :pointer)
(resource-list :pointer))
(cffi:defcfun ("wlr_surface_get_root_surface" surface-get-root-surface) :pointer
(surface :pointer))
(cffi:defcfun ("wlr_surface_point_accepts_input" surface-point-accepts-input) :pointer
(surface :pointer)
(sx :double)
(sy :double))
(cffi:defcfun ("wlr_surface_surface_at" surface-surface-at) :pointer
(surface :pointer)
(sx :double)
(sy :double)
(sub-x :pointer)
(sub-y :pointer))
(cffi:defcfun ("wlr_surface_send_enter" surface-send-enter) :void
(surface :pointer)
(output (:pointer (:struct output))))
(cffi:defcfun ("wlr_surface_send_leave" surface-send-leave) :void
(surface :pointer)
(output (:pointer (:struct output))))
(cffi:defcfun ("wlr_surface_send_frame_done" surface-send-frame-done) :void
(surface :pointer)
(time :pointer))
(cffi:defcfun ("wlr_surface_get_extends" surface-get-extends) :void
(surface :pointer)
(box box))
(cffi:defcfun ("wlr_surface_from_resource" surface-from-resource) :pointer
(resource :pointer))
(cffi:defcfun ("wlr_surface_for_each_surface" surface-for-each-surface) :void
(surface :pointer)
(iterator :pointer)
(user-data :pointer))
| null | https://raw.githubusercontent.com/swaywm/cl-wlroots/f8a33979e45086ecd5c7deefd5ee067b941e0998/wlr/types/surface.lisp | lisp | (in-package #:wlr/types/surface)
(export '(subsurface
subsurface-create
subsurface-state
surface
surface-create
surface-for-each-surface
surface-from-resource
surface-get-extends
surface-get-root-surface
surface-get-texture
surface-has-buffer
surface-point-accepts-input
surface-role
surface-send-enter
surface-send-frame-done
surface-send-leave
surface-set-role
surface-state
surface-state-field
surface-surface-at))
(cffi:defcfun ("wlr_surface_create" surface-create) :pointer
(client :pointer)
(version :uint32)
(id :uint32)
(renderer :pointer)
(resource-list :pointer))
(cffi:defcfun ("wlr_surface_set_role" surface-set-role) :pointer
(surface :pointer)
(role :pointer)
(role-data :pointer)
(error-resource :pointer)
(error-code :uint32))
(cffi:defcfun ("wlr_surface_has_buffer" surface-has-buffer) :pointer
(surface :pointer))
(cffi:defcfun ("wlr_surface_get_texture" surface-get-texture) :pointer
(surface :pointer))
(cffi:defcfun ("wlr_subsurface_create" subsurface-create) :pointer
(surface :pointer)
(parent :pointer)
(version :uint32)
(id :pointer)
(resource-list :pointer))
(cffi:defcfun ("wlr_surface_get_root_surface" surface-get-root-surface) :pointer
(surface :pointer))
(cffi:defcfun ("wlr_surface_point_accepts_input" surface-point-accepts-input) :pointer
(surface :pointer)
(sx :double)
(sy :double))
(cffi:defcfun ("wlr_surface_surface_at" surface-surface-at) :pointer
(surface :pointer)
(sx :double)
(sy :double)
(sub-x :pointer)
(sub-y :pointer))
(cffi:defcfun ("wlr_surface_send_enter" surface-send-enter) :void
(surface :pointer)
(output (:pointer (:struct output))))
(cffi:defcfun ("wlr_surface_send_leave" surface-send-leave) :void
(surface :pointer)
(output (:pointer (:struct output))))
(cffi:defcfun ("wlr_surface_send_frame_done" surface-send-frame-done) :void
(surface :pointer)
(time :pointer))
(cffi:defcfun ("wlr_surface_get_extends" surface-get-extends) :void
(surface :pointer)
(box box))
(cffi:defcfun ("wlr_surface_from_resource" surface-from-resource) :pointer
(resource :pointer))
(cffi:defcfun ("wlr_surface_for_each_surface" surface-for-each-surface) :void
(surface :pointer)
(iterator :pointer)
(user-data :pointer))
| |
047eeba43b701e2978163be38f4566daf5e926970d35b7e74823fe023e5ed843 | wavewave/hoodle | Histo.hs | {-# LANGUAGE BangPatterns #-}
module Util.Histo
( aggregateCount,
histoAdd,
)
where
import Data.List (group, sort)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (mapMaybe)
aggregateCount :: [String] -> [(String, Int)]
aggregateCount = mapMaybe count . group . sort
where
count ys@(x : _) = Just (x, length ys)
count [] = Nothing
histoAdd :: Map String Int -> (String, Int) -> Map String Int
histoAdd !hist (key, value) = Map.alter upd key hist
where
upd Nothing = Just value
upd (Just value0) = Just (value0 + value)
| null | https://raw.githubusercontent.com/wavewave/hoodle/7296b8a9b5646d5f1ad844ffc42e655eb10732b7/log/app/logcat/Util/Histo.hs | haskell | # LANGUAGE BangPatterns # |
module Util.Histo
( aggregateCount,
histoAdd,
)
where
import Data.List (group, sort)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe (mapMaybe)
aggregateCount :: [String] -> [(String, Int)]
aggregateCount = mapMaybe count . group . sort
where
count ys@(x : _) = Just (x, length ys)
count [] = Nothing
histoAdd :: Map String Int -> (String, Int) -> Map String Int
histoAdd !hist (key, value) = Map.alter upd key hist
where
upd Nothing = Just value
upd (Just value0) = Just (value0 + value)
|
65b2584b645bbf351da65f34fd6630607283eefeb501733c6f775e0a19144f60 | camlp5/camlp5 | q_MLast_test.ml | (* camlp5r *)
(* q_MLast_test.ml *)
open Testutil ;
open Testutil2 ;
open OUnit2 ;
open OUnitTest ;
Pcaml.inter_phrases.val := Some (";\n") ;
value pa1 = PAPR.Implem.pa1 ;
value pr = PAPR.Implem.pr ;
value fmt_string s = Printf.sprintf "<<%s>>" s ;
type instance = {
name : string
; code : string
; expect : string
}
;
value mktest i =
i.name >:: (fun [ _ ->
assert_equal ~{msg="not equal"} ~{printer=fmt_string}
i.expect
(pr (pa1 i.code))
])
;
value tests = "test pa_r+quotations -> pr_r" >::: (List.map mktest
[
{
name = "prototype";
code = {foo||foo};
expect = {foo||foo}
}
;{
name = "expr-simplest";
code = {foo| <:expr< 1 >> ; |foo};
expect = {foo|MLast.ExInt loc (Ploc.VaVal "1") "";
|foo}
}
;{
name = "expr-patt-any";
code = {foo| <:patt< _ >> ; |foo} ;
expect = {foo|MLast.PaAny loc;
|foo}
}
;{
name = "patt-patt-any";
code = {foo| match x with [ <:patt< _ >> -> 1 ]; |foo} ;
expect = {foo|match x with [ MLast.PaAny _ -> 1 ];
|foo}
}
; { name = "expr-apply-1" ;
expect = {foo|MLast.ExApp loc e1 e2;
|foo} ;
code = {foo|<:expr< $e1$ $e2$ >>;|foo}
}
; { name = "expr-apply-2" ;
expect = {foo|fun
[ MLast.ExApp _ _ e2 -> 1 ];
|foo} ;
code = {foo|fun [ <:expr< $_$ $e2$ >> -> 1 ];|foo}
}
; { name = "expr-new-1" ;
expect = {foo|MLast.ExNew loc
(Ploc.VaVal
(Some (Ploc.VaVal (MLast.LiUid loc (Ploc.VaVal "A"))), Ploc.VaVal "x"));
|foo} ;
code = {foo|<:expr< new A.x >>;|foo}
}
; { name = "expr-new-2" ;
expect = {foo|MLast.ExNew loc (Ploc.VaVal (None, Ploc.VaVal "x"));
|foo} ;
code = {foo|<:expr< new x >>;|foo}
}
; { name = "expr-new-3" ;
expect = {foo|MLast.ExNew loc (Ploc.VaVal (Some (Ploc.VaVal li), Ploc.VaVal id));
|foo} ;
code = {foo|<:expr< new $longid:li$ . $lid:id$ >>;|foo}
}
; { name = "expr-new-4" ;
expect = {foo|MLast.ExNew loc (Ploc.VaVal (None, Ploc.VaVal id));
|foo} ;
code = {foo|<:expr< new $lid:id$ >>;|foo}
}
; { name = "expr-new-5" ;
expect = {foo|MLast.ExNew loc (Ploc.VaVal li);
|foo} ;
code = {foo|<:expr< new $lilongid:li$ >>;|foo}
}
; { name = "ctyp-tycls-1" ;
expect = {foo|MLast.TyCls loc (Ploc.VaVal (None, Ploc.VaVal "a"));
|foo} ;
code = {foo|<:ctyp< # a >> ;|foo}
}
; { name = "ctyp-tycls-2" ;
expect = {foo|MLast.TyCls loc
(Ploc.VaVal
(Some (Ploc.VaVal (MLast.LiUid loc (Ploc.VaVal "A"))), Ploc.VaVal "a"));
|foo} ;
code = {foo|<:ctyp< # A.a >> ;|foo}
}
; { name = "ctyp-tycls-3" ;
expect = {foo|MLast.TyCls loc (Ploc.VaVal (Some (Ploc.VaVal li), Ploc.VaVal id));
|foo} ;
code = {foo|<:ctyp< # $longid:li$ . $lid:id$ >> ;|foo}
}
; { name = "ctyp-tycls-4" ;
expect = {foo|MLast.TyCls loc (Ploc.VaVal li);
|foo} ;
code = {foo|<:ctyp< # $lilongid:li$ >> ;|foo}
}
; { name = "class-expr-cecon-1" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal (None, Ploc.VaVal "a"))
(Ploc.VaVal
[MLast.TyLid loc (Ploc.VaVal "b"); MLast.TyLid loc (Ploc.VaVal "c")]);
|foo} ;
code = {foo|<:class_expr< [ b, c ] a >> ;|foo}
}
; { name = "class-expr-cecon-2" ;
expect = {foo|MLast.CeCon loc
(Ploc.VaVal
(Some (Ploc.VaVal (MLast.LiUid loc (Ploc.VaVal "A"))), Ploc.VaVal "a"))
(Ploc.VaVal
[MLast.TyLid loc (Ploc.VaVal "b"); MLast.TyLid loc (Ploc.VaVal "c")]);
|foo} ;
code = {foo|<:class_expr< [ b, c ] A.a >> ;|foo}
}
; { name = "class-expr-cecon-3" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal (Some (Ploc.VaVal li), Ploc.VaVal id))
(Ploc.VaVal
[MLast.TyLid loc (Ploc.VaVal "b"); MLast.TyLid loc (Ploc.VaVal "c")]);
|foo} ;
code = {foo|<:class_expr< [ b, c ] $longid:li$ . $lid:id$ >> ;|foo}
}
; { name = "class-expr-cecon-4" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal li)
(Ploc.VaVal
[MLast.TyLid loc (Ploc.VaVal "b"); MLast.TyLid loc (Ploc.VaVal "c")]);
|foo} ;
code = {foo|<:class_expr< [ b, c ] $lilongid:li$ >> ;|foo}
}
; { name = "class-expr-cecon-5" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal (None, Ploc.VaVal "a")) (Ploc.VaVal []);
|foo} ;
code = {foo|<:class_expr< a >> ;|foo}
}
; { name = "class-expr-cecon-6" ;
expect = {foo|MLast.CeCon loc
(Ploc.VaVal
(Some (Ploc.VaVal (MLast.LiUid loc (Ploc.VaVal "A"))), Ploc.VaVal "a"))
(Ploc.VaVal []);
|foo} ;
code = {foo|<:class_expr< A.a >> ;|foo}
}
; { name = "class-expr-cecon-7" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal (Some (Ploc.VaVal li), Ploc.VaVal id))
(Ploc.VaVal []);
|foo} ;
code = {foo|<:class_expr< $longid:li$ . $lid:id$ >> ;|foo}
}
; { name = "class-expr-cecon-8" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal li) (Ploc.VaVal []);
|foo} ;
code = {foo|<:class_expr< $lilongid:li$ >> ;|foo}
}
; { name = "attribute-1" ;
expect = {foo|MLast.ExExten loc
(Ploc.VaVal (Ploc.VaVal (loc, "a"), MLast.StAttr loc (Ploc.VaVal [])));
|foo} ;
code = {foo| <:expr< [%a] >> ; |foo}
}
; { name = "attribute-2" ;
expect = {foo|MLast.ExExten loc
(Ploc.VaVal
(Ploc.VaVal (loc, "a"),
MLast.StAttr loc
(Ploc.VaVal
[MLast.StExp loc (MLast.ExLid loc (Ploc.VaVal "b"))
(Ploc.VaVal [])])));
|foo} ;
code = {foo| <:expr< [%a b;] >> ; |foo}
}
; { name = "variants-1" ;
expect = {foo|MLast.TyVrn loc (Ploc.VaVal l) None;
|foo} ;
code = {foo|<:ctyp< [= $list:l$ ] >>; |foo}
}
; { name = "variants-2" ;
expect = {foo|MLast.PaVrn loc (Ploc.VaVal "Foo");
|foo} ;
code = {foo|<:patt< `Foo >> ;|foo}
}
; { name = "variants-3" ;
expect = {foo|MLast.PaVrn loc (Ploc.VaVal "foo");
|foo} ;
code = {foo|<:patt< `foo >> ;|foo}
}
; { name = "patt-empty-list" ;
expect = {foo|MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "[]")) (Ploc.VaVal []);
|foo} ;
code = {foo|<:patt< [] >> ;|foo}
}
; { name = "patt-list-1" ;
expect = {foo|MLast.PaApp loc
(MLast.PaApp loc
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "::")) (Ploc.VaVal []))
(MLast.PaLid loc (Ploc.VaVal "a")))
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "[]")) (Ploc.VaVal []));
|foo} ;
code = {foo|<:patt< [a] >> ;|foo}
}
; { name = "patt-list-2" ;
expect = {foo|MLast.PaApp loc
(MLast.PaApp loc
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "::")) (Ploc.VaVal []))
(MLast.PaLid loc (Ploc.VaVal "a")))
(MLast.PaApp loc
(MLast.PaApp loc
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "::")) (Ploc.VaVal []))
(MLast.PaLid loc (Ploc.VaVal "b")))
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "[]")) (Ploc.VaVal [])));
|foo} ;
code = {foo|<:patt< [a;b] >> ;|foo}
}
; { name = "patt-type-0" ;
expect = {foo|MLast.PaNty loc (Ploc.VaVal "a");
|foo} ;
code = {foo|<:patt< (type a) >> ;|foo}
}
; { name = "patt-type-1" ;
expect = {foo|MLast.PaNty loc (Ploc.VaVal (PM.type_id p));
|foo} ;
code = {foo|<:patt< (type $lid:PM.type_id p$) >> ;|foo}
}
; { name = "type-extension" ;
expect = {foo|MLast.StTypExten loc
{MLast.teNam = Ploc.VaVal (None, Ploc.VaVal "t");
MLast.tePrm = Ploc.VaVal []; MLast.tePrv = Ploc.VaVal False;
MLast.teECs =
Ploc.VaVal
[MLast.EcTuple loc
(loc, Ploc.VaVal "A", Ploc.VaVal [], Ploc.VaVal [], Ploc.VaVal None,
Ploc.VaVal [])];
MLast.teAttributes = Ploc.VaVal []};
|foo} ;
code = {foo|<:str_item< type t += [ A ] >> ;|foo}
}
; { name = "expr-long-1" ;
expect = {foo|MLast.ExLong loc
(MLast.LiAcc loc (MLast.LiUid loc (Ploc.VaVal "A")) (Ploc.VaVal "B"));
|foo} ;
code = {foo|<:expr< A . B >>;|foo}
}
; { name = "expr-acc-1d" ;
expect = {foo|MLast.ExFle loc (MLast.ExLong loc (MLast.LiUid loc (Ploc.VaVal e1)))
(Ploc.VaVal (None, Ploc.VaVal m));
|foo} ;
code = {foo|<:expr< $uid:e1$ . $lid:m$ >> ;|foo}
}
; { name = "typedecl-0" ;
expect = {foo|MLast.StTyp loc (Ploc.VaVal False)
(Ploc.VaVal
[{MLast.tdIsDecl = Ploc.VaVal True;
MLast.tdNam = Ploc.VaVal (loc, Ploc.VaVal li);
MLast.tdPrm = Ploc.VaVal []; MLast.tdPrv = Ploc.VaVal False;
MLast.tdDef =
MLast.TySum loc
(Ploc.VaVal
[(loc, Ploc.VaVal "A", Ploc.VaVal [], Ploc.VaVal [],
Ploc.VaVal None, Ploc.VaVal [])]);
MLast.tdCon = Ploc.VaVal []; MLast.tdAttributes = Ploc.VaVal []}]);
|foo} ;
code = {foo|<:str_item< type $lid:li$ = [ A ] >>;|foo}
}
; { name = "typedecl-1" ;
expect = {foo|fun
[ MLast.SgTyp _ (Ploc.VaVal False)
(Ploc.VaVal
[{MLast.tdIsDecl = Ploc.VaVal True;
MLast.tdNam = Ploc.VaVal (_, Ploc.VaVal x);
MLast.tdPrm = Ploc.VaVal _; MLast.tdPrv = Ploc.VaVal _;
MLast.tdDef = MLast.TyOpn _; MLast.tdCon = Ploc.VaVal [];
MLast.tdAttributes = _}]) ->
1 ];
|foo} ;
code = {foo|fun [ <:sig_item< type $lid:x$ $list:_$ = $priv:_$ .. $_itemattrs:_$ >> -> 1 ] ;|foo}
}
; { name = "typedecl-1" ;
expect = {foo|{MLast.tdIsDecl = Ploc.VaVal True; MLast.tdNam = Ploc.VaVal x;
MLast.tdPrm = Ploc.VaVal pl; MLast.tdPrv = Ploc.VaVal False;
MLast.tdDef = tk; MLast.tdCon = Ploc.VaVal [];
MLast.tdAttributes = Ploc.VaVal []};
|foo} ;
code = {foo|<:type_decl< $tp:x$ $list:pl$ = $tk$ >>;|foo}
}
; { name = "typedecl-2" ;
expect = {foo|{MLast.tdIsDecl = Ploc.VaVal True; MLast.tdNam = Ploc.VaVal (loc, x);
MLast.tdPrm = Ploc.VaVal pl; MLast.tdPrv = Ploc.VaVal False;
MLast.tdDef = tk; MLast.tdCon = Ploc.VaVal [];
MLast.tdAttributes = Ploc.VaVal []};
|foo} ;
code = {foo|<:type_decl< $tp:(loc,x)$ $list:pl$ = $tk$ >>;|foo}
}
; { name = "attribute-body-1" ;
expect = {foo|fun
[ (Ploc.VaVal (_, "add"), MLast.StAttr _ (Ploc.VaVal [si])) -> si ];
|foo} ;
code = {foo|fun [ <:attribute_body< "add" $stri:si$ ; >> -> si ] ;|foo}
}
; { name = "attribute-body-2" ;
expect = {foo|(Ploc.VaVal (loc, "add"), MLast.StAttr loc (Ploc.VaVal [si]));
|foo} ;
code = {foo|<:attribute_body< "add" $stri:si$ ; >> ;|foo}
}
; { name = "dotop-1" ;
expect = {foo|MLast.ExAre loc (Ploc.VaVal s) e (Ploc.VaVal le);
|foo} ;
code = {foo|<:expr< $e$ $dotop:s$ ( $list:le$ ) >> ;|foo}
}
; { name = "two-level-expr-1" ;
expect = {foo|MLast.ExTup loc
(Ploc.VaVal
[MLast.ExLid loc (Ploc.VaVal x); MLast.ExLid loc (Ploc.VaVal y)]);
|foo} ;
code = {foo|<:expr< ($lid:x$, $lid:y$) >> ;|foo}
}
; { name = "two-level-patt-1" ;
expect = {foo|fun
[ MLast.ExTup loc
(Ploc.VaVal
[MLast.ExLid _ (Ploc.VaVal x); MLast.ExLid _ (Ploc.VaVal y)]) ->
1 ];
|foo} ;
code = {foo|fun [ <:expr:< ($lid:x$, $lid:y$) >> -> 1 ] ;|foo}
}
; { name = "extended-longident-1" ;
expect = {foo|MLast.LiAcc loc li (Ploc.VaVal m);
|foo} ;
code = {foo|<:extended_longident< $longid:li$ . $uid:m$ >> ;|foo}
}
; { name = "generic-constructor-1" ;
expect = {foo|fun
[ (loc, Ploc.VaVal ci, Ploc.VaVal [], Ploc.VaVal tl, Ploc.VaVal None, l) ->
1 ];
|foo} ;
code = {foo|fun [ <:constructor:< $uid:ci$ of $list:tl$ $_algattrs:l$ >> -> 1 ];|foo}
}
; { name = "generic-constructor-2" ;
expect = {foo|fun
[ (loc, Ploc.VaVal ci, Ploc.VaVal [], Ploc.VaVal tl, Ploc.VaVal None,
l) as gc ->
1 ];
|foo} ;
code = {foo|fun [ <:constructor:< $uid:ci$ of $list:tl$ $_algattrs:l$ >> as gc -> 1 ];|foo}
}
; { name = "generic-constructor-3" ;
expect = {foo|match b with
[ (loc, Ploc.VaVal ci, Ploc.VaVal [], Ploc.VaVal tl, Ploc.VaVal None,
_) as gc ->
1 ];
|foo} ;
code = {foo|match b with [
<:constructor:< $uid:ci$ of $list:tl$ $_algattrs:_$ >> as gc -> 1 ];|foo}
}
; {
name = "expr-extension-type-1";
code = {foo|<:expr< [%typ: bool] >>;|foo};
expect = {foo|MLast.ExExten loc
(Ploc.VaVal
(Ploc.VaVal (loc, "typ"),
MLast.TyAttr loc (Ploc.VaVal (MLast.TyLid loc (Ploc.VaVal "bool")))));
|foo}
}
; {
name = "patt-PaLong-1";
code = {foo|<:patt< $longid:li$ (type $_list:loc_ids$ ) >>;|foo};
expect = {foo|MLast.PaLong loc li loc_ids;
|foo}
}
; {
name = "patt-PaLong-2";
code = {foo|<:patt< $longid:li$ >>;|foo};
expect = {foo|MLast.PaLong loc li (Ploc.VaVal []);
|foo}
}
; {
name = "patt-PaLong-3";
code = {foo|<:patt< $longid:li$ (type a) >>;|foo};
expect = {foo|MLast.PaLong loc li (Ploc.VaVal [(loc, "a")]);
|foo}
}
; {
name = "patt-PaLong-4";
code = {foo|<:patt< $longid:li$ (type a b c) >>;|foo};
expect = {foo|MLast.PaLong loc li (Ploc.VaVal [(loc, "a"); (loc, "b"); (loc, "c")]);
|foo}
}
; {
name = "binders-constructor-1";
code = {foo|<:constructor< $_uid:ci$ of $_list:ls$ . $_list:tl$ $_rto:rto$ $_algattrs:attrs$ >> ;|foo};
expect = {foo|(loc, ci, ls, tl, rto, attrs);
|foo}
}
; {
name = "binders-external-1";
code = {foo|<:str_item< external $_lid:i$ : $_list:ls$ . $t$ = $_list:pd$ $_itemattrs:attrs$ >> ;|foo};
expect = {foo|MLast.StExt loc i ls t pd attrs;
|foo}
}
; {
name = "binders-external-2";
code = {foo|<:sig_item< external $_lid:i$ : $t$ = $_list:pd$ $_itemattrs:attrs$ >> ;|foo};
expect = {foo|MLast.SgExt loc i (Ploc.VaVal []) t pd attrs;
|foo}
}
])
;
value _ =
if not Sys.interactive.val then
run_test_tt_main tests
else ()
;
(*
;;; Local Variables: ***
;;; mode:tuareg ***
;;; End: ***
*)
| null | https://raw.githubusercontent.com/camlp5/camlp5/9e8155f8ae5a584bbb4ad96d10d6fec63ed8204c/testsuite/q_MLast_test.ml | ocaml | camlp5r
q_MLast_test.ml
;;; Local Variables: ***
;;; mode:tuareg ***
;;; End: ***
|
open Testutil ;
open Testutil2 ;
open OUnit2 ;
open OUnitTest ;
Pcaml.inter_phrases.val := Some (";\n") ;
value pa1 = PAPR.Implem.pa1 ;
value pr = PAPR.Implem.pr ;
value fmt_string s = Printf.sprintf "<<%s>>" s ;
type instance = {
name : string
; code : string
; expect : string
}
;
value mktest i =
i.name >:: (fun [ _ ->
assert_equal ~{msg="not equal"} ~{printer=fmt_string}
i.expect
(pr (pa1 i.code))
])
;
value tests = "test pa_r+quotations -> pr_r" >::: (List.map mktest
[
{
name = "prototype";
code = {foo||foo};
expect = {foo||foo}
}
;{
name = "expr-simplest";
code = {foo| <:expr< 1 >> ; |foo};
expect = {foo|MLast.ExInt loc (Ploc.VaVal "1") "";
|foo}
}
;{
name = "expr-patt-any";
code = {foo| <:patt< _ >> ; |foo} ;
expect = {foo|MLast.PaAny loc;
|foo}
}
;{
name = "patt-patt-any";
code = {foo| match x with [ <:patt< _ >> -> 1 ]; |foo} ;
expect = {foo|match x with [ MLast.PaAny _ -> 1 ];
|foo}
}
; { name = "expr-apply-1" ;
expect = {foo|MLast.ExApp loc e1 e2;
|foo} ;
code = {foo|<:expr< $e1$ $e2$ >>;|foo}
}
; { name = "expr-apply-2" ;
expect = {foo|fun
[ MLast.ExApp _ _ e2 -> 1 ];
|foo} ;
code = {foo|fun [ <:expr< $_$ $e2$ >> -> 1 ];|foo}
}
; { name = "expr-new-1" ;
expect = {foo|MLast.ExNew loc
(Ploc.VaVal
(Some (Ploc.VaVal (MLast.LiUid loc (Ploc.VaVal "A"))), Ploc.VaVal "x"));
|foo} ;
code = {foo|<:expr< new A.x >>;|foo}
}
; { name = "expr-new-2" ;
expect = {foo|MLast.ExNew loc (Ploc.VaVal (None, Ploc.VaVal "x"));
|foo} ;
code = {foo|<:expr< new x >>;|foo}
}
; { name = "expr-new-3" ;
expect = {foo|MLast.ExNew loc (Ploc.VaVal (Some (Ploc.VaVal li), Ploc.VaVal id));
|foo} ;
code = {foo|<:expr< new $longid:li$ . $lid:id$ >>;|foo}
}
; { name = "expr-new-4" ;
expect = {foo|MLast.ExNew loc (Ploc.VaVal (None, Ploc.VaVal id));
|foo} ;
code = {foo|<:expr< new $lid:id$ >>;|foo}
}
; { name = "expr-new-5" ;
expect = {foo|MLast.ExNew loc (Ploc.VaVal li);
|foo} ;
code = {foo|<:expr< new $lilongid:li$ >>;|foo}
}
; { name = "ctyp-tycls-1" ;
expect = {foo|MLast.TyCls loc (Ploc.VaVal (None, Ploc.VaVal "a"));
|foo} ;
code = {foo|<:ctyp< # a >> ;|foo}
}
; { name = "ctyp-tycls-2" ;
expect = {foo|MLast.TyCls loc
(Ploc.VaVal
(Some (Ploc.VaVal (MLast.LiUid loc (Ploc.VaVal "A"))), Ploc.VaVal "a"));
|foo} ;
code = {foo|<:ctyp< # A.a >> ;|foo}
}
; { name = "ctyp-tycls-3" ;
expect = {foo|MLast.TyCls loc (Ploc.VaVal (Some (Ploc.VaVal li), Ploc.VaVal id));
|foo} ;
code = {foo|<:ctyp< # $longid:li$ . $lid:id$ >> ;|foo}
}
; { name = "ctyp-tycls-4" ;
expect = {foo|MLast.TyCls loc (Ploc.VaVal li);
|foo} ;
code = {foo|<:ctyp< # $lilongid:li$ >> ;|foo}
}
; { name = "class-expr-cecon-1" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal (None, Ploc.VaVal "a"))
(Ploc.VaVal
[MLast.TyLid loc (Ploc.VaVal "b"); MLast.TyLid loc (Ploc.VaVal "c")]);
|foo} ;
code = {foo|<:class_expr< [ b, c ] a >> ;|foo}
}
; { name = "class-expr-cecon-2" ;
expect = {foo|MLast.CeCon loc
(Ploc.VaVal
(Some (Ploc.VaVal (MLast.LiUid loc (Ploc.VaVal "A"))), Ploc.VaVal "a"))
(Ploc.VaVal
[MLast.TyLid loc (Ploc.VaVal "b"); MLast.TyLid loc (Ploc.VaVal "c")]);
|foo} ;
code = {foo|<:class_expr< [ b, c ] A.a >> ;|foo}
}
; { name = "class-expr-cecon-3" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal (Some (Ploc.VaVal li), Ploc.VaVal id))
(Ploc.VaVal
[MLast.TyLid loc (Ploc.VaVal "b"); MLast.TyLid loc (Ploc.VaVal "c")]);
|foo} ;
code = {foo|<:class_expr< [ b, c ] $longid:li$ . $lid:id$ >> ;|foo}
}
; { name = "class-expr-cecon-4" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal li)
(Ploc.VaVal
[MLast.TyLid loc (Ploc.VaVal "b"); MLast.TyLid loc (Ploc.VaVal "c")]);
|foo} ;
code = {foo|<:class_expr< [ b, c ] $lilongid:li$ >> ;|foo}
}
; { name = "class-expr-cecon-5" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal (None, Ploc.VaVal "a")) (Ploc.VaVal []);
|foo} ;
code = {foo|<:class_expr< a >> ;|foo}
}
; { name = "class-expr-cecon-6" ;
expect = {foo|MLast.CeCon loc
(Ploc.VaVal
(Some (Ploc.VaVal (MLast.LiUid loc (Ploc.VaVal "A"))), Ploc.VaVal "a"))
(Ploc.VaVal []);
|foo} ;
code = {foo|<:class_expr< A.a >> ;|foo}
}
; { name = "class-expr-cecon-7" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal (Some (Ploc.VaVal li), Ploc.VaVal id))
(Ploc.VaVal []);
|foo} ;
code = {foo|<:class_expr< $longid:li$ . $lid:id$ >> ;|foo}
}
; { name = "class-expr-cecon-8" ;
expect = {foo|MLast.CeCon loc (Ploc.VaVal li) (Ploc.VaVal []);
|foo} ;
code = {foo|<:class_expr< $lilongid:li$ >> ;|foo}
}
; { name = "attribute-1" ;
expect = {foo|MLast.ExExten loc
(Ploc.VaVal (Ploc.VaVal (loc, "a"), MLast.StAttr loc (Ploc.VaVal [])));
|foo} ;
code = {foo| <:expr< [%a] >> ; |foo}
}
; { name = "attribute-2" ;
expect = {foo|MLast.ExExten loc
(Ploc.VaVal
(Ploc.VaVal (loc, "a"),
MLast.StAttr loc
(Ploc.VaVal
[MLast.StExp loc (MLast.ExLid loc (Ploc.VaVal "b"))
(Ploc.VaVal [])])));
|foo} ;
code = {foo| <:expr< [%a b;] >> ; |foo}
}
; { name = "variants-1" ;
expect = {foo|MLast.TyVrn loc (Ploc.VaVal l) None;
|foo} ;
code = {foo|<:ctyp< [= $list:l$ ] >>; |foo}
}
; { name = "variants-2" ;
expect = {foo|MLast.PaVrn loc (Ploc.VaVal "Foo");
|foo} ;
code = {foo|<:patt< `Foo >> ;|foo}
}
; { name = "variants-3" ;
expect = {foo|MLast.PaVrn loc (Ploc.VaVal "foo");
|foo} ;
code = {foo|<:patt< `foo >> ;|foo}
}
; { name = "patt-empty-list" ;
expect = {foo|MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "[]")) (Ploc.VaVal []);
|foo} ;
code = {foo|<:patt< [] >> ;|foo}
}
; { name = "patt-list-1" ;
expect = {foo|MLast.PaApp loc
(MLast.PaApp loc
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "::")) (Ploc.VaVal []))
(MLast.PaLid loc (Ploc.VaVal "a")))
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "[]")) (Ploc.VaVal []));
|foo} ;
code = {foo|<:patt< [a] >> ;|foo}
}
; { name = "patt-list-2" ;
expect = {foo|MLast.PaApp loc
(MLast.PaApp loc
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "::")) (Ploc.VaVal []))
(MLast.PaLid loc (Ploc.VaVal "a")))
(MLast.PaApp loc
(MLast.PaApp loc
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "::")) (Ploc.VaVal []))
(MLast.PaLid loc (Ploc.VaVal "b")))
(MLast.PaLong loc (MLast.LiUid loc (Ploc.VaVal "[]")) (Ploc.VaVal [])));
|foo} ;
code = {foo|<:patt< [a;b] >> ;|foo}
}
; { name = "patt-type-0" ;
expect = {foo|MLast.PaNty loc (Ploc.VaVal "a");
|foo} ;
code = {foo|<:patt< (type a) >> ;|foo}
}
; { name = "patt-type-1" ;
expect = {foo|MLast.PaNty loc (Ploc.VaVal (PM.type_id p));
|foo} ;
code = {foo|<:patt< (type $lid:PM.type_id p$) >> ;|foo}
}
; { name = "type-extension" ;
expect = {foo|MLast.StTypExten loc
{MLast.teNam = Ploc.VaVal (None, Ploc.VaVal "t");
MLast.tePrm = Ploc.VaVal []; MLast.tePrv = Ploc.VaVal False;
MLast.teECs =
Ploc.VaVal
[MLast.EcTuple loc
(loc, Ploc.VaVal "A", Ploc.VaVal [], Ploc.VaVal [], Ploc.VaVal None,
Ploc.VaVal [])];
MLast.teAttributes = Ploc.VaVal []};
|foo} ;
code = {foo|<:str_item< type t += [ A ] >> ;|foo}
}
; { name = "expr-long-1" ;
expect = {foo|MLast.ExLong loc
(MLast.LiAcc loc (MLast.LiUid loc (Ploc.VaVal "A")) (Ploc.VaVal "B"));
|foo} ;
code = {foo|<:expr< A . B >>;|foo}
}
; { name = "expr-acc-1d" ;
expect = {foo|MLast.ExFle loc (MLast.ExLong loc (MLast.LiUid loc (Ploc.VaVal e1)))
(Ploc.VaVal (None, Ploc.VaVal m));
|foo} ;
code = {foo|<:expr< $uid:e1$ . $lid:m$ >> ;|foo}
}
; { name = "typedecl-0" ;
expect = {foo|MLast.StTyp loc (Ploc.VaVal False)
(Ploc.VaVal
[{MLast.tdIsDecl = Ploc.VaVal True;
MLast.tdNam = Ploc.VaVal (loc, Ploc.VaVal li);
MLast.tdPrm = Ploc.VaVal []; MLast.tdPrv = Ploc.VaVal False;
MLast.tdDef =
MLast.TySum loc
(Ploc.VaVal
[(loc, Ploc.VaVal "A", Ploc.VaVal [], Ploc.VaVal [],
Ploc.VaVal None, Ploc.VaVal [])]);
MLast.tdCon = Ploc.VaVal []; MLast.tdAttributes = Ploc.VaVal []}]);
|foo} ;
code = {foo|<:str_item< type $lid:li$ = [ A ] >>;|foo}
}
; { name = "typedecl-1" ;
expect = {foo|fun
[ MLast.SgTyp _ (Ploc.VaVal False)
(Ploc.VaVal
[{MLast.tdIsDecl = Ploc.VaVal True;
MLast.tdNam = Ploc.VaVal (_, Ploc.VaVal x);
MLast.tdPrm = Ploc.VaVal _; MLast.tdPrv = Ploc.VaVal _;
MLast.tdDef = MLast.TyOpn _; MLast.tdCon = Ploc.VaVal [];
MLast.tdAttributes = _}]) ->
1 ];
|foo} ;
code = {foo|fun [ <:sig_item< type $lid:x$ $list:_$ = $priv:_$ .. $_itemattrs:_$ >> -> 1 ] ;|foo}
}
; { name = "typedecl-1" ;
expect = {foo|{MLast.tdIsDecl = Ploc.VaVal True; MLast.tdNam = Ploc.VaVal x;
MLast.tdPrm = Ploc.VaVal pl; MLast.tdPrv = Ploc.VaVal False;
MLast.tdDef = tk; MLast.tdCon = Ploc.VaVal [];
MLast.tdAttributes = Ploc.VaVal []};
|foo} ;
code = {foo|<:type_decl< $tp:x$ $list:pl$ = $tk$ >>;|foo}
}
; { name = "typedecl-2" ;
expect = {foo|{MLast.tdIsDecl = Ploc.VaVal True; MLast.tdNam = Ploc.VaVal (loc, x);
MLast.tdPrm = Ploc.VaVal pl; MLast.tdPrv = Ploc.VaVal False;
MLast.tdDef = tk; MLast.tdCon = Ploc.VaVal [];
MLast.tdAttributes = Ploc.VaVal []};
|foo} ;
code = {foo|<:type_decl< $tp:(loc,x)$ $list:pl$ = $tk$ >>;|foo}
}
; { name = "attribute-body-1" ;
expect = {foo|fun
[ (Ploc.VaVal (_, "add"), MLast.StAttr _ (Ploc.VaVal [si])) -> si ];
|foo} ;
code = {foo|fun [ <:attribute_body< "add" $stri:si$ ; >> -> si ] ;|foo}
}
; { name = "attribute-body-2" ;
expect = {foo|(Ploc.VaVal (loc, "add"), MLast.StAttr loc (Ploc.VaVal [si]));
|foo} ;
code = {foo|<:attribute_body< "add" $stri:si$ ; >> ;|foo}
}
; { name = "dotop-1" ;
expect = {foo|MLast.ExAre loc (Ploc.VaVal s) e (Ploc.VaVal le);
|foo} ;
code = {foo|<:expr< $e$ $dotop:s$ ( $list:le$ ) >> ;|foo}
}
; { name = "two-level-expr-1" ;
expect = {foo|MLast.ExTup loc
(Ploc.VaVal
[MLast.ExLid loc (Ploc.VaVal x); MLast.ExLid loc (Ploc.VaVal y)]);
|foo} ;
code = {foo|<:expr< ($lid:x$, $lid:y$) >> ;|foo}
}
; { name = "two-level-patt-1" ;
expect = {foo|fun
[ MLast.ExTup loc
(Ploc.VaVal
[MLast.ExLid _ (Ploc.VaVal x); MLast.ExLid _ (Ploc.VaVal y)]) ->
1 ];
|foo} ;
code = {foo|fun [ <:expr:< ($lid:x$, $lid:y$) >> -> 1 ] ;|foo}
}
; { name = "extended-longident-1" ;
expect = {foo|MLast.LiAcc loc li (Ploc.VaVal m);
|foo} ;
code = {foo|<:extended_longident< $longid:li$ . $uid:m$ >> ;|foo}
}
; { name = "generic-constructor-1" ;
expect = {foo|fun
[ (loc, Ploc.VaVal ci, Ploc.VaVal [], Ploc.VaVal tl, Ploc.VaVal None, l) ->
1 ];
|foo} ;
code = {foo|fun [ <:constructor:< $uid:ci$ of $list:tl$ $_algattrs:l$ >> -> 1 ];|foo}
}
; { name = "generic-constructor-2" ;
expect = {foo|fun
[ (loc, Ploc.VaVal ci, Ploc.VaVal [], Ploc.VaVal tl, Ploc.VaVal None,
l) as gc ->
1 ];
|foo} ;
code = {foo|fun [ <:constructor:< $uid:ci$ of $list:tl$ $_algattrs:l$ >> as gc -> 1 ];|foo}
}
; { name = "generic-constructor-3" ;
expect = {foo|match b with
[ (loc, Ploc.VaVal ci, Ploc.VaVal [], Ploc.VaVal tl, Ploc.VaVal None,
_) as gc ->
1 ];
|foo} ;
code = {foo|match b with [
<:constructor:< $uid:ci$ of $list:tl$ $_algattrs:_$ >> as gc -> 1 ];|foo}
}
; {
name = "expr-extension-type-1";
code = {foo|<:expr< [%typ: bool] >>;|foo};
expect = {foo|MLast.ExExten loc
(Ploc.VaVal
(Ploc.VaVal (loc, "typ"),
MLast.TyAttr loc (Ploc.VaVal (MLast.TyLid loc (Ploc.VaVal "bool")))));
|foo}
}
; {
name = "patt-PaLong-1";
code = {foo|<:patt< $longid:li$ (type $_list:loc_ids$ ) >>;|foo};
expect = {foo|MLast.PaLong loc li loc_ids;
|foo}
}
; {
name = "patt-PaLong-2";
code = {foo|<:patt< $longid:li$ >>;|foo};
expect = {foo|MLast.PaLong loc li (Ploc.VaVal []);
|foo}
}
; {
name = "patt-PaLong-3";
code = {foo|<:patt< $longid:li$ (type a) >>;|foo};
expect = {foo|MLast.PaLong loc li (Ploc.VaVal [(loc, "a")]);
|foo}
}
; {
name = "patt-PaLong-4";
code = {foo|<:patt< $longid:li$ (type a b c) >>;|foo};
expect = {foo|MLast.PaLong loc li (Ploc.VaVal [(loc, "a"); (loc, "b"); (loc, "c")]);
|foo}
}
; {
name = "binders-constructor-1";
code = {foo|<:constructor< $_uid:ci$ of $_list:ls$ . $_list:tl$ $_rto:rto$ $_algattrs:attrs$ >> ;|foo};
expect = {foo|(loc, ci, ls, tl, rto, attrs);
|foo}
}
; {
name = "binders-external-1";
code = {foo|<:str_item< external $_lid:i$ : $_list:ls$ . $t$ = $_list:pd$ $_itemattrs:attrs$ >> ;|foo};
expect = {foo|MLast.StExt loc i ls t pd attrs;
|foo}
}
; {
name = "binders-external-2";
code = {foo|<:sig_item< external $_lid:i$ : $t$ = $_list:pd$ $_itemattrs:attrs$ >> ;|foo};
expect = {foo|MLast.SgExt loc i (Ploc.VaVal []) t pd attrs;
|foo}
}
])
;
value _ =
if not Sys.interactive.val then
run_test_tt_main tests
else ()
;
|
9e7c02ccdcf01b19aac3269f9fb6f5f3ce4421e47fda0fac179513afd9e065d9 | kelvin-mai/clj-contacts | nav.cljs | (ns contacts.components.nav
(:require [helix.core :refer [defnc]]
[helix.dom :as d]))
(defnc nav []
(d/nav {:class '[py-4 shadow]}
(d/div {:class '[container]}
(d/h2 {:class '[text-xl]} "Contact Book"))))
| null | https://raw.githubusercontent.com/kelvin-mai/clj-contacts/0b349e706179aee2d1e1e7df02f38c6ee8faae72/src/cljs/contacts/components/nav.cljs | clojure | (ns contacts.components.nav
(:require [helix.core :refer [defnc]]
[helix.dom :as d]))
(defnc nav []
(d/nav {:class '[py-4 shadow]}
(d/div {:class '[container]}
(d/h2 {:class '[text-xl]} "Contact Book"))))
| |
d720a5e1402cebe89d1d072dbcb25c041d66d3f35743dbd5645442e59a0e42de | savonet/ocaml-posix | posix_uname_stubs.ml | open Ctypes
module Def (F : Cstubs.FOREIGN) = struct
open F
module Types = Posix_uname_types.Def (Posix_uname_generated_types)
open Types
let uname = foreign "uname" (ptr Utsname.t @-> returning int)
let strlen = foreign "strlen" (ptr char @-> returning int)
end
| null | https://raw.githubusercontent.com/savonet/ocaml-posix/d46d011de16154b34324eae6ee6e7010138cf4af/posix-uname/src/stubs/posix_uname_stubs.ml | ocaml | open Ctypes
module Def (F : Cstubs.FOREIGN) = struct
open F
module Types = Posix_uname_types.Def (Posix_uname_generated_types)
open Types
let uname = foreign "uname" (ptr Utsname.t @-> returning int)
let strlen = foreign "strlen" (ptr char @-> returning int)
end
| |
c428e6413d9499722b02916d99c63427e2463c850c2152025addddea795e2045 | fjvallarino/monomer | PopupSpec.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
module Monomer.Widgets.Containers.PopupSpec where
import Control.Lens
import Control.Lens.TH (abbreviatedFields, makeLensesWith)
import Data.Sequence (Seq)
import Data.Text (Text)
import Test.Hspec
import qualified Data.Sequence as Seq
import Monomer.Core
import Monomer.Core.Combinators
import Monomer.Core.Themes.SampleThemes
import Monomer.Event
import Monomer.TestEventUtil
import Monomer.TestUtil
import Monomer.Widgets.Composite
import Monomer.Widgets.Containers.Grid
import Monomer.Widgets.Containers.Popup
import Monomer.Widgets.Containers.Stack
import Monomer.Widgets.Singles.Label
import Monomer.Widgets.Singles.Spacer
import Monomer.Widgets.Singles.ToggleButton
import qualified Monomer.Lens as L
newtype TestEvent
= OnPopupChange Bool
deriving (Eq, Show)
data TestModel = TestModel {
_tmOpen :: Bool,
_tmPopupToggle :: Bool
} deriving (Eq, Show)
makeLensesWith abbreviatedFields ''TestModel
spec :: Spec
spec = describe "Popup" $ do
handleEvent
handleEventAnchor
handleEvent :: Spec
handleEvent = describe "handleEvent" $ do
describe "basics" $ do
it "should update the model when the popup is open" $ do
let evts = [evtClick (Point 50 10)]
modelBase evts ^. open `shouldBe` True
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should close the popup when clicked outside the content" $ do
let evts = [evtClick (Point 50 10), evtClick (Point 50 100)]
modelBase evts `shouldBe` TestModel False False
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
it "should close the popup when Esc is pressed" $ do
let evts = [evtClick (Point 50 10), evtK keyEscape]
modelBase evts `shouldBe` TestModel False False
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
it "should close the popup when clicked in the content's toggle button" $ do
let evts = [evtClick (Point 50 10), evtClick (Point 40 60)]
modelBase evts `shouldBe` TestModel False False
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
it "should not close the popup when clicked in the content's test toggle button" $ do
let evts = [evtClick (Point 50 10), evtClick (Point 80 60)]
modelBase evts `shouldBe` TestModel True True
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True]
describe "popupDisabledClose" $ do
it "should not close the popup when clicked outside the content if popupDisableClose is set" $ do
let evts = [evtClick (Point 50 10), evtClick (Point 50 100)]
modelDisable evts `shouldBe` TestModel True False
eventsDisable evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should not close the popup when Esc is pressed if popupDisableClose is set" $ do
let evts = [evtClick (Point 50 10), evtK keyEscape]
modelDisable evts `shouldBe` TestModel True False
eventsDisable evts `shouldBe` Seq.fromList [OnPopupChange True]
describe "alignment" $ do
it "should toggle the popupToggle button when aligned center to the widget" $ do
let cfgs = [popupOffset (Point 10 10), alignCenter]
let evts = [evtClick (Point 50 10), evtClick (Point 340 60)]
modelAlign cfgs evts `shouldBe` TestModel True True
eventsAlign cfgs evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should toggle the popupToggle button when aligned top-center to the window" $ do
let cfgs = [popupAlignToWindow, popupOffset (Point 10 10), alignTop, alignCenter]
let evts = [evtClick (Point 50 10), evtClick (Point 340 10)]
modelAlign cfgs evts `shouldBe` TestModel True True
eventsAlign cfgs evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should toggle the popupToggle button when aligned bottom-right to the window" $ do
let cfgs = [popupAlignToWindow, popupOffset (Point 10 10), alignBottom, alignRight]
let evts = [evtClick (Point 50 10), evtClick (Point 620 460)]
modelAlign cfgs evts `shouldBe` TestModel True True
eventsAlign cfgs evts `shouldBe` Seq.fromList [OnPopupChange True]
where
wenv = mockWenv (TestModel False False)
& L.theme .~ darkTheme
handleEvent :: EventHandler TestModel TestEvent TestModel TestEvent
handleEvent wenv node model evt = [ Report evt ]
buildUI cfgs wenv model = vstack [
toggleButton "Open" open,
popup_ open cfgs $ hgrid [
toggleButton "Close" open,
toggleButton "Test" popupToggle
],
filler
]
popupNode cfgs = composite "popupNode" id (buildUI cfgs) handleEvent
modelBase es = localHandleEventModel wenv es (popupNode [])
modelDisable es = localHandleEventModel wenv es (popupNode [popupDisableClose])
modelAlign cfgs es = localHandleEventModel wenv es (popupNode (popupDisableClose : cfgs))
eventsBase es = localHandleEventEvts wenv es (popupNode [onChange OnPopupChange])
eventsDisable es = localHandleEventEvts wenv es (popupNode [onChange OnPopupChange, popupDisableClose])
eventsAlign cfgs es = localHandleEventEvts wenv es (popupNode (onChange OnPopupChange : popupDisableClose : cfgs))
handleEventAnchor :: Spec
handleEventAnchor = describe "handleEventAnchor" $ do
describe "alignment outer border" $ do
it "should toggle the popupToggle button when aligned above the widget" $ do
let cfgs = [popupAlignToOuterV, alignTop, alignRight]
let evts = [evtClick (Point 50 110), evtClick (Point 600 80)]
modelAlign cfgs [] evts `shouldBe` TestModel True True
eventsAlign cfgs [] evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should toggle the popupToggle button when aligned below the widget" $ do
let cfgs = [popupAlignToOuterV, alignBottom, alignRight]
let evts = [evtClick (Point 50 110), evtClick (Point 600 140)]
modelAlign cfgs [] evts `shouldBe` TestModel True True
eventsAlign cfgs [] evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should close the popup when aligned above the widget and the toggle button is clicked" $ do
let cfgs = [popupAlignToOuterV, alignTop, alignRight]
let evts = [evtClick (Point 50 110), evtClick (Point 520 80)]
modelAlign cfgs [] evts `shouldBe` TestModel False False
eventsAlign cfgs [] evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
it "should close the popup when aligned below the widget and the toggle button is clicked" $ do
let cfgs = [popupAlignToOuterV, alignBottom, alignRight]
let evts = [evtClick (Point 50 110), evtClick (Point 520 140)]
modelAlign cfgs [] evts `shouldBe` TestModel False False
eventsAlign cfgs [] evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
describe "Re align outer" $ do
it "should re-locate the anchor below the widget, because it did not fit above" $ do
let cfgs = [popupAlignToOuterV, alignTop, alignRight]
let styles = [height 200]
let evts = [evtClick (Point 50 110), evtClick (Point 600 140)]
modelAlign cfgs styles evts `shouldBe` TestModel True True
eventsAlign cfgs styles evts `shouldBe` Seq.fromList [OnPopupChange True]
where
wenv = mockWenv (TestModel False False)
& L.theme .~ darkTheme
handleEvent :: EventHandler TestModel TestEvent TestModel TestEvent
handleEvent wenv node model evt = [ Report evt ]
buildUI cfgs styles wenv model = vstack [
spacer `styleBasic` [height 100],
popup_ open cfgs $ hgrid [
toggleButton "Close" open,
toggleButton "Test" popupToggle
] `styleBasic` styles,
filler
]
popupNode cfgs styles = composite "popupNode" id (buildUI cfgs styles) handleEvent
baseCfgs = [popupAnchor (toggleButton "Open" open), onChange OnPopupChange]
modelAlign cfgs styles es = localHandleEventModel wenv es $
popupNode (popupDisableClose : (baseCfgs ++ cfgs)) styles
eventsAlign cfgs styles es = localHandleEventEvts wenv es $
popupNode (popupDisableClose : (baseCfgs ++ cfgs)) styles
localHandleEventModel :: (Eq s, WidgetModel s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> s
localHandleEventModel wenv steps node = _weModel wenv2 where
stepEvts = (: []) <$> steps
(wenv2, _, _) = fst $ nodeHandleEventsSteps wenv WInit stepEvts node
localHandleEventEvts :: Eq s => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> Seq e
localHandleEventEvts wenv steps node = eventsFromReqs reqs where
stepEvts = (: []) <$> steps
(_, _, reqs) = fst $ nodeHandleEventsSteps wenv WInit stepEvts node
| null | https://raw.githubusercontent.com/fjvallarino/monomer/7b1d59d754d75588aae1097a231712264cf61719/test/unit/Monomer/Widgets/Containers/PopupSpec.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
module Monomer.Widgets.Containers.PopupSpec where
import Control.Lens
import Control.Lens.TH (abbreviatedFields, makeLensesWith)
import Data.Sequence (Seq)
import Data.Text (Text)
import Test.Hspec
import qualified Data.Sequence as Seq
import Monomer.Core
import Monomer.Core.Combinators
import Monomer.Core.Themes.SampleThemes
import Monomer.Event
import Monomer.TestEventUtil
import Monomer.TestUtil
import Monomer.Widgets.Composite
import Monomer.Widgets.Containers.Grid
import Monomer.Widgets.Containers.Popup
import Monomer.Widgets.Containers.Stack
import Monomer.Widgets.Singles.Label
import Monomer.Widgets.Singles.Spacer
import Monomer.Widgets.Singles.ToggleButton
import qualified Monomer.Lens as L
newtype TestEvent
= OnPopupChange Bool
deriving (Eq, Show)
data TestModel = TestModel {
_tmOpen :: Bool,
_tmPopupToggle :: Bool
} deriving (Eq, Show)
makeLensesWith abbreviatedFields ''TestModel
spec :: Spec
spec = describe "Popup" $ do
handleEvent
handleEventAnchor
handleEvent :: Spec
handleEvent = describe "handleEvent" $ do
describe "basics" $ do
it "should update the model when the popup is open" $ do
let evts = [evtClick (Point 50 10)]
modelBase evts ^. open `shouldBe` True
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should close the popup when clicked outside the content" $ do
let evts = [evtClick (Point 50 10), evtClick (Point 50 100)]
modelBase evts `shouldBe` TestModel False False
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
it "should close the popup when Esc is pressed" $ do
let evts = [evtClick (Point 50 10), evtK keyEscape]
modelBase evts `shouldBe` TestModel False False
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
it "should close the popup when clicked in the content's toggle button" $ do
let evts = [evtClick (Point 50 10), evtClick (Point 40 60)]
modelBase evts `shouldBe` TestModel False False
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
it "should not close the popup when clicked in the content's test toggle button" $ do
let evts = [evtClick (Point 50 10), evtClick (Point 80 60)]
modelBase evts `shouldBe` TestModel True True
eventsBase evts `shouldBe` Seq.fromList [OnPopupChange True]
describe "popupDisabledClose" $ do
it "should not close the popup when clicked outside the content if popupDisableClose is set" $ do
let evts = [evtClick (Point 50 10), evtClick (Point 50 100)]
modelDisable evts `shouldBe` TestModel True False
eventsDisable evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should not close the popup when Esc is pressed if popupDisableClose is set" $ do
let evts = [evtClick (Point 50 10), evtK keyEscape]
modelDisable evts `shouldBe` TestModel True False
eventsDisable evts `shouldBe` Seq.fromList [OnPopupChange True]
describe "alignment" $ do
it "should toggle the popupToggle button when aligned center to the widget" $ do
let cfgs = [popupOffset (Point 10 10), alignCenter]
let evts = [evtClick (Point 50 10), evtClick (Point 340 60)]
modelAlign cfgs evts `shouldBe` TestModel True True
eventsAlign cfgs evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should toggle the popupToggle button when aligned top-center to the window" $ do
let cfgs = [popupAlignToWindow, popupOffset (Point 10 10), alignTop, alignCenter]
let evts = [evtClick (Point 50 10), evtClick (Point 340 10)]
modelAlign cfgs evts `shouldBe` TestModel True True
eventsAlign cfgs evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should toggle the popupToggle button when aligned bottom-right to the window" $ do
let cfgs = [popupAlignToWindow, popupOffset (Point 10 10), alignBottom, alignRight]
let evts = [evtClick (Point 50 10), evtClick (Point 620 460)]
modelAlign cfgs evts `shouldBe` TestModel True True
eventsAlign cfgs evts `shouldBe` Seq.fromList [OnPopupChange True]
where
wenv = mockWenv (TestModel False False)
& L.theme .~ darkTheme
handleEvent :: EventHandler TestModel TestEvent TestModel TestEvent
handleEvent wenv node model evt = [ Report evt ]
buildUI cfgs wenv model = vstack [
toggleButton "Open" open,
popup_ open cfgs $ hgrid [
toggleButton "Close" open,
toggleButton "Test" popupToggle
],
filler
]
popupNode cfgs = composite "popupNode" id (buildUI cfgs) handleEvent
modelBase es = localHandleEventModel wenv es (popupNode [])
modelDisable es = localHandleEventModel wenv es (popupNode [popupDisableClose])
modelAlign cfgs es = localHandleEventModel wenv es (popupNode (popupDisableClose : cfgs))
eventsBase es = localHandleEventEvts wenv es (popupNode [onChange OnPopupChange])
eventsDisable es = localHandleEventEvts wenv es (popupNode [onChange OnPopupChange, popupDisableClose])
eventsAlign cfgs es = localHandleEventEvts wenv es (popupNode (onChange OnPopupChange : popupDisableClose : cfgs))
handleEventAnchor :: Spec
handleEventAnchor = describe "handleEventAnchor" $ do
describe "alignment outer border" $ do
it "should toggle the popupToggle button when aligned above the widget" $ do
let cfgs = [popupAlignToOuterV, alignTop, alignRight]
let evts = [evtClick (Point 50 110), evtClick (Point 600 80)]
modelAlign cfgs [] evts `shouldBe` TestModel True True
eventsAlign cfgs [] evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should toggle the popupToggle button when aligned below the widget" $ do
let cfgs = [popupAlignToOuterV, alignBottom, alignRight]
let evts = [evtClick (Point 50 110), evtClick (Point 600 140)]
modelAlign cfgs [] evts `shouldBe` TestModel True True
eventsAlign cfgs [] evts `shouldBe` Seq.fromList [OnPopupChange True]
it "should close the popup when aligned above the widget and the toggle button is clicked" $ do
let cfgs = [popupAlignToOuterV, alignTop, alignRight]
let evts = [evtClick (Point 50 110), evtClick (Point 520 80)]
modelAlign cfgs [] evts `shouldBe` TestModel False False
eventsAlign cfgs [] evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
it "should close the popup when aligned below the widget and the toggle button is clicked" $ do
let cfgs = [popupAlignToOuterV, alignBottom, alignRight]
let evts = [evtClick (Point 50 110), evtClick (Point 520 140)]
modelAlign cfgs [] evts `shouldBe` TestModel False False
eventsAlign cfgs [] evts `shouldBe` Seq.fromList [OnPopupChange True, OnPopupChange False]
describe "Re align outer" $ do
it "should re-locate the anchor below the widget, because it did not fit above" $ do
let cfgs = [popupAlignToOuterV, alignTop, alignRight]
let styles = [height 200]
let evts = [evtClick (Point 50 110), evtClick (Point 600 140)]
modelAlign cfgs styles evts `shouldBe` TestModel True True
eventsAlign cfgs styles evts `shouldBe` Seq.fromList [OnPopupChange True]
where
wenv = mockWenv (TestModel False False)
& L.theme .~ darkTheme
handleEvent :: EventHandler TestModel TestEvent TestModel TestEvent
handleEvent wenv node model evt = [ Report evt ]
buildUI cfgs styles wenv model = vstack [
spacer `styleBasic` [height 100],
popup_ open cfgs $ hgrid [
toggleButton "Close" open,
toggleButton "Test" popupToggle
] `styleBasic` styles,
filler
]
popupNode cfgs styles = composite "popupNode" id (buildUI cfgs styles) handleEvent
baseCfgs = [popupAnchor (toggleButton "Open" open), onChange OnPopupChange]
modelAlign cfgs styles es = localHandleEventModel wenv es $
popupNode (popupDisableClose : (baseCfgs ++ cfgs)) styles
eventsAlign cfgs styles es = localHandleEventEvts wenv es $
popupNode (popupDisableClose : (baseCfgs ++ cfgs)) styles
localHandleEventModel :: (Eq s, WidgetModel s) => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> s
localHandleEventModel wenv steps node = _weModel wenv2 where
stepEvts = (: []) <$> steps
(wenv2, _, _) = fst $ nodeHandleEventsSteps wenv WInit stepEvts node
localHandleEventEvts :: Eq s => WidgetEnv s e -> [SystemEvent] -> WidgetNode s e -> Seq e
localHandleEventEvts wenv steps node = eventsFromReqs reqs where
stepEvts = (: []) <$> steps
(_, _, reqs) = fst $ nodeHandleEventsSteps wenv WInit stepEvts node
| |
ced39cd1b01adc02a386acfb89f5d2652ed82bbc0d11bdbc73ee72da9105c31f | iand675/hs-opentelemetry | Raw.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE DerivingStrategies #
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE Strict #-}
module Raw (
newTraceIdFromHeader,
newSpanIdFromHeader,
newHeaderFromTraceId,
newHeaderFromSpanId,
showWord64BS,
readWord64BS,
asciiWord8ToWord8,
word8ToAsciiWord8,
) where
import Control.Monad.ST (ST, runST)
import Data.Bits (Bits (complement, shift, (.&.)))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Internal as BI
import Data.ByteString.Short (ShortByteString)
import qualified Data.ByteString.Short.Internal as SBI
import qualified Data.Char as C
import Data.Primitive.ByteArray (
ByteArray (ByteArray),
MutableByteArray,
freezeByteArray,
indexByteArray,
newByteArray,
writeByteArray,
)
import Data.Primitive.Ptr (writeOffPtr)
import Data.Word (Word64, Word8)
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Storable (peekElemOff)
import System.IO.Unsafe (unsafeDupablePerformIO)
newTraceIdFromHeader ::
-- | ASCII numeric text
ByteString ->
ShortByteString
newTraceIdFromHeader bs =
let
len = 16 :: Int
!(ByteArray ba) =
runST $ do
mba <- newByteArray len
let w64 = readWord64BS bs
fill zeros to one upper Word64 - size area
offset one Word64 - size
freezeByteArray mba 0 len
in
SBI.SBS ba
newSpanIdFromHeader ::
-- | ASCII numeric text
ByteString ->
ShortByteString
newSpanIdFromHeader bs =
let
len = 8 :: Int
!(ByteArray ba) =
runST $ do
mba <- newByteArray len
let w64 = readWord64BS bs
writeByteArrayNbo mba 0 w64
freezeByteArray mba 0 len
in
SBI.SBS ba
{- | Write a primitive value to the byte array with network-byte-order (big-endian).
The offset is given in elements of type @a@ rather than in bytes.
-}
writeByteArrayNbo :: MutableByteArray s -> Int -> Word64 -> ST s ()
writeByteArrayNbo mba offset value = do
writeByteArray mba offset (0 :: Word64)
loop 0 value
where
loop _ 0 = pure ()
loop 8 _ = pure ()
loop n v = do
let
-- equivelent:
( p , q ) = v ` divMod ` ( 2 ^ ( 8 : : Int ) )
p = shift v (-8)
q = v .&. complement (shift p 8)
writeByteArray mba (8 * (offset + 1) - n - 1) (fromIntegral q :: Word8)
loop (n + 1) p
readWord64BS :: ByteString -> Word64
readWord64BS (BI.PS fptr _ len) =
unsafeDupablePerformIO $
withForeignPtr fptr readWord64Ptr
where
readWord64Ptr ptr =
readWord64PtrOffset 0 0
where
readWord64PtrOffset offset acc
| offset < len = do
b <- peekElemOff ptr offset
let n = fromIntegral $ asciiWord8ToWord8 b :: Word64
readWord64PtrOffset (offset + 1) $ n + acc * 10
| otherwise = pure acc
asciiWord8ToWord8 :: Word8 -> Word8
asciiWord8ToWord8 b = b - fromIntegral (C.ord '0')
newHeaderFromTraceId :: ShortByteString -> ByteString
newHeaderFromTraceId (SBI.SBS ba) =
let w64 = indexByteArrayNbo (ByteArray ba) 1
in showWord64BS w64
newHeaderFromSpanId :: ShortByteString -> ByteString
newHeaderFromSpanId (SBI.SBS ba) =
let w64 = indexByteArrayNbo (ByteArray ba) 0
in showWord64BS w64
indexByteArrayNbo :: ByteArray -> Int -> Word64
indexByteArrayNbo ba offset =
loop 0 0
where
loop 8 acc = acc
loop n acc = loop (n + 1) $ shift acc 8 + word8ToWord64 (indexByteArray ba $ 8 * offset + n)
showWord64BS :: Word64 -> ByteString
showWord64BS v =
unsafeDupablePerformIO $
20 = length ( show ( maxBound : : Word64 ) )
where
writeWord64Ptr ptr =
loop (19 :: Int) v 0 False
where
loop 0 v offset _ = do
writeOffPtr ptr offset (word8ToAsciiWord8 $ fromIntegral v)
pure $ offset + 1
loop n v offset upper = do
let (p, q) = v `divMod` (10 ^ n)
if p == 0 && not upper
then loop (n - 1) q offset upper
else do
writeOffPtr ptr offset (word8ToAsciiWord8 $ fromIntegral p)
loop (n - 1) q (offset + 1) True
word8ToAsciiWord8 :: Word8 -> Word8
word8ToAsciiWord8 b = b + fromIntegral (C.ord '0')
word8ToWord64 :: Word8 -> Word64
word8ToWord64 = fromIntegral
| null | https://raw.githubusercontent.com/iand675/hs-opentelemetry/1f0328eb59fec2a97aec7ef98fe4f1e0d5c8f2ac/propagators/datadog/old-src/Raw.hs | haskell | # LANGUAGE BangPatterns #
# LANGUAGE OverloadedStrings #
# LANGUAGE Strict #
| ASCII numeric text
| ASCII numeric text
| Write a primitive value to the byte array with network-byte-order (big-endian).
The offset is given in elements of type @a@ rather than in bytes.
equivelent: | # LANGUAGE DerivingStrategies #
module Raw (
newTraceIdFromHeader,
newSpanIdFromHeader,
newHeaderFromTraceId,
newHeaderFromSpanId,
showWord64BS,
readWord64BS,
asciiWord8ToWord8,
word8ToAsciiWord8,
) where
import Control.Monad.ST (ST, runST)
import Data.Bits (Bits (complement, shift, (.&.)))
import Data.ByteString (ByteString)
import qualified Data.ByteString.Internal as BI
import Data.ByteString.Short (ShortByteString)
import qualified Data.ByteString.Short.Internal as SBI
import qualified Data.Char as C
import Data.Primitive.ByteArray (
ByteArray (ByteArray),
MutableByteArray,
freezeByteArray,
indexByteArray,
newByteArray,
writeByteArray,
)
import Data.Primitive.Ptr (writeOffPtr)
import Data.Word (Word64, Word8)
import Foreign.ForeignPtr (withForeignPtr)
import Foreign.Storable (peekElemOff)
import System.IO.Unsafe (unsafeDupablePerformIO)
newTraceIdFromHeader ::
ByteString ->
ShortByteString
newTraceIdFromHeader bs =
let
len = 16 :: Int
!(ByteArray ba) =
runST $ do
mba <- newByteArray len
let w64 = readWord64BS bs
fill zeros to one upper Word64 - size area
offset one Word64 - size
freezeByteArray mba 0 len
in
SBI.SBS ba
newSpanIdFromHeader ::
ByteString ->
ShortByteString
newSpanIdFromHeader bs =
let
len = 8 :: Int
!(ByteArray ba) =
runST $ do
mba <- newByteArray len
let w64 = readWord64BS bs
writeByteArrayNbo mba 0 w64
freezeByteArray mba 0 len
in
SBI.SBS ba
writeByteArrayNbo :: MutableByteArray s -> Int -> Word64 -> ST s ()
writeByteArrayNbo mba offset value = do
writeByteArray mba offset (0 :: Word64)
loop 0 value
where
loop _ 0 = pure ()
loop 8 _ = pure ()
loop n v = do
let
( p , q ) = v ` divMod ` ( 2 ^ ( 8 : : Int ) )
p = shift v (-8)
q = v .&. complement (shift p 8)
writeByteArray mba (8 * (offset + 1) - n - 1) (fromIntegral q :: Word8)
loop (n + 1) p
readWord64BS :: ByteString -> Word64
readWord64BS (BI.PS fptr _ len) =
unsafeDupablePerformIO $
withForeignPtr fptr readWord64Ptr
where
readWord64Ptr ptr =
readWord64PtrOffset 0 0
where
readWord64PtrOffset offset acc
| offset < len = do
b <- peekElemOff ptr offset
let n = fromIntegral $ asciiWord8ToWord8 b :: Word64
readWord64PtrOffset (offset + 1) $ n + acc * 10
| otherwise = pure acc
asciiWord8ToWord8 :: Word8 -> Word8
asciiWord8ToWord8 b = b - fromIntegral (C.ord '0')
newHeaderFromTraceId :: ShortByteString -> ByteString
newHeaderFromTraceId (SBI.SBS ba) =
let w64 = indexByteArrayNbo (ByteArray ba) 1
in showWord64BS w64
newHeaderFromSpanId :: ShortByteString -> ByteString
newHeaderFromSpanId (SBI.SBS ba) =
let w64 = indexByteArrayNbo (ByteArray ba) 0
in showWord64BS w64
indexByteArrayNbo :: ByteArray -> Int -> Word64
indexByteArrayNbo ba offset =
loop 0 0
where
loop 8 acc = acc
loop n acc = loop (n + 1) $ shift acc 8 + word8ToWord64 (indexByteArray ba $ 8 * offset + n)
showWord64BS :: Word64 -> ByteString
showWord64BS v =
unsafeDupablePerformIO $
20 = length ( show ( maxBound : : Word64 ) )
where
writeWord64Ptr ptr =
loop (19 :: Int) v 0 False
where
loop 0 v offset _ = do
writeOffPtr ptr offset (word8ToAsciiWord8 $ fromIntegral v)
pure $ offset + 1
loop n v offset upper = do
let (p, q) = v `divMod` (10 ^ n)
if p == 0 && not upper
then loop (n - 1) q offset upper
else do
writeOffPtr ptr offset (word8ToAsciiWord8 $ fromIntegral p)
loop (n - 1) q (offset + 1) True
word8ToAsciiWord8 :: Word8 -> Word8
word8ToAsciiWord8 b = b + fromIntegral (C.ord '0')
word8ToWord64 :: Word8 -> Word64
word8ToWord64 = fromIntegral
|
78f20c018fb40c6c1b1eb057fe37aa2ddc3cfe6f43a1d36ae0c9b5446f971fec | coq/coq | cbn.mli | (************************************************************************)
(* * The Coq Proof Assistant / The Coq Development Team *)
v * INRIA , CNRS and contributors - Copyright 1999 - 2019
(* <O___,, * (see CREDITS file for the list of authors) *)
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
* GNU Lesser General Public License Version 2.1
(* * (see LICENSE file for the text of the license) *)
(************************************************************************)
* Weak - head reduction . Despite the name , the cbn reduction is a complex
reduction distinct from call - by - name or call - by - need .
reduction distinct from call-by-name or call-by-need. *)
val whd_cbn :
CClosure.RedFlags.reds ->
Environ.env -> Evd.evar_map -> EConstr.constr -> EConstr.constr
* Strong variant of cbn reduction .
val norm_cbn :
CClosure.RedFlags.reds ->
Environ.env -> Evd.evar_map -> EConstr.constr -> EConstr.constr
| null | https://raw.githubusercontent.com/coq/coq/110921a449fcb830ec2a1cd07e3acc32319feae6/tactics/cbn.mli | ocaml | **********************************************************************
* The Coq Proof Assistant / The Coq Development Team
<O___,, * (see CREDITS file for the list of authors)
// * This file is distributed under the terms of the
* (see LICENSE file for the text of the license)
********************************************************************** | v * INRIA , CNRS and contributors - Copyright 1999 - 2019
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GNU Lesser General Public License Version 2.1
* Weak - head reduction . Despite the name , the cbn reduction is a complex
reduction distinct from call - by - name or call - by - need .
reduction distinct from call-by-name or call-by-need. *)
val whd_cbn :
CClosure.RedFlags.reds ->
Environ.env -> Evd.evar_map -> EConstr.constr -> EConstr.constr
* Strong variant of cbn reduction .
val norm_cbn :
CClosure.RedFlags.reds ->
Environ.env -> Evd.evar_map -> EConstr.constr -> EConstr.constr
|
41229631670c5c24cc0649482c49fbb7b482ca2ef08e61a8958e924a7e715fbb | eugeneia/athens | cast5.lisp | ;;;; -*- mode: lisp; indent-tabs-mode: nil -*-
cast5.lisp -- implementation of rfc2144 CAST5 algorithm
(in-package :crypto)
;;; s-boxes
(declaim (type (simple-array (unsigned-byte 32) (256))
+cast5-sbox0+ +cast5-sbox1+ +cast5-sbox2+ +cast5-sbox3+
+cast5-sbox4+ +cast5-sbox5+ +cast5-sbox6+ +cast5-sbox7+))
(defconst +cast5-sbox0+
#32@(#x30fb40d4 #x9fa0ff0b #x6beccd2f #x3f258c7a #x1e213f2f #x9c004dd3 #x6003e540 #xcf9fc949
#xbfd4af27 #x88bbbdb5 #xe2034090 #x98d09675 #x6e63a0e0 #x15c361d2 #xc2e7661d #x22d4ff8e
#x28683b6f #xc07fd059 #xff2379c8 #x775f50e2 #x43c340d3 #xdf2f8656 #x887ca41a #xa2d2bd2d
#xa1c9e0d6 #x346c4819 #x61b76d87 #x22540f2f #x2abe32e1 #xaa54166b #x22568e3a #xa2d341d0
#x66db40c8 #xa784392f #x004dff2f #x2db9d2de #x97943fac #x4a97c1d8 #x527644b7 #xb5f437a7
#xb82cbaef #xd751d159 #x6ff7f0ed #x5a097a1f #x827b68d0 #x90ecf52e #x22b0c054 #xbc8e5935
#x4b6d2f7f #x50bb64a2 #xd2664910 #xbee5812d #xb7332290 #xe93b159f #xb48ee411 #x4bff345d
#xfd45c240 #xad31973f #xc4f6d02e #x55fc8165 #xd5b1caad #xa1ac2dae #xa2d4b76d #xc19b0c50
#x882240f2 #x0c6e4f38 #xa4e4bfd7 #x4f5ba272 #x564c1d2f #xc59c5319 #xb949e354 #xb04669fe
#xb1b6ab8a #xc71358dd #x6385c545 #x110f935d #x57538ad5 #x6a390493 #xe63d37e0 #x2a54f6b3
#x3a787d5f #x6276a0b5 #x19a6fcdf #x7a42206a #x29f9d4d5 #xf61b1891 #xbb72275e #xaa508167
#x38901091 #xc6b505eb #x84c7cb8c #x2ad75a0f #x874a1427 #xa2d1936b #x2ad286af #xaa56d291
#xd7894360 #x425c750d #x93b39e26 #x187184c9 #x6c00b32d #x73e2bb14 #xa0bebc3c #x54623779
#x64459eab #x3f328b82 #x7718cf82 #x59a2cea6 #x04ee002e #x89fe78e6 #x3fab0950 #x325ff6c2
#x81383f05 #x6963c5c8 #x76cb5ad6 #xd49974c9 #xca180dcf #x380782d5 #xc7fa5cf6 #x8ac31511
#x35e79e13 #x47da91d0 #xf40f9086 #xa7e2419e #x31366241 #x051ef495 #xaa573b04 #x4a805d8d
#x548300d0 #x00322a3c #xbf64cddf #xba57a68e #x75c6372b #x50afd341 #xa7c13275 #x915a0bf5
#x6b54bfab #x2b0b1426 #xab4cc9d7 #x449ccd82 #xf7fbf265 #xab85c5f3 #x1b55db94 #xaad4e324
#xcfa4bd3f #x2deaa3e2 #x9e204d02 #xc8bd25ac #xeadf55b3 #xd5bd9e98 #xe31231b2 #x2ad5ad6c
#x954329de #xadbe4528 #xd8710f69 #xaa51c90f #xaa786bf6 #x22513f1e #xaa51a79b #x2ad344cc
#x7b5a41f0 #xd37cfbad #x1b069505 #x41ece491 #xb4c332e6 #x032268d4 #xc9600acc #xce387e6d
#xbf6bb16c #x6a70fb78 #x0d03d9c9 #xd4df39de #xe01063da #x4736f464 #x5ad328d8 #xb347cc96
#x75bb0fc3 #x98511bfb #x4ffbcc35 #xb58bcf6a #xe11f0abc #xbfc5fe4a #xa70aec10 #xac39570a
#x3f04442f #x6188b153 #xe0397a2e #x5727cb79 #x9ceb418f #x1cacd68d #x2ad37c96 #x0175cb9d
#xc69dff09 #xc75b65f0 #xd9db40d8 #xec0e7779 #x4744ead4 #xb11c3274 #xdd24cb9e #x7e1c54bd
#xf01144f9 #xd2240eb1 #x9675b3fd #xa3ac3755 #xd47c27af #x51c85f4d #x56907596 #xa5bb15e6
#x580304f0 #xca042cf1 #x011a37ea #x8dbfaadb #x35ba3e4a #x3526ffa0 #xc37b4d09 #xbc306ed9
#x98a52666 #x5648f725 #xff5e569d #x0ced63d0 #x7c63b2cf #x700b45e1 #xd5ea50f1 #x85a92872
#xaf1fbda7 #xd4234870 #xa7870bf3 #x2d3b4d79 #x42e04198 #x0cd0ede7 #x26470db8 #xf881814c
#x474d6ad7 #x7c0c5e5c #xd1231959 #x381b7298 #xf5d2f4db #xab838653 #x6e2f1e23 #x83719c9e
#xbd91e046 #x9a56456e #xdc39200c #x20c8c571 #x962bda1c #xe1e696ff #xb141ab08 #x7cca89b9
#x1a69e783 #x02cc4843 #xa2f7c579 #x429ef47d #x427b169c #x5ac9f049 #xdd8f0f00 #x5c8165bf))
(defconst +cast5-sbox1+
#32@(#x1f201094 #xef0ba75b #x69e3cf7e #x393f4380 #xfe61cf7a #xeec5207a #x55889c94 #x72fc0651
#xada7ef79 #x4e1d7235 #xd55a63ce #xde0436ba #x99c430ef #x5f0c0794 #x18dcdb7d #xa1d6eff3
#xa0b52f7b #x59e83605 #xee15b094 #xe9ffd909 #xdc440086 #xef944459 #xba83ccb3 #xe0c3cdfb
#xd1da4181 #x3b092ab1 #xf997f1c1 #xa5e6cf7b #x01420ddb #xe4e7ef5b #x25a1ff41 #xe180f806
#x1fc41080 #x179bee7a #xd37ac6a9 #xfe5830a4 #x98de8b7f #x77e83f4e #x79929269 #x24fa9f7b
#xe113c85b #xacc40083 #xd7503525 #xf7ea615f #x62143154 #x0d554b63 #x5d681121 #xc866c359
#x3d63cf73 #xcee234c0 #xd4d87e87 #x5c672b21 #x071f6181 #x39f7627f #x361e3084 #xe4eb573b
#x602f64a4 #xd63acd9c #x1bbc4635 #x9e81032d #x2701f50c #x99847ab4 #xa0e3df79 #xba6cf38c
#x10843094 #x2537a95e #xf46f6ffe #xa1ff3b1f #x208cfb6a #x8f458c74 #xd9e0a227 #x4ec73a34
#xfc884f69 #x3e4de8df #xef0e0088 #x3559648d #x8a45388c #x1d804366 #x721d9bfd #xa58684bb
#xe8256333 #x844e8212 #x128d8098 #xfed33fb4 #xce280ae1 #x27e19ba5 #xd5a6c252 #xe49754bd
#xc5d655dd #xeb667064 #x77840b4d #xa1b6a801 #x84db26a9 #xe0b56714 #x21f043b7 #xe5d05860
#x54f03084 #x066ff472 #xa31aa153 #xdadc4755 #xb5625dbf #x68561be6 #x83ca6b94 #x2d6ed23b
#xeccf01db #xa6d3d0ba #xb6803d5c #xaf77a709 #x33b4a34c #x397bc8d6 #x5ee22b95 #x5f0e5304
#x81ed6f61 #x20e74364 #xb45e1378 #xde18639b #x881ca122 #xb96726d1 #x8049a7e8 #x22b7da7b
#x5e552d25 #x5272d237 #x79d2951c #xc60d894c #x488cb402 #x1ba4fe5b #xa4b09f6b #x1ca815cf
#xa20c3005 #x8871df63 #xb9de2fcb #x0cc6c9e9 #x0beeff53 #xe3214517 #xb4542835 #x9f63293c
#xee41e729 #x6e1d2d7c #x50045286 #x1e6685f3 #xf33401c6 #x30a22c95 #x31a70850 #x60930f13
#x73f98417 #xa1269859 #xec645c44 #x52c877a9 #xcdff33a6 #xa02b1741 #x7cbad9a2 #x2180036f
#x50d99c08 #xcb3f4861 #xc26bd765 #x64a3f6ab #x80342676 #x25a75e7b #xe4e6d1fc #x20c710e6
#xcdf0b680 #x17844d3b #x31eef84d #x7e0824e4 #x2ccb49eb #x846a3bae #x8ff77888 #xee5d60f6
#x7af75673 #x2fdd5cdb #xa11631c1 #x30f66f43 #xb3faec54 #x157fd7fa #xef8579cc #xd152de58
#xdb2ffd5e #x8f32ce19 #x306af97a #x02f03ef8 #x99319ad5 #xc242fa0f #xa7e3ebb0 #xc68e4906
#xb8da230c #x80823028 #xdcdef3c8 #xd35fb171 #x088a1bc8 #xbec0c560 #x61a3c9e8 #xbca8f54d
#xc72feffa #x22822e99 #x82c570b4 #xd8d94e89 #x8b1c34bc #x301e16e6 #x273be979 #xb0ffeaa6
#x61d9b8c6 #x00b24869 #xb7ffce3f #x08dc283b #x43daf65a #xf7e19798 #x7619b72f #x8f1c9ba4
#xdc8637a0 #x16a7d3b1 #x9fc393b7 #xa7136eeb #xc6bcc63e #x1a513742 #xef6828bc #x520365d6
#x2d6a77ab #x3527ed4b #x821fd216 #x095c6e2e #xdb92f2fb #x5eea29cb #x145892f5 #x91584f7f
#x5483697b #x2667a8cc #x85196048 #x8c4bacea #x833860d4 #x0d23e0f9 #x6c387e8a #x0ae6d249
#xb284600c #xd835731d #xdcb1c647 #xac4c56ea #x3ebd81b3 #x230eabb0 #x6438bc87 #xf0b5b1fa
#x8f5ea2b3 #xfc184642 #x0a036b7a #x4fb089bd #x649da589 #xa345415e #x5c038323 #x3e5d3bb9
#x43d79572 #x7e6dd07c #x06dfdf1e #x6c6cc4ef #x7160a539 #x73bfbe70 #x83877605 #x4523ecf1))
(defconst +cast5-sbox2+
#32@(#x8defc240 #x25fa5d9f #xeb903dbf #xe810c907 #x47607fff #x369fe44b #x8c1fc644 #xaececa90
#xbeb1f9bf #xeefbcaea #xe8cf1950 #x51df07ae #x920e8806 #xf0ad0548 #xe13c8d83 #x927010d5
#x11107d9f #x07647db9 #xb2e3e4d4 #x3d4f285e #xb9afa820 #xfade82e0 #xa067268b #x8272792e
#x553fb2c0 #x489ae22b #xd4ef9794 #x125e3fbc #x21fffcee #x825b1bfd #x9255c5ed #x1257a240
#x4e1a8302 #xbae07fff #x528246e7 #x8e57140e #x3373f7bf #x8c9f8188 #xa6fc4ee8 #xc982b5a5
#xa8c01db7 #x579fc264 #x67094f31 #xf2bd3f5f #x40fff7c1 #x1fb78dfc #x8e6bd2c1 #x437be59b
#x99b03dbf #xb5dbc64b #x638dc0e6 #x55819d99 #xa197c81c #x4a012d6e #xc5884a28 #xccc36f71
#xb843c213 #x6c0743f1 #x8309893c #x0feddd5f #x2f7fe850 #xd7c07f7e #x02507fbf #x5afb9a04
#xa747d2d0 #x1651192e #xaf70bf3e #x58c31380 #x5f98302e #x727cc3c4 #x0a0fb402 #x0f7fef82
#x8c96fdad #x5d2c2aae #x8ee99a49 #x50da88b8 #x8427f4a0 #x1eac5790 #x796fb449 #x8252dc15
#xefbd7d9b #xa672597d #xada840d8 #x45f54504 #xfa5d7403 #xe83ec305 #x4f91751a #x925669c2
#x23efe941 #xa903f12e #x60270df2 #x0276e4b6 #x94fd6574 #x927985b2 #x8276dbcb #x02778176
#xf8af918d #x4e48f79e #x8f616ddf #xe29d840e #x842f7d83 #x340ce5c8 #x96bbb682 #x93b4b148
#xef303cab #x984faf28 #x779faf9b #x92dc560d #x224d1e20 #x8437aa88 #x7d29dc96 #x2756d3dc
#x8b907cee #xb51fd240 #xe7c07ce3 #xe566b4a1 #xc3e9615e #x3cf8209d #x6094d1e3 #xcd9ca341
#x5c76460e #x00ea983b #xd4d67881 #xfd47572c #xf76cedd9 #xbda8229c #x127dadaa #x438a074e
#x1f97c090 #x081bdb8a #x93a07ebe #xb938ca15 #x97b03cff #x3dc2c0f8 #x8d1ab2ec #x64380e51
#x68cc7bfb #xd90f2788 #x12490181 #x5de5ffd4 #xdd7ef86a #x76a2e214 #xb9a40368 #x925d958f
#x4b39fffa #xba39aee9 #xa4ffd30b #xfaf7933b #x6d498623 #x193cbcfa #x27627545 #x825cf47a
#x61bd8ba0 #xd11e42d1 #xcead04f4 #x127ea392 #x10428db7 #x8272a972 #x9270c4a8 #x127de50b
#x285ba1c8 #x3c62f44f #x35c0eaa5 #xe805d231 #x428929fb #xb4fcdf82 #x4fb66a53 #x0e7dc15b
#x1f081fab #x108618ae #xfcfd086d #xf9ff2889 #x694bcc11 #x236a5cae #x12deca4d #x2c3f8cc5
#xd2d02dfe #xf8ef5896 #xe4cf52da #x95155b67 #x494a488c #xb9b6a80c #x5c8f82bc #x89d36b45
#x3a609437 #xec00c9a9 #x44715253 #x0a874b49 #xd773bc40 #x7c34671c #x02717ef6 #x4feb5536
#xa2d02fff #xd2bf60c4 #xd43f03c0 #x50b4ef6d #x07478cd1 #x006e1888 #xa2e53f55 #xb9e6d4bc
#xa2048016 #x97573833 #xd7207d67 #xde0f8f3d #x72f87b33 #xabcc4f33 #x7688c55d #x7b00a6b0
#x947b0001 #x570075d2 #xf9bb88f8 #x8942019e #x4264a5ff #x856302e0 #x72dbd92b #xee971b69
#x6ea22fde #x5f08ae2b #xaf7a616d #xe5c98767 #xcf1febd2 #x61efc8c2 #xf1ac2571 #xcc8239c2
#x67214cb8 #xb1e583d1 #xb7dc3e62 #x7f10bdce #xf90a5c38 #x0ff0443d #x606e6dc6 #x60543a49
#x5727c148 #x2be98a1d #x8ab41738 #x20e1be24 #xaf96da0f #x68458425 #x99833be5 #x600d457d
#x282f9350 #x8334b362 #xd91d1120 #x2b6d8da0 #x642b1e31 #x9c305a00 #x52bce688 #x1b03588a
#xf7baefd5 #x4142ed9c #xa4315c11 #x83323ec5 #xdfef4636 #xa133c501 #xe9d3531c #xee353783))
(defconst +cast5-sbox3+
#32@(#x9db30420 #x1fb6e9de #xa7be7bef #xd273a298 #x4a4f7bdb #x64ad8c57 #x85510443 #xfa020ed1
#x7e287aff #xe60fb663 #x095f35a1 #x79ebf120 #xfd059d43 #x6497b7b1 #xf3641f63 #x241e4adf
#x28147f5f #x4fa2b8cd #xc9430040 #x0cc32220 #xfdd30b30 #xc0a5374f #x1d2d00d9 #x24147b15
#xee4d111a #x0fca5167 #x71ff904c #x2d195ffe #x1a05645f #x0c13fefe #x081b08ca #x05170121
#x80530100 #xe83e5efe #xac9af4f8 #x7fe72701 #xd2b8ee5f #x06df4261 #xbb9e9b8a #x7293ea25
#xce84ffdf #xf5718801 #x3dd64b04 #xa26f263b #x7ed48400 #x547eebe6 #x446d4ca0 #x6cf3d6f5
#x2649abdf #xaea0c7f5 #x36338cc1 #x503f7e93 #xd3772061 #x11b638e1 #x72500e03 #xf80eb2bb
#xabe0502e #xec8d77de #x57971e81 #xe14f6746 #xc9335400 #x6920318f #x081dbb99 #xffc304a5
#x4d351805 #x7f3d5ce3 #xa6c866c6 #x5d5bcca9 #xdaec6fea #x9f926f91 #x9f46222f #x3991467d
#xa5bf6d8e #x1143c44f #x43958302 #xd0214eeb #x022083b8 #x3fb6180c #x18f8931e #x281658e6
#x26486e3e #x8bd78a70 #x7477e4c1 #xb506e07c #xf32d0a25 #x79098b02 #xe4eabb81 #x28123b23
#x69dead38 #x1574ca16 #xdf871b62 #x211c40b7 #xa51a9ef9 #x0014377b #x041e8ac8 #x09114003
#xbd59e4d2 #xe3d156d5 #x4fe876d5 #x2f91a340 #x557be8de #x00eae4a7 #x0ce5c2ec #x4db4bba6
#xe756bdff #xdd3369ac #xec17b035 #x06572327 #x99afc8b0 #x56c8c391 #x6b65811c #x5e146119
#x6e85cb75 #xbe07c002 #xc2325577 #x893ff4ec #x5bbfc92d #xd0ec3b25 #xb7801ab7 #x8d6d3b24
#x20c763ef #xc366a5fc #x9c382880 #x0ace3205 #xaac9548a #xeca1d7c7 #x041afa32 #x1d16625a
#x6701902c #x9b757a54 #x31d477f7 #x9126b031 #x36cc6fdb #xc70b8b46 #xd9e66a48 #x56e55a79
#x026a4ceb #x52437eff #x2f8f76b4 #x0df980a5 #x8674cde3 #xedda04eb #x17a9be04 #x2c18f4df
#xb7747f9d #xab2af7b4 #xefc34d20 #x2e096b7c #x1741a254 #xe5b6a035 #x213d42f6 #x2c1c7c26
#x61c2f50f #x6552daf9 #xd2c231f8 #x25130f69 #xd8167fa2 #x0418f2c8 #x001a96a6 #x0d1526ab
#x63315c21 #x5e0a72ec #x49bafefd #x187908d9 #x8d0dbd86 #x311170a7 #x3e9b640c #xcc3e10d7
#xd5cad3b6 #x0caec388 #xf73001e1 #x6c728aff #x71eae2a1 #x1f9af36e #xcfcbd12f #xc1de8417
#xac07be6b #xcb44a1d8 #x8b9b0f56 #x013988c3 #xb1c52fca #xb4be31cd #xd8782806 #x12a3a4e2
#x6f7de532 #x58fd7eb6 #xd01ee900 #x24adffc2 #xf4990fc5 #x9711aac5 #x001d7b95 #x82e5e7d2
#x109873f6 #x00613096 #xc32d9521 #xada121ff #x29908415 #x7fbb977f #xaf9eb3db #x29c9ed2a
#x5ce2a465 #xa730f32c #xd0aa3fe8 #x8a5cc091 #xd49e2ce7 #x0ce454a9 #xd60acd86 #x015f1919
#x77079103 #xdea03af6 #x78a8565e #xdee356df #x21f05cbe #x8b75e387 #xb3c50651 #xb8a5c3ef
#xd8eeb6d2 #xe523be77 #xc2154529 #x2f69efdf #xafe67afb #xf470c4b2 #xf3e0eb5b #xd6cc9876
#x39e4460c #x1fda8538 #x1987832f #xca007367 #xa99144f8 #x296b299e #x492fc295 #x9266beab
#xb5676e69 #x9bd3ddda #xdf7e052f #xdb25701c #x1b5e51ee #xf65324e6 #x6afce36c #x0316cc04
#x8644213e #xb7dc59d0 #x7965291f #xccd6fd43 #x41823979 #x932bcdf6 #xb657c34d #x4edfd282
#x7ae5290c #x3cb9536b #x851e20fe #x9833557e #x13ecf0b0 #xd3ffb372 #x3f85c5c1 #x0aef7ed2))
(defconst +cast5-sbox4+
#32@(#x7ec90c04 #x2c6e74b9 #x9b0e66df #xa6337911 #xb86a7fff #x1dd358f5 #x44dd9d44 #x1731167f
#x08fbf1fa #xe7f511cc #xd2051b00 #x735aba00 #x2ab722d8 #x386381cb #xacf6243a #x69befd7a
#xe6a2e77f #xf0c720cd #xc4494816 #xccf5c180 #x38851640 #x15b0a848 #xe68b18cb #x4caadeff
#x5f480a01 #x0412b2aa #x259814fc #x41d0efe2 #x4e40b48d #x248eb6fb #x8dba1cfe #x41a99b02
#x1a550a04 #xba8f65cb #x7251f4e7 #x95a51725 #xc106ecd7 #x97a5980a #xc539b9aa #x4d79fe6a
#xf2f3f763 #x68af8040 #xed0c9e56 #x11b4958b #xe1eb5a88 #x8709e6b0 #xd7e07156 #x4e29fea7
#x6366e52d #x02d1c000 #xc4ac8e05 #x9377f571 #x0c05372a #x578535f2 #x2261be02 #xd642a0c9
#xdf13a280 #x74b55bd2 #x682199c0 #xd421e5ec #x53fb3ce8 #xc8adedb3 #x28a87fc9 #x3d959981
#x5c1ff900 #xfe38d399 #x0c4eff0b #x062407ea #xaa2f4fb1 #x4fb96976 #x90c79505 #xb0a8a774
#xef55a1ff #xe59ca2c2 #xa6b62d27 #xe66a4263 #xdf65001f #x0ec50966 #xdfdd55bc #x29de0655
#x911e739a #x17af8975 #x32c7911c #x89f89468 #x0d01e980 #x524755f4 #x03b63cc9 #x0cc844b2
#xbcf3f0aa #x87ac36e9 #xe53a7426 #x01b3d82b #x1a9e7449 #x64ee2d7e #xcddbb1da #x01c94910
#xb868bf80 #x0d26f3fd #x9342ede7 #x04a5c284 #x636737b6 #x50f5b616 #xf24766e3 #x8eca36c1
#x136e05db #xfef18391 #xfb887a37 #xd6e7f7d4 #xc7fb7dc9 #x3063fcdf #xb6f589de #xec2941da
#x26e46695 #xb7566419 #xf654efc5 #xd08d58b7 #x48925401 #xc1bacb7f #xe5ff550f #xb6083049
#x5bb5d0e8 #x87d72e5a #xab6a6ee1 #x223a66ce #xc62bf3cd #x9e0885f9 #x68cb3e47 #x086c010f
#xa21de820 #xd18b69de #xf3f65777 #xfa02c3f6 #x407edac3 #xcbb3d550 #x1793084d #xb0d70eba
#x0ab378d5 #xd951fb0c #xded7da56 #x4124bbe4 #x94ca0b56 #x0f5755d1 #xe0e1e56e #x6184b5be
#x580a249f #x94f74bc0 #xe327888e #x9f7b5561 #xc3dc0280 #x05687715 #x646c6bd7 #x44904db3
#x66b4f0a3 #xc0f1648a #x697ed5af #x49e92ff6 #x309e374f #x2cb6356a #x85808573 #x4991f840
#x76f0ae02 #x083be84d #x28421c9a #x44489406 #x736e4cb8 #xc1092910 #x8bc95fc6 #x7d869cf4
#x134f616f #x2e77118d #xb31b2be1 #xaa90b472 #x3ca5d717 #x7d161bba #x9cad9010 #xaf462ba2
#x9fe459d2 #x45d34559 #xd9f2da13 #xdbc65487 #xf3e4f94e #x176d486f #x097c13ea #x631da5c7
#x445f7382 #x175683f4 #xcdc66a97 #x70be0288 #xb3cdcf72 #x6e5dd2f3 #x20936079 #x459b80a5
#xbe60e2db #xa9c23101 #xeba5315c #x224e42f2 #x1c5c1572 #xf6721b2c #x1ad2fff3 #x8c25404e
#x324ed72f #x4067b7fd #x0523138e #x5ca3bc78 #xdc0fd66e #x75922283 #x784d6b17 #x58ebb16e
#x44094f85 #x3f481d87 #xfcfeae7b #x77b5ff76 #x8c2302bf #xaaf47556 #x5f46b02a #x2b092801
#x3d38f5f7 #x0ca81f36 #x52af4a8a #x66d5e7c0 #xdf3b0874 #x95055110 #x1b5ad7a8 #xf61ed5ad
#x6cf6e479 #x20758184 #xd0cefa65 #x88f7be58 #x4a046826 #x0ff6f8f3 #xa09c7f70 #x5346aba0
#x5ce96c28 #xe176eda3 #x6bac307f #x376829d2 #x85360fa9 #x17e3fe2a #x24b79767 #xf5a96b20
#xd6cd2595 #x68ff1ebf #x7555442c #xf19f06be #xf9e0659a #xeeb9491d #x34010718 #xbb30cab8
#xe822fe15 #x88570983 #x750e6249 #xda627e55 #x5e76ffa8 #xb1534546 #x6d47de08 #xefe9e7d4))
(defconst +cast5-sbox5+
#32@(#xf6fa8f9d #x2cac6ce1 #x4ca34867 #xe2337f7c #x95db08e7 #x016843b4 #xeced5cbc #x325553ac
#xbf9f0960 #xdfa1e2ed #x83f0579d #x63ed86b9 #x1ab6a6b8 #xde5ebe39 #xf38ff732 #x8989b138
#x33f14961 #xc01937bd #xf506c6da #xe4625e7e #xa308ea99 #x4e23e33c #x79cbd7cc #x48a14367
#xa3149619 #xfec94bd5 #xa114174a #xeaa01866 #xa084db2d #x09a8486f #xa888614a #x2900af98
#x01665991 #xe1992863 #xc8f30c60 #x2e78ef3c #xd0d51932 #xcf0fec14 #xf7ca07d2 #xd0a82072
#xfd41197e #x9305a6b0 #xe86be3da #x74bed3cd #x372da53c #x4c7f4448 #xdab5d440 #x6dba0ec3
#x083919a7 #x9fbaeed9 #x49dbcfb0 #x4e670c53 #x5c3d9c01 #x64bdb941 #x2c0e636a #xba7dd9cd
#xea6f7388 #xe70bc762 #x35f29adb #x5c4cdd8d #xf0d48d8c #xb88153e2 #x08a19866 #x1ae2eac8
#x284caf89 #xaa928223 #x9334be53 #x3b3a21bf #x16434be3 #x9aea3906 #xefe8c36e #xf890cdd9
#x80226dae #xc340a4a3 #xdf7e9c09 #xa694a807 #x5b7c5ecc #x221db3a6 #x9a69a02f #x68818a54
#xceb2296f #x53c0843a #xfe893655 #x25bfe68a #xb4628abc #xcf222ebf #x25ac6f48 #xa9a99387
#x53bddb65 #xe76ffbe7 #xe967fd78 #x0ba93563 #x8e342bc1 #xe8a11be9 #x4980740d #xc8087dfc
#x8de4bf99 #xa11101a0 #x7fd37975 #xda5a26c0 #xe81f994f #x9528cd89 #xfd339fed #xb87834bf
#x5f04456d #x22258698 #xc9c4c83b #x2dc156be #x4f628daa #x57f55ec5 #xe2220abe #xd2916ebf
#x4ec75b95 #x24f2c3c0 #x42d15d99 #xcd0d7fa0 #x7b6e27ff #xa8dc8af0 #x7345c106 #xf41e232f
#x35162386 #xe6ea8926 #x3333b094 #x157ec6f2 #x372b74af #x692573e4 #xe9a9d848 #xf3160289
#x3a62ef1d #xa787e238 #xf3a5f676 #x74364853 #x20951063 #x4576698d #xb6fad407 #x592af950
#x36f73523 #x4cfb6e87 #x7da4cec0 #x6c152daa #xcb0396a8 #xc50dfe5d #xfcd707ab #x0921c42f
#x89dff0bb #x5fe2be78 #x448f4f33 #x754613c9 #x2b05d08d #x48b9d585 #xdc049441 #xc8098f9b
#x7dede786 #xc39a3373 #x42410005 #x6a091751 #x0ef3c8a6 #x890072d6 #x28207682 #xa9a9f7be
#xbf32679d #xd45b5b75 #xb353fd00 #xcbb0e358 #x830f220a #x1f8fb214 #xd372cf08 #xcc3c4a13
#x8cf63166 #x061c87be #x88c98f88 #x6062e397 #x47cf8e7a #xb6c85283 #x3cc2acfb #x3fc06976
#x4e8f0252 #x64d8314d #xda3870e3 #x1e665459 #xc10908f0 #x513021a5 #x6c5b68b7 #x822f8aa0
#x3007cd3e #x74719eef #xdc872681 #x073340d4 #x7e432fd9 #x0c5ec241 #x8809286c #xf592d891
#x08a930f6 #x957ef305 #xb7fbffbd #xc266e96f #x6fe4ac98 #xb173ecc0 #xbc60b42a #x953498da
#xfba1ae12 #x2d4bd736 #x0f25faab #xa4f3fceb #xe2969123 #x257f0c3d #x9348af49 #x361400bc
#xe8816f4a #x3814f200 #xa3f94043 #x9c7a54c2 #xbc704f57 #xda41e7f9 #xc25ad33a #x54f4a084
#xb17f5505 #x59357cbe #xedbd15c8 #x7f97c5ab #xba5ac7b5 #xb6f6deaf #x3a479c3a #x5302da25
#x653d7e6a #x54268d49 #x51a477ea #x5017d55b #xd7d25d88 #x44136c76 #x0404a8c8 #xb8e5a121
#xb81a928a #x60ed5869 #x97c55b96 #xeaec991b #x29935913 #x01fdb7f1 #x088e8dfa #x9ab6f6f5
#x3b4cbf9f #x4a5de3ab #xe6051d35 #xa0e1d855 #xd36b4cf1 #xf544edeb #xb0e93524 #xbebb8fbd
#xa2d762cf #x49c92f54 #x38b5f331 #x7128a454 #x48392905 #xa65b1db8 #x851c97bd #xd675cf2f))
(defconst +cast5-sbox6+
#32@(#x85e04019 #x332bf567 #x662dbfff #xcfc65693 #x2a8d7f6f #xab9bc912 #xde6008a1 #x2028da1f
#x0227bce7 #x4d642916 #x18fac300 #x50f18b82 #x2cb2cb11 #xb232e75c #x4b3695f2 #xb28707de
#xa05fbcf6 #xcd4181e9 #xe150210c #xe24ef1bd #xb168c381 #xfde4e789 #x5c79b0d8 #x1e8bfd43
#x4d495001 #x38be4341 #x913cee1d #x92a79c3f #x089766be #xbaeeadf4 #x1286becf #xb6eacb19
#x2660c200 #x7565bde4 #x64241f7a #x8248dca9 #xc3b3ad66 #x28136086 #x0bd8dfa8 #x356d1cf2
#x107789be #xb3b2e9ce #x0502aa8f #x0bc0351e #x166bf52a #xeb12ff82 #xe3486911 #xd34d7516
#x4e7b3aff #x5f43671b #x9cf6e037 #x4981ac83 #x334266ce #x8c9341b7 #xd0d854c0 #xcb3a6c88
#x47bc2829 #x4725ba37 #xa66ad22b #x7ad61f1e #x0c5cbafa #x4437f107 #xb6e79962 #x42d2d816
#x0a961288 #xe1a5c06e #x13749e67 #x72fc081a #xb1d139f7 #xf9583745 #xcf19df58 #xbec3f756
#xc06eba30 #x07211b24 #x45c28829 #xc95e317f #xbc8ec511 #x38bc46e9 #xc6e6fa14 #xbae8584a
#xad4ebc46 #x468f508b #x7829435f #xf124183b #x821dba9f #xaff60ff4 #xea2c4e6d #x16e39264
#x92544a8b #x009b4fc3 #xaba68ced #x9ac96f78 #x06a5b79a #xb2856e6e #x1aec3ca9 #xbe838688
#x0e0804e9 #x55f1be56 #xe7e5363b #xb3a1f25d #xf7debb85 #x61fe033c #x16746233 #x3c034c28
#xda6d0c74 #x79aac56c #x3ce4e1ad #x51f0c802 #x98f8f35a #x1626a49f #xeed82b29 #x1d382fe3
#x0c4fb99a #xbb325778 #x3ec6d97b #x6e77a6a9 #xcb658b5c #xd45230c7 #x2bd1408b #x60c03eb7
#xb9068d78 #xa33754f4 #xf430c87d #xc8a71302 #xb96d8c32 #xebd4e7be #xbe8b9d2d #x7979fb06
#xe7225308 #x8b75cf77 #x11ef8da4 #xe083c858 #x8d6b786f #x5a6317a6 #xfa5cf7a0 #x5dda0033
#xf28ebfb0 #xf5b9c310 #xa0eac280 #x08b9767a #xa3d9d2b0 #x79d34217 #x021a718d #x9ac6336a
#x2711fd60 #x438050e3 #x069908a8 #x3d7fedc4 #x826d2bef #x4eeb8476 #x488dcf25 #x36c9d566
#x28e74e41 #xc2610aca #x3d49a9cf #xbae3b9df #xb65f8de6 #x92aeaf64 #x3ac7d5e6 #x9ea80509
#xf22b017d #xa4173f70 #xdd1e16c3 #x15e0d7f9 #x50b1b887 #x2b9f4fd5 #x625aba82 #x6a017962
#x2ec01b9c #x15488aa9 #xd716e740 #x40055a2c #x93d29a22 #xe32dbf9a #x058745b9 #x3453dc1e
#xd699296e #x496cff6f #x1c9f4986 #xdfe2ed07 #xb87242d1 #x19de7eae #x053e561a #x15ad6f8c
#x66626c1c #x7154c24c #xea082b2a #x93eb2939 #x17dcb0f0 #x58d4f2ae #x9ea294fb #x52cf564c
#x9883fe66 #x2ec40581 #x763953c3 #x01d6692e #xd3a0c108 #xa1e7160e #xe4f2dfa6 #x693ed285
#x74904698 #x4c2b0edd #x4f757656 #x5d393378 #xa132234f #x3d321c5d #xc3f5e194 #x4b269301
#xc79f022f #x3c997e7e #x5e4f9504 #x3ffafbbd #x76f7ad0e #x296693f4 #x3d1fce6f #xc61e45be
#xd3b5ab34 #xf72bf9b7 #x1b0434c0 #x4e72b567 #x5592a33d #xb5229301 #xcfd2a87f #x60aeb767
#x1814386b #x30bcc33d #x38a0c07d #xfd1606f2 #xc363519b #x589dd390 #x5479f8e6 #x1cb8d647
#x97fd61a9 #xea7759f4 #x2d57539d #x569a58cf #xe84e63ad #x462e1b78 #x6580f87e #xf3817914
#x91da55f4 #x40a230f3 #xd1988f35 #xb6e318d2 #x3ffa50bc #x3d40f021 #xc3c0bdae #x4958c24c
#x518f36b2 #x84b1d370 #x0fedce83 #x878ddada #xf2a279c7 #x94e01be8 #x90716f4b #x954b8aa3))
(defconst +cast5-sbox7+
#32@(#xe216300d #xbbddfffc #xa7ebdabd #x35648095 #x7789f8b7 #xe6c1121b #x0e241600 #x052ce8b5
#x11a9cfb0 #xe5952f11 #xece7990a #x9386d174 #x2a42931c #x76e38111 #xb12def3a #x37ddddfc
#xde9adeb1 #x0a0cc32c #xbe197029 #x84a00940 #xbb243a0f #xb4d137cf #xb44e79f0 #x049eedfd
#x0b15a15d #x480d3168 #x8bbbde5a #x669ded42 #xc7ece831 #x3f8f95e7 #x72df191b #x7580330d
#x94074251 #x5c7dcdfa #xabbe6d63 #xaa402164 #xb301d40a #x02e7d1ca #x53571dae #x7a3182a2
#x12a8ddec #xfdaa335d #x176f43e8 #x71fb46d4 #x38129022 #xce949ad4 #xb84769ad #x965bd862
#x82f3d055 #x66fb9767 #x15b80b4e #x1d5b47a0 #x4cfde06f #xc28ec4b8 #x57e8726e #x647a78fc
#x99865d44 #x608bd593 #x6c200e03 #x39dc5ff6 #x5d0b00a3 #xae63aff2 #x7e8bd632 #x70108c0c
#xbbd35049 #x2998df04 #x980cf42a #x9b6df491 #x9e7edd53 #x06918548 #x58cb7e07 #x3b74ef2e
#x522fffb1 #xd24708cc #x1c7e27cd #xa4eb215b #x3cf1d2e2 #x19b47a38 #x424f7618 #x35856039
#x9d17dee7 #x27eb35e6 #xc9aff67b #x36baf5b8 #x09c467cd #xc18910b1 #xe11dbf7b #x06cd1af8
#x7170c608 #x2d5e3354 #xd4de495a #x64c6d006 #xbcc0c62c #x3dd00db3 #x708f8f34 #x77d51b42
#x264f620f #x24b8d2bf #x15c1b79e #x46a52564 #xf8d7e54e #x3e378160 #x7895cda5 #x859c15a5
#xe6459788 #xc37bc75f #xdb07ba0c #x0676a3ab #x7f229b1e #x31842e7b #x24259fd7 #xf8bef472
#x835ffcb8 #x6df4c1f2 #x96f5b195 #xfd0af0fc #xb0fe134c #xe2506d3d #x4f9b12ea #xf215f225
#xa223736f #x9fb4c428 #x25d04979 #x34c713f8 #xc4618187 #xea7a6e98 #x7cd16efc #x1436876c
#xf1544107 #xbedeee14 #x56e9af27 #xa04aa441 #x3cf7c899 #x92ecbae6 #xdd67016d #x151682eb
#xa842eedf #xfdba60b4 #xf1907b75 #x20e3030f #x24d8c29e #xe139673b #xefa63fb8 #x71873054
#xb6f2cf3b #x9f326442 #xcb15a4cc #xb01a4504 #xf1e47d8d #x844a1be5 #xbae7dfdc #x42cbda70
#xcd7dae0a #x57e85b7a #xd53f5af6 #x20cf4d8c #xcea4d428 #x79d130a4 #x3486ebfb #x33d3cddc
#x77853b53 #x37effcb5 #xc5068778 #xe580b3e6 #x4e68b8f4 #xc5c8b37e #x0d809ea2 #x398feb7c
#x132a4f94 #x43b7950e #x2fee7d1c #x223613bd #xdd06caa2 #x37df932b #xc4248289 #xacf3ebc3
#x5715f6b7 #xef3478dd #xf267616f #xc148cbe4 #x9052815e #x5e410fab #xb48a2465 #x2eda7fa4
#xe87b40e4 #xe98ea084 #x5889e9e1 #xefd390fc #xdd07d35b #xdb485694 #x38d7e5b2 #x57720101
#x730edebc #x5b643113 #x94917e4f #x503c2fba #x646f1282 #x7523d24a #xe0779695 #xf9c17a8f
#x7a5b2121 #xd187b896 #x29263a4d #xba510cdf #x81f47c9f #xad1163ed #xea7b5965 #x1a00726e
#x11403092 #x00da6d77 #x4a0cdd61 #xad1f4603 #x605bdfb0 #x9eedc364 #x22ebe6a8 #xcee7d28a
#xa0e736a0 #x5564a6b9 #x10853209 #xc7eb8f37 #x2de705ca #x8951570f #xdf09822b #xbd691a6c
#xaa12e4f2 #x87451c0f #xe0f6a27a #x3ada4819 #x4cf1764f #x0d771c2b #x67cdb156 #x350d8384
#x5938fa0f #x42399ef3 #x36997b07 #x0e84093d #x4aa93e61 #x8360d87b #x1fa98b0c #x1149382c
#xe97625a5 #x0614d1b7 #x0e25244b #x0c768347 #x589e8d82 #x0d2059d1 #xa466bb1e #xf8da0a82
#x04f19130 #xba6e4ec0 #x99265164 #x1ee7230d #x50b2ad80 #xeaee6801 #x8db2a283 #xea8bf59e))
the actual CAST5 implementation
(deftype cast5-mask-vector () '(simple-array (unsigned-byte 32) (16)))
(deftype cast5-rotate-vector () '(simple-array (unsigned-byte 8) (16)))
(defclass cast5 (cipher 8-byte-block-mixin)
((mask-vector :accessor mask-vector :type cast5-mask-vector)
(rotate-vector :accessor rotate-vector :type cast5-rotate-vector)
(n-rounds :accessor n-rounds)))
(declaim (inline cast5-f1 cast5-f2 cast5-f3))
(macrolet ((cast5-s-box (s-box-index index)
`(aref ,(intern (format nil "+~A~A+" '#:cast5-sbox s-box-index))
,index)))
(defun cast5-f1 (input mask rotate)
(declare (type (unsigned-byte 32) input mask))
(declare (type (unsigned-byte 5) rotate))
(let ((value (rol32 (mod32+ input mask) rotate)))
(declare (type (unsigned-byte 32) value))
(mod32+ (cast5-s-box 3 (first-byte value))
(mod32- (logxor (cast5-s-box 1 (third-byte value))
(cast5-s-box 0 (fourth-byte value)))
(cast5-s-box 2 (second-byte value))))))
(defun cast5-f2 (input mask rotate)
(declare (type (unsigned-byte 32) input mask))
(declare (type (unsigned-byte 5) rotate))
(let ((value (rol32 (logxor input mask) rotate)))
(declare (type (unsigned-byte 32) value))
(logxor (cast5-s-box 3 (first-byte value))
(mod32+ (cast5-s-box 2 (second-byte value))
(mod32- (cast5-s-box 0 (fourth-byte value))
(cast5-s-box 1 (third-byte value)))))))
(defun cast5-f3 (input mask rotate)
(declare (type (unsigned-byte 32) input mask))
(declare (type (unsigned-byte 5) rotate))
(let ((value (rol32 (mod32- mask input) rotate)))
(declare (type (unsigned-byte 32) value))
(mod32- (logxor (cast5-s-box 2 (second-byte value))
(mod32+ (cast5-s-box 1 (third-byte value))
(cast5-s-box 0 (fourth-byte value))))
(cast5-s-box 3 (first-byte value)))))
(define-block-encryptor cast5 8
(let ((mask-vector (mask-vector context))
(rotate-vector (rotate-vector context))
(n-rounds (n-rounds context)))
(declare (type cast5-mask-vector mask-vector))
(declare (type cast5-rotate-vector rotate-vector))
(declare (type (or (integer 12 12) (integer 16 16)) n-rounds))
(with-words ((l0 r0) plaintext plaintext-start)
#.(loop for i from 0 below 16
for round-function = (ecase i
((0 3 6 9 12 15) 'cast5-f1)
((1 4 7 10 13) 'cast5-f2)
((2 5 8 11 14) 'cast5-f3))
collect `(let ((x (logxor l0 (,round-function r0
(aref mask-vector ,i)
(aref rotate-vector ,i)))))
(declare (type (unsigned-byte 32) x))
(setf l0 r0 r0 x)) into forms
finally (return `(progn ,@(subseq forms 0 12)
(when (= n-rounds 16)
,@(subseq forms 12)))))
(store-words ciphertext ciphertext-start r0 l0))))
(define-block-decryptor cast5 8
(let ((mask-vector (mask-vector context))
(rotate-vector (rotate-vector context))
(n-rounds (n-rounds context)))
(declare (type cast5-mask-vector mask-vector))
(declare (type cast5-rotate-vector rotate-vector))
(declare (type (or (integer 12 12) (integer 16 16)) n-rounds))
(with-words ((l0 r0) ciphertext ciphertext-start)
#.(loop for i from 15 downto 0
for round-function = (ecase i
((0 3 6 9 12 15) 'cast5-f1)
((1 4 7 10 13) 'cast5-f2)
((2 5 8 11 14) 'cast5-f3))
collect `(let ((x (logxor l0 (,round-function r0
(aref mask-vector ,i)
(aref rotate-vector ,i)))))
(declare (type (unsigned-byte 32) x))
(setf l0 r0 r0 x)) into forms
finally (return `(progn (when (= n-rounds 16)
,@(subseq forms 0 4))
,@(subseq forms 4))))
(store-words plaintext plaintext-start r0 l0))))
MACROLET
(defun generate-cast5-key-schedule (key)
(declare (type (simple-array (unsigned-byte 8) (16)) key))
(with-words ((x0 x4 x8 xc) key 0)
(let* ((mask-vector (make-array 16 :element-type '(unsigned-byte 32)))
(rotate-vector (make-array 16 :element-type '(unsigned-byte 8)))
(z0 0)
(z4 0)
(z8 0)
(zc 0))
(declare (type (unsigned-byte 32) z0 z4 z8 zc))
;;; generate mask material
(setf z0 (logxor x0 (aref +cast5-sbox4+ (third-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (second-byte xc)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf z4 (logxor x8 (aref +cast5-sbox4+ (fourth-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte x8))))
(setf z8 (logxor xc (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox4+ (third-byte x8))))
(setf zc (logxor x4 (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z8)) (aref +cast5-sbox7+ (fourth-byte z8)) (aref +cast5-sbox5+ (first-byte x8))))
(setf (aref mask-vector (- 1 1)) (logxor (aref +cast5-sbox4+ (fourth-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox4+ (second-byte z0))))
(setf (aref mask-vector (- 2 1)) (logxor (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (first-byte z8)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox5+ (second-byte z4))))
(setf (aref mask-vector (- 3 1)) (logxor (aref +cast5-sbox4+ (fourth-byte zc)) (aref +cast5-sbox5+ (third-byte zc)) (aref +cast5-sbox6+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z8))))
(setf (aref mask-vector (- 4 1)) (logxor (aref +cast5-sbox4+ (second-byte zc)) (aref +cast5-sbox5+ (first-byte zc)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (fourth-byte z0)) (aref +cast5-sbox7+ (fourth-byte zc))))
(setf x0 (logxor z8 (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (first-byte z4)) (aref +cast5-sbox6+ (fourth-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z0))))
(setf x4 (logxor z0 (aref +cast5-sbox4+ (fourth-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte z0))))
(setf x8 (logxor z4 (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox4+ (third-byte z0))))
(setf xc (logxor zc (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x8)) (aref +cast5-sbox7+ (fourth-byte x8)) (aref +cast5-sbox5+ (first-byte z0))))
(setf (aref mask-vector (- 5 1)) (logxor (aref +cast5-sbox4+ (first-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (third-byte xc)) (aref +cast5-sbox4+ (fourth-byte x8))))
(setf (aref mask-vector (- 6 1)) (logxor (aref +cast5-sbox4+ (third-byte x0)) (aref +cast5-sbox5+ (fourth-byte x0)) (aref +cast5-sbox6+ (second-byte xc)) (aref +cast5-sbox7+ (first-byte xc)) (aref +cast5-sbox5+ (third-byte xc))))
(setf (aref mask-vector (- 7 1)) (logxor (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (fourth-byte x8)) (aref +cast5-sbox7+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x0))))
(setf (aref mask-vector (- 8 1)) (logxor (aref +cast5-sbox4+ (third-byte x4)) (aref +cast5-sbox5+ (fourth-byte x4)) (aref +cast5-sbox6+ (second-byte x8)) (aref +cast5-sbox7+ (first-byte x8)) (aref +cast5-sbox7+ (first-byte x4))))
(setf z0 (logxor x0 (aref +cast5-sbox4+ (third-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (second-byte xc)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf z4 (logxor x8 (aref +cast5-sbox4+ (fourth-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte x8))))
(setf z8 (logxor xc (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox4+ (third-byte x8))))
(setf zc (logxor x4 (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z8)) (aref +cast5-sbox7+ (fourth-byte z8)) (aref +cast5-sbox5+ (first-byte x8))))
(setf (aref mask-vector (- 9 1)) (logxor (aref +cast5-sbox4+ (first-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (fourth-byte zc)) (aref +cast5-sbox7+ (third-byte zc)) (aref +cast5-sbox4+ (third-byte z8))))
(setf (aref mask-vector (- 10 1)) (logxor (aref +cast5-sbox4+ (third-byte z0)) (aref +cast5-sbox5+ (fourth-byte z0)) (aref +cast5-sbox6+ (second-byte zc)) (aref +cast5-sbox7+ (first-byte zc)) (aref +cast5-sbox5+ (fourth-byte zc))))
(setf (aref mask-vector (- 11 1)) (logxor (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z8)) (aref +cast5-sbox7+ (third-byte z8)) (aref +cast5-sbox6+ (second-byte z0))))
(setf (aref mask-vector (- 12 1)) (logxor (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (fourth-byte z4)) (aref +cast5-sbox6+ (second-byte z8)) (aref +cast5-sbox7+ (first-byte z8)) (aref +cast5-sbox7+ (second-byte z4))))
(setf x0 (logxor z8 (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (first-byte z4)) (aref +cast5-sbox6+ (fourth-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z0))))
(setf x4 (logxor z0 (aref +cast5-sbox4+ (fourth-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte z0))))
(setf x8 (logxor z4 (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox4+ (third-byte z0))))
(setf xc (logxor zc (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x8)) (aref +cast5-sbox7+ (fourth-byte x8)) (aref +cast5-sbox5+ (first-byte z0))))
(setf (aref mask-vector (- 13 1)) (logxor (aref +cast5-sbox4+ (fourth-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x4)) (aref +cast5-sbox7+ (second-byte x4)) (aref +cast5-sbox4+ (first-byte x0))))
(setf (aref mask-vector (- 14 1)) (logxor (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (first-byte x8)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox5+ (first-byte x4))))
(setf (aref mask-vector (- 15 1)) (logxor (aref +cast5-sbox4+ (fourth-byte xc)) (aref +cast5-sbox5+ (third-byte xc)) (aref +cast5-sbox6+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte x0)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf (aref mask-vector (- 16 1)) (logxor (aref +cast5-sbox4+ (second-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (fourth-byte x0)) (aref +cast5-sbox7+ (third-byte xc))))
;;; generate shift amounts
(setf z0 (logxor x0 (aref +cast5-sbox4+ (third-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (second-byte xc)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf z4 (logxor x8 (aref +cast5-sbox4+ (fourth-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte x8))))
(setf z8 (logxor xc (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox4+ (third-byte x8))))
(setf zc (logxor x4 (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z8)) (aref +cast5-sbox7+ (fourth-byte z8)) (aref +cast5-sbox5+ (first-byte x8))))
(setf (aref rotate-vector (- 17 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (fourth-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox4+ (second-byte z0)))))
(setf (aref rotate-vector (- 18 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (first-byte z8)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox5+ (second-byte z4)))))
(setf (aref rotate-vector (- 19 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (fourth-byte zc)) (aref +cast5-sbox5+ (third-byte zc)) (aref +cast5-sbox6+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z8)))))
(setf (aref rotate-vector (- 20 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (second-byte zc)) (aref +cast5-sbox5+ (first-byte zc)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (fourth-byte z0)) (aref +cast5-sbox7+ (fourth-byte zc)))))
(setf x0 (logxor z8 (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (first-byte z4)) (aref +cast5-sbox6+ (fourth-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z0))))
(setf x4 (logxor z0 (aref +cast5-sbox4+ (fourth-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte z0))))
(setf x8 (logxor z4 (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox4+ (third-byte z0))))
(setf xc (logxor zc (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x8)) (aref +cast5-sbox7+ (fourth-byte x8)) (aref +cast5-sbox5+ (first-byte z0))))
(setf (aref rotate-vector (- 21 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (first-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (third-byte xc)) (aref +cast5-sbox4+ (fourth-byte x8)))))
(setf (aref rotate-vector (- 22 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (third-byte x0)) (aref +cast5-sbox5+ (fourth-byte x0)) (aref +cast5-sbox6+ (second-byte xc)) (aref +cast5-sbox7+ (first-byte xc)) (aref +cast5-sbox5+ (third-byte xc)))))
(setf (aref rotate-vector (- 23 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (fourth-byte x8)) (aref +cast5-sbox7+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x0)))))
(setf (aref rotate-vector (- 24 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (third-byte x4)) (aref +cast5-sbox5+ (fourth-byte x4)) (aref +cast5-sbox6+ (second-byte x8)) (aref +cast5-sbox7+ (first-byte x8)) (aref +cast5-sbox7+ (first-byte x4)))))
(setf z0 (logxor x0 (aref +cast5-sbox4+ (third-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (second-byte xc)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf z4 (logxor x8 (aref +cast5-sbox4+ (fourth-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte x8))))
(setf z8 (logxor xc (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox4+ (third-byte x8))))
(setf zc (logxor x4 (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z8)) (aref +cast5-sbox7+ (fourth-byte z8)) (aref +cast5-sbox5+ (first-byte x8))))
(setf (aref rotate-vector (- 25 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (first-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (fourth-byte zc)) (aref +cast5-sbox7+ (third-byte zc)) (aref +cast5-sbox4+ (third-byte z8)))))
(setf (aref rotate-vector (- 26 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (third-byte z0)) (aref +cast5-sbox5+ (fourth-byte z0)) (aref +cast5-sbox6+ (second-byte zc)) (aref +cast5-sbox7+ (first-byte zc)) (aref +cast5-sbox5+ (fourth-byte zc)))))
(setf (aref rotate-vector (- 27 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z8)) (aref +cast5-sbox7+ (third-byte z8)) (aref +cast5-sbox6+ (second-byte z0)))))
(setf (aref rotate-vector (- 28 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (fourth-byte z4)) (aref +cast5-sbox6+ (second-byte z8)) (aref +cast5-sbox7+ (first-byte z8)) (aref +cast5-sbox7+ (second-byte z4)))))
(setf x0 (logxor z8 (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (first-byte z4)) (aref +cast5-sbox6+ (fourth-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z0))))
(setf x4 (logxor z0 (aref +cast5-sbox4+ (fourth-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte z0))))
(setf x8 (logxor z4 (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox4+ (third-byte z0))))
(setf xc (logxor zc (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x8)) (aref +cast5-sbox7+ (fourth-byte x8)) (aref +cast5-sbox5+ (first-byte z0))))
(setf (aref rotate-vector (- 29 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (fourth-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x4)) (aref +cast5-sbox7+ (second-byte x4)) (aref +cast5-sbox4+ (first-byte x0)))))
(setf (aref rotate-vector (- 30 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (first-byte x8)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox5+ (first-byte x4)))))
(setf (aref rotate-vector (- 31 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (fourth-byte xc)) (aref +cast5-sbox5+ (third-byte xc)) (aref +cast5-sbox6+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte x0)) (aref +cast5-sbox6+ (fourth-byte x8)))))
(setf (aref rotate-vector (- 32 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (second-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (fourth-byte x0)) (aref +cast5-sbox7+ (third-byte xc)))))
(values mask-vector rotate-vector))))
(defmethod schedule-key ((cipher cast5) key)
(declare (type (simple-array (unsigned-byte 8) (*)) key))
(let ((length (length key))
(key (if (= (length key) 16)
;; no padding necessary
key
(let ((tmp (make-array 16 :element-type '(unsigned-byte 8)
:initial-element 0)))
(replace tmp key)))))
(declare (type (simple-array (unsigned-byte 8) (16)) key))
(multiple-value-bind (mask-vector rotate-vector)
(generate-cast5-key-schedule key)
(let ((n-rounds (if (<= length 10)
12
16)))
(setf (mask-vector cipher) mask-vector
(rotate-vector cipher) rotate-vector
(n-rounds cipher) n-rounds)
cipher))))
(defcipher cast5
(:encrypt-function cast5-encrypt-block)
(:decrypt-function cast5-decrypt-block)
(:block-length 8)
(:key-length (:variable 5 16 1)))
| null | https://raw.githubusercontent.com/eugeneia/athens/cc9d456edd3891b764b0fbf0202a3e2f58865cbf/quicklisp/dists/quicklisp/software/ironclad-v0.40/src/ciphers/cast5.lisp | lisp | -*- mode: lisp; indent-tabs-mode: nil -*-
s-boxes
generate mask material
generate shift amounts
no padding necessary | cast5.lisp -- implementation of rfc2144 CAST5 algorithm
(in-package :crypto)
(declaim (type (simple-array (unsigned-byte 32) (256))
+cast5-sbox0+ +cast5-sbox1+ +cast5-sbox2+ +cast5-sbox3+
+cast5-sbox4+ +cast5-sbox5+ +cast5-sbox6+ +cast5-sbox7+))
(defconst +cast5-sbox0+
#32@(#x30fb40d4 #x9fa0ff0b #x6beccd2f #x3f258c7a #x1e213f2f #x9c004dd3 #x6003e540 #xcf9fc949
#xbfd4af27 #x88bbbdb5 #xe2034090 #x98d09675 #x6e63a0e0 #x15c361d2 #xc2e7661d #x22d4ff8e
#x28683b6f #xc07fd059 #xff2379c8 #x775f50e2 #x43c340d3 #xdf2f8656 #x887ca41a #xa2d2bd2d
#xa1c9e0d6 #x346c4819 #x61b76d87 #x22540f2f #x2abe32e1 #xaa54166b #x22568e3a #xa2d341d0
#x66db40c8 #xa784392f #x004dff2f #x2db9d2de #x97943fac #x4a97c1d8 #x527644b7 #xb5f437a7
#xb82cbaef #xd751d159 #x6ff7f0ed #x5a097a1f #x827b68d0 #x90ecf52e #x22b0c054 #xbc8e5935
#x4b6d2f7f #x50bb64a2 #xd2664910 #xbee5812d #xb7332290 #xe93b159f #xb48ee411 #x4bff345d
#xfd45c240 #xad31973f #xc4f6d02e #x55fc8165 #xd5b1caad #xa1ac2dae #xa2d4b76d #xc19b0c50
#x882240f2 #x0c6e4f38 #xa4e4bfd7 #x4f5ba272 #x564c1d2f #xc59c5319 #xb949e354 #xb04669fe
#xb1b6ab8a #xc71358dd #x6385c545 #x110f935d #x57538ad5 #x6a390493 #xe63d37e0 #x2a54f6b3
#x3a787d5f #x6276a0b5 #x19a6fcdf #x7a42206a #x29f9d4d5 #xf61b1891 #xbb72275e #xaa508167
#x38901091 #xc6b505eb #x84c7cb8c #x2ad75a0f #x874a1427 #xa2d1936b #x2ad286af #xaa56d291
#xd7894360 #x425c750d #x93b39e26 #x187184c9 #x6c00b32d #x73e2bb14 #xa0bebc3c #x54623779
#x64459eab #x3f328b82 #x7718cf82 #x59a2cea6 #x04ee002e #x89fe78e6 #x3fab0950 #x325ff6c2
#x81383f05 #x6963c5c8 #x76cb5ad6 #xd49974c9 #xca180dcf #x380782d5 #xc7fa5cf6 #x8ac31511
#x35e79e13 #x47da91d0 #xf40f9086 #xa7e2419e #x31366241 #x051ef495 #xaa573b04 #x4a805d8d
#x548300d0 #x00322a3c #xbf64cddf #xba57a68e #x75c6372b #x50afd341 #xa7c13275 #x915a0bf5
#x6b54bfab #x2b0b1426 #xab4cc9d7 #x449ccd82 #xf7fbf265 #xab85c5f3 #x1b55db94 #xaad4e324
#xcfa4bd3f #x2deaa3e2 #x9e204d02 #xc8bd25ac #xeadf55b3 #xd5bd9e98 #xe31231b2 #x2ad5ad6c
#x954329de #xadbe4528 #xd8710f69 #xaa51c90f #xaa786bf6 #x22513f1e #xaa51a79b #x2ad344cc
#x7b5a41f0 #xd37cfbad #x1b069505 #x41ece491 #xb4c332e6 #x032268d4 #xc9600acc #xce387e6d
#xbf6bb16c #x6a70fb78 #x0d03d9c9 #xd4df39de #xe01063da #x4736f464 #x5ad328d8 #xb347cc96
#x75bb0fc3 #x98511bfb #x4ffbcc35 #xb58bcf6a #xe11f0abc #xbfc5fe4a #xa70aec10 #xac39570a
#x3f04442f #x6188b153 #xe0397a2e #x5727cb79 #x9ceb418f #x1cacd68d #x2ad37c96 #x0175cb9d
#xc69dff09 #xc75b65f0 #xd9db40d8 #xec0e7779 #x4744ead4 #xb11c3274 #xdd24cb9e #x7e1c54bd
#xf01144f9 #xd2240eb1 #x9675b3fd #xa3ac3755 #xd47c27af #x51c85f4d #x56907596 #xa5bb15e6
#x580304f0 #xca042cf1 #x011a37ea #x8dbfaadb #x35ba3e4a #x3526ffa0 #xc37b4d09 #xbc306ed9
#x98a52666 #x5648f725 #xff5e569d #x0ced63d0 #x7c63b2cf #x700b45e1 #xd5ea50f1 #x85a92872
#xaf1fbda7 #xd4234870 #xa7870bf3 #x2d3b4d79 #x42e04198 #x0cd0ede7 #x26470db8 #xf881814c
#x474d6ad7 #x7c0c5e5c #xd1231959 #x381b7298 #xf5d2f4db #xab838653 #x6e2f1e23 #x83719c9e
#xbd91e046 #x9a56456e #xdc39200c #x20c8c571 #x962bda1c #xe1e696ff #xb141ab08 #x7cca89b9
#x1a69e783 #x02cc4843 #xa2f7c579 #x429ef47d #x427b169c #x5ac9f049 #xdd8f0f00 #x5c8165bf))
(defconst +cast5-sbox1+
#32@(#x1f201094 #xef0ba75b #x69e3cf7e #x393f4380 #xfe61cf7a #xeec5207a #x55889c94 #x72fc0651
#xada7ef79 #x4e1d7235 #xd55a63ce #xde0436ba #x99c430ef #x5f0c0794 #x18dcdb7d #xa1d6eff3
#xa0b52f7b #x59e83605 #xee15b094 #xe9ffd909 #xdc440086 #xef944459 #xba83ccb3 #xe0c3cdfb
#xd1da4181 #x3b092ab1 #xf997f1c1 #xa5e6cf7b #x01420ddb #xe4e7ef5b #x25a1ff41 #xe180f806
#x1fc41080 #x179bee7a #xd37ac6a9 #xfe5830a4 #x98de8b7f #x77e83f4e #x79929269 #x24fa9f7b
#xe113c85b #xacc40083 #xd7503525 #xf7ea615f #x62143154 #x0d554b63 #x5d681121 #xc866c359
#x3d63cf73 #xcee234c0 #xd4d87e87 #x5c672b21 #x071f6181 #x39f7627f #x361e3084 #xe4eb573b
#x602f64a4 #xd63acd9c #x1bbc4635 #x9e81032d #x2701f50c #x99847ab4 #xa0e3df79 #xba6cf38c
#x10843094 #x2537a95e #xf46f6ffe #xa1ff3b1f #x208cfb6a #x8f458c74 #xd9e0a227 #x4ec73a34
#xfc884f69 #x3e4de8df #xef0e0088 #x3559648d #x8a45388c #x1d804366 #x721d9bfd #xa58684bb
#xe8256333 #x844e8212 #x128d8098 #xfed33fb4 #xce280ae1 #x27e19ba5 #xd5a6c252 #xe49754bd
#xc5d655dd #xeb667064 #x77840b4d #xa1b6a801 #x84db26a9 #xe0b56714 #x21f043b7 #xe5d05860
#x54f03084 #x066ff472 #xa31aa153 #xdadc4755 #xb5625dbf #x68561be6 #x83ca6b94 #x2d6ed23b
#xeccf01db #xa6d3d0ba #xb6803d5c #xaf77a709 #x33b4a34c #x397bc8d6 #x5ee22b95 #x5f0e5304
#x81ed6f61 #x20e74364 #xb45e1378 #xde18639b #x881ca122 #xb96726d1 #x8049a7e8 #x22b7da7b
#x5e552d25 #x5272d237 #x79d2951c #xc60d894c #x488cb402 #x1ba4fe5b #xa4b09f6b #x1ca815cf
#xa20c3005 #x8871df63 #xb9de2fcb #x0cc6c9e9 #x0beeff53 #xe3214517 #xb4542835 #x9f63293c
#xee41e729 #x6e1d2d7c #x50045286 #x1e6685f3 #xf33401c6 #x30a22c95 #x31a70850 #x60930f13
#x73f98417 #xa1269859 #xec645c44 #x52c877a9 #xcdff33a6 #xa02b1741 #x7cbad9a2 #x2180036f
#x50d99c08 #xcb3f4861 #xc26bd765 #x64a3f6ab #x80342676 #x25a75e7b #xe4e6d1fc #x20c710e6
#xcdf0b680 #x17844d3b #x31eef84d #x7e0824e4 #x2ccb49eb #x846a3bae #x8ff77888 #xee5d60f6
#x7af75673 #x2fdd5cdb #xa11631c1 #x30f66f43 #xb3faec54 #x157fd7fa #xef8579cc #xd152de58
#xdb2ffd5e #x8f32ce19 #x306af97a #x02f03ef8 #x99319ad5 #xc242fa0f #xa7e3ebb0 #xc68e4906
#xb8da230c #x80823028 #xdcdef3c8 #xd35fb171 #x088a1bc8 #xbec0c560 #x61a3c9e8 #xbca8f54d
#xc72feffa #x22822e99 #x82c570b4 #xd8d94e89 #x8b1c34bc #x301e16e6 #x273be979 #xb0ffeaa6
#x61d9b8c6 #x00b24869 #xb7ffce3f #x08dc283b #x43daf65a #xf7e19798 #x7619b72f #x8f1c9ba4
#xdc8637a0 #x16a7d3b1 #x9fc393b7 #xa7136eeb #xc6bcc63e #x1a513742 #xef6828bc #x520365d6
#x2d6a77ab #x3527ed4b #x821fd216 #x095c6e2e #xdb92f2fb #x5eea29cb #x145892f5 #x91584f7f
#x5483697b #x2667a8cc #x85196048 #x8c4bacea #x833860d4 #x0d23e0f9 #x6c387e8a #x0ae6d249
#xb284600c #xd835731d #xdcb1c647 #xac4c56ea #x3ebd81b3 #x230eabb0 #x6438bc87 #xf0b5b1fa
#x8f5ea2b3 #xfc184642 #x0a036b7a #x4fb089bd #x649da589 #xa345415e #x5c038323 #x3e5d3bb9
#x43d79572 #x7e6dd07c #x06dfdf1e #x6c6cc4ef #x7160a539 #x73bfbe70 #x83877605 #x4523ecf1))
(defconst +cast5-sbox2+
#32@(#x8defc240 #x25fa5d9f #xeb903dbf #xe810c907 #x47607fff #x369fe44b #x8c1fc644 #xaececa90
#xbeb1f9bf #xeefbcaea #xe8cf1950 #x51df07ae #x920e8806 #xf0ad0548 #xe13c8d83 #x927010d5
#x11107d9f #x07647db9 #xb2e3e4d4 #x3d4f285e #xb9afa820 #xfade82e0 #xa067268b #x8272792e
#x553fb2c0 #x489ae22b #xd4ef9794 #x125e3fbc #x21fffcee #x825b1bfd #x9255c5ed #x1257a240
#x4e1a8302 #xbae07fff #x528246e7 #x8e57140e #x3373f7bf #x8c9f8188 #xa6fc4ee8 #xc982b5a5
#xa8c01db7 #x579fc264 #x67094f31 #xf2bd3f5f #x40fff7c1 #x1fb78dfc #x8e6bd2c1 #x437be59b
#x99b03dbf #xb5dbc64b #x638dc0e6 #x55819d99 #xa197c81c #x4a012d6e #xc5884a28 #xccc36f71
#xb843c213 #x6c0743f1 #x8309893c #x0feddd5f #x2f7fe850 #xd7c07f7e #x02507fbf #x5afb9a04
#xa747d2d0 #x1651192e #xaf70bf3e #x58c31380 #x5f98302e #x727cc3c4 #x0a0fb402 #x0f7fef82
#x8c96fdad #x5d2c2aae #x8ee99a49 #x50da88b8 #x8427f4a0 #x1eac5790 #x796fb449 #x8252dc15
#xefbd7d9b #xa672597d #xada840d8 #x45f54504 #xfa5d7403 #xe83ec305 #x4f91751a #x925669c2
#x23efe941 #xa903f12e #x60270df2 #x0276e4b6 #x94fd6574 #x927985b2 #x8276dbcb #x02778176
#xf8af918d #x4e48f79e #x8f616ddf #xe29d840e #x842f7d83 #x340ce5c8 #x96bbb682 #x93b4b148
#xef303cab #x984faf28 #x779faf9b #x92dc560d #x224d1e20 #x8437aa88 #x7d29dc96 #x2756d3dc
#x8b907cee #xb51fd240 #xe7c07ce3 #xe566b4a1 #xc3e9615e #x3cf8209d #x6094d1e3 #xcd9ca341
#x5c76460e #x00ea983b #xd4d67881 #xfd47572c #xf76cedd9 #xbda8229c #x127dadaa #x438a074e
#x1f97c090 #x081bdb8a #x93a07ebe #xb938ca15 #x97b03cff #x3dc2c0f8 #x8d1ab2ec #x64380e51
#x68cc7bfb #xd90f2788 #x12490181 #x5de5ffd4 #xdd7ef86a #x76a2e214 #xb9a40368 #x925d958f
#x4b39fffa #xba39aee9 #xa4ffd30b #xfaf7933b #x6d498623 #x193cbcfa #x27627545 #x825cf47a
#x61bd8ba0 #xd11e42d1 #xcead04f4 #x127ea392 #x10428db7 #x8272a972 #x9270c4a8 #x127de50b
#x285ba1c8 #x3c62f44f #x35c0eaa5 #xe805d231 #x428929fb #xb4fcdf82 #x4fb66a53 #x0e7dc15b
#x1f081fab #x108618ae #xfcfd086d #xf9ff2889 #x694bcc11 #x236a5cae #x12deca4d #x2c3f8cc5
#xd2d02dfe #xf8ef5896 #xe4cf52da #x95155b67 #x494a488c #xb9b6a80c #x5c8f82bc #x89d36b45
#x3a609437 #xec00c9a9 #x44715253 #x0a874b49 #xd773bc40 #x7c34671c #x02717ef6 #x4feb5536
#xa2d02fff #xd2bf60c4 #xd43f03c0 #x50b4ef6d #x07478cd1 #x006e1888 #xa2e53f55 #xb9e6d4bc
#xa2048016 #x97573833 #xd7207d67 #xde0f8f3d #x72f87b33 #xabcc4f33 #x7688c55d #x7b00a6b0
#x947b0001 #x570075d2 #xf9bb88f8 #x8942019e #x4264a5ff #x856302e0 #x72dbd92b #xee971b69
#x6ea22fde #x5f08ae2b #xaf7a616d #xe5c98767 #xcf1febd2 #x61efc8c2 #xf1ac2571 #xcc8239c2
#x67214cb8 #xb1e583d1 #xb7dc3e62 #x7f10bdce #xf90a5c38 #x0ff0443d #x606e6dc6 #x60543a49
#x5727c148 #x2be98a1d #x8ab41738 #x20e1be24 #xaf96da0f #x68458425 #x99833be5 #x600d457d
#x282f9350 #x8334b362 #xd91d1120 #x2b6d8da0 #x642b1e31 #x9c305a00 #x52bce688 #x1b03588a
#xf7baefd5 #x4142ed9c #xa4315c11 #x83323ec5 #xdfef4636 #xa133c501 #xe9d3531c #xee353783))
(defconst +cast5-sbox3+
#32@(#x9db30420 #x1fb6e9de #xa7be7bef #xd273a298 #x4a4f7bdb #x64ad8c57 #x85510443 #xfa020ed1
#x7e287aff #xe60fb663 #x095f35a1 #x79ebf120 #xfd059d43 #x6497b7b1 #xf3641f63 #x241e4adf
#x28147f5f #x4fa2b8cd #xc9430040 #x0cc32220 #xfdd30b30 #xc0a5374f #x1d2d00d9 #x24147b15
#xee4d111a #x0fca5167 #x71ff904c #x2d195ffe #x1a05645f #x0c13fefe #x081b08ca #x05170121
#x80530100 #xe83e5efe #xac9af4f8 #x7fe72701 #xd2b8ee5f #x06df4261 #xbb9e9b8a #x7293ea25
#xce84ffdf #xf5718801 #x3dd64b04 #xa26f263b #x7ed48400 #x547eebe6 #x446d4ca0 #x6cf3d6f5
#x2649abdf #xaea0c7f5 #x36338cc1 #x503f7e93 #xd3772061 #x11b638e1 #x72500e03 #xf80eb2bb
#xabe0502e #xec8d77de #x57971e81 #xe14f6746 #xc9335400 #x6920318f #x081dbb99 #xffc304a5
#x4d351805 #x7f3d5ce3 #xa6c866c6 #x5d5bcca9 #xdaec6fea #x9f926f91 #x9f46222f #x3991467d
#xa5bf6d8e #x1143c44f #x43958302 #xd0214eeb #x022083b8 #x3fb6180c #x18f8931e #x281658e6
#x26486e3e #x8bd78a70 #x7477e4c1 #xb506e07c #xf32d0a25 #x79098b02 #xe4eabb81 #x28123b23
#x69dead38 #x1574ca16 #xdf871b62 #x211c40b7 #xa51a9ef9 #x0014377b #x041e8ac8 #x09114003
#xbd59e4d2 #xe3d156d5 #x4fe876d5 #x2f91a340 #x557be8de #x00eae4a7 #x0ce5c2ec #x4db4bba6
#xe756bdff #xdd3369ac #xec17b035 #x06572327 #x99afc8b0 #x56c8c391 #x6b65811c #x5e146119
#x6e85cb75 #xbe07c002 #xc2325577 #x893ff4ec #x5bbfc92d #xd0ec3b25 #xb7801ab7 #x8d6d3b24
#x20c763ef #xc366a5fc #x9c382880 #x0ace3205 #xaac9548a #xeca1d7c7 #x041afa32 #x1d16625a
#x6701902c #x9b757a54 #x31d477f7 #x9126b031 #x36cc6fdb #xc70b8b46 #xd9e66a48 #x56e55a79
#x026a4ceb #x52437eff #x2f8f76b4 #x0df980a5 #x8674cde3 #xedda04eb #x17a9be04 #x2c18f4df
#xb7747f9d #xab2af7b4 #xefc34d20 #x2e096b7c #x1741a254 #xe5b6a035 #x213d42f6 #x2c1c7c26
#x61c2f50f #x6552daf9 #xd2c231f8 #x25130f69 #xd8167fa2 #x0418f2c8 #x001a96a6 #x0d1526ab
#x63315c21 #x5e0a72ec #x49bafefd #x187908d9 #x8d0dbd86 #x311170a7 #x3e9b640c #xcc3e10d7
#xd5cad3b6 #x0caec388 #xf73001e1 #x6c728aff #x71eae2a1 #x1f9af36e #xcfcbd12f #xc1de8417
#xac07be6b #xcb44a1d8 #x8b9b0f56 #x013988c3 #xb1c52fca #xb4be31cd #xd8782806 #x12a3a4e2
#x6f7de532 #x58fd7eb6 #xd01ee900 #x24adffc2 #xf4990fc5 #x9711aac5 #x001d7b95 #x82e5e7d2
#x109873f6 #x00613096 #xc32d9521 #xada121ff #x29908415 #x7fbb977f #xaf9eb3db #x29c9ed2a
#x5ce2a465 #xa730f32c #xd0aa3fe8 #x8a5cc091 #xd49e2ce7 #x0ce454a9 #xd60acd86 #x015f1919
#x77079103 #xdea03af6 #x78a8565e #xdee356df #x21f05cbe #x8b75e387 #xb3c50651 #xb8a5c3ef
#xd8eeb6d2 #xe523be77 #xc2154529 #x2f69efdf #xafe67afb #xf470c4b2 #xf3e0eb5b #xd6cc9876
#x39e4460c #x1fda8538 #x1987832f #xca007367 #xa99144f8 #x296b299e #x492fc295 #x9266beab
#xb5676e69 #x9bd3ddda #xdf7e052f #xdb25701c #x1b5e51ee #xf65324e6 #x6afce36c #x0316cc04
#x8644213e #xb7dc59d0 #x7965291f #xccd6fd43 #x41823979 #x932bcdf6 #xb657c34d #x4edfd282
#x7ae5290c #x3cb9536b #x851e20fe #x9833557e #x13ecf0b0 #xd3ffb372 #x3f85c5c1 #x0aef7ed2))
(defconst +cast5-sbox4+
#32@(#x7ec90c04 #x2c6e74b9 #x9b0e66df #xa6337911 #xb86a7fff #x1dd358f5 #x44dd9d44 #x1731167f
#x08fbf1fa #xe7f511cc #xd2051b00 #x735aba00 #x2ab722d8 #x386381cb #xacf6243a #x69befd7a
#xe6a2e77f #xf0c720cd #xc4494816 #xccf5c180 #x38851640 #x15b0a848 #xe68b18cb #x4caadeff
#x5f480a01 #x0412b2aa #x259814fc #x41d0efe2 #x4e40b48d #x248eb6fb #x8dba1cfe #x41a99b02
#x1a550a04 #xba8f65cb #x7251f4e7 #x95a51725 #xc106ecd7 #x97a5980a #xc539b9aa #x4d79fe6a
#xf2f3f763 #x68af8040 #xed0c9e56 #x11b4958b #xe1eb5a88 #x8709e6b0 #xd7e07156 #x4e29fea7
#x6366e52d #x02d1c000 #xc4ac8e05 #x9377f571 #x0c05372a #x578535f2 #x2261be02 #xd642a0c9
#xdf13a280 #x74b55bd2 #x682199c0 #xd421e5ec #x53fb3ce8 #xc8adedb3 #x28a87fc9 #x3d959981
#x5c1ff900 #xfe38d399 #x0c4eff0b #x062407ea #xaa2f4fb1 #x4fb96976 #x90c79505 #xb0a8a774
#xef55a1ff #xe59ca2c2 #xa6b62d27 #xe66a4263 #xdf65001f #x0ec50966 #xdfdd55bc #x29de0655
#x911e739a #x17af8975 #x32c7911c #x89f89468 #x0d01e980 #x524755f4 #x03b63cc9 #x0cc844b2
#xbcf3f0aa #x87ac36e9 #xe53a7426 #x01b3d82b #x1a9e7449 #x64ee2d7e #xcddbb1da #x01c94910
#xb868bf80 #x0d26f3fd #x9342ede7 #x04a5c284 #x636737b6 #x50f5b616 #xf24766e3 #x8eca36c1
#x136e05db #xfef18391 #xfb887a37 #xd6e7f7d4 #xc7fb7dc9 #x3063fcdf #xb6f589de #xec2941da
#x26e46695 #xb7566419 #xf654efc5 #xd08d58b7 #x48925401 #xc1bacb7f #xe5ff550f #xb6083049
#x5bb5d0e8 #x87d72e5a #xab6a6ee1 #x223a66ce #xc62bf3cd #x9e0885f9 #x68cb3e47 #x086c010f
#xa21de820 #xd18b69de #xf3f65777 #xfa02c3f6 #x407edac3 #xcbb3d550 #x1793084d #xb0d70eba
#x0ab378d5 #xd951fb0c #xded7da56 #x4124bbe4 #x94ca0b56 #x0f5755d1 #xe0e1e56e #x6184b5be
#x580a249f #x94f74bc0 #xe327888e #x9f7b5561 #xc3dc0280 #x05687715 #x646c6bd7 #x44904db3
#x66b4f0a3 #xc0f1648a #x697ed5af #x49e92ff6 #x309e374f #x2cb6356a #x85808573 #x4991f840
#x76f0ae02 #x083be84d #x28421c9a #x44489406 #x736e4cb8 #xc1092910 #x8bc95fc6 #x7d869cf4
#x134f616f #x2e77118d #xb31b2be1 #xaa90b472 #x3ca5d717 #x7d161bba #x9cad9010 #xaf462ba2
#x9fe459d2 #x45d34559 #xd9f2da13 #xdbc65487 #xf3e4f94e #x176d486f #x097c13ea #x631da5c7
#x445f7382 #x175683f4 #xcdc66a97 #x70be0288 #xb3cdcf72 #x6e5dd2f3 #x20936079 #x459b80a5
#xbe60e2db #xa9c23101 #xeba5315c #x224e42f2 #x1c5c1572 #xf6721b2c #x1ad2fff3 #x8c25404e
#x324ed72f #x4067b7fd #x0523138e #x5ca3bc78 #xdc0fd66e #x75922283 #x784d6b17 #x58ebb16e
#x44094f85 #x3f481d87 #xfcfeae7b #x77b5ff76 #x8c2302bf #xaaf47556 #x5f46b02a #x2b092801
#x3d38f5f7 #x0ca81f36 #x52af4a8a #x66d5e7c0 #xdf3b0874 #x95055110 #x1b5ad7a8 #xf61ed5ad
#x6cf6e479 #x20758184 #xd0cefa65 #x88f7be58 #x4a046826 #x0ff6f8f3 #xa09c7f70 #x5346aba0
#x5ce96c28 #xe176eda3 #x6bac307f #x376829d2 #x85360fa9 #x17e3fe2a #x24b79767 #xf5a96b20
#xd6cd2595 #x68ff1ebf #x7555442c #xf19f06be #xf9e0659a #xeeb9491d #x34010718 #xbb30cab8
#xe822fe15 #x88570983 #x750e6249 #xda627e55 #x5e76ffa8 #xb1534546 #x6d47de08 #xefe9e7d4))
(defconst +cast5-sbox5+
#32@(#xf6fa8f9d #x2cac6ce1 #x4ca34867 #xe2337f7c #x95db08e7 #x016843b4 #xeced5cbc #x325553ac
#xbf9f0960 #xdfa1e2ed #x83f0579d #x63ed86b9 #x1ab6a6b8 #xde5ebe39 #xf38ff732 #x8989b138
#x33f14961 #xc01937bd #xf506c6da #xe4625e7e #xa308ea99 #x4e23e33c #x79cbd7cc #x48a14367
#xa3149619 #xfec94bd5 #xa114174a #xeaa01866 #xa084db2d #x09a8486f #xa888614a #x2900af98
#x01665991 #xe1992863 #xc8f30c60 #x2e78ef3c #xd0d51932 #xcf0fec14 #xf7ca07d2 #xd0a82072
#xfd41197e #x9305a6b0 #xe86be3da #x74bed3cd #x372da53c #x4c7f4448 #xdab5d440 #x6dba0ec3
#x083919a7 #x9fbaeed9 #x49dbcfb0 #x4e670c53 #x5c3d9c01 #x64bdb941 #x2c0e636a #xba7dd9cd
#xea6f7388 #xe70bc762 #x35f29adb #x5c4cdd8d #xf0d48d8c #xb88153e2 #x08a19866 #x1ae2eac8
#x284caf89 #xaa928223 #x9334be53 #x3b3a21bf #x16434be3 #x9aea3906 #xefe8c36e #xf890cdd9
#x80226dae #xc340a4a3 #xdf7e9c09 #xa694a807 #x5b7c5ecc #x221db3a6 #x9a69a02f #x68818a54
#xceb2296f #x53c0843a #xfe893655 #x25bfe68a #xb4628abc #xcf222ebf #x25ac6f48 #xa9a99387
#x53bddb65 #xe76ffbe7 #xe967fd78 #x0ba93563 #x8e342bc1 #xe8a11be9 #x4980740d #xc8087dfc
#x8de4bf99 #xa11101a0 #x7fd37975 #xda5a26c0 #xe81f994f #x9528cd89 #xfd339fed #xb87834bf
#x5f04456d #x22258698 #xc9c4c83b #x2dc156be #x4f628daa #x57f55ec5 #xe2220abe #xd2916ebf
#x4ec75b95 #x24f2c3c0 #x42d15d99 #xcd0d7fa0 #x7b6e27ff #xa8dc8af0 #x7345c106 #xf41e232f
#x35162386 #xe6ea8926 #x3333b094 #x157ec6f2 #x372b74af #x692573e4 #xe9a9d848 #xf3160289
#x3a62ef1d #xa787e238 #xf3a5f676 #x74364853 #x20951063 #x4576698d #xb6fad407 #x592af950
#x36f73523 #x4cfb6e87 #x7da4cec0 #x6c152daa #xcb0396a8 #xc50dfe5d #xfcd707ab #x0921c42f
#x89dff0bb #x5fe2be78 #x448f4f33 #x754613c9 #x2b05d08d #x48b9d585 #xdc049441 #xc8098f9b
#x7dede786 #xc39a3373 #x42410005 #x6a091751 #x0ef3c8a6 #x890072d6 #x28207682 #xa9a9f7be
#xbf32679d #xd45b5b75 #xb353fd00 #xcbb0e358 #x830f220a #x1f8fb214 #xd372cf08 #xcc3c4a13
#x8cf63166 #x061c87be #x88c98f88 #x6062e397 #x47cf8e7a #xb6c85283 #x3cc2acfb #x3fc06976
#x4e8f0252 #x64d8314d #xda3870e3 #x1e665459 #xc10908f0 #x513021a5 #x6c5b68b7 #x822f8aa0
#x3007cd3e #x74719eef #xdc872681 #x073340d4 #x7e432fd9 #x0c5ec241 #x8809286c #xf592d891
#x08a930f6 #x957ef305 #xb7fbffbd #xc266e96f #x6fe4ac98 #xb173ecc0 #xbc60b42a #x953498da
#xfba1ae12 #x2d4bd736 #x0f25faab #xa4f3fceb #xe2969123 #x257f0c3d #x9348af49 #x361400bc
#xe8816f4a #x3814f200 #xa3f94043 #x9c7a54c2 #xbc704f57 #xda41e7f9 #xc25ad33a #x54f4a084
#xb17f5505 #x59357cbe #xedbd15c8 #x7f97c5ab #xba5ac7b5 #xb6f6deaf #x3a479c3a #x5302da25
#x653d7e6a #x54268d49 #x51a477ea #x5017d55b #xd7d25d88 #x44136c76 #x0404a8c8 #xb8e5a121
#xb81a928a #x60ed5869 #x97c55b96 #xeaec991b #x29935913 #x01fdb7f1 #x088e8dfa #x9ab6f6f5
#x3b4cbf9f #x4a5de3ab #xe6051d35 #xa0e1d855 #xd36b4cf1 #xf544edeb #xb0e93524 #xbebb8fbd
#xa2d762cf #x49c92f54 #x38b5f331 #x7128a454 #x48392905 #xa65b1db8 #x851c97bd #xd675cf2f))
(defconst +cast5-sbox6+
#32@(#x85e04019 #x332bf567 #x662dbfff #xcfc65693 #x2a8d7f6f #xab9bc912 #xde6008a1 #x2028da1f
#x0227bce7 #x4d642916 #x18fac300 #x50f18b82 #x2cb2cb11 #xb232e75c #x4b3695f2 #xb28707de
#xa05fbcf6 #xcd4181e9 #xe150210c #xe24ef1bd #xb168c381 #xfde4e789 #x5c79b0d8 #x1e8bfd43
#x4d495001 #x38be4341 #x913cee1d #x92a79c3f #x089766be #xbaeeadf4 #x1286becf #xb6eacb19
#x2660c200 #x7565bde4 #x64241f7a #x8248dca9 #xc3b3ad66 #x28136086 #x0bd8dfa8 #x356d1cf2
#x107789be #xb3b2e9ce #x0502aa8f #x0bc0351e #x166bf52a #xeb12ff82 #xe3486911 #xd34d7516
#x4e7b3aff #x5f43671b #x9cf6e037 #x4981ac83 #x334266ce #x8c9341b7 #xd0d854c0 #xcb3a6c88
#x47bc2829 #x4725ba37 #xa66ad22b #x7ad61f1e #x0c5cbafa #x4437f107 #xb6e79962 #x42d2d816
#x0a961288 #xe1a5c06e #x13749e67 #x72fc081a #xb1d139f7 #xf9583745 #xcf19df58 #xbec3f756
#xc06eba30 #x07211b24 #x45c28829 #xc95e317f #xbc8ec511 #x38bc46e9 #xc6e6fa14 #xbae8584a
#xad4ebc46 #x468f508b #x7829435f #xf124183b #x821dba9f #xaff60ff4 #xea2c4e6d #x16e39264
#x92544a8b #x009b4fc3 #xaba68ced #x9ac96f78 #x06a5b79a #xb2856e6e #x1aec3ca9 #xbe838688
#x0e0804e9 #x55f1be56 #xe7e5363b #xb3a1f25d #xf7debb85 #x61fe033c #x16746233 #x3c034c28
#xda6d0c74 #x79aac56c #x3ce4e1ad #x51f0c802 #x98f8f35a #x1626a49f #xeed82b29 #x1d382fe3
#x0c4fb99a #xbb325778 #x3ec6d97b #x6e77a6a9 #xcb658b5c #xd45230c7 #x2bd1408b #x60c03eb7
#xb9068d78 #xa33754f4 #xf430c87d #xc8a71302 #xb96d8c32 #xebd4e7be #xbe8b9d2d #x7979fb06
#xe7225308 #x8b75cf77 #x11ef8da4 #xe083c858 #x8d6b786f #x5a6317a6 #xfa5cf7a0 #x5dda0033
#xf28ebfb0 #xf5b9c310 #xa0eac280 #x08b9767a #xa3d9d2b0 #x79d34217 #x021a718d #x9ac6336a
#x2711fd60 #x438050e3 #x069908a8 #x3d7fedc4 #x826d2bef #x4eeb8476 #x488dcf25 #x36c9d566
#x28e74e41 #xc2610aca #x3d49a9cf #xbae3b9df #xb65f8de6 #x92aeaf64 #x3ac7d5e6 #x9ea80509
#xf22b017d #xa4173f70 #xdd1e16c3 #x15e0d7f9 #x50b1b887 #x2b9f4fd5 #x625aba82 #x6a017962
#x2ec01b9c #x15488aa9 #xd716e740 #x40055a2c #x93d29a22 #xe32dbf9a #x058745b9 #x3453dc1e
#xd699296e #x496cff6f #x1c9f4986 #xdfe2ed07 #xb87242d1 #x19de7eae #x053e561a #x15ad6f8c
#x66626c1c #x7154c24c #xea082b2a #x93eb2939 #x17dcb0f0 #x58d4f2ae #x9ea294fb #x52cf564c
#x9883fe66 #x2ec40581 #x763953c3 #x01d6692e #xd3a0c108 #xa1e7160e #xe4f2dfa6 #x693ed285
#x74904698 #x4c2b0edd #x4f757656 #x5d393378 #xa132234f #x3d321c5d #xc3f5e194 #x4b269301
#xc79f022f #x3c997e7e #x5e4f9504 #x3ffafbbd #x76f7ad0e #x296693f4 #x3d1fce6f #xc61e45be
#xd3b5ab34 #xf72bf9b7 #x1b0434c0 #x4e72b567 #x5592a33d #xb5229301 #xcfd2a87f #x60aeb767
#x1814386b #x30bcc33d #x38a0c07d #xfd1606f2 #xc363519b #x589dd390 #x5479f8e6 #x1cb8d647
#x97fd61a9 #xea7759f4 #x2d57539d #x569a58cf #xe84e63ad #x462e1b78 #x6580f87e #xf3817914
#x91da55f4 #x40a230f3 #xd1988f35 #xb6e318d2 #x3ffa50bc #x3d40f021 #xc3c0bdae #x4958c24c
#x518f36b2 #x84b1d370 #x0fedce83 #x878ddada #xf2a279c7 #x94e01be8 #x90716f4b #x954b8aa3))
(defconst +cast5-sbox7+
#32@(#xe216300d #xbbddfffc #xa7ebdabd #x35648095 #x7789f8b7 #xe6c1121b #x0e241600 #x052ce8b5
#x11a9cfb0 #xe5952f11 #xece7990a #x9386d174 #x2a42931c #x76e38111 #xb12def3a #x37ddddfc
#xde9adeb1 #x0a0cc32c #xbe197029 #x84a00940 #xbb243a0f #xb4d137cf #xb44e79f0 #x049eedfd
#x0b15a15d #x480d3168 #x8bbbde5a #x669ded42 #xc7ece831 #x3f8f95e7 #x72df191b #x7580330d
#x94074251 #x5c7dcdfa #xabbe6d63 #xaa402164 #xb301d40a #x02e7d1ca #x53571dae #x7a3182a2
#x12a8ddec #xfdaa335d #x176f43e8 #x71fb46d4 #x38129022 #xce949ad4 #xb84769ad #x965bd862
#x82f3d055 #x66fb9767 #x15b80b4e #x1d5b47a0 #x4cfde06f #xc28ec4b8 #x57e8726e #x647a78fc
#x99865d44 #x608bd593 #x6c200e03 #x39dc5ff6 #x5d0b00a3 #xae63aff2 #x7e8bd632 #x70108c0c
#xbbd35049 #x2998df04 #x980cf42a #x9b6df491 #x9e7edd53 #x06918548 #x58cb7e07 #x3b74ef2e
#x522fffb1 #xd24708cc #x1c7e27cd #xa4eb215b #x3cf1d2e2 #x19b47a38 #x424f7618 #x35856039
#x9d17dee7 #x27eb35e6 #xc9aff67b #x36baf5b8 #x09c467cd #xc18910b1 #xe11dbf7b #x06cd1af8
#x7170c608 #x2d5e3354 #xd4de495a #x64c6d006 #xbcc0c62c #x3dd00db3 #x708f8f34 #x77d51b42
#x264f620f #x24b8d2bf #x15c1b79e #x46a52564 #xf8d7e54e #x3e378160 #x7895cda5 #x859c15a5
#xe6459788 #xc37bc75f #xdb07ba0c #x0676a3ab #x7f229b1e #x31842e7b #x24259fd7 #xf8bef472
#x835ffcb8 #x6df4c1f2 #x96f5b195 #xfd0af0fc #xb0fe134c #xe2506d3d #x4f9b12ea #xf215f225
#xa223736f #x9fb4c428 #x25d04979 #x34c713f8 #xc4618187 #xea7a6e98 #x7cd16efc #x1436876c
#xf1544107 #xbedeee14 #x56e9af27 #xa04aa441 #x3cf7c899 #x92ecbae6 #xdd67016d #x151682eb
#xa842eedf #xfdba60b4 #xf1907b75 #x20e3030f #x24d8c29e #xe139673b #xefa63fb8 #x71873054
#xb6f2cf3b #x9f326442 #xcb15a4cc #xb01a4504 #xf1e47d8d #x844a1be5 #xbae7dfdc #x42cbda70
#xcd7dae0a #x57e85b7a #xd53f5af6 #x20cf4d8c #xcea4d428 #x79d130a4 #x3486ebfb #x33d3cddc
#x77853b53 #x37effcb5 #xc5068778 #xe580b3e6 #x4e68b8f4 #xc5c8b37e #x0d809ea2 #x398feb7c
#x132a4f94 #x43b7950e #x2fee7d1c #x223613bd #xdd06caa2 #x37df932b #xc4248289 #xacf3ebc3
#x5715f6b7 #xef3478dd #xf267616f #xc148cbe4 #x9052815e #x5e410fab #xb48a2465 #x2eda7fa4
#xe87b40e4 #xe98ea084 #x5889e9e1 #xefd390fc #xdd07d35b #xdb485694 #x38d7e5b2 #x57720101
#x730edebc #x5b643113 #x94917e4f #x503c2fba #x646f1282 #x7523d24a #xe0779695 #xf9c17a8f
#x7a5b2121 #xd187b896 #x29263a4d #xba510cdf #x81f47c9f #xad1163ed #xea7b5965 #x1a00726e
#x11403092 #x00da6d77 #x4a0cdd61 #xad1f4603 #x605bdfb0 #x9eedc364 #x22ebe6a8 #xcee7d28a
#xa0e736a0 #x5564a6b9 #x10853209 #xc7eb8f37 #x2de705ca #x8951570f #xdf09822b #xbd691a6c
#xaa12e4f2 #x87451c0f #xe0f6a27a #x3ada4819 #x4cf1764f #x0d771c2b #x67cdb156 #x350d8384
#x5938fa0f #x42399ef3 #x36997b07 #x0e84093d #x4aa93e61 #x8360d87b #x1fa98b0c #x1149382c
#xe97625a5 #x0614d1b7 #x0e25244b #x0c768347 #x589e8d82 #x0d2059d1 #xa466bb1e #xf8da0a82
#x04f19130 #xba6e4ec0 #x99265164 #x1ee7230d #x50b2ad80 #xeaee6801 #x8db2a283 #xea8bf59e))
the actual CAST5 implementation
(deftype cast5-mask-vector () '(simple-array (unsigned-byte 32) (16)))
(deftype cast5-rotate-vector () '(simple-array (unsigned-byte 8) (16)))
(defclass cast5 (cipher 8-byte-block-mixin)
((mask-vector :accessor mask-vector :type cast5-mask-vector)
(rotate-vector :accessor rotate-vector :type cast5-rotate-vector)
(n-rounds :accessor n-rounds)))
(declaim (inline cast5-f1 cast5-f2 cast5-f3))
(macrolet ((cast5-s-box (s-box-index index)
`(aref ,(intern (format nil "+~A~A+" '#:cast5-sbox s-box-index))
,index)))
(defun cast5-f1 (input mask rotate)
(declare (type (unsigned-byte 32) input mask))
(declare (type (unsigned-byte 5) rotate))
(let ((value (rol32 (mod32+ input mask) rotate)))
(declare (type (unsigned-byte 32) value))
(mod32+ (cast5-s-box 3 (first-byte value))
(mod32- (logxor (cast5-s-box 1 (third-byte value))
(cast5-s-box 0 (fourth-byte value)))
(cast5-s-box 2 (second-byte value))))))
(defun cast5-f2 (input mask rotate)
(declare (type (unsigned-byte 32) input mask))
(declare (type (unsigned-byte 5) rotate))
(let ((value (rol32 (logxor input mask) rotate)))
(declare (type (unsigned-byte 32) value))
(logxor (cast5-s-box 3 (first-byte value))
(mod32+ (cast5-s-box 2 (second-byte value))
(mod32- (cast5-s-box 0 (fourth-byte value))
(cast5-s-box 1 (third-byte value)))))))
(defun cast5-f3 (input mask rotate)
(declare (type (unsigned-byte 32) input mask))
(declare (type (unsigned-byte 5) rotate))
(let ((value (rol32 (mod32- mask input) rotate)))
(declare (type (unsigned-byte 32) value))
(mod32- (logxor (cast5-s-box 2 (second-byte value))
(mod32+ (cast5-s-box 1 (third-byte value))
(cast5-s-box 0 (fourth-byte value))))
(cast5-s-box 3 (first-byte value)))))
(define-block-encryptor cast5 8
(let ((mask-vector (mask-vector context))
(rotate-vector (rotate-vector context))
(n-rounds (n-rounds context)))
(declare (type cast5-mask-vector mask-vector))
(declare (type cast5-rotate-vector rotate-vector))
(declare (type (or (integer 12 12) (integer 16 16)) n-rounds))
(with-words ((l0 r0) plaintext plaintext-start)
#.(loop for i from 0 below 16
for round-function = (ecase i
((0 3 6 9 12 15) 'cast5-f1)
((1 4 7 10 13) 'cast5-f2)
((2 5 8 11 14) 'cast5-f3))
collect `(let ((x (logxor l0 (,round-function r0
(aref mask-vector ,i)
(aref rotate-vector ,i)))))
(declare (type (unsigned-byte 32) x))
(setf l0 r0 r0 x)) into forms
finally (return `(progn ,@(subseq forms 0 12)
(when (= n-rounds 16)
,@(subseq forms 12)))))
(store-words ciphertext ciphertext-start r0 l0))))
(define-block-decryptor cast5 8
(let ((mask-vector (mask-vector context))
(rotate-vector (rotate-vector context))
(n-rounds (n-rounds context)))
(declare (type cast5-mask-vector mask-vector))
(declare (type cast5-rotate-vector rotate-vector))
(declare (type (or (integer 12 12) (integer 16 16)) n-rounds))
(with-words ((l0 r0) ciphertext ciphertext-start)
#.(loop for i from 15 downto 0
for round-function = (ecase i
((0 3 6 9 12 15) 'cast5-f1)
((1 4 7 10 13) 'cast5-f2)
((2 5 8 11 14) 'cast5-f3))
collect `(let ((x (logxor l0 (,round-function r0
(aref mask-vector ,i)
(aref rotate-vector ,i)))))
(declare (type (unsigned-byte 32) x))
(setf l0 r0 r0 x)) into forms
finally (return `(progn (when (= n-rounds 16)
,@(subseq forms 0 4))
,@(subseq forms 4))))
(store-words plaintext plaintext-start r0 l0))))
MACROLET
(defun generate-cast5-key-schedule (key)
(declare (type (simple-array (unsigned-byte 8) (16)) key))
(with-words ((x0 x4 x8 xc) key 0)
(let* ((mask-vector (make-array 16 :element-type '(unsigned-byte 32)))
(rotate-vector (make-array 16 :element-type '(unsigned-byte 8)))
(z0 0)
(z4 0)
(z8 0)
(zc 0))
(declare (type (unsigned-byte 32) z0 z4 z8 zc))
(setf z0 (logxor x0 (aref +cast5-sbox4+ (third-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (second-byte xc)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf z4 (logxor x8 (aref +cast5-sbox4+ (fourth-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte x8))))
(setf z8 (logxor xc (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox4+ (third-byte x8))))
(setf zc (logxor x4 (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z8)) (aref +cast5-sbox7+ (fourth-byte z8)) (aref +cast5-sbox5+ (first-byte x8))))
(setf (aref mask-vector (- 1 1)) (logxor (aref +cast5-sbox4+ (fourth-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox4+ (second-byte z0))))
(setf (aref mask-vector (- 2 1)) (logxor (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (first-byte z8)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox5+ (second-byte z4))))
(setf (aref mask-vector (- 3 1)) (logxor (aref +cast5-sbox4+ (fourth-byte zc)) (aref +cast5-sbox5+ (third-byte zc)) (aref +cast5-sbox6+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z8))))
(setf (aref mask-vector (- 4 1)) (logxor (aref +cast5-sbox4+ (second-byte zc)) (aref +cast5-sbox5+ (first-byte zc)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (fourth-byte z0)) (aref +cast5-sbox7+ (fourth-byte zc))))
(setf x0 (logxor z8 (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (first-byte z4)) (aref +cast5-sbox6+ (fourth-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z0))))
(setf x4 (logxor z0 (aref +cast5-sbox4+ (fourth-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte z0))))
(setf x8 (logxor z4 (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox4+ (third-byte z0))))
(setf xc (logxor zc (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x8)) (aref +cast5-sbox7+ (fourth-byte x8)) (aref +cast5-sbox5+ (first-byte z0))))
(setf (aref mask-vector (- 5 1)) (logxor (aref +cast5-sbox4+ (first-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (third-byte xc)) (aref +cast5-sbox4+ (fourth-byte x8))))
(setf (aref mask-vector (- 6 1)) (logxor (aref +cast5-sbox4+ (third-byte x0)) (aref +cast5-sbox5+ (fourth-byte x0)) (aref +cast5-sbox6+ (second-byte xc)) (aref +cast5-sbox7+ (first-byte xc)) (aref +cast5-sbox5+ (third-byte xc))))
(setf (aref mask-vector (- 7 1)) (logxor (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (fourth-byte x8)) (aref +cast5-sbox7+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x0))))
(setf (aref mask-vector (- 8 1)) (logxor (aref +cast5-sbox4+ (third-byte x4)) (aref +cast5-sbox5+ (fourth-byte x4)) (aref +cast5-sbox6+ (second-byte x8)) (aref +cast5-sbox7+ (first-byte x8)) (aref +cast5-sbox7+ (first-byte x4))))
(setf z0 (logxor x0 (aref +cast5-sbox4+ (third-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (second-byte xc)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf z4 (logxor x8 (aref +cast5-sbox4+ (fourth-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte x8))))
(setf z8 (logxor xc (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox4+ (third-byte x8))))
(setf zc (logxor x4 (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z8)) (aref +cast5-sbox7+ (fourth-byte z8)) (aref +cast5-sbox5+ (first-byte x8))))
(setf (aref mask-vector (- 9 1)) (logxor (aref +cast5-sbox4+ (first-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (fourth-byte zc)) (aref +cast5-sbox7+ (third-byte zc)) (aref +cast5-sbox4+ (third-byte z8))))
(setf (aref mask-vector (- 10 1)) (logxor (aref +cast5-sbox4+ (third-byte z0)) (aref +cast5-sbox5+ (fourth-byte z0)) (aref +cast5-sbox6+ (second-byte zc)) (aref +cast5-sbox7+ (first-byte zc)) (aref +cast5-sbox5+ (fourth-byte zc))))
(setf (aref mask-vector (- 11 1)) (logxor (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z8)) (aref +cast5-sbox7+ (third-byte z8)) (aref +cast5-sbox6+ (second-byte z0))))
(setf (aref mask-vector (- 12 1)) (logxor (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (fourth-byte z4)) (aref +cast5-sbox6+ (second-byte z8)) (aref +cast5-sbox7+ (first-byte z8)) (aref +cast5-sbox7+ (second-byte z4))))
(setf x0 (logxor z8 (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (first-byte z4)) (aref +cast5-sbox6+ (fourth-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z0))))
(setf x4 (logxor z0 (aref +cast5-sbox4+ (fourth-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte z0))))
(setf x8 (logxor z4 (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox4+ (third-byte z0))))
(setf xc (logxor zc (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x8)) (aref +cast5-sbox7+ (fourth-byte x8)) (aref +cast5-sbox5+ (first-byte z0))))
(setf (aref mask-vector (- 13 1)) (logxor (aref +cast5-sbox4+ (fourth-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x4)) (aref +cast5-sbox7+ (second-byte x4)) (aref +cast5-sbox4+ (first-byte x0))))
(setf (aref mask-vector (- 14 1)) (logxor (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (first-byte x8)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox5+ (first-byte x4))))
(setf (aref mask-vector (- 15 1)) (logxor (aref +cast5-sbox4+ (fourth-byte xc)) (aref +cast5-sbox5+ (third-byte xc)) (aref +cast5-sbox6+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte x0)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf (aref mask-vector (- 16 1)) (logxor (aref +cast5-sbox4+ (second-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (fourth-byte x0)) (aref +cast5-sbox7+ (third-byte xc))))
(setf z0 (logxor x0 (aref +cast5-sbox4+ (third-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (second-byte xc)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf z4 (logxor x8 (aref +cast5-sbox4+ (fourth-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte x8))))
(setf z8 (logxor xc (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox4+ (third-byte x8))))
(setf zc (logxor x4 (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z8)) (aref +cast5-sbox7+ (fourth-byte z8)) (aref +cast5-sbox5+ (first-byte x8))))
(setf (aref rotate-vector (- 17 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (fourth-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox4+ (second-byte z0)))))
(setf (aref rotate-vector (- 18 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (first-byte z8)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox5+ (second-byte z4)))))
(setf (aref rotate-vector (- 19 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (fourth-byte zc)) (aref +cast5-sbox5+ (third-byte zc)) (aref +cast5-sbox6+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z8)))))
(setf (aref rotate-vector (- 20 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (second-byte zc)) (aref +cast5-sbox5+ (first-byte zc)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (fourth-byte z0)) (aref +cast5-sbox7+ (fourth-byte zc)))))
(setf x0 (logxor z8 (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (first-byte z4)) (aref +cast5-sbox6+ (fourth-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z0))))
(setf x4 (logxor z0 (aref +cast5-sbox4+ (fourth-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte z0))))
(setf x8 (logxor z4 (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox4+ (third-byte z0))))
(setf xc (logxor zc (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x8)) (aref +cast5-sbox7+ (fourth-byte x8)) (aref +cast5-sbox5+ (first-byte z0))))
(setf (aref rotate-vector (- 21 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (first-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (third-byte xc)) (aref +cast5-sbox4+ (fourth-byte x8)))))
(setf (aref rotate-vector (- 22 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (third-byte x0)) (aref +cast5-sbox5+ (fourth-byte x0)) (aref +cast5-sbox6+ (second-byte xc)) (aref +cast5-sbox7+ (first-byte xc)) (aref +cast5-sbox5+ (third-byte xc)))))
(setf (aref rotate-vector (- 23 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (fourth-byte x8)) (aref +cast5-sbox7+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x0)))))
(setf (aref rotate-vector (- 24 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (third-byte x4)) (aref +cast5-sbox5+ (fourth-byte x4)) (aref +cast5-sbox6+ (second-byte x8)) (aref +cast5-sbox7+ (first-byte x8)) (aref +cast5-sbox7+ (first-byte x4)))))
(setf z0 (logxor x0 (aref +cast5-sbox4+ (third-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (fourth-byte xc)) (aref +cast5-sbox7+ (second-byte xc)) (aref +cast5-sbox6+ (fourth-byte x8))))
(setf z4 (logxor x8 (aref +cast5-sbox4+ (fourth-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (third-byte z0)) (aref +cast5-sbox7+ (first-byte z0)) (aref +cast5-sbox7+ (second-byte x8))))
(setf z8 (logxor xc (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (third-byte z4)) (aref +cast5-sbox7+ (fourth-byte z4)) (aref +cast5-sbox4+ (third-byte x8))))
(setf zc (logxor x4 (aref +cast5-sbox4+ (second-byte z8)) (aref +cast5-sbox5+ (third-byte z8)) (aref +cast5-sbox6+ (first-byte z8)) (aref +cast5-sbox7+ (fourth-byte z8)) (aref +cast5-sbox5+ (first-byte x8))))
(setf (aref rotate-vector (- 25 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (first-byte z0)) (aref +cast5-sbox5+ (second-byte z0)) (aref +cast5-sbox6+ (fourth-byte zc)) (aref +cast5-sbox7+ (third-byte zc)) (aref +cast5-sbox4+ (third-byte z8)))))
(setf (aref rotate-vector (- 26 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (third-byte z0)) (aref +cast5-sbox5+ (fourth-byte z0)) (aref +cast5-sbox6+ (second-byte zc)) (aref +cast5-sbox7+ (first-byte zc)) (aref +cast5-sbox5+ (fourth-byte zc)))))
(setf (aref rotate-vector (- 27 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (first-byte z4)) (aref +cast5-sbox5+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z8)) (aref +cast5-sbox7+ (third-byte z8)) (aref +cast5-sbox6+ (second-byte z0)))))
(setf (aref rotate-vector (- 28 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (fourth-byte z4)) (aref +cast5-sbox6+ (second-byte z8)) (aref +cast5-sbox7+ (first-byte z8)) (aref +cast5-sbox7+ (second-byte z4)))))
(setf x0 (logxor z8 (aref +cast5-sbox4+ (third-byte z4)) (aref +cast5-sbox5+ (first-byte z4)) (aref +cast5-sbox6+ (fourth-byte z4)) (aref +cast5-sbox7+ (second-byte z4)) (aref +cast5-sbox6+ (fourth-byte z0))))
(setf x4 (logxor z0 (aref +cast5-sbox4+ (fourth-byte x0)) (aref +cast5-sbox5+ (second-byte x0)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte z0))))
(setf x8 (logxor z4 (aref +cast5-sbox4+ (first-byte x4)) (aref +cast5-sbox5+ (second-byte x4)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox4+ (third-byte z0))))
(setf xc (logxor zc (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x8)) (aref +cast5-sbox7+ (fourth-byte x8)) (aref +cast5-sbox5+ (first-byte z0))))
(setf (aref rotate-vector (- 29 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (fourth-byte x8)) (aref +cast5-sbox5+ (third-byte x8)) (aref +cast5-sbox6+ (first-byte x4)) (aref +cast5-sbox7+ (second-byte x4)) (aref +cast5-sbox4+ (first-byte x0)))))
(setf (aref rotate-vector (- 30 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (second-byte x8)) (aref +cast5-sbox5+ (first-byte x8)) (aref +cast5-sbox6+ (third-byte x4)) (aref +cast5-sbox7+ (fourth-byte x4)) (aref +cast5-sbox5+ (first-byte x4)))))
(setf (aref rotate-vector (- 31 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (fourth-byte xc)) (aref +cast5-sbox5+ (third-byte xc)) (aref +cast5-sbox6+ (first-byte x0)) (aref +cast5-sbox7+ (second-byte x0)) (aref +cast5-sbox6+ (fourth-byte x8)))))
(setf (aref rotate-vector (- 32 17)) (ldb (byte 5 0) (logxor (aref +cast5-sbox4+ (second-byte xc)) (aref +cast5-sbox5+ (first-byte xc)) (aref +cast5-sbox6+ (third-byte x0)) (aref +cast5-sbox7+ (fourth-byte x0)) (aref +cast5-sbox7+ (third-byte xc)))))
(values mask-vector rotate-vector))))
(defmethod schedule-key ((cipher cast5) key)
(declare (type (simple-array (unsigned-byte 8) (*)) key))
(let ((length (length key))
(key (if (= (length key) 16)
key
(let ((tmp (make-array 16 :element-type '(unsigned-byte 8)
:initial-element 0)))
(replace tmp key)))))
(declare (type (simple-array (unsigned-byte 8) (16)) key))
(multiple-value-bind (mask-vector rotate-vector)
(generate-cast5-key-schedule key)
(let ((n-rounds (if (<= length 10)
12
16)))
(setf (mask-vector cipher) mask-vector
(rotate-vector cipher) rotate-vector
(n-rounds cipher) n-rounds)
cipher))))
(defcipher cast5
(:encrypt-function cast5-encrypt-block)
(:decrypt-function cast5-decrypt-block)
(:block-length 8)
(:key-length (:variable 5 16 1)))
|
3511f7b1624bd95d63ec918bd589d205406322cd9aef027e72fb65abd27fc80d | samrushing/irken-compiler | t_sexp0.scm | ;; -*- Mode: Irken -*-
(include "lib/basis.scm")
(include "lib/map.scm")
(pp (sexp (int 1) (sym 'x) (char #\a) (sexp (int 0) (int 3) (string "test"))) 20)
(pp (sexp (rec (a (sym 'int)) (b (sym 'list)))) 20)
(define list0 (sexp (int 0) (int 1) (int 2)))
(define list1 (sexpl (int 0) (int 1) (int 2)))
(pp (sexp (string "[") list0 (string "]")) 20)
(pp (sexp (string "[") (list list1) (string "]")
(undef) (cons 'list 'nil)
(attr (sym 'x) 'name)
(attr (sexp (int 0) (int 1)) 'name)
(vec (int 0) (int 1) (int 2))
)
10)
| null | https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/t_sexp0.scm | scheme | -*- Mode: Irken -*- |
(include "lib/basis.scm")
(include "lib/map.scm")
(pp (sexp (int 1) (sym 'x) (char #\a) (sexp (int 0) (int 3) (string "test"))) 20)
(pp (sexp (rec (a (sym 'int)) (b (sym 'list)))) 20)
(define list0 (sexp (int 0) (int 1) (int 2)))
(define list1 (sexpl (int 0) (int 1) (int 2)))
(pp (sexp (string "[") list0 (string "]")) 20)
(pp (sexp (string "[") (list list1) (string "]")
(undef) (cons 'list 'nil)
(attr (sym 'x) 'name)
(attr (sexp (int 0) (int 1)) 'name)
(vec (int 0) (int 1) (int 2))
)
10)
|
9c66886f27db778a8c9eae5f11b93b7d5e6f6be4e4c0400568c1c110bbb775c1 | facebook/flow | ast_loc_utils.mli |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
Converts a ( Loc.t , Loc.t ) AST into a ( ALoc.t , ALoc.t ) AST . Leaves the underlying representation
* of the contained ALoc.ts concrete .
* of the contained ALoc.ts concrete. *)
val loc_to_aloc_mapper : (Loc.t, Loc.t, ALoc.t, ALoc.t) Flow_polymorphic_ast_mapper.mapper
| null | https://raw.githubusercontent.com/facebook/flow/741104e69c43057ebd32804dd6bcc1b5e97548ea/src/parser_utils/ast_loc_utils.mli | ocaml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
Converts a ( Loc.t , Loc.t ) AST into a ( ALoc.t , ALoc.t ) AST . Leaves the underlying representation
* of the contained ALoc.ts concrete .
* of the contained ALoc.ts concrete. *)
val loc_to_aloc_mapper : (Loc.t, Loc.t, ALoc.t, ALoc.t) Flow_polymorphic_ast_mapper.mapper
| |
9e4384fb4648e6be2bd7d4169cee4c1e166f083c8855776b07be9e01a8b959e5 | AshleyYakeley/Truth | GTK.hs | module Pinafore.Language.Library.GTK
( allGTKStuff
, LangContext(..)
) where
import Pinafore.Language.API
import Pinafore.Language.Library.GTK.Clipboard
import Pinafore.Language.Library.GTK.Context
import Pinafore.Language.Library.GTK.Debug
import Pinafore.Language.Library.GTK.Element
import Pinafore.Language.Library.GTK.Element.Drawing
import Pinafore.Language.Library.GTK.MenuItem
import Pinafore.Language.Library.GTK.Window
import Shapes
gtkStuff :: BindDocTree ()
gtkStuff =
headingBDT "GTK" "User interface, using GTK." $
pure $ namespaceBDT "GTK" "" [elementStuff, drawingStuff, menuItemStuff, windowStuff, clipboardStuff, dialogStuff]
allGTKStuff :: [BindDocTree ()]
allGTKStuff = [gtkStuff, gtkDebugStuff]
| null | https://raw.githubusercontent.com/AshleyYakeley/Truth/53900d89022f68bffb08d5c07b4e783ab0a0542e/Pinafore/pinafore-gnome/lib/Pinafore/Language/Library/GTK.hs | haskell | module Pinafore.Language.Library.GTK
( allGTKStuff
, LangContext(..)
) where
import Pinafore.Language.API
import Pinafore.Language.Library.GTK.Clipboard
import Pinafore.Language.Library.GTK.Context
import Pinafore.Language.Library.GTK.Debug
import Pinafore.Language.Library.GTK.Element
import Pinafore.Language.Library.GTK.Element.Drawing
import Pinafore.Language.Library.GTK.MenuItem
import Pinafore.Language.Library.GTK.Window
import Shapes
gtkStuff :: BindDocTree ()
gtkStuff =
headingBDT "GTK" "User interface, using GTK." $
pure $ namespaceBDT "GTK" "" [elementStuff, drawingStuff, menuItemStuff, windowStuff, clipboardStuff, dialogStuff]
allGTKStuff :: [BindDocTree ()]
allGTKStuff = [gtkStuff, gtkDebugStuff]
| |
4156a8790f8d8f3e2208cec9334e831ba63022f0e45d3ea744fbc7ce34db3676 | racket/gui | const.rkt | #lang racket/base
(provide (except-out (all-defined-out) <<))
(define (<< a b) (arithmetic-shift a b))
(define NSTitledWindowMask 1)
(define NSBorderlessWindowMask 0)
(define NSClosableWindowMask 2)
(define NSMiniaturizableWindowMask 4)
(define NSResizableWindowMask 8)
(define NSUtilityWindowMask (1 . << . 4))
(define NSTexturedBackgroundWindowMask 256)
(define NSBackingStoreBuffered 2)
(define NSRoundedBezelStyle 1)
(define NSRegularSquareBezelStyle 2)
(define NSLeftMouseDown 1)
(define NSLeftMouseUp 2)
(define NSRightMouseDown 3)
(define NSRightMouseUp 4)
(define NSMouseMoved 5)
(define NSLeftMouseDragged 6)
(define NSRightMouseDragged 7)
(define NSMouseEntered 8)
(define NSMouseExited 9)
(define NSKeyDown 10)
(define NSKeyUp 11)
(define NSFlagsChanged 12)
(define NSAppKitDefined 13)
(define NSSystemDefined 14)
(define NSApplicationDefined 15)
(define NSPeriodic 16)
(define NSCursorUpdate 17)
(define NSScrollWheel 22)
(define NSTabletPoint 23)
(define NSTabletProximity 24)
(define NSOtherMouseDown 25)
(define NSOtherMouseUp 26)
(define NSOtherMouseDragged 27)
(define NSEventTypeGesture 29)
(define NSEventTypeMagnify 30)
(define NSEventTypeSwipe 31)
(define NSEventTypeRotate 18)
(define NSEventTypeBeginGesture 19)
(define NSEventTypeEndGesture 20)
(define MouseAndKeyEventMask
(bitwise-ior
(1 . << . NSLeftMouseDown)
(1 . << . NSLeftMouseUp)
(1 . << . NSRightMouseDown)
(1 . << . NSRightMouseUp)
(1 . << . NSMouseMoved)
(1 . << . NSLeftMouseDragged)
(1 . << . NSRightMouseDragged)
(1 . << . NSMouseEntered)
(1 . << . NSMouseExited)
(1 . << . NSKeyDown)
(1 . << . NSKeyUp)
(1 . << . NSScrollWheel)
(1 . << . NSTabletPoint)
(1 . << . NSTabletProximity)
(1 . << . NSOtherMouseDown)
(1 . << . NSOtherMouseUp)
(1 . << . NSOtherMouseDragged)
(1 . << . NSEventTypeGesture)
(1 . << . NSEventTypeMagnify)
(1 . << . NSEventTypeSwipe)
(1 . << . NSEventTypeRotate)
(1 . << . NSEventTypeBeginGesture)
(1 . << . NSEventTypeEndGesture)))
(define NSAlphaShiftKeyMask (1 . << . 16))
(define NSShiftKeyMask (1 . << . 17))
(define NSControlKeyMask (1 . << . 18))
(define NSAlternateKeyMask (1 . << . 19))
(define NSCommandKeyMask (1 . << . 20))
(define NSNumericPadKeyMask (1 . << . 21))
(define NSHelpKeyMask (1 . << . 22))
(define NSFunctionKeyMask (1 . << . 23))
(define NSScrollerNoPart 0)
(define NSScrollerDecrementPage 1)
(define NSScrollerKnob 2)
(define NSScrollerIncrementPage 3)
(define NSScrollerDecrementLine 4)
(define NSScrollerIncrementLine 5)
(define NSScrollerKnobSlot 6)
(define NSMomentaryLightButton 0)
(define NSPushOnPushOffButton 1)
(define NSToggleButton 2)
(define NSSwitchButton 3)
(define NSRadioButton 4)
(define NSMomentaryChangeButton 5)
(define NSOnOffButton 6)
(define NSMomentaryPushInButton 7)
(define NSMomentaryPushButton 0)
(define NSMomentaryLight 7)
(define NSFocusRingTypeDefault 0)
(define NSFocusRingTypeNone 1)
(define NSFocusRingTypeExterior 2)
(define kCGBitmapAlphaInfoMask #x1F)
(define kCGBitmapFloatComponents (1 . << . 8))
(define kCGBitmapByteOrderMask #x7000)
(define kCGBitmapByteOrderDefault (0 . << . 12))
(define kCGBitmapByteOrder16Little (1 . << . 12))
(define kCGBitmapByteOrder32Little (2 . << . 12))
(define kCGBitmapByteOrder16Big (3 . << . 12))
(define kCGBitmapByteOrder32Big (4 . << . 12))
(define kCGImageAlphaNone 0)
(define kCGImageAlphaPremultipliedLast 1)
(define kCGImageAlphaPremultipliedFirst 2)
(define kCGImageAlphaLast 3)
(define kCGImageAlphaFirst 4)
(define kCGImageAlphaNoneSkipLast 5)
(define kCGImageAlphaNoneSkipFirst 6)
(define NSWindowCollectionBehaviorFullScreenPrimary 128)
(define NSWindowCollectionBehaviorFullScreenAuxiliary 256)
(define NSFullScreenWindowMask (1 . << . 14))
Amount of scroll to count as one step :
(define WHEEL-STEP-AMT 12.0)
| null | https://raw.githubusercontent.com/racket/gui/d1fef7a43a482c0fdd5672be9a6e713f16d8be5c/gui-lib/mred/private/wx/cocoa/const.rkt | racket | #lang racket/base
(provide (except-out (all-defined-out) <<))
(define (<< a b) (arithmetic-shift a b))
(define NSTitledWindowMask 1)
(define NSBorderlessWindowMask 0)
(define NSClosableWindowMask 2)
(define NSMiniaturizableWindowMask 4)
(define NSResizableWindowMask 8)
(define NSUtilityWindowMask (1 . << . 4))
(define NSTexturedBackgroundWindowMask 256)
(define NSBackingStoreBuffered 2)
(define NSRoundedBezelStyle 1)
(define NSRegularSquareBezelStyle 2)
(define NSLeftMouseDown 1)
(define NSLeftMouseUp 2)
(define NSRightMouseDown 3)
(define NSRightMouseUp 4)
(define NSMouseMoved 5)
(define NSLeftMouseDragged 6)
(define NSRightMouseDragged 7)
(define NSMouseEntered 8)
(define NSMouseExited 9)
(define NSKeyDown 10)
(define NSKeyUp 11)
(define NSFlagsChanged 12)
(define NSAppKitDefined 13)
(define NSSystemDefined 14)
(define NSApplicationDefined 15)
(define NSPeriodic 16)
(define NSCursorUpdate 17)
(define NSScrollWheel 22)
(define NSTabletPoint 23)
(define NSTabletProximity 24)
(define NSOtherMouseDown 25)
(define NSOtherMouseUp 26)
(define NSOtherMouseDragged 27)
(define NSEventTypeGesture 29)
(define NSEventTypeMagnify 30)
(define NSEventTypeSwipe 31)
(define NSEventTypeRotate 18)
(define NSEventTypeBeginGesture 19)
(define NSEventTypeEndGesture 20)
(define MouseAndKeyEventMask
(bitwise-ior
(1 . << . NSLeftMouseDown)
(1 . << . NSLeftMouseUp)
(1 . << . NSRightMouseDown)
(1 . << . NSRightMouseUp)
(1 . << . NSMouseMoved)
(1 . << . NSLeftMouseDragged)
(1 . << . NSRightMouseDragged)
(1 . << . NSMouseEntered)
(1 . << . NSMouseExited)
(1 . << . NSKeyDown)
(1 . << . NSKeyUp)
(1 . << . NSScrollWheel)
(1 . << . NSTabletPoint)
(1 . << . NSTabletProximity)
(1 . << . NSOtherMouseDown)
(1 . << . NSOtherMouseUp)
(1 . << . NSOtherMouseDragged)
(1 . << . NSEventTypeGesture)
(1 . << . NSEventTypeMagnify)
(1 . << . NSEventTypeSwipe)
(1 . << . NSEventTypeRotate)
(1 . << . NSEventTypeBeginGesture)
(1 . << . NSEventTypeEndGesture)))
(define NSAlphaShiftKeyMask (1 . << . 16))
(define NSShiftKeyMask (1 . << . 17))
(define NSControlKeyMask (1 . << . 18))
(define NSAlternateKeyMask (1 . << . 19))
(define NSCommandKeyMask (1 . << . 20))
(define NSNumericPadKeyMask (1 . << . 21))
(define NSHelpKeyMask (1 . << . 22))
(define NSFunctionKeyMask (1 . << . 23))
(define NSScrollerNoPart 0)
(define NSScrollerDecrementPage 1)
(define NSScrollerKnob 2)
(define NSScrollerIncrementPage 3)
(define NSScrollerDecrementLine 4)
(define NSScrollerIncrementLine 5)
(define NSScrollerKnobSlot 6)
(define NSMomentaryLightButton 0)
(define NSPushOnPushOffButton 1)
(define NSToggleButton 2)
(define NSSwitchButton 3)
(define NSRadioButton 4)
(define NSMomentaryChangeButton 5)
(define NSOnOffButton 6)
(define NSMomentaryPushInButton 7)
(define NSMomentaryPushButton 0)
(define NSMomentaryLight 7)
(define NSFocusRingTypeDefault 0)
(define NSFocusRingTypeNone 1)
(define NSFocusRingTypeExterior 2)
(define kCGBitmapAlphaInfoMask #x1F)
(define kCGBitmapFloatComponents (1 . << . 8))
(define kCGBitmapByteOrderMask #x7000)
(define kCGBitmapByteOrderDefault (0 . << . 12))
(define kCGBitmapByteOrder16Little (1 . << . 12))
(define kCGBitmapByteOrder32Little (2 . << . 12))
(define kCGBitmapByteOrder16Big (3 . << . 12))
(define kCGBitmapByteOrder32Big (4 . << . 12))
(define kCGImageAlphaNone 0)
(define kCGImageAlphaPremultipliedLast 1)
(define kCGImageAlphaPremultipliedFirst 2)
(define kCGImageAlphaLast 3)
(define kCGImageAlphaFirst 4)
(define kCGImageAlphaNoneSkipLast 5)
(define kCGImageAlphaNoneSkipFirst 6)
(define NSWindowCollectionBehaviorFullScreenPrimary 128)
(define NSWindowCollectionBehaviorFullScreenAuxiliary 256)
(define NSFullScreenWindowMask (1 . << . 14))
Amount of scroll to count as one step :
(define WHEEL-STEP-AMT 12.0)
| |
d038df725b5edd981af812b88af65d7459e04bbfce4df2075744f942f40183da | ssor/erlangDemos | echo_get.erl | %% Feel free to use, reuse and abuse the code in this file.
-module(echo_get).
%% API.
-export([start/0]).
%% API.
start() ->
ok = application:start(cowboy),
ok = application:start(echo_get).
| null | https://raw.githubusercontent.com/ssor/erlangDemos/632cd905be2c4f275f1c1ae15238e711d7bb9147/cowboy_examples/echo_get/src/echo_get.erl | erlang | Feel free to use, reuse and abuse the code in this file.
API.
API. |
-module(echo_get).
-export([start/0]).
start() ->
ok = application:start(cowboy),
ok = application:start(echo_get).
|
1825d3da65931f52e1fb7d63beb86740d9beac8dfc92fa48864fbb154d17f62b | alex-hhh/ActivityLog2 | validating-input-field.rkt | #lang racket/base
;; This file is part of ActivityLog2, an fitness activity tracker
Copyright ( C ) 2018 < >
;;
;; This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option )
;; any later version.
;;
;; This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
;; more details.
(require racket/class
racket/gui/base
racket/string)
(provide validating-input-field%)
;; An input field that allows validating its input and converting it to
;; different types. For example, can be used to read numbers or dates. You
;; usually want to derive a class from this, for more convenience, but the
;; class can also be used directly.
(define validating-input-field%
(class text-field%
(init-field
;; Function to validate the text input (-> text (or/c #t #f)). If the
function returns # f , the field is invalid .
validate-fn
;; Function to convert a text value into the actual data type entered
into this field ( e.g. to convert the time string " 4:00 " to 240
;; seconds).
convert-fn
;; Callback called when a new valid value is entered in the field.
[valid-value-cb #f]
;; Text to be displayed in the input field when it is empty, can be used
;; to provide hints on what valid values look like (e.g for entering
durations , the cue - text might be " hh : : ss " )
[cue-text ""]
;; allow-empty? means an empty field is valid.
[allow-empty? #t]
[label ""])
(super-new [label label])
(inherit get-field-background set-field-background get-editor)
(define (vfn data)
(let ((t (string-trim data)))
(cond ((and (not allow-empty?) (= (string-length t) 0)) ;; Not valid
#f)
(#t
(validate-fn t)))))
(define old-value #f)
(define showing-cue? #f)
(define original-value #f)
When set to # t , mark this field as invalid , regardless of the VFN
;; result, until the next edit is performed.
(define global-invalid #f)
;; The background of the field will change to `bad-bg` if the value it
;; contains is invalid.
(define good-bg (get-field-background))
(define bad-bg (make-object color% 255 120 124)) ; red
;; Text style for cue text
(define cue-fg
(let ((grey-text (new style-delta%)))
(send grey-text set-delta-foreground "gray")
grey-text))
;; Text style for normal text
(define text-fg
(let ((black-text (new style-delta%)))
(send black-text set-delta-foreground "black")
black-text))
(define (clear-cue-text)
(when showing-cue?
(let ([editor (get-editor)])
(send editor erase)
(send editor clear-undos)
(send editor change-style text-fg 'start 'end #f)
(set! showing-cue? #f))))
;; Insert the cue text if the input field is empty
(define (maybe-insert-cue-text)
(unless (or showing-cue? (> (string-length (super get-value)) 0))
(let ([editor (get-editor)])
(send editor change-style cue-fg 'start 'end #f)
(send editor insert cue-text)
(set! showing-cue? #t))))
Validate the contents and , if valid , setup a 500ms timer for the
;; valid-value-cb (unless report-valid-value? is #f). The timer is used
;; so that we don't fire a sequence of valid values when the user is
;; typing.
;;
;; Note that this is public and it allows the user to write validation
;; functions that depend on some external factors.
(define/public (validate [report-valid-value? #t])
(let* ((value (send this get-value))
(valid? (and (vfn value) (not global-invalid))))
(set-field-background (if valid? good-bg bad-bg))
(if (and report-valid-value? valid?)
(send cb-timer start 500 #t)
(send cb-timer stop))))
;; Mark this field as unconditionally invalid or valid (e.g. if the
;; contents of this field are invalid due to some external factors). If
;; FLAG is #t the field is marked invalid, if flag is #f the field is
;; maker valid or not depending on the result of the validate-fn
;;
This can be used , for example , to link two fields together , where the
value in the first field must always be " less " than the value in the
second .
(define/public (mark-valid flag)
(set! global-invalid (not flag))
(validate))
;; The user is notified of a valid value via a timer. This prevents the
;; callback to fire multiple times as the user enters the value (e.g, when
the user types " 123 " , we do n't want to fire the callback with 1 , 12 and
123 )
(define cb-timer
(new timer% [notify-callback
(lambda ()
(let ((value (send this get-value)))
(unless (equal? old-value value)
(when valid-value-cb
(valid-value-cb (convert-fn value)))
(set! old-value value))))]))
(define/override (on-focus on?)
(if on? (clear-cue-text) (maybe-insert-cue-text))
(super on-focus on?))
(define/override (on-subwindow-char receiver event)
;; Let the parent handle the on-subwindow-char, after it is finished, we
;; validate the contents.
(let ((result (super on-subwindow-char receiver event)))
(set! global-invalid #f)
(validate)
result))
(define/override (set-value v)
(clear-cue-text)
(super set-value v)
(set! original-value v)
(validate #f) ; dont report valid values for externally set data
(maybe-insert-cue-text))
(define/override (get-value)
(if showing-cue? "" (super get-value)))
(define/public (has-valid-value?)
;; NOTE: the empty value might be valid, let vfn decide
(vfn (send this get-value)))
(define/public (has-changed?)
(let ((new-value (send this get-value)))
(not (string=? new-value original-value))))
(define/public (get-converted-value)
(let ((v (send this get-value)))
(if (vfn v) (convert-fn v) #f)))
(define/public (set-cue-text text)
(set! cue-text text)
(maybe-insert-cue-text))
(validate #f)
(maybe-insert-cue-text)))
| null | https://raw.githubusercontent.com/alex-hhh/ActivityLog2/36a4bb8af45db19cea02e982e22379acb18d0c49/rkt/widgets/validating-input-field.rkt | racket | This file is part of ActivityLog2, an fitness activity tracker
This program is free software: you can redistribute it and/or modify it
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
An input field that allows validating its input and converting it to
different types. For example, can be used to read numbers or dates. You
usually want to derive a class from this, for more convenience, but the
class can also be used directly.
Function to validate the text input (-> text (or/c #t #f)). If the
Function to convert a text value into the actual data type entered
seconds).
Callback called when a new valid value is entered in the field.
Text to be displayed in the input field when it is empty, can be used
to provide hints on what valid values look like (e.g for entering
allow-empty? means an empty field is valid.
Not valid
result, until the next edit is performed.
The background of the field will change to `bad-bg` if the value it
contains is invalid.
red
Text style for cue text
Text style for normal text
Insert the cue text if the input field is empty
valid-value-cb (unless report-valid-value? is #f). The timer is used
so that we don't fire a sequence of valid values when the user is
typing.
Note that this is public and it allows the user to write validation
functions that depend on some external factors.
Mark this field as unconditionally invalid or valid (e.g. if the
contents of this field are invalid due to some external factors). If
FLAG is #t the field is marked invalid, if flag is #f the field is
maker valid or not depending on the result of the validate-fn
The user is notified of a valid value via a timer. This prevents the
callback to fire multiple times as the user enters the value (e.g, when
Let the parent handle the on-subwindow-char, after it is finished, we
validate the contents.
dont report valid values for externally set data
NOTE: the empty value might be valid, let vfn decide | #lang racket/base
Copyright ( C ) 2018 < >
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 )
(require racket/class
racket/gui/base
racket/string)
(provide validating-input-field%)
(define validating-input-field%
(class text-field%
(init-field
function returns # f , the field is invalid .
validate-fn
into this field ( e.g. to convert the time string " 4:00 " to 240
convert-fn
[valid-value-cb #f]
durations , the cue - text might be " hh : : ss " )
[cue-text ""]
[allow-empty? #t]
[label ""])
(super-new [label label])
(inherit get-field-background set-field-background get-editor)
(define (vfn data)
(let ((t (string-trim data)))
#f)
(#t
(validate-fn t)))))
(define old-value #f)
(define showing-cue? #f)
(define original-value #f)
When set to # t , mark this field as invalid , regardless of the VFN
(define global-invalid #f)
(define good-bg (get-field-background))
(define cue-fg
(let ((grey-text (new style-delta%)))
(send grey-text set-delta-foreground "gray")
grey-text))
(define text-fg
(let ((black-text (new style-delta%)))
(send black-text set-delta-foreground "black")
black-text))
(define (clear-cue-text)
(when showing-cue?
(let ([editor (get-editor)])
(send editor erase)
(send editor clear-undos)
(send editor change-style text-fg 'start 'end #f)
(set! showing-cue? #f))))
(define (maybe-insert-cue-text)
(unless (or showing-cue? (> (string-length (super get-value)) 0))
(let ([editor (get-editor)])
(send editor change-style cue-fg 'start 'end #f)
(send editor insert cue-text)
(set! showing-cue? #t))))
Validate the contents and , if valid , setup a 500ms timer for the
(define/public (validate [report-valid-value? #t])
(let* ((value (send this get-value))
(valid? (and (vfn value) (not global-invalid))))
(set-field-background (if valid? good-bg bad-bg))
(if (and report-valid-value? valid?)
(send cb-timer start 500 #t)
(send cb-timer stop))))
This can be used , for example , to link two fields together , where the
value in the first field must always be " less " than the value in the
second .
(define/public (mark-valid flag)
(set! global-invalid (not flag))
(validate))
the user types " 123 " , we do n't want to fire the callback with 1 , 12 and
123 )
(define cb-timer
(new timer% [notify-callback
(lambda ()
(let ((value (send this get-value)))
(unless (equal? old-value value)
(when valid-value-cb
(valid-value-cb (convert-fn value)))
(set! old-value value))))]))
(define/override (on-focus on?)
(if on? (clear-cue-text) (maybe-insert-cue-text))
(super on-focus on?))
(define/override (on-subwindow-char receiver event)
(let ((result (super on-subwindow-char receiver event)))
(set! global-invalid #f)
(validate)
result))
(define/override (set-value v)
(clear-cue-text)
(super set-value v)
(set! original-value v)
(maybe-insert-cue-text))
(define/override (get-value)
(if showing-cue? "" (super get-value)))
(define/public (has-valid-value?)
(vfn (send this get-value)))
(define/public (has-changed?)
(let ((new-value (send this get-value)))
(not (string=? new-value original-value))))
(define/public (get-converted-value)
(let ((v (send this get-value)))
(if (vfn v) (convert-fn v) #f)))
(define/public (set-cue-text text)
(set! cue-text text)
(maybe-insert-cue-text))
(validate #f)
(maybe-insert-cue-text)))
|
3572a12d3e0d5df7a472e1fa97344e9fe90ce19ed88712b5cefd157af5b8137b | hyperfiddle/electric | rec.cljc | (ns dustin.rec
(:require [hfdl.lang :as r :refer []]
[hyperfiddle.photon-dom :as d]
[missionary.core :as m]))
(r/def bmi 30)
(r/def weight 10)
(r/defn slider [fv min max]
(d/input {"type" "range"
"value" (f bmi)
"min" min
"max" max
:style {:width "100%"}}
(d/events "input" (map (dom/oget :target :value)))))
(r/defn bmi-component []
(let [height (r/$ slider 170 100 220)]
(r/binding [weight (r/$ slider (r/fn [bmi] (* bmi height height)) 30 150)
bmi (r/$ slider #'(/ weight (* height height)) 10 50)]
bmi)))
(def ^:dynamic bmi)
(def ^:dynamic weight)
(defn slider' [f min max]
(println (f bmi weight)))
(defn bmi-component' []
(let [height (slider 170 100 220)]
(binding [weight (slider (fn [bmi weight] (m/cp 30)) 30 150)
bmi (slider (fn [bmi weight] (m/cp 10)) 10 50)]
(binding [weight (slider (fn [bmi weight] (* bmi height height)) 30 150)
bmi (slider (fn [bmi weight] (/ weight (* height height))) 10 50)]
bmi))))
(r/defn bmi-component []
(let [height (r/$ slider 170 100 220)]
(r/rec [weight (r/$ slider #'(* bmi height height) 30 150)
bmi (r/$ slider #'(/ weight (* height height)) 10 50)]
bmi))) | null | https://raw.githubusercontent.com/hyperfiddle/electric/1c6c3891cbf13123fef8d33e6555d300f0dac134/scratch/dustin/y2021/photon/rec.cljc | clojure | (ns dustin.rec
(:require [hfdl.lang :as r :refer []]
[hyperfiddle.photon-dom :as d]
[missionary.core :as m]))
(r/def bmi 30)
(r/def weight 10)
(r/defn slider [fv min max]
(d/input {"type" "range"
"value" (f bmi)
"min" min
"max" max
:style {:width "100%"}}
(d/events "input" (map (dom/oget :target :value)))))
(r/defn bmi-component []
(let [height (r/$ slider 170 100 220)]
(r/binding [weight (r/$ slider (r/fn [bmi] (* bmi height height)) 30 150)
bmi (r/$ slider #'(/ weight (* height height)) 10 50)]
bmi)))
(def ^:dynamic bmi)
(def ^:dynamic weight)
(defn slider' [f min max]
(println (f bmi weight)))
(defn bmi-component' []
(let [height (slider 170 100 220)]
(binding [weight (slider (fn [bmi weight] (m/cp 30)) 30 150)
bmi (slider (fn [bmi weight] (m/cp 10)) 10 50)]
(binding [weight (slider (fn [bmi weight] (* bmi height height)) 30 150)
bmi (slider (fn [bmi weight] (/ weight (* height height))) 10 50)]
bmi))))
(r/defn bmi-component []
(let [height (r/$ slider 170 100 220)]
(r/rec [weight (r/$ slider #'(* bmi height height) 30 150)
bmi (r/$ slider #'(/ weight (* height height)) 10 50)]
bmi))) | |
3632c09739c9cac554f297e6aa823c54f98a3ab5ca32442fff23e0ce59543f53 | JunSuzukiJapan/cl-reex | where-test.lisp | (defpackage where-test
(:use :cl
:cl-reex
:cl-reex-test.logger
:prove)
(:shadowing-import-from :cl-reex :skip) )
(in-package :where-test)
NOTE : To run this test file , execute ` ( asdf : test - system : cl - reex ) ' in your Lisp .
(plan 1)
;; blah blah blah.
(defparameter logger (make-instance 'logger))
(defparameter observer (make-observer
(on-next (x) (add logger x))
(on-error (x) (add logger (format nil "error: ~A" x)))
(on-completed () (add logger "completed")) ))
(with-observable (observable-from '(1 2 3 4 5 6 7 8 9 10))
(where (x) (evenp x))
(subscribe observer)
(dispose) )
(is (result logger)
'(2 4 6 8 10 "completed") )
(finalize)
| null | https://raw.githubusercontent.com/JunSuzukiJapan/cl-reex/94928c7949c235b41902138d9e4a5654b92d67eb/tests/where-test.lisp | lisp | blah blah blah. | (defpackage where-test
(:use :cl
:cl-reex
:cl-reex-test.logger
:prove)
(:shadowing-import-from :cl-reex :skip) )
(in-package :where-test)
NOTE : To run this test file , execute ` ( asdf : test - system : cl - reex ) ' in your Lisp .
(plan 1)
(defparameter logger (make-instance 'logger))
(defparameter observer (make-observer
(on-next (x) (add logger x))
(on-error (x) (add logger (format nil "error: ~A" x)))
(on-completed () (add logger "completed")) ))
(with-observable (observable-from '(1 2 3 4 5 6 7 8 9 10))
(where (x) (evenp x))
(subscribe observer)
(dispose) )
(is (result logger)
'(2 4 6 8 10 "completed") )
(finalize)
|
56cf33f5a6ad74a77f2c4c9d5cd1af75965beabc6c126f1d82a394cd83196244 | hiroshi-unno/coar | baParser.ml | open Core
open CSyntax
open Common.Util.LexingHelper
exception Err of string
let parse_from_lexbuf lexbuf =
try
let graph = BaParsing.toplevel BaLexer.main lexbuf in
let strid_to_intid_buf = Hashtbl.Poly.create ~size:123456 () in
let initial_state = ref (-1) in
let final_states = ref [] in
let states = ref 0 in
let register strid =
let intid = !states in
states := !states + 1;
if String.is_prefix strid ~prefix:"accept_" then
final_states := intid :: !final_states;
if String.is_suffix strid ~suffix:"_init" then (
if !initial_state >= 0 then
raise (Err "initial state is anbiguous");
initial_state := intid
);
Hashtbl.Poly.add_exn strid_to_intid_buf ~key:strid ~data:intid
in
let strid_to_intid strid =
if not (Hashtbl.Poly.mem strid_to_intid_buf strid) then
register strid;
Hashtbl.find_exn strid_to_intid_buf strid
in
let transition =
List.map
~f:(fun (from_strid, to_strid, cond) ->
strid_to_intid from_strid, strid_to_intid to_strid, cond
)
graph
in
if !initial_state < 0 then
raise (Err "can't find an initial state");
Ok (BuchiAutomaton.init_ba ~states:!states ~initial_state:!initial_state ~final_states:!final_states ~transition)
with
| CSyntax.SemanticError error ->
Error (Printf.sprintf "semantic error: %s" error)
| CSyntax.SyntaxError error ->
Error (Printf.sprintf "%s: syntax error: %s" (get_position_string lexbuf) error)
| BaParsing.Error ->
Error (Printf.sprintf "%s: syntax error" (get_position_string lexbuf))
| BaLexer.ErrorFormatted error ->
Error error
| BaLexer.SyntaxError error ->
Error (Printf.sprintf "%s: syntax error: %s" (get_position_string lexbuf) error)
| Err error ->
Error error
let from_file file =
file
|> In_channel.create
|> Lexing.from_channel
|> parse_from_lexbuf
let parse str =
str
|> Lexing.from_string
|> parse_from_lexbuf
| null | https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/c/baParser.ml | ocaml | open Core
open CSyntax
open Common.Util.LexingHelper
exception Err of string
let parse_from_lexbuf lexbuf =
try
let graph = BaParsing.toplevel BaLexer.main lexbuf in
let strid_to_intid_buf = Hashtbl.Poly.create ~size:123456 () in
let initial_state = ref (-1) in
let final_states = ref [] in
let states = ref 0 in
let register strid =
let intid = !states in
states := !states + 1;
if String.is_prefix strid ~prefix:"accept_" then
final_states := intid :: !final_states;
if String.is_suffix strid ~suffix:"_init" then (
if !initial_state >= 0 then
raise (Err "initial state is anbiguous");
initial_state := intid
);
Hashtbl.Poly.add_exn strid_to_intid_buf ~key:strid ~data:intid
in
let strid_to_intid strid =
if not (Hashtbl.Poly.mem strid_to_intid_buf strid) then
register strid;
Hashtbl.find_exn strid_to_intid_buf strid
in
let transition =
List.map
~f:(fun (from_strid, to_strid, cond) ->
strid_to_intid from_strid, strid_to_intid to_strid, cond
)
graph
in
if !initial_state < 0 then
raise (Err "can't find an initial state");
Ok (BuchiAutomaton.init_ba ~states:!states ~initial_state:!initial_state ~final_states:!final_states ~transition)
with
| CSyntax.SemanticError error ->
Error (Printf.sprintf "semantic error: %s" error)
| CSyntax.SyntaxError error ->
Error (Printf.sprintf "%s: syntax error: %s" (get_position_string lexbuf) error)
| BaParsing.Error ->
Error (Printf.sprintf "%s: syntax error" (get_position_string lexbuf))
| BaLexer.ErrorFormatted error ->
Error error
| BaLexer.SyntaxError error ->
Error (Printf.sprintf "%s: syntax error: %s" (get_position_string lexbuf) error)
| Err error ->
Error error
let from_file file =
file
|> In_channel.create
|> Lexing.from_channel
|> parse_from_lexbuf
let parse str =
str
|> Lexing.from_string
|> parse_from_lexbuf
| |
c99485bcfbf740a2b578343e1b36e521a3ce49b6dc395befdff602e5ccf58e61 | crategus/cl-cffi-gtk | gtk.table.lisp | ;;; ----------------------------------------------------------------------------
;;; gtk.table.lisp
;;;
;;; The documentation of this file is taken from the GTK 3 Reference Manual
Version 3.24 and modified to document the Lisp binding to the GTK library .
;;; See <>. The API documentation of the Lisp binding is
available from < -cffi-gtk/ > .
;;;
Copyright ( C ) 2009 - 2011
Copyright ( C ) 2011 - 2021
;;;
;;; This program is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Lesser General Public License for Lisp
as published by the Free Software Foundation , either version 3 of the
;;; License, or (at your option) any later version and with a preamble to
the GNU Lesser General Public License that clarifies the terms for use
;;; with Lisp programs and is referred as the LLGPL.
;;;
;;; 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 and the preamble to the Gnu Lesser
;;; General Public License. If not, see </>
;;; and <>.
;;; ----------------------------------------------------------------------------
;;;
GtkTable
;;;
;;; Pack widgets in regular patterns
;;;
;;; Types and Values
;;;
GtkTable
;;; GtkAttachOptions
;;;
;;; Functions
;;;
;;; gtk_table_new
;;; gtk_table_resize
;;; gtk_table_get_size
;;; gtk_table_attach
;;; gtk_table_attach_defaults
;;; gtk_table_set_row_spacing
;;; gtk_table_set_col_spacing
;;; gtk_table_set_row_spacings
;;; gtk_table_set_col_spacings
;;; gtk_table_set_homogeneous
;;; gtk_table_get_default_row_spacing
;;; gtk_table_get_homogeneous
;;; gtk_table_get_row_spacing
;;; gtk_table_get_col_spacing
;;; gtk_table_get_default_col_spacing
;;;
;;; Properties
;;;
guint column - spacing Read / Write
;;; gboolean homogeneous Read / Write
guint n - columns Read / Write
guint n - rows Read / Write
guint row - spacing Read / Write
;;;
;;; Child Properties
;;;
guint bottom - attach Read / Write
guint left - attach Read / Write
guint right - attach Read / Write
guint top - attach Read / Write
;;; GtkAttachOptions x-options Read / Write
guint x - padding Read / Write
;;; GtkAttachOptions y-options Read / Write
guint y - padding Read / Write
;;;
;;; Object Hierarchy
;;;
;;; GObject
;;; ╰── GInitiallyUnowned
╰ ─ ─
╰ ─ ─ GtkContainer
╰ ─ ─
;;;
;;; Implemented Interfaces
;;;
GtkTable implements AtkImplementorIface and GtkBuildable .
;;; ----------------------------------------------------------------------------
(in-package :gtk)
;;; ----------------------------------------------------------------------------
;;; enum GtkAttachOptions
;;; ----------------------------------------------------------------------------
(define-g-flags "GtkAttachOptions" gtk-attach-options
(:export t
:type-initializer "gtk_attach_options_get_type")
(:expand 1)
(:shrink 2)
(:fill 4))
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-attach-options atdoc:*symbol-name-alias*)
"GFlags"
(gethash 'gtk-attach-options atdoc:*external-symbols*)
"@version{2021-5-26}
@begin{short}
Denotes the expansion properties that a widget will have in a
@class{gtk-table} widget when it or its parent is resized.
@end{short}
@begin{pre}
(define-g-flags \"GtkAttachOptions\" gtk-attach-options
(:export t
:type-initializer \"gtk_attach_options_get_type\")
(:expand 1)
(:shrink 2)
(:fill 4))
@end{pre}
@begin[code]{table}
@entry[:expand]{The widget should expand to take up any extra space in its
container that has been allocated.}
@entry[:shrink]{The widget should shrink as and when possible.}
@entry[:fill]{The widget should fill the space allocated to it.}
@end{table}
@see-class{gtk-table}")
;;; ----------------------------------------------------------------------------
struct GtkTable
;;; ----------------------------------------------------------------------------
(define-g-object-class "GtkTable" gtk-table
(:superclass gtk-container
:export t
:interfaces ("AtkImplementorIface"
"GtkBuildable")
:type-initializer "gtk_table_get_type")
((column-spacing
gtk-table-column-spacing
"column-spacing" "guint" t t)
(homogeneous
gtk-table-homogeneous
"homogeneous" "gboolean" t t)
(n-columns
gtk-table-n-columns
"n-columns" "guint" t t)
(n-rows
gtk-table-n-rows
"n-rows" "guint" t t)
(row-spacing
gtk-table-row-spacing
"row-spacing" "guint" t t)))
#+cl-cffi-gtk-documentation
(setf (documentation 'gtk-table 'type)
"@version{*2021-7-20}
@begin{short}
The @sym{gtk-table} widget allows the programmer to arrange widgets in
rows and columns, making it easy to align many widgets next to each other,
horizontally and vertically.
@end{short}
Tables are created with a call to the function @fun{gtk-table-new}, the size
of which can later be changed with the function @fun{gtk-table-resize}.
Widgets can be added to a table using the function @fun{gtk-table-attach}.
To alter the space next to a specific row, use the function
@fun{gtk-table-set-row-spacing}, and for a column the function
@fun{gtk-table-set-col-spacing}. The gaps between all rows or columns can be
changed by calling the functions @fun{gtk-table-row-spacing} or
@fun{gtk-table-column-spacing} respectively. Note that spacing is added
between the children, while padding added by the function
@fun{gtk-table-attach} is added on either side of the widget it belongs to.
The function @fun{gtk-table-homogeneous} can be used to set whether all
cells in the table will resize themselves to the size of the largest widget
in the table.
@begin[Warning]{dictionary}
The @sym{gtk-table} widget has been deprecated since GTK 3.4. Use the
@class{gtk-grid} widget instead. It provides the same capabilities as the
@sym{gtk-table} widget for arranging widgets in a rectangular grid, but
does support height-for-width geometry management.
@end{dictionary}
@begin[Child Property Details]{dictionary}
@begin[code]{table}
@begin[bottom-attach]{entry}
The @code{bottom-attach} child property of type @code{:uint}
(Read / Write) @br{}
The row number to attach the bottom of the child widget to. @br{}
Allowed values: [1,65535] @br{}
Default value: 1
@end{entry}
@begin[left-attach]{entry}
The @code{left-attach} child property of type @code{:uint}
(Read / Write) @br{}
The column number to attach the left side of the child widget to. @br{}
Allowed values: <= 65535 @br{}
Default value: 0
@end{entry}
@begin[right-attach]{entry}
The @code{right-attach} child property of type @code{:uint}
(Read / Write) @br{}
The column number to attach the right side of a child widget to. @br{}
Allowed values: [1,65535] @br{}
Default value: 1
@end{entry}
@begin[top-attach]{entry}
The @code{top-attach} child property of type @code{:uint}
(Read / Write) @br{}
The row number to attach the top of a child widget to. @br{}
Allowed values: <= 65535 @br{}
Default value: 0
@end{entry}
@begin[x-options]{entry}
The @code{x-options} child property of type @symbol{gtk-attach-options}
(Read / Write) @br{}
Options specifying the horizontal behaviour of the child widget. @br{}
Default value: @code{'(:expand :fill)}
@end{entry}
@begin[x-padding]{entry}
The @code{x-padding} child property of type @code{:uint}
(Read / Write) @br{}
Extra space to put between the child widget and its left and right
neighbors, in pixels. @br{}
Allowed values: <= 65535 @br{}
Default value: 0
@end{entry}
@begin[y-options]{entry}
The @code{y-options} child property of type @symbol{gtk-attach-options}
(Read / Write) @br{}
Options specifying the vertical behaviour of the child widget. @br{}
Default value: @code{'(:expand :fill)}
@end{entry}
@begin[y-padding]{entry}
The @code{y-padding} child property of type @code{:uint}
(Read / Write) @br{}
Extra space to put between the child widget and its upper and lower
neighbors, in pixels. @br{}
Allowed values: <= 65535 @br{}
Default value: 0
@end{entry}
@end{table}
@end{dictionary}
@see-slot{gtk-table-column-spacing}
@see-slot{gtk-table-homogeneous}
@see-slot{gtk-table-n-columns}
@see-slot{gtk-table-n-rows}
@see-slot{gtk-table-row-spacing}
@see-class{gtk-grid}")
;;; ----------------------------------------------------------------------------
;;; Property and Accessor Details
;;; ----------------------------------------------------------------------------
;;; --- gtk-table-column-spacing -----------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "column-spacing" 'gtk-table) 't)
"The @code{column-spacing} property of type @code{:uint}
(Read / Write) @br{}
The amount of space between two consecutive columns. @br{}
Allowed values: <= 65535 @br{}
Default value: 0")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-column-spacing atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-column-spacing 'function)
"@version{*2021-7-20}
@syntax[]{(gtk-table-column-spacing object) => spacing}
@syntax[]{(setf (gtk-table-column-spacing object) spacing)}
@argument[table]{a @class{gtk-table} widget}
@argument[spacing]{an unsigned integer with the number of pixels of space to
place between every column in the table}
@begin{short}
Accessor of the @slot[gtk-table]{column-spacing} property of the
@class{gtk-table} class.
@end{short}
The slot access function @sym{gtk-table-column-spacing} gets the default
column spacing for the table. The slot access function
@sym{(setf gtk-table-column-spacing)} sets the column spacing. This is the
spacing that will be used for newly added columns.
@begin[Lisp implementation]{dictionary}
The C library has the functions @code{gtk_table_get_default_col_spacing ()}
and @code{gtk_table_set_col_spacings ()}, which correspond to the
slot access function @sym{gtk-table-column-spacing}. These C functions are
not implemented in the Lisp library.
@end{dictionary}
@begin[Warning]{dictionary}
The function @sym{gtk-table-column-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget with the function @fun{gtk-grid-column-spacing}.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-grid-column-spacing}")
;;; --- gtk-table-homogeneous -------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "homogeneous" 'gtk-table) 't)
"The @code{homogeneous} property of type @code{:boolean}
(Read / Write) @br{}
If @em{true}, the table cells are all the same width/height. @br{}
Default value: @em{false}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-homogeneous atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-homogeneous 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-homogeneous object) => homogeneous}
@syntax[]{(setf (gtk-table-homogeneous object) homogeneous)}
@argument[object]{a @class{gtk-table} widget}
@argument[homogeneous]{set to @em{true} to ensure all table cells are the
same size, set to @em{false} if this is not the desired behaviour}
@begin{short}
Accessor of the @slot[gtk-table]{homogeneous} slot of the
@class{gtk-table} class.
@end{short}
The slot access function @sym{gtk-table-homogeneous} returns whether the
table cells are all constrained to the same width and height. The slot access
function @sym{(setf gtk-table-homogeneous)} changes the
@slot[gtk-table]{homogeneous} property.
@begin[Warning]{dictionary}
The function @sym{gtk-table-homogeneous} has been deprecated since version
3.4 and should not be used in newly written code. Use the @class{gtk-grid}
widget with the functions @fun{gtk-grid-row-homogeneous} and
@fun{gtk-grid-column-homogeneous}.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-grid-column-homogeneous}
@see-function{gtk-grid-row-homogeneous}")
;;; --- gtk-table-n-columns ----------------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "n-columns" 'gtk-table) 't)
"The @code{n-columns} property of type @code{:uint} (Read / Write) @br{}
The number of columns in the table. @br{}
Allowed values: [1,65535] @br{}
Default value: 1")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-n-columns atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-n-columns 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-n-columns object) => n-columns}
@syntax[]{(setf (gtk-table-n-columns object) n-columns)}
@argument[object]{a @class{gtk-table} widget}
@argument[n-columns]{an unsigned integer with the number of columns}
@begin{short}
Accessor of the @slot[gtk-table]{n-columns} slot of the @class{gtk-table}
class.
@end{short}
The number of columns in the table.
@begin[Warning]{dictionary}
The function @sym{gtk-table-n-columns} has been deprecated since version
3.4 and should not be used in newly written code. Use the @class{gtk-grid}
widget which does not expose the number of columns and rows.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}")
;;; --- gtk-table-n-rows -------------------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "n-rows" 'gtk-table) 't)
"The @code{n-rows} property of type @code{:uint} (Read / Write) @br{}
The number of rows in the table. @br{}
Allowed values: [1,65535] @br{}
Default value: 1")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-n-rows atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-n-rows 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-n-rows object) => n-rows}
@syntax[]{(setf (gtk-table-n-rows object) n-rows)}
@argument[object]{a @class{gtk-table} widget}
@argument[n-rows]{an unsigned integer with the number of rows}
@begin{short}
Accessor of the @slot[gtk-table]{n-rows} slot of the @class{gtk-table}
class.
@end{short}
The number of rows in the table.
@begin[Warning]{dictionary}
The function @sym{gtk-table-n-rows} has been deprecated since version 3.4
and should not be used in newly written code. Use the @class{gtk-grid}
widget which does not expose the number of columns and rows.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}")
;;; --- gtk-table-row-spacing --------------------------------------------------
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "row-spacing" 'gtk-table) 't)
"The @code{row-spacing} property of type @code{:uint} (Read / Write) @br{}
The amount of space between two consecutive rows. @br{}
Allowed values: <= 65535 @br{}
Default value: 0")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-row-spacing atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-row-spacing 'function)
"@version{*2021-7-20}
@syntax[]{(gtk-table-row-spacing object) => spacing}
@syntax[]{(setf (gtk-table-row-spacing object) spacing)}
@argument[table]{a @class{gtk-table} widget}
@argument[spacing]{an unsigned integer with the number of pixels of space to
place between every row in the table}
@begin{short}
Accessor of the @slot[gtk-table]{row-spacing} slot of the
@class{gtk-table} class.
@end{short}
The slot access function @sym{gtk-table-row-spacing} gets the default row
spacing for the table. The slot access function @sym{gtk-table-row-spacing}
sets the row spacing. This is the spacing that will be used for newly added
rows.
@begin[Lisp implementation]{dictionary}
The C library has the functions @code{gtk_table_get_default_row_spacing ()}
and @code{gtk_table_set_row_spacings ()}, which correspond to the
slot access function @sym{gtk-table-row-spacing}. These C functions are not
implemented in the Lisp library.
@end{dictionary}
@begin[Warning]{dictionary}
The function @sym{gtk-table-row-spacing} has been deprecated since version
3.4 and should not be used in newly written code. Use the @class{gtk-grid}
widget with the function @fun{gtk-grid-row-spacing}.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-grid-row-spacing}")
;;; ----------------------------------------------------------------------------
Accessors of Child Properties
;;; ----------------------------------------------------------------------------
(eval-when (:compile-toplevel :load-toplevel :execute)
(register-object-type "GtkTable" 'gtk-table))
;;; --- gtk-table-child-bottom-attach ------------------------------------------
(define-child-property "GtkTable"
gtk-table-child-bottom-attach
"bottom-attach" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-bottom-attach atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-bottom-attach 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-bottom-attach container child) => attach}
@syntax[]{(setf (gtk-table-child-bottom-attach container child) attach)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[attach]{an unsigned integer with the row number to attach the
bottom of the child widget to}
@begin{short}
Accessor of the @code{bottom-attach} child property of the
@class{gtk-table} class.
@end{short}
The row number to attach the bottom of the child widget to.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-bottom-attach} has been deprecated since
version 3.4. and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
;;; --- gtk-table-child-left-attach --------------------------------------------
(define-child-property "GtkTable"
gtk-table-child-left-attach
"left-attach" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-left-attach atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-left-attach 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-left-attach container child) => attach}
@syntax[]{(setf (gtk-table-child-left-attach container child) attach)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[attach]{an unsigned integer with the column number to attach the
left side of the child widget to}
@begin{short}
Accessor of the @code{left-attach} child property of the @class{gtk-table}
class.
@end{short}
The column number to attach the left side of the child widget to.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-left-attach} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
;;; --- gtk-table-child-right-attach -------------------------------------------
(define-child-property "GtkTable"
gtk-table-child-right-attach
"right-attach" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-right-attach atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-right-attach 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-right-attach container child) => attach}
@syntax[]{(setf (gtk-table-child-right-attach container child) attach)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[attach]{an unsigned integer with the column number to attach the
right side of the child widget to}
@begin{short}
Accessor of the @code{right-attach} child property of the @class{gtk-table}
class.
@end{short}
The column number to attach the right side of the child widget to.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-right-attach} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
;;; --- gtk-table-child-top-attach ---------------------------------------------
(define-child-property "GtkTable"
gtk-table-child-top-attach
"top-attach" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-top-attach atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-top-attach 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-top-attach container child) => attach}
@syntax[]{(setf (gtk-table-child-top-attach container child) attach)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[attach]{an unsigned integer with the row number to attach the top
of the child widget to}
@begin{short}
Accessor of the @code{top-attach} child property of the @class{gtk-table}
class.
@end{short}
The row number to attach the top of the child widget to.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-top-attach} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
;;; --- gtk-table-child-x-options ----------------------------------------------
(define-child-property "GtkTable"
gtk-table-child-x-options
"x-options" "GtkAttachOptions" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-x-options atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-x-options 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-x-options container child) => options}
@syntax[]{(setf (gtk-table-child-x-options container child) options)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[options]{the @symbol{gtk-attach-options} flags}
@begin{short}
Accessor of the @code{x-options} child property of the @class{gtk-table}
class.
@end{short}
Options specifying the horizontal behaviour of the child widget.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-x-options} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}
@see-symbol{gtk-attach-options}")
;;; --- gtk-table-child-y-options ----------------------------------------------
(define-child-property "GtkTable"
gtk-table-child-y-options
"y-options" "GtkAttachOptions" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-y-options atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-y-options 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-y-options container child) => options}
@syntax[]{(setf (gtk-table-child-y-options container child) options)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[options]{the @symbol{gtk-attach-options} flags}
@begin{short}
Accessor of the @code{y-options} child property of the @class{gtk-table}
class.
@end{short}
Options specifying the vertical behaviour of the child widget.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-y-options} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}
@see-symbol{gtk-attach-options}")
;;; --- gtk-table-child-x-padding ----------------------------------------------
(define-child-property "GtkTable"
gtk-table-child-x-padding
"x-padding" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-x-padding atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-x-padding 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-x-padding container child) => padding}
@syntax[]{(setf (gtk-table-child-x-padding container child) padding)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[padding]{an unsigned integer with the space to put between the
child widget and its neighbors}
@begin{short}
Accessor of the @code{x-padding} child property of the @class{gtk-table}
class.
@end{short}
Extra space to put between the child widget and its left and right neighbors,
in pixels.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-x-padding} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
;;; --- gtk-table-child-y-padding ----------------------------------------------
(define-child-property "GtkTable"
gtk-table-child-y-padding
"y-padding" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-y-padding atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-y-padding 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-y-padding container child) => padding}
@syntax[]{(setf (gtk-table-child-y-padding container child) padding)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[padding]{an unsigned integer with the space to put between the
child widget and its neighbors}
@begin{short}
Accessor of the @code{y-padding} child property of the @class{gtk-table}
class.
@end{short}
Extra space to put between the child widget and its upper and lower
neighbors, in pixels.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-y-padding} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
;;; ----------------------------------------------------------------------------
;;; gtk_table_new ()
;;; ----------------------------------------------------------------------------
(declaim (inline gtk-table-new))
(defun gtk-table-new (rows columns homogeneous)
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[rows]{an unsigned integer with the number of rows the new table
should have}
@argument[columns]{an unsigned integer with the number of columns the new
table should have}
@argument[homogeneous]{if set to @em{true}, all table cells are resized to
the size of the cell containing the largest widget}
@return{The the newly created @class{gtk-table} widget.}
@begin{short}
Used to create a new table.
@end{short}
An initial size must be given by specifying how many rows and columns the
table should have, although this can be changed later with the function
@fun{gtk-table-resize}. The arguments @arg{rows} and @arg{columns} must both
be in the range 1 ... 65535. For historical reasons, 0 is accepted as well
and is silently interpreted as 1.
@begin[Warning]{dictionary}
The function @sym{gtk-table-new} has been deprecated since version 3.4 and
should not be used in newly written code. Use the @class{gtk-grid} widget
with the function @fun{gtk-grid-new}.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-table-resize}
@see-function{gtk-grid-new}"
(make-instance 'gtk-table
:rows rows
:columns columns
:homogeneous homogeneous))
(export 'gtk-table-new)
;;; ----------------------------------------------------------------------------
gtk_table_resize ( )
;;; ----------------------------------------------------------------------------
(declaim (inline gtk-table-resize))
(defun gtk-table-resize (table rows columns)
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{the @class{gtk-table} widget you wish to change the size of}
@argument[rows]{an unsigned integer with the new number of rows}
@argument[columns]{an unsigned integer with the new number of columns}
@begin{short}
If you need to change the size of the table after it has been created, this
function allows you to do so.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-resize} has been deprecated since version 3.4
and should not be used in newly written code. Use the @class{gtk-grid}
widget which resizes automatically.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}"
(setf (gtk-table-n-rows table) rows
(gtk-table-n-columns table) columns))
(export 'gtk-table-resize)
;;; ----------------------------------------------------------------------------
;;; gtk_table_get_size () -> gtk-table-size
;;; ----------------------------------------------------------------------------
(defun gtk-table-size (table)
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget}
@begin{return}
@code{n-rows} -- an unsigned integer with the number of rows @br{}
@code{n-columns} -- an unsigned integer with the number of columns
@end{return}
@short{Gets the number of rows and columns in the table.}
@begin[Warning]{dictionary}
The function @sym{gtk-table-size} has been deprecated since version 3.4
and should not be used in newly written code. Use the @class{gtk-grid}
widget which does not expose the number of columns and rows.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}"
(values (gtk-table-n-rows table)
(gtk-table-n-columns table)))
(export 'gtk-table-size)
;;; ----------------------------------------------------------------------------
;;; gtk_table_attach ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_table_attach" %gtk-table-attach) :void
(table (g-object gtk-table))
(child (g-object gtk-widget))
(left :uint)
(right :uint)
(top :uint)
(bottom :uint)
(x-options gtk-attach-options)
(y-options gtk-attach-options)
(x-padding :uint)
(y-padding :uint))
(defun gtk-table-attach (table child left right top bottom
&key (x-options '(:expand :fill))
(y-options '(:expand :fill))
(x-padding 0)
(y-padding 0))
#+cl-cffi-gtk-documentation
"@version{*2021-7-20}
@argument[table]{the @class{gtk-table} widget to add a new widget to}
@argument[child]{the @class{gtk-widget} child widget to add}
@argument[left]{an unsigned integer with the column number to attach the left
side of a child widget to}
@argument[right]{an unsigned integer with the column number to attach the
right side of a child widget to}
@argument[top]{an unsigned ineger with the row number to attach the top of a
child widget to}
@argument[bottom]{an unsigned integer with the row number to attach the bottom
of a child widget to}
@argument[x-options]{the @symbol{gtk-attach-options} flags used to specify the
properties of the child widget when the table is resized}
@argument[y-options]{the same as @arg{x-options}, except this field
determines behaviour of vertical resizing}
@argument[x-padding]{an unsigned integer specifying the padding on the left
and right of the child widget being added to the table}
@argument[y-padding]{an unsigned integer with the amount of padding above and
below the child widget}
@begin{short}
Adds a child widget to a table.
@end{short}
The number of cells that a child widget will occupy is specified by the
arguments @arg{left}, @arg{right}, @arg{top} and @arg{bottom}. These each
represent the leftmost, rightmost, uppermost and lowest column and row
numbers of the table. Columns and rows are indexed from zero.
The keyword arguments @code{x-options} and @code{y-options} have the default
value @code{'(:expand :fill)}. The keyword arguments @code{x-padding} and
@code{y-padding} have the default value 0.
@begin[Example]{dictionary}
To make a button occupy the lower right cell of a 2 x 2 table, use
@begin{pre}
(gtk-table-attach table button 1 2 1 2)
@end{pre}
If you want to make the button span the entire bottom row, use
@begin{pre}
(gtk-table-attach table button 0 2 1 2)
@end{pre}
@end{dictionary}
@begin[Lisp implementation]{dictionary}
The C library has the function @code{gtk_table_attach_default ()}. This
function is included in the Lisp library via keyword arguments with default
values for the function @sym{gtk-table-attach}.
@end{dictionary}
@begin[Warning]{dictionary}
The function @sym{gtk-table-attach} has been deprecated since version 3.4
and should not be used in newly written code. Use the @class{gtk-grid}
widget with the function @fun{gtk-grid-attach}. Note that the attach
arguments differ between those two functions.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-symbol{gtk-attach-options}
@see-function{gtk-grid-attach}"
(%gtk-table-attach table child
left right top bottom
x-options y-options
x-padding y-padding))
(export 'gtk-table-attach)
;;; ----------------------------------------------------------------------------
;;; gtk_table_attach_defaults () not exported
;;; ----------------------------------------------------------------------------
(defun gtk-table-attach-defaults (table child left right top bottom)
#+cl-cffi-gtk-documentation
"@version{2020-1-20}
@argument[table]{the table to add a new child widget to}
@argument[widget]{the child widget to add}
@argument[left-attach]{the column number to attach the left side of the child
widget to}
@argument[right-attach]{the column number to attach the right side of the
child widget to}
@argument[top-attach]{the row number to attach the top of the child widget
to}
@argument[bottom-attach]{the row number to attach the bottom of the child
widget to}
@begin{short}
As there are many options associated with the function
@fun{gtk-table-attach}, this convenience function provides the programmer
with a means to add children to a table with identical padding and
expansion options.
@end{short}
The values used for the @symbol{gtk-attach-options} are
@code{'(:expand :fill)}, and the padding is set to 0.
@begin[Warning]{dictionary}
The function @sym{gtk-table-attach-defaults} has been deprecated since
version 3.4 and should not be used in newly written code. Use the function
@fun{gtk-grid-attach} with @class{gtk-grid}. Note that the attach arguments
differ between those two functions.
@end{dictionary}
@see-class{gtk-table}"
(gtk-table-attach table child left right top bottom))
;;; ----------------------------------------------------------------------------
;;; gtk_table_set_row_spacing ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_table_set_row_spacing" gtk-table-set-row-spacing) :void
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget containing the row whose
properties you wish to change}
@argument[row]{an unsigned integer with the row number whose spacing will be
changed}
@argument[spacing]{an unsigned integer with the number of pixels that the
spacing should take up}
@begin{short}
Changes the space between a given table row and the subsequent row.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-set-row-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. Use the functions
@fun{gtk-widget-margin-top} and @fun{gtk-widget-margin-bottom} on the
widgets contained in the row if you need this functionality.
The @class{gtk-grid} widget does not support per-row spacing.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-widget-margin-top}
@see-function{gtk-widget-margin-bottom}"
(table (g-object gtk-table))
(row :uint)
(spacing :uint))
(export 'gtk-table-set-row-spacing)
;;; ----------------------------------------------------------------------------
;;; gtk_table_set_col_spacing ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_table_set_col_spacing" gtk-table-set-col-spacing) :void
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget}
@argument[column]{an unsigned integer with the column whose spacing should be
changed}
@argument[spacing]{an unsigned integer with the number of pixels that the
spacing should take up}
@begin{short}
Alters the amount of space between a given table column and the following
column.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-set-col-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. Use the functions
@fun{gtk-widget-margin-start} and @fun{gtk-widget-margin-end} on
the widgets contained in the row if you need this functionality.
The @class{gtk-grid} widget does not support per-column spacing.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-widget-margin-start}
@see-function{gtk-widget-margin-end}"
(table (g-object gtk-table))
(column :uint)
(spacing :uint))
(export 'gtk-table-set-col-spacing)
;;; ----------------------------------------------------------------------------
;;; gtk_table_get_row_spacing ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_table_get_row_spacing" gtk-table-get-row-spacing) :uint
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget}
@argument[row]{an unsigned integer with a row in the table, 0 indicates the
first row}
@return{An unsigned integer with the row spacing.}
@begin{short}
Gets the amount of space between @arg{row}, and @arg{row + 1}.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-get-row-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. The
@class{gtk-grid} widget does not offer a replacement for this functionality.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}"
(table (g-object gtk-table))
(row :uint))
(export 'gtk-table-get-row-spacing)
;;; ----------------------------------------------------------------------------
;;; gtk_table_get_col_spacing ()
;;; ----------------------------------------------------------------------------
(defcfun ("gtk_table_get_col_spacing" gtk-table-get-col-spacing) :uint
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget}
@argument[column]{an unsigned integer with a column in the table, 0 indicates
the first column}
@return{An unsigned integer with the column spacing.}
@begin{short}
Gets the amount of space between @arg{column}, and @arg{column + 1}.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-get-col-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. The
@class{gtk-grid} widget does not offer a replacement for this functionality.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}"
(table (g-object gtk-table))
(column :uint))
(export 'gtk-table-get-col-spacing)
;;; --- End of file gtk.table.lisp ---------------------------------------------
| null | https://raw.githubusercontent.com/crategus/cl-cffi-gtk/ba198f7d29cb06de1e8965e1b8a78522d5430516/gtk/gtk.table.lisp | lisp | ----------------------------------------------------------------------------
gtk.table.lisp
The documentation of this file is taken from the GTK 3 Reference Manual
See <>. The API documentation of the Lisp binding is
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License for Lisp
License, or (at your option) any later version and with a preamble to
with Lisp programs and is referred as the LLGPL.
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
General Public License. If not, see </>
and <>.
----------------------------------------------------------------------------
Pack widgets in regular patterns
Types and Values
GtkAttachOptions
Functions
gtk_table_new
gtk_table_resize
gtk_table_get_size
gtk_table_attach
gtk_table_attach_defaults
gtk_table_set_row_spacing
gtk_table_set_col_spacing
gtk_table_set_row_spacings
gtk_table_set_col_spacings
gtk_table_set_homogeneous
gtk_table_get_default_row_spacing
gtk_table_get_homogeneous
gtk_table_get_row_spacing
gtk_table_get_col_spacing
gtk_table_get_default_col_spacing
Properties
gboolean homogeneous Read / Write
Child Properties
GtkAttachOptions x-options Read / Write
GtkAttachOptions y-options Read / Write
Object Hierarchy
GObject
╰── GInitiallyUnowned
Implemented Interfaces
----------------------------------------------------------------------------
----------------------------------------------------------------------------
enum GtkAttachOptions
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
Property and Accessor Details
----------------------------------------------------------------------------
--- gtk-table-column-spacing -----------------------------------------------
--- gtk-table-homogeneous -------------------------------------------
--- gtk-table-n-columns ----------------------------------------------------
--- gtk-table-n-rows -------------------------------------------------------
--- gtk-table-row-spacing --------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
--- gtk-table-child-bottom-attach ------------------------------------------
--- gtk-table-child-left-attach --------------------------------------------
--- gtk-table-child-right-attach -------------------------------------------
--- gtk-table-child-top-attach ---------------------------------------------
--- gtk-table-child-x-options ----------------------------------------------
--- gtk-table-child-y-options ----------------------------------------------
--- gtk-table-child-x-padding ----------------------------------------------
--- gtk-table-child-y-padding ----------------------------------------------
----------------------------------------------------------------------------
gtk_table_new ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_table_get_size () -> gtk-table-size
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_table_attach ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_table_attach_defaults () not exported
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_table_set_row_spacing ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_table_set_col_spacing ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_table_get_row_spacing ()
----------------------------------------------------------------------------
----------------------------------------------------------------------------
gtk_table_get_col_spacing ()
----------------------------------------------------------------------------
--- End of file gtk.table.lisp --------------------------------------------- | Version 3.24 and modified to document the Lisp binding to the GTK library .
available from < -cffi-gtk/ > .
Copyright ( C ) 2009 - 2011
Copyright ( C ) 2011 - 2021
as published by the Free Software Foundation , either version 3 of the
the GNU Lesser General Public License that clarifies the terms for use
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 and the preamble to the Gnu Lesser
GtkTable
GtkTable
guint column - spacing Read / Write
guint n - columns Read / Write
guint n - rows Read / Write
guint row - spacing Read / Write
guint bottom - attach Read / Write
guint left - attach Read / Write
guint right - attach Read / Write
guint top - attach Read / Write
guint x - padding Read / Write
guint y - padding Read / Write
╰ ─ ─
╰ ─ ─ GtkContainer
╰ ─ ─
GtkTable implements AtkImplementorIface and GtkBuildable .
(in-package :gtk)
(define-g-flags "GtkAttachOptions" gtk-attach-options
(:export t
:type-initializer "gtk_attach_options_get_type")
(:expand 1)
(:shrink 2)
(:fill 4))
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-attach-options atdoc:*symbol-name-alias*)
"GFlags"
(gethash 'gtk-attach-options atdoc:*external-symbols*)
"@version{2021-5-26}
@begin{short}
Denotes the expansion properties that a widget will have in a
@class{gtk-table} widget when it or its parent is resized.
@end{short}
@begin{pre}
(define-g-flags \"GtkAttachOptions\" gtk-attach-options
(:export t
:type-initializer \"gtk_attach_options_get_type\")
(:expand 1)
(:shrink 2)
(:fill 4))
@end{pre}
@begin[code]{table}
@entry[:expand]{The widget should expand to take up any extra space in its
container that has been allocated.}
@entry[:shrink]{The widget should shrink as and when possible.}
@entry[:fill]{The widget should fill the space allocated to it.}
@end{table}
@see-class{gtk-table}")
struct GtkTable
(define-g-object-class "GtkTable" gtk-table
(:superclass gtk-container
:export t
:interfaces ("AtkImplementorIface"
"GtkBuildable")
:type-initializer "gtk_table_get_type")
((column-spacing
gtk-table-column-spacing
"column-spacing" "guint" t t)
(homogeneous
gtk-table-homogeneous
"homogeneous" "gboolean" t t)
(n-columns
gtk-table-n-columns
"n-columns" "guint" t t)
(n-rows
gtk-table-n-rows
"n-rows" "guint" t t)
(row-spacing
gtk-table-row-spacing
"row-spacing" "guint" t t)))
#+cl-cffi-gtk-documentation
(setf (documentation 'gtk-table 'type)
"@version{*2021-7-20}
@begin{short}
The @sym{gtk-table} widget allows the programmer to arrange widgets in
rows and columns, making it easy to align many widgets next to each other,
horizontally and vertically.
@end{short}
Tables are created with a call to the function @fun{gtk-table-new}, the size
of which can later be changed with the function @fun{gtk-table-resize}.
Widgets can be added to a table using the function @fun{gtk-table-attach}.
To alter the space next to a specific row, use the function
@fun{gtk-table-set-row-spacing}, and for a column the function
@fun{gtk-table-set-col-spacing}. The gaps between all rows or columns can be
changed by calling the functions @fun{gtk-table-row-spacing} or
@fun{gtk-table-column-spacing} respectively. Note that spacing is added
between the children, while padding added by the function
@fun{gtk-table-attach} is added on either side of the widget it belongs to.
The function @fun{gtk-table-homogeneous} can be used to set whether all
cells in the table will resize themselves to the size of the largest widget
in the table.
@begin[Warning]{dictionary}
The @sym{gtk-table} widget has been deprecated since GTK 3.4. Use the
@class{gtk-grid} widget instead. It provides the same capabilities as the
@sym{gtk-table} widget for arranging widgets in a rectangular grid, but
does support height-for-width geometry management.
@end{dictionary}
@begin[Child Property Details]{dictionary}
@begin[code]{table}
@begin[bottom-attach]{entry}
The @code{bottom-attach} child property of type @code{:uint}
(Read / Write) @br{}
The row number to attach the bottom of the child widget to. @br{}
Allowed values: [1,65535] @br{}
Default value: 1
@end{entry}
@begin[left-attach]{entry}
The @code{left-attach} child property of type @code{:uint}
(Read / Write) @br{}
The column number to attach the left side of the child widget to. @br{}
Allowed values: <= 65535 @br{}
Default value: 0
@end{entry}
@begin[right-attach]{entry}
The @code{right-attach} child property of type @code{:uint}
(Read / Write) @br{}
The column number to attach the right side of a child widget to. @br{}
Allowed values: [1,65535] @br{}
Default value: 1
@end{entry}
@begin[top-attach]{entry}
The @code{top-attach} child property of type @code{:uint}
(Read / Write) @br{}
The row number to attach the top of a child widget to. @br{}
Allowed values: <= 65535 @br{}
Default value: 0
@end{entry}
@begin[x-options]{entry}
The @code{x-options} child property of type @symbol{gtk-attach-options}
(Read / Write) @br{}
Options specifying the horizontal behaviour of the child widget. @br{}
Default value: @code{'(:expand :fill)}
@end{entry}
@begin[x-padding]{entry}
The @code{x-padding} child property of type @code{:uint}
(Read / Write) @br{}
Extra space to put between the child widget and its left and right
neighbors, in pixels. @br{}
Allowed values: <= 65535 @br{}
Default value: 0
@end{entry}
@begin[y-options]{entry}
The @code{y-options} child property of type @symbol{gtk-attach-options}
(Read / Write) @br{}
Options specifying the vertical behaviour of the child widget. @br{}
Default value: @code{'(:expand :fill)}
@end{entry}
@begin[y-padding]{entry}
The @code{y-padding} child property of type @code{:uint}
(Read / Write) @br{}
Extra space to put between the child widget and its upper and lower
neighbors, in pixels. @br{}
Allowed values: <= 65535 @br{}
Default value: 0
@end{entry}
@end{table}
@end{dictionary}
@see-slot{gtk-table-column-spacing}
@see-slot{gtk-table-homogeneous}
@see-slot{gtk-table-n-columns}
@see-slot{gtk-table-n-rows}
@see-slot{gtk-table-row-spacing}
@see-class{gtk-grid}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "column-spacing" 'gtk-table) 't)
"The @code{column-spacing} property of type @code{:uint}
(Read / Write) @br{}
The amount of space between two consecutive columns. @br{}
Allowed values: <= 65535 @br{}
Default value: 0")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-column-spacing atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-column-spacing 'function)
"@version{*2021-7-20}
@syntax[]{(gtk-table-column-spacing object) => spacing}
@syntax[]{(setf (gtk-table-column-spacing object) spacing)}
@argument[table]{a @class{gtk-table} widget}
@argument[spacing]{an unsigned integer with the number of pixels of space to
place between every column in the table}
@begin{short}
Accessor of the @slot[gtk-table]{column-spacing} property of the
@class{gtk-table} class.
@end{short}
The slot access function @sym{gtk-table-column-spacing} gets the default
column spacing for the table. The slot access function
@sym{(setf gtk-table-column-spacing)} sets the column spacing. This is the
spacing that will be used for newly added columns.
@begin[Lisp implementation]{dictionary}
The C library has the functions @code{gtk_table_get_default_col_spacing ()}
and @code{gtk_table_set_col_spacings ()}, which correspond to the
slot access function @sym{gtk-table-column-spacing}. These C functions are
not implemented in the Lisp library.
@end{dictionary}
@begin[Warning]{dictionary}
The function @sym{gtk-table-column-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget with the function @fun{gtk-grid-column-spacing}.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-grid-column-spacing}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "homogeneous" 'gtk-table) 't)
"The @code{homogeneous} property of type @code{:boolean}
(Read / Write) @br{}
If @em{true}, the table cells are all the same width/height. @br{}
Default value: @em{false}")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-homogeneous atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-homogeneous 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-homogeneous object) => homogeneous}
@syntax[]{(setf (gtk-table-homogeneous object) homogeneous)}
@argument[object]{a @class{gtk-table} widget}
@argument[homogeneous]{set to @em{true} to ensure all table cells are the
same size, set to @em{false} if this is not the desired behaviour}
@begin{short}
Accessor of the @slot[gtk-table]{homogeneous} slot of the
@class{gtk-table} class.
@end{short}
The slot access function @sym{gtk-table-homogeneous} returns whether the
table cells are all constrained to the same width and height. The slot access
function @sym{(setf gtk-table-homogeneous)} changes the
@slot[gtk-table]{homogeneous} property.
@begin[Warning]{dictionary}
The function @sym{gtk-table-homogeneous} has been deprecated since version
3.4 and should not be used in newly written code. Use the @class{gtk-grid}
widget with the functions @fun{gtk-grid-row-homogeneous} and
@fun{gtk-grid-column-homogeneous}.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-grid-column-homogeneous}
@see-function{gtk-grid-row-homogeneous}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "n-columns" 'gtk-table) 't)
"The @code{n-columns} property of type @code{:uint} (Read / Write) @br{}
The number of columns in the table. @br{}
Allowed values: [1,65535] @br{}
Default value: 1")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-n-columns atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-n-columns 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-n-columns object) => n-columns}
@syntax[]{(setf (gtk-table-n-columns object) n-columns)}
@argument[object]{a @class{gtk-table} widget}
@argument[n-columns]{an unsigned integer with the number of columns}
@begin{short}
Accessor of the @slot[gtk-table]{n-columns} slot of the @class{gtk-table}
class.
@end{short}
The number of columns in the table.
@begin[Warning]{dictionary}
The function @sym{gtk-table-n-columns} has been deprecated since version
3.4 and should not be used in newly written code. Use the @class{gtk-grid}
widget which does not expose the number of columns and rows.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "n-rows" 'gtk-table) 't)
"The @code{n-rows} property of type @code{:uint} (Read / Write) @br{}
The number of rows in the table. @br{}
Allowed values: [1,65535] @br{}
Default value: 1")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-n-rows atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-n-rows 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-n-rows object) => n-rows}
@syntax[]{(setf (gtk-table-n-rows object) n-rows)}
@argument[object]{a @class{gtk-table} widget}
@argument[n-rows]{an unsigned integer with the number of rows}
@begin{short}
Accessor of the @slot[gtk-table]{n-rows} slot of the @class{gtk-table}
class.
@end{short}
The number of rows in the table.
@begin[Warning]{dictionary}
The function @sym{gtk-table-n-rows} has been deprecated since version 3.4
and should not be used in newly written code. Use the @class{gtk-grid}
widget which does not expose the number of columns and rows.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}")
#+cl-cffi-gtk-documentation
(setf (documentation (atdoc:get-slot-from-name "row-spacing" 'gtk-table) 't)
"The @code{row-spacing} property of type @code{:uint} (Read / Write) @br{}
The amount of space between two consecutive rows. @br{}
Allowed values: <= 65535 @br{}
Default value: 0")
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-row-spacing atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-row-spacing 'function)
"@version{*2021-7-20}
@syntax[]{(gtk-table-row-spacing object) => spacing}
@syntax[]{(setf (gtk-table-row-spacing object) spacing)}
@argument[table]{a @class{gtk-table} widget}
@argument[spacing]{an unsigned integer with the number of pixels of space to
place between every row in the table}
@begin{short}
Accessor of the @slot[gtk-table]{row-spacing} slot of the
@class{gtk-table} class.
@end{short}
The slot access function @sym{gtk-table-row-spacing} gets the default row
spacing for the table. The slot access function @sym{gtk-table-row-spacing}
sets the row spacing. This is the spacing that will be used for newly added
rows.
@begin[Lisp implementation]{dictionary}
The C library has the functions @code{gtk_table_get_default_row_spacing ()}
and @code{gtk_table_set_row_spacings ()}, which correspond to the
slot access function @sym{gtk-table-row-spacing}. These C functions are not
implemented in the Lisp library.
@end{dictionary}
@begin[Warning]{dictionary}
The function @sym{gtk-table-row-spacing} has been deprecated since version
3.4 and should not be used in newly written code. Use the @class{gtk-grid}
widget with the function @fun{gtk-grid-row-spacing}.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-grid-row-spacing}")
Accessors of Child Properties
(eval-when (:compile-toplevel :load-toplevel :execute)
(register-object-type "GtkTable" 'gtk-table))
(define-child-property "GtkTable"
gtk-table-child-bottom-attach
"bottom-attach" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-bottom-attach atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-bottom-attach 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-bottom-attach container child) => attach}
@syntax[]{(setf (gtk-table-child-bottom-attach container child) attach)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[attach]{an unsigned integer with the row number to attach the
bottom of the child widget to}
@begin{short}
Accessor of the @code{bottom-attach} child property of the
@class{gtk-table} class.
@end{short}
The row number to attach the bottom of the child widget to.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-bottom-attach} has been deprecated since
version 3.4. and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
(define-child-property "GtkTable"
gtk-table-child-left-attach
"left-attach" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-left-attach atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-left-attach 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-left-attach container child) => attach}
@syntax[]{(setf (gtk-table-child-left-attach container child) attach)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[attach]{an unsigned integer with the column number to attach the
left side of the child widget to}
@begin{short}
Accessor of the @code{left-attach} child property of the @class{gtk-table}
class.
@end{short}
The column number to attach the left side of the child widget to.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-left-attach} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
(define-child-property "GtkTable"
gtk-table-child-right-attach
"right-attach" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-right-attach atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-right-attach 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-right-attach container child) => attach}
@syntax[]{(setf (gtk-table-child-right-attach container child) attach)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[attach]{an unsigned integer with the column number to attach the
right side of the child widget to}
@begin{short}
Accessor of the @code{right-attach} child property of the @class{gtk-table}
class.
@end{short}
The column number to attach the right side of the child widget to.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-right-attach} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
(define-child-property "GtkTable"
gtk-table-child-top-attach
"top-attach" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-top-attach atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-top-attach 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-top-attach container child) => attach}
@syntax[]{(setf (gtk-table-child-top-attach container child) attach)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[attach]{an unsigned integer with the row number to attach the top
of the child widget to}
@begin{short}
Accessor of the @code{top-attach} child property of the @class{gtk-table}
class.
@end{short}
The row number to attach the top of the child widget to.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-top-attach} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
(define-child-property "GtkTable"
gtk-table-child-x-options
"x-options" "GtkAttachOptions" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-x-options atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-x-options 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-x-options container child) => options}
@syntax[]{(setf (gtk-table-child-x-options container child) options)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[options]{the @symbol{gtk-attach-options} flags}
@begin{short}
Accessor of the @code{x-options} child property of the @class{gtk-table}
class.
@end{short}
Options specifying the horizontal behaviour of the child widget.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-x-options} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}
@see-symbol{gtk-attach-options}")
(define-child-property "GtkTable"
gtk-table-child-y-options
"y-options" "GtkAttachOptions" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-y-options atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-y-options 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-y-options container child) => options}
@syntax[]{(setf (gtk-table-child-y-options container child) options)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[options]{the @symbol{gtk-attach-options} flags}
@begin{short}
Accessor of the @code{y-options} child property of the @class{gtk-table}
class.
@end{short}
Options specifying the vertical behaviour of the child widget.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-y-options} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}
@see-symbol{gtk-attach-options}")
(define-child-property "GtkTable"
gtk-table-child-x-padding
"x-padding" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-x-padding atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-x-padding 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-x-padding container child) => padding}
@syntax[]{(setf (gtk-table-child-x-padding container child) padding)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[padding]{an unsigned integer with the space to put between the
child widget and its neighbors}
@begin{short}
Accessor of the @code{x-padding} child property of the @class{gtk-table}
class.
@end{short}
Extra space to put between the child widget and its left and right neighbors,
in pixels.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-x-padding} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
(define-child-property "GtkTable"
gtk-table-child-y-padding
"y-padding" "guint" t t t)
#+cl-cffi-gtk-documentation
(setf (gethash 'gtk-table-child-y-padding atdoc:*function-name-alias*)
"Accessor"
(documentation 'gtk-table-child-y-padding 'function)
"@version{2021-7-20}
@syntax[]{(gtk-table-child-y-padding container child) => padding}
@syntax[]{(setf (gtk-table-child-y-padding container child) padding)}
@argument[container]{a @class{gtk-table} widget}
@argument[child]{a @class{gtk-widget} child widget}
@argument[padding]{an unsigned integer with the space to put between the
child widget and its neighbors}
@begin{short}
Accessor of the @code{y-padding} child property of the @class{gtk-table}
class.
@end{short}
Extra space to put between the child widget and its upper and lower
neighbors, in pixels.
@begin[Warning]{dictionary}
The function @sym{gtk-table-child-y-padding} has been deprecated since
version 3.4 and should not be used in newly written code. Use the
@class{gtk-grid} widget instead.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-widget}
@see-class{gtk-grid}")
(declaim (inline gtk-table-new))
(defun gtk-table-new (rows columns homogeneous)
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[rows]{an unsigned integer with the number of rows the new table
should have}
@argument[columns]{an unsigned integer with the number of columns the new
table should have}
@argument[homogeneous]{if set to @em{true}, all table cells are resized to
the size of the cell containing the largest widget}
@return{The the newly created @class{gtk-table} widget.}
@begin{short}
Used to create a new table.
@end{short}
An initial size must be given by specifying how many rows and columns the
table should have, although this can be changed later with the function
@fun{gtk-table-resize}. The arguments @arg{rows} and @arg{columns} must both
be in the range 1 ... 65535. For historical reasons, 0 is accepted as well
and is silently interpreted as 1.
@begin[Warning]{dictionary}
The function @sym{gtk-table-new} has been deprecated since version 3.4 and
should not be used in newly written code. Use the @class{gtk-grid} widget
with the function @fun{gtk-grid-new}.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-table-resize}
@see-function{gtk-grid-new}"
(make-instance 'gtk-table
:rows rows
:columns columns
:homogeneous homogeneous))
(export 'gtk-table-new)
gtk_table_resize ( )
(declaim (inline gtk-table-resize))
(defun gtk-table-resize (table rows columns)
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{the @class{gtk-table} widget you wish to change the size of}
@argument[rows]{an unsigned integer with the new number of rows}
@argument[columns]{an unsigned integer with the new number of columns}
@begin{short}
If you need to change the size of the table after it has been created, this
function allows you to do so.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-resize} has been deprecated since version 3.4
and should not be used in newly written code. Use the @class{gtk-grid}
widget which resizes automatically.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}"
(setf (gtk-table-n-rows table) rows
(gtk-table-n-columns table) columns))
(export 'gtk-table-resize)
(defun gtk-table-size (table)
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget}
@begin{return}
@code{n-rows} -- an unsigned integer with the number of rows @br{}
@code{n-columns} -- an unsigned integer with the number of columns
@end{return}
@short{Gets the number of rows and columns in the table.}
@begin[Warning]{dictionary}
The function @sym{gtk-table-size} has been deprecated since version 3.4
and should not be used in newly written code. Use the @class{gtk-grid}
widget which does not expose the number of columns and rows.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}"
(values (gtk-table-n-rows table)
(gtk-table-n-columns table)))
(export 'gtk-table-size)
(defcfun ("gtk_table_attach" %gtk-table-attach) :void
(table (g-object gtk-table))
(child (g-object gtk-widget))
(left :uint)
(right :uint)
(top :uint)
(bottom :uint)
(x-options gtk-attach-options)
(y-options gtk-attach-options)
(x-padding :uint)
(y-padding :uint))
(defun gtk-table-attach (table child left right top bottom
&key (x-options '(:expand :fill))
(y-options '(:expand :fill))
(x-padding 0)
(y-padding 0))
#+cl-cffi-gtk-documentation
"@version{*2021-7-20}
@argument[table]{the @class{gtk-table} widget to add a new widget to}
@argument[child]{the @class{gtk-widget} child widget to add}
@argument[left]{an unsigned integer with the column number to attach the left
side of a child widget to}
@argument[right]{an unsigned integer with the column number to attach the
right side of a child widget to}
@argument[top]{an unsigned ineger with the row number to attach the top of a
child widget to}
@argument[bottom]{an unsigned integer with the row number to attach the bottom
of a child widget to}
@argument[x-options]{the @symbol{gtk-attach-options} flags used to specify the
properties of the child widget when the table is resized}
@argument[y-options]{the same as @arg{x-options}, except this field
determines behaviour of vertical resizing}
@argument[x-padding]{an unsigned integer specifying the padding on the left
and right of the child widget being added to the table}
@argument[y-padding]{an unsigned integer with the amount of padding above and
below the child widget}
@begin{short}
Adds a child widget to a table.
@end{short}
The number of cells that a child widget will occupy is specified by the
arguments @arg{left}, @arg{right}, @arg{top} and @arg{bottom}. These each
represent the leftmost, rightmost, uppermost and lowest column and row
numbers of the table. Columns and rows are indexed from zero.
The keyword arguments @code{x-options} and @code{y-options} have the default
value @code{'(:expand :fill)}. The keyword arguments @code{x-padding} and
@code{y-padding} have the default value 0.
@begin[Example]{dictionary}
To make a button occupy the lower right cell of a 2 x 2 table, use
@begin{pre}
(gtk-table-attach table button 1 2 1 2)
@end{pre}
If you want to make the button span the entire bottom row, use
@begin{pre}
(gtk-table-attach table button 0 2 1 2)
@end{pre}
@end{dictionary}
@begin[Lisp implementation]{dictionary}
The C library has the function @code{gtk_table_attach_default ()}. This
function is included in the Lisp library via keyword arguments with default
values for the function @sym{gtk-table-attach}.
@end{dictionary}
@begin[Warning]{dictionary}
The function @sym{gtk-table-attach} has been deprecated since version 3.4
and should not be used in newly written code. Use the @class{gtk-grid}
widget with the function @fun{gtk-grid-attach}. Note that the attach
arguments differ between those two functions.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-symbol{gtk-attach-options}
@see-function{gtk-grid-attach}"
(%gtk-table-attach table child
left right top bottom
x-options y-options
x-padding y-padding))
(export 'gtk-table-attach)
(defun gtk-table-attach-defaults (table child left right top bottom)
#+cl-cffi-gtk-documentation
"@version{2020-1-20}
@argument[table]{the table to add a new child widget to}
@argument[widget]{the child widget to add}
@argument[left-attach]{the column number to attach the left side of the child
widget to}
@argument[right-attach]{the column number to attach the right side of the
child widget to}
@argument[top-attach]{the row number to attach the top of the child widget
to}
@argument[bottom-attach]{the row number to attach the bottom of the child
widget to}
@begin{short}
As there are many options associated with the function
@fun{gtk-table-attach}, this convenience function provides the programmer
with a means to add children to a table with identical padding and
expansion options.
@end{short}
The values used for the @symbol{gtk-attach-options} are
@code{'(:expand :fill)}, and the padding is set to 0.
@begin[Warning]{dictionary}
The function @sym{gtk-table-attach-defaults} has been deprecated since
version 3.4 and should not be used in newly written code. Use the function
@fun{gtk-grid-attach} with @class{gtk-grid}. Note that the attach arguments
differ between those two functions.
@end{dictionary}
@see-class{gtk-table}"
(gtk-table-attach table child left right top bottom))
(defcfun ("gtk_table_set_row_spacing" gtk-table-set-row-spacing) :void
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget containing the row whose
properties you wish to change}
@argument[row]{an unsigned integer with the row number whose spacing will be
changed}
@argument[spacing]{an unsigned integer with the number of pixels that the
spacing should take up}
@begin{short}
Changes the space between a given table row and the subsequent row.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-set-row-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. Use the functions
@fun{gtk-widget-margin-top} and @fun{gtk-widget-margin-bottom} on the
widgets contained in the row if you need this functionality.
The @class{gtk-grid} widget does not support per-row spacing.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-widget-margin-top}
@see-function{gtk-widget-margin-bottom}"
(table (g-object gtk-table))
(row :uint)
(spacing :uint))
(export 'gtk-table-set-row-spacing)
(defcfun ("gtk_table_set_col_spacing" gtk-table-set-col-spacing) :void
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget}
@argument[column]{an unsigned integer with the column whose spacing should be
changed}
@argument[spacing]{an unsigned integer with the number of pixels that the
spacing should take up}
@begin{short}
Alters the amount of space between a given table column and the following
column.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-set-col-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. Use the functions
@fun{gtk-widget-margin-start} and @fun{gtk-widget-margin-end} on
the widgets contained in the row if you need this functionality.
The @class{gtk-grid} widget does not support per-column spacing.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}
@see-function{gtk-widget-margin-start}
@see-function{gtk-widget-margin-end}"
(table (g-object gtk-table))
(column :uint)
(spacing :uint))
(export 'gtk-table-set-col-spacing)
(defcfun ("gtk_table_get_row_spacing" gtk-table-get-row-spacing) :uint
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget}
@argument[row]{an unsigned integer with a row in the table, 0 indicates the
first row}
@return{An unsigned integer with the row spacing.}
@begin{short}
Gets the amount of space between @arg{row}, and @arg{row + 1}.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-get-row-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. The
@class{gtk-grid} widget does not offer a replacement for this functionality.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}"
(table (g-object gtk-table))
(row :uint))
(export 'gtk-table-get-row-spacing)
(defcfun ("gtk_table_get_col_spacing" gtk-table-get-col-spacing) :uint
#+cl-cffi-gtk-documentation
"@version{2021-7-20}
@argument[table]{a @class{gtk-table} widget}
@argument[column]{an unsigned integer with a column in the table, 0 indicates
the first column}
@return{An unsigned integer with the column spacing.}
@begin{short}
Gets the amount of space between @arg{column}, and @arg{column + 1}.
@end{short}
@begin[Warning]{dictionary}
The function @sym{gtk-table-get-col-spacing} has been deprecated since
version 3.4 and should not be used in newly written code. The
@class{gtk-grid} widget does not offer a replacement for this functionality.
@end{dictionary}
@see-class{gtk-table}
@see-class{gtk-grid}"
(table (g-object gtk-table))
(column :uint))
(export 'gtk-table-get-col-spacing)
|
7ee0390c332094bd3628ade7607550b6fd2d3b33bf91c8853c2289832d1bc30e | jabber-at/ejabberd | mod_disco.erl | %%%----------------------------------------------------------------------
File :
Author : < >
Purpose : Service Discovery ( XEP-0030 ) support
Created : 1 Jan 2003 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(mod_disco).
-author('').
-protocol({xep, 30, '2.4'}).
-protocol({xep, 157, '1.0'}).
-behaviour(gen_mod).
-export([start/2, stop/1, reload/3, process_local_iq_items/1,
process_local_iq_info/1, get_local_identity/5,
get_local_features/5, get_local_services/5,
process_sm_iq_items/1, process_sm_iq_info/1,
get_sm_identity/5, get_sm_features/5, get_sm_items/5,
get_info/5, transform_module_options/1, mod_opt_type/1,
mod_options/1, depends/2]).
-include("logger.hrl").
-include("translate.hrl").
-include("xmpp.hrl").
-include_lib("stdlib/include/ms_transform.hrl").
-include("mod_roster.hrl").
-type features_acc() :: {error, stanza_error()} | {result, [binary()]} | empty.
-type items_acc() :: {error, stanza_error()} | {result, [disco_item()]} | empty.
start(Host, Opts) ->
gen_iq_handler:add_iq_handler(ejabberd_local, Host,
?NS_DISCO_ITEMS, ?MODULE,
process_local_iq_items),
gen_iq_handler:add_iq_handler(ejabberd_local, Host,
?NS_DISCO_INFO, ?MODULE,
process_local_iq_info),
gen_iq_handler:add_iq_handler(ejabberd_sm, Host,
?NS_DISCO_ITEMS, ?MODULE, process_sm_iq_items),
gen_iq_handler:add_iq_handler(ejabberd_sm, Host,
?NS_DISCO_INFO, ?MODULE, process_sm_iq_info),
catch ets:new(disco_extra_domains,
[named_table, ordered_set, public,
{heir, erlang:group_leader(), none}]),
ExtraDomains = gen_mod:get_opt(extra_domains, Opts),
lists:foreach(fun (Domain) ->
register_extra_domain(Host, Domain)
end,
ExtraDomains),
ejabberd_hooks:add(disco_local_items, Host, ?MODULE,
get_local_services, 100),
ejabberd_hooks:add(disco_local_features, Host, ?MODULE,
get_local_features, 100),
ejabberd_hooks:add(disco_local_identity, Host, ?MODULE,
get_local_identity, 100),
ejabberd_hooks:add(disco_sm_items, Host, ?MODULE,
get_sm_items, 100),
ejabberd_hooks:add(disco_sm_features, Host, ?MODULE,
get_sm_features, 100),
ejabberd_hooks:add(disco_sm_identity, Host, ?MODULE,
get_sm_identity, 100),
ejabberd_hooks:add(disco_info, Host, ?MODULE, get_info,
100),
ok.
stop(Host) ->
ejabberd_hooks:delete(disco_sm_identity, Host, ?MODULE,
get_sm_identity, 100),
ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE,
get_sm_features, 100),
ejabberd_hooks:delete(disco_sm_items, Host, ?MODULE,
get_sm_items, 100),
ejabberd_hooks:delete(disco_local_identity, Host,
?MODULE, get_local_identity, 100),
ejabberd_hooks:delete(disco_local_features, Host,
?MODULE, get_local_features, 100),
ejabberd_hooks:delete(disco_local_items, Host, ?MODULE,
get_local_services, 100),
ejabberd_hooks:delete(disco_info, Host, ?MODULE,
get_info, 100),
gen_iq_handler:remove_iq_handler(ejabberd_local, Host,
?NS_DISCO_ITEMS),
gen_iq_handler:remove_iq_handler(ejabberd_local, Host,
?NS_DISCO_INFO),
gen_iq_handler:remove_iq_handler(ejabberd_sm, Host,
?NS_DISCO_ITEMS),
gen_iq_handler:remove_iq_handler(ejabberd_sm, Host,
?NS_DISCO_INFO),
catch ets:match_delete(disco_extra_domains,
{{'_', Host}}),
ok.
reload(Host, NewOpts, OldOpts) ->
case gen_mod:is_equal_opt(extra_domains, NewOpts, OldOpts) of
{false, NewDomains, OldDomains} ->
lists:foreach(
fun(Domain) ->
register_extra_domain(Host, Domain)
end, NewDomains -- OldDomains),
lists:foreach(
fun(Domain) ->
unregister_extra_domain(Host, Domain)
end, OldDomains -- NewDomains);
true ->
ok
end.
-spec register_extra_domain(binary(), binary()) -> true.
register_extra_domain(Host, Domain) ->
ets:insert(disco_extra_domains, {{Domain, Host}}).
-spec unregister_extra_domain(binary(), binary()) -> true.
unregister_extra_domain(Host, Domain) ->
ets:delete_object(disco_extra_domains, {{Domain, Host}}).
-spec process_local_iq_items(iq()) -> iq().
process_local_iq_items(#iq{type = set, lang = Lang} = IQ) ->
Txt = <<"Value 'set' of 'type' attribute is not allowed">>,
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang));
process_local_iq_items(#iq{type = get, lang = Lang,
from = From, to = To,
sub_els = [#disco_items{node = Node}]} = IQ) ->
Host = To#jid.lserver,
case ejabberd_hooks:run_fold(disco_local_items, Host,
empty, [From, To, Node, Lang]) of
{result, Items} ->
xmpp:make_iq_result(IQ, #disco_items{node = Node, items = Items});
{error, Error} ->
xmpp:make_error(IQ, Error)
end.
-spec process_local_iq_info(iq()) -> iq().
process_local_iq_info(#iq{type = set, lang = Lang} = IQ) ->
Txt = <<"Value 'set' of 'type' attribute is not allowed">>,
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang));
process_local_iq_info(#iq{type = get, lang = Lang,
from = From, to = To,
sub_els = [#disco_info{node = Node}]} = IQ) ->
Host = To#jid.lserver,
Identity = ejabberd_hooks:run_fold(disco_local_identity,
Host, [], [From, To, Node, Lang]),
Info = ejabberd_hooks:run_fold(disco_info, Host, [],
[Host, ?MODULE, Node, Lang]),
case ejabberd_hooks:run_fold(disco_local_features, Host,
empty, [From, To, Node, Lang]) of
{result, Features} ->
xmpp:make_iq_result(IQ, #disco_info{node = Node,
identities = Identity,
xdata = Info,
features = Features});
{error, Error} ->
xmpp:make_error(IQ, Error)
end.
-spec get_local_identity([identity()], jid(), jid(),
binary(), binary()) -> [identity()].
get_local_identity(Acc, _From, To, <<"">>, _Lang) ->
Host = To#jid.lserver,
Name = gen_mod:get_module_opt(Host, ?MODULE, name),
Acc ++ [#identity{category = <<"server">>,
type = <<"im">>,
name = Name}];
get_local_identity(Acc, _From, _To, _Node, _Lang) ->
Acc.
-spec get_local_features(features_acc(), jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [binary()]}.
get_local_features({error, _Error} = Acc, _From, _To,
_Node, _Lang) ->
Acc;
get_local_features(Acc, _From, To, <<"">>, _Lang) ->
Feats = case Acc of
{result, Features} -> Features;
empty -> []
end,
{result, lists:usort(
lists:flatten(
[?NS_FEATURE_IQ, ?NS_FEATURE_PRESENCE,
?NS_DISCO_INFO, ?NS_DISCO_ITEMS, Feats,
ejabberd_local:get_features(To#jid.lserver)]))};
get_local_features(Acc, _From, _To, _Node, Lang) ->
case Acc of
{result, _Features} -> Acc;
empty ->
Txt = <<"No features available">>,
{error, xmpp:err_item_not_found(Txt, Lang)}
end.
-spec get_local_services(items_acc(), jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [disco_item()]}.
get_local_services({error, _Error} = Acc, _From, _To,
_Node, _Lang) ->
Acc;
get_local_services(Acc, _From, To, <<"">>, _Lang) ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Host = To#jid.lserver,
{result,
lists:usort(
lists:map(
fun(Domain) -> #disco_item{jid = jid:make(Domain)} end,
get_vh_services(Host) ++
ets:select(disco_extra_domains,
ets:fun2ms(
fun({{D, H}}) when H == Host -> D end))))
++ Items};
get_local_services({result, _} = Acc, _From, _To, _Node,
_Lang) ->
Acc;
get_local_services(empty, _From, _To, _Node, Lang) ->
{error, xmpp:err_item_not_found(<<"No services available">>, Lang)}.
-spec get_vh_services(binary()) -> [binary()].
get_vh_services(Host) ->
Hosts = lists:sort(fun (H1, H2) ->
byte_size(H1) >= byte_size(H2)
end,
ejabberd_config:get_myhosts()),
lists:filter(fun (H) ->
case lists:dropwhile(fun (VH) ->
not
str:suffix(
<<".", VH/binary>>,
H)
end,
Hosts)
of
[] -> false;
[VH | _] -> VH == Host
end
end,
ejabberd_router:get_all_routes()).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-spec process_sm_iq_items(iq()) -> iq().
process_sm_iq_items(#iq{type = set, lang = Lang} = IQ) ->
Txt = <<"Value 'set' of 'type' attribute is not allowed">>,
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang));
process_sm_iq_items(#iq{type = get, lang = Lang,
from = From, to = To,
sub_els = [#disco_items{node = Node}]} = IQ) ->
case mod_roster:is_subscribed(From, To) of
true ->
Host = To#jid.lserver,
case ejabberd_hooks:run_fold(disco_sm_items, Host,
empty, [From, To, Node, Lang]) of
{result, Items} ->
xmpp:make_iq_result(
IQ, #disco_items{node = Node, items = Items});
{error, Error} ->
xmpp:make_error(IQ, Error)
end;
false ->
Txt = <<"Not subscribed">>,
xmpp:make_error(IQ, xmpp:err_subscription_required(Txt, Lang))
end.
-spec get_sm_items(items_acc(), jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [disco_item()]}.
get_sm_items({error, _Error} = Acc, _From, _To, _Node,
_Lang) ->
Acc;
get_sm_items(Acc, From,
#jid{user = User, server = Server} = To, <<"">>, _Lang) ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Items1 = case mod_roster:is_subscribed(From, To) of
true -> get_user_resources(User, Server);
_ -> []
end,
{result, Items ++ Items1};
get_sm_items({result, _} = Acc, _From, _To, _Node,
_Lang) ->
Acc;
get_sm_items(empty, From, To, _Node, Lang) ->
#jid{luser = LFrom, lserver = LSFrom} = From,
#jid{luser = LTo, lserver = LSTo} = To,
case {LFrom, LSFrom} of
{LTo, LSTo} -> {error, xmpp:err_item_not_found()};
_ ->
Txt = <<"Query to another users is forbidden">>,
{error, xmpp:err_not_allowed(Txt, Lang)}
end.
-spec process_sm_iq_info(iq()) -> iq().
process_sm_iq_info(#iq{type = set, lang = Lang} = IQ) ->
Txt = <<"Value 'set' of 'type' attribute is not allowed">>,
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang));
process_sm_iq_info(#iq{type = get, lang = Lang,
from = From, to = To,
sub_els = [#disco_info{node = Node}]} = IQ) ->
case mod_roster:is_subscribed(From, To) of
true ->
Host = To#jid.lserver,
Identity = ejabberd_hooks:run_fold(disco_sm_identity,
Host, [],
[From, To, Node, Lang]),
Info = ejabberd_hooks:run_fold(disco_info, Host, [],
[From, To, Node, Lang]),
case ejabberd_hooks:run_fold(disco_sm_features, Host,
empty, [From, To, Node, Lang]) of
{result, Features} ->
xmpp:make_iq_result(IQ, #disco_info{node = Node,
identities = Identity,
xdata = Info,
features = Features});
{error, Error} ->
xmpp:make_error(IQ, Error)
end;
false ->
Txt = <<"Not subscribed">>,
xmpp:make_error(IQ, xmpp:err_subscription_required(Txt, Lang))
end.
-spec get_sm_identity([identity()], jid(), jid(),
binary(), binary()) -> [identity()].
get_sm_identity(Acc, _From,
#jid{luser = LUser, lserver = LServer}, _Node, _Lang) ->
Acc ++
case ejabberd_auth:user_exists(LUser, LServer) of
true ->
[#identity{category = <<"account">>, type = <<"registered">>}];
_ -> []
end.
-spec get_sm_features(features_acc(), jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [binary()]}.
get_sm_features(empty, From, To, Node, Lang) ->
#jid{luser = LFrom, lserver = LSFrom} = From,
#jid{luser = LTo, lserver = LSTo} = To,
case {LFrom, LSFrom} of
{LTo, LSTo} ->
case Node of
<<"">> -> {result, [?NS_DISCO_INFO, ?NS_DISCO_ITEMS]};
_ -> {error, xmpp:err_item_not_found()}
end;
_ ->
Txt = <<"Query to another users is forbidden">>,
{error, xmpp:err_not_allowed(Txt, Lang)}
end;
get_sm_features({result, Features}, _From, _To, <<"">>, _Lang) ->
{result, [?NS_DISCO_INFO, ?NS_DISCO_ITEMS|Features]};
get_sm_features(Acc, _From, _To, _Node, _Lang) -> Acc.
-spec get_user_resources(binary(), binary()) -> [disco_item()].
get_user_resources(User, Server) ->
Rs = ejabberd_sm:get_user_resources(User, Server),
[#disco_item{jid = jid:make(User, Server, Resource), name = User}
|| Resource <- lists:sort(Rs)].
-spec transform_module_options(gen_mod:opts()) -> gen_mod:opts().
transform_module_options(Opts) ->
lists:map(
fun({server_info, Infos}) ->
NewInfos = lists:map(
fun({Modules, Name, URLs}) ->
[[{modules, Modules},
{name, Name},
{urls, URLs}]];
(Opt) ->
Opt
end, Infos),
{server_info, NewInfos};
(Opt) ->
Opt
end, Opts).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Support for : XEP-0157 Contact Addresses for XMPP Services
-spec get_info([xdata()], binary(), module(), binary(), binary()) -> [xdata()];
([xdata()], jid(), jid(), binary(), binary()) -> [xdata()].
get_info(_A, Host, Mod, Node, _Lang) when is_atom(Mod), Node == <<"">> ->
Module = case Mod of
undefined -> ?MODULE;
_ -> Mod
end,
[#xdata{type = result,
fields = [#xdata_field{type = hidden,
var = <<"FORM_TYPE">>,
values = [?NS_SERVERINFO]}
| get_fields(Host, Module)]}];
get_info(Acc, _, _, _Node, _) -> Acc.
-spec get_fields(binary(), module()) -> [xdata_field()].
get_fields(Host, Module) ->
Fields = gen_mod:get_module_opt(Host, ?MODULE, server_info),
Fields1 = lists:filter(fun ({Modules, _, _}) ->
case Modules of
all -> true;
Modules ->
lists:member(Module, Modules)
end
end,
Fields),
[#xdata_field{var = Var,
type = 'list-multi',
values = Values} || {_, Var, Values} <- Fields1].
-spec depends(binary(), gen_mod:opts()) -> [].
depends(_Host, _Opts) ->
[].
mod_opt_type(extra_domains) ->
fun (Hs) -> [iolist_to_binary(H) || H <- Hs] end;
mod_opt_type(name) -> fun iolist_to_binary/1;
mod_opt_type(server_info) ->
fun (L) ->
lists:map(fun (Opts) ->
Mods = proplists:get_value(modules, Opts, all),
Name = proplists:get_value(name, Opts, <<>>),
URLs = proplists:get_value(urls, Opts, []),
{Mods, Name, URLs}
end,
L)
end.
mod_options(_Host) ->
[{extra_domains, []},
{server_info, []},
{name, ?T("ejabberd")}].
| null | https://raw.githubusercontent.com/jabber-at/ejabberd/7bfec36856eaa4df21b26e879d3ba90285bad1aa/src/mod_disco.erl | erlang | ----------------------------------------------------------------------
This program is free software; you can redistribute it and/or
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.
----------------------------------------------------------------------
| File :
Author : < >
Purpose : Service Discovery ( XEP-0030 ) support
Created : 1 Jan 2003 by < >
ejabberd , Copyright ( C ) 2002 - 2018 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(mod_disco).
-author('').
-protocol({xep, 30, '2.4'}).
-protocol({xep, 157, '1.0'}).
-behaviour(gen_mod).
-export([start/2, stop/1, reload/3, process_local_iq_items/1,
process_local_iq_info/1, get_local_identity/5,
get_local_features/5, get_local_services/5,
process_sm_iq_items/1, process_sm_iq_info/1,
get_sm_identity/5, get_sm_features/5, get_sm_items/5,
get_info/5, transform_module_options/1, mod_opt_type/1,
mod_options/1, depends/2]).
-include("logger.hrl").
-include("translate.hrl").
-include("xmpp.hrl").
-include_lib("stdlib/include/ms_transform.hrl").
-include("mod_roster.hrl").
-type features_acc() :: {error, stanza_error()} | {result, [binary()]} | empty.
-type items_acc() :: {error, stanza_error()} | {result, [disco_item()]} | empty.
start(Host, Opts) ->
gen_iq_handler:add_iq_handler(ejabberd_local, Host,
?NS_DISCO_ITEMS, ?MODULE,
process_local_iq_items),
gen_iq_handler:add_iq_handler(ejabberd_local, Host,
?NS_DISCO_INFO, ?MODULE,
process_local_iq_info),
gen_iq_handler:add_iq_handler(ejabberd_sm, Host,
?NS_DISCO_ITEMS, ?MODULE, process_sm_iq_items),
gen_iq_handler:add_iq_handler(ejabberd_sm, Host,
?NS_DISCO_INFO, ?MODULE, process_sm_iq_info),
catch ets:new(disco_extra_domains,
[named_table, ordered_set, public,
{heir, erlang:group_leader(), none}]),
ExtraDomains = gen_mod:get_opt(extra_domains, Opts),
lists:foreach(fun (Domain) ->
register_extra_domain(Host, Domain)
end,
ExtraDomains),
ejabberd_hooks:add(disco_local_items, Host, ?MODULE,
get_local_services, 100),
ejabberd_hooks:add(disco_local_features, Host, ?MODULE,
get_local_features, 100),
ejabberd_hooks:add(disco_local_identity, Host, ?MODULE,
get_local_identity, 100),
ejabberd_hooks:add(disco_sm_items, Host, ?MODULE,
get_sm_items, 100),
ejabberd_hooks:add(disco_sm_features, Host, ?MODULE,
get_sm_features, 100),
ejabberd_hooks:add(disco_sm_identity, Host, ?MODULE,
get_sm_identity, 100),
ejabberd_hooks:add(disco_info, Host, ?MODULE, get_info,
100),
ok.
stop(Host) ->
ejabberd_hooks:delete(disco_sm_identity, Host, ?MODULE,
get_sm_identity, 100),
ejabberd_hooks:delete(disco_sm_features, Host, ?MODULE,
get_sm_features, 100),
ejabberd_hooks:delete(disco_sm_items, Host, ?MODULE,
get_sm_items, 100),
ejabberd_hooks:delete(disco_local_identity, Host,
?MODULE, get_local_identity, 100),
ejabberd_hooks:delete(disco_local_features, Host,
?MODULE, get_local_features, 100),
ejabberd_hooks:delete(disco_local_items, Host, ?MODULE,
get_local_services, 100),
ejabberd_hooks:delete(disco_info, Host, ?MODULE,
get_info, 100),
gen_iq_handler:remove_iq_handler(ejabberd_local, Host,
?NS_DISCO_ITEMS),
gen_iq_handler:remove_iq_handler(ejabberd_local, Host,
?NS_DISCO_INFO),
gen_iq_handler:remove_iq_handler(ejabberd_sm, Host,
?NS_DISCO_ITEMS),
gen_iq_handler:remove_iq_handler(ejabberd_sm, Host,
?NS_DISCO_INFO),
catch ets:match_delete(disco_extra_domains,
{{'_', Host}}),
ok.
reload(Host, NewOpts, OldOpts) ->
case gen_mod:is_equal_opt(extra_domains, NewOpts, OldOpts) of
{false, NewDomains, OldDomains} ->
lists:foreach(
fun(Domain) ->
register_extra_domain(Host, Domain)
end, NewDomains -- OldDomains),
lists:foreach(
fun(Domain) ->
unregister_extra_domain(Host, Domain)
end, OldDomains -- NewDomains);
true ->
ok
end.
-spec register_extra_domain(binary(), binary()) -> true.
register_extra_domain(Host, Domain) ->
ets:insert(disco_extra_domains, {{Domain, Host}}).
-spec unregister_extra_domain(binary(), binary()) -> true.
unregister_extra_domain(Host, Domain) ->
ets:delete_object(disco_extra_domains, {{Domain, Host}}).
-spec process_local_iq_items(iq()) -> iq().
process_local_iq_items(#iq{type = set, lang = Lang} = IQ) ->
Txt = <<"Value 'set' of 'type' attribute is not allowed">>,
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang));
process_local_iq_items(#iq{type = get, lang = Lang,
from = From, to = To,
sub_els = [#disco_items{node = Node}]} = IQ) ->
Host = To#jid.lserver,
case ejabberd_hooks:run_fold(disco_local_items, Host,
empty, [From, To, Node, Lang]) of
{result, Items} ->
xmpp:make_iq_result(IQ, #disco_items{node = Node, items = Items});
{error, Error} ->
xmpp:make_error(IQ, Error)
end.
-spec process_local_iq_info(iq()) -> iq().
process_local_iq_info(#iq{type = set, lang = Lang} = IQ) ->
Txt = <<"Value 'set' of 'type' attribute is not allowed">>,
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang));
process_local_iq_info(#iq{type = get, lang = Lang,
from = From, to = To,
sub_els = [#disco_info{node = Node}]} = IQ) ->
Host = To#jid.lserver,
Identity = ejabberd_hooks:run_fold(disco_local_identity,
Host, [], [From, To, Node, Lang]),
Info = ejabberd_hooks:run_fold(disco_info, Host, [],
[Host, ?MODULE, Node, Lang]),
case ejabberd_hooks:run_fold(disco_local_features, Host,
empty, [From, To, Node, Lang]) of
{result, Features} ->
xmpp:make_iq_result(IQ, #disco_info{node = Node,
identities = Identity,
xdata = Info,
features = Features});
{error, Error} ->
xmpp:make_error(IQ, Error)
end.
-spec get_local_identity([identity()], jid(), jid(),
binary(), binary()) -> [identity()].
get_local_identity(Acc, _From, To, <<"">>, _Lang) ->
Host = To#jid.lserver,
Name = gen_mod:get_module_opt(Host, ?MODULE, name),
Acc ++ [#identity{category = <<"server">>,
type = <<"im">>,
name = Name}];
get_local_identity(Acc, _From, _To, _Node, _Lang) ->
Acc.
-spec get_local_features(features_acc(), jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [binary()]}.
get_local_features({error, _Error} = Acc, _From, _To,
_Node, _Lang) ->
Acc;
get_local_features(Acc, _From, To, <<"">>, _Lang) ->
Feats = case Acc of
{result, Features} -> Features;
empty -> []
end,
{result, lists:usort(
lists:flatten(
[?NS_FEATURE_IQ, ?NS_FEATURE_PRESENCE,
?NS_DISCO_INFO, ?NS_DISCO_ITEMS, Feats,
ejabberd_local:get_features(To#jid.lserver)]))};
get_local_features(Acc, _From, _To, _Node, Lang) ->
case Acc of
{result, _Features} -> Acc;
empty ->
Txt = <<"No features available">>,
{error, xmpp:err_item_not_found(Txt, Lang)}
end.
-spec get_local_services(items_acc(), jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [disco_item()]}.
get_local_services({error, _Error} = Acc, _From, _To,
_Node, _Lang) ->
Acc;
get_local_services(Acc, _From, To, <<"">>, _Lang) ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Host = To#jid.lserver,
{result,
lists:usort(
lists:map(
fun(Domain) -> #disco_item{jid = jid:make(Domain)} end,
get_vh_services(Host) ++
ets:select(disco_extra_domains,
ets:fun2ms(
fun({{D, H}}) when H == Host -> D end))))
++ Items};
get_local_services({result, _} = Acc, _From, _To, _Node,
_Lang) ->
Acc;
get_local_services(empty, _From, _To, _Node, Lang) ->
{error, xmpp:err_item_not_found(<<"No services available">>, Lang)}.
-spec get_vh_services(binary()) -> [binary()].
get_vh_services(Host) ->
Hosts = lists:sort(fun (H1, H2) ->
byte_size(H1) >= byte_size(H2)
end,
ejabberd_config:get_myhosts()),
lists:filter(fun (H) ->
case lists:dropwhile(fun (VH) ->
not
str:suffix(
<<".", VH/binary>>,
H)
end,
Hosts)
of
[] -> false;
[VH | _] -> VH == Host
end
end,
ejabberd_router:get_all_routes()).
-spec process_sm_iq_items(iq()) -> iq().
process_sm_iq_items(#iq{type = set, lang = Lang} = IQ) ->
Txt = <<"Value 'set' of 'type' attribute is not allowed">>,
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang));
process_sm_iq_items(#iq{type = get, lang = Lang,
from = From, to = To,
sub_els = [#disco_items{node = Node}]} = IQ) ->
case mod_roster:is_subscribed(From, To) of
true ->
Host = To#jid.lserver,
case ejabberd_hooks:run_fold(disco_sm_items, Host,
empty, [From, To, Node, Lang]) of
{result, Items} ->
xmpp:make_iq_result(
IQ, #disco_items{node = Node, items = Items});
{error, Error} ->
xmpp:make_error(IQ, Error)
end;
false ->
Txt = <<"Not subscribed">>,
xmpp:make_error(IQ, xmpp:err_subscription_required(Txt, Lang))
end.
-spec get_sm_items(items_acc(), jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [disco_item()]}.
get_sm_items({error, _Error} = Acc, _From, _To, _Node,
_Lang) ->
Acc;
get_sm_items(Acc, From,
#jid{user = User, server = Server} = To, <<"">>, _Lang) ->
Items = case Acc of
{result, Its} -> Its;
empty -> []
end,
Items1 = case mod_roster:is_subscribed(From, To) of
true -> get_user_resources(User, Server);
_ -> []
end,
{result, Items ++ Items1};
get_sm_items({result, _} = Acc, _From, _To, _Node,
_Lang) ->
Acc;
get_sm_items(empty, From, To, _Node, Lang) ->
#jid{luser = LFrom, lserver = LSFrom} = From,
#jid{luser = LTo, lserver = LSTo} = To,
case {LFrom, LSFrom} of
{LTo, LSTo} -> {error, xmpp:err_item_not_found()};
_ ->
Txt = <<"Query to another users is forbidden">>,
{error, xmpp:err_not_allowed(Txt, Lang)}
end.
-spec process_sm_iq_info(iq()) -> iq().
process_sm_iq_info(#iq{type = set, lang = Lang} = IQ) ->
Txt = <<"Value 'set' of 'type' attribute is not allowed">>,
xmpp:make_error(IQ, xmpp:err_not_allowed(Txt, Lang));
process_sm_iq_info(#iq{type = get, lang = Lang,
from = From, to = To,
sub_els = [#disco_info{node = Node}]} = IQ) ->
case mod_roster:is_subscribed(From, To) of
true ->
Host = To#jid.lserver,
Identity = ejabberd_hooks:run_fold(disco_sm_identity,
Host, [],
[From, To, Node, Lang]),
Info = ejabberd_hooks:run_fold(disco_info, Host, [],
[From, To, Node, Lang]),
case ejabberd_hooks:run_fold(disco_sm_features, Host,
empty, [From, To, Node, Lang]) of
{result, Features} ->
xmpp:make_iq_result(IQ, #disco_info{node = Node,
identities = Identity,
xdata = Info,
features = Features});
{error, Error} ->
xmpp:make_error(IQ, Error)
end;
false ->
Txt = <<"Not subscribed">>,
xmpp:make_error(IQ, xmpp:err_subscription_required(Txt, Lang))
end.
-spec get_sm_identity([identity()], jid(), jid(),
binary(), binary()) -> [identity()].
get_sm_identity(Acc, _From,
#jid{luser = LUser, lserver = LServer}, _Node, _Lang) ->
Acc ++
case ejabberd_auth:user_exists(LUser, LServer) of
true ->
[#identity{category = <<"account">>, type = <<"registered">>}];
_ -> []
end.
-spec get_sm_features(features_acc(), jid(), jid(), binary(), binary()) ->
{error, stanza_error()} | {result, [binary()]}.
get_sm_features(empty, From, To, Node, Lang) ->
#jid{luser = LFrom, lserver = LSFrom} = From,
#jid{luser = LTo, lserver = LSTo} = To,
case {LFrom, LSFrom} of
{LTo, LSTo} ->
case Node of
<<"">> -> {result, [?NS_DISCO_INFO, ?NS_DISCO_ITEMS]};
_ -> {error, xmpp:err_item_not_found()}
end;
_ ->
Txt = <<"Query to another users is forbidden">>,
{error, xmpp:err_not_allowed(Txt, Lang)}
end;
get_sm_features({result, Features}, _From, _To, <<"">>, _Lang) ->
{result, [?NS_DISCO_INFO, ?NS_DISCO_ITEMS|Features]};
get_sm_features(Acc, _From, _To, _Node, _Lang) -> Acc.
-spec get_user_resources(binary(), binary()) -> [disco_item()].
get_user_resources(User, Server) ->
Rs = ejabberd_sm:get_user_resources(User, Server),
[#disco_item{jid = jid:make(User, Server, Resource), name = User}
|| Resource <- lists:sort(Rs)].
-spec transform_module_options(gen_mod:opts()) -> gen_mod:opts().
transform_module_options(Opts) ->
lists:map(
fun({server_info, Infos}) ->
NewInfos = lists:map(
fun({Modules, Name, URLs}) ->
[[{modules, Modules},
{name, Name},
{urls, URLs}]];
(Opt) ->
Opt
end, Infos),
{server_info, NewInfos};
(Opt) ->
Opt
end, Opts).
Support for : XEP-0157 Contact Addresses for XMPP Services
-spec get_info([xdata()], binary(), module(), binary(), binary()) -> [xdata()];
([xdata()], jid(), jid(), binary(), binary()) -> [xdata()].
get_info(_A, Host, Mod, Node, _Lang) when is_atom(Mod), Node == <<"">> ->
Module = case Mod of
undefined -> ?MODULE;
_ -> Mod
end,
[#xdata{type = result,
fields = [#xdata_field{type = hidden,
var = <<"FORM_TYPE">>,
values = [?NS_SERVERINFO]}
| get_fields(Host, Module)]}];
get_info(Acc, _, _, _Node, _) -> Acc.
-spec get_fields(binary(), module()) -> [xdata_field()].
get_fields(Host, Module) ->
Fields = gen_mod:get_module_opt(Host, ?MODULE, server_info),
Fields1 = lists:filter(fun ({Modules, _, _}) ->
case Modules of
all -> true;
Modules ->
lists:member(Module, Modules)
end
end,
Fields),
[#xdata_field{var = Var,
type = 'list-multi',
values = Values} || {_, Var, Values} <- Fields1].
-spec depends(binary(), gen_mod:opts()) -> [].
depends(_Host, _Opts) ->
[].
mod_opt_type(extra_domains) ->
fun (Hs) -> [iolist_to_binary(H) || H <- Hs] end;
mod_opt_type(name) -> fun iolist_to_binary/1;
mod_opt_type(server_info) ->
fun (L) ->
lists:map(fun (Opts) ->
Mods = proplists:get_value(modules, Opts, all),
Name = proplists:get_value(name, Opts, <<>>),
URLs = proplists:get_value(urls, Opts, []),
{Mods, Name, URLs}
end,
L)
end.
mod_options(_Host) ->
[{extra_domains, []},
{server_info, []},
{name, ?T("ejabberd")}].
|
6fae0124502894b8ba52bb22eb4efe0ac184cd4f14e2a7f6ec751aa588225965 | haskell-webgear/webgear | Basic.hs | module Properties.Trait.Auth.Basic (
tests,
) where
import Control.Arrow (returnA, (>>>))
import Data.ByteString.Base64 (encode)
import Data.ByteString.Char8 (elem)
import Data.Either (fromRight)
import Data.Functor.Identity (Identity, runIdentity)
import Network.Wai (defaultRequest, requestHeaders)
import Test.QuickCheck (
Discard (..),
Property,
allProperties,
counterexample,
property,
(.&&.),
(===),
)
import Test.QuickCheck.Instances ()
import Test.Tasty (TestTree)
import Test.Tasty.QuickCheck (testProperties)
import WebGear.Core.Request (Request (..))
import WebGear.Core.Trait (Linked, getTrait, linkzero, probe)
import WebGear.Core.Trait.Auth.Basic (
BasicAuth,
BasicAuth' (..),
Credentials (..),
Password (..),
Username (..),
)
import WebGear.Core.Trait.Auth.Common (AuthorizationHeader)
import WebGear.Core.Trait.Header (Header (..))
import WebGear.Server.Handler (ServerHandler, runServerHandler)
import WebGear.Server.Trait.Auth.Basic ()
import WebGear.Server.Trait.Header ()
import Prelude hiding (elem)
prop_basicAuth :: Property
prop_basicAuth = property f
where
f (username, password)
| ':' `elem` username = property Discard
| otherwise =
let hval = "Basic " <> encode (username <> ":" <> password)
mkRequest :: ServerHandler Identity () (Linked '[AuthorizationHeader "Basic"] Request)
mkRequest = proc () -> do
let req = Request $ defaultRequest{requestHeaders = [("Authorization", hval)]}
r <- probe Header -< linkzero req
returnA -< fromRight undefined r
authCfg :: BasicAuth Identity () Credentials
authCfg = BasicAuth'{toBasicAttribute = pure . Right}
in runIdentity $ do
res <- runServerHandler (mkRequest >>> getTrait authCfg) [""] ()
pure $ case res of
Right (Right creds) ->
credentialsUsername creds === Username username
.&&. credentialsPassword creds === Password password
e -> counterexample ("Unexpected failure: " <> show e) (property False)
Hack for TH splicing
return []
tests :: TestTree
tests = testProperties "Trait.Auth.Basic" $allProperties
| null | https://raw.githubusercontent.com/haskell-webgear/webgear/13cf7733bfc090609b2d7307a3b220e99609fb4e/webgear-server/test/Properties/Trait/Auth/Basic.hs | haskell | module Properties.Trait.Auth.Basic (
tests,
) where
import Control.Arrow (returnA, (>>>))
import Data.ByteString.Base64 (encode)
import Data.ByteString.Char8 (elem)
import Data.Either (fromRight)
import Data.Functor.Identity (Identity, runIdentity)
import Network.Wai (defaultRequest, requestHeaders)
import Test.QuickCheck (
Discard (..),
Property,
allProperties,
counterexample,
property,
(.&&.),
(===),
)
import Test.QuickCheck.Instances ()
import Test.Tasty (TestTree)
import Test.Tasty.QuickCheck (testProperties)
import WebGear.Core.Request (Request (..))
import WebGear.Core.Trait (Linked, getTrait, linkzero, probe)
import WebGear.Core.Trait.Auth.Basic (
BasicAuth,
BasicAuth' (..),
Credentials (..),
Password (..),
Username (..),
)
import WebGear.Core.Trait.Auth.Common (AuthorizationHeader)
import WebGear.Core.Trait.Header (Header (..))
import WebGear.Server.Handler (ServerHandler, runServerHandler)
import WebGear.Server.Trait.Auth.Basic ()
import WebGear.Server.Trait.Header ()
import Prelude hiding (elem)
prop_basicAuth :: Property
prop_basicAuth = property f
where
f (username, password)
| ':' `elem` username = property Discard
| otherwise =
let hval = "Basic " <> encode (username <> ":" <> password)
mkRequest :: ServerHandler Identity () (Linked '[AuthorizationHeader "Basic"] Request)
mkRequest = proc () -> do
let req = Request $ defaultRequest{requestHeaders = [("Authorization", hval)]}
r <- probe Header -< linkzero req
returnA -< fromRight undefined r
authCfg :: BasicAuth Identity () Credentials
authCfg = BasicAuth'{toBasicAttribute = pure . Right}
in runIdentity $ do
res <- runServerHandler (mkRequest >>> getTrait authCfg) [""] ()
pure $ case res of
Right (Right creds) ->
credentialsUsername creds === Username username
.&&. credentialsPassword creds === Password password
e -> counterexample ("Unexpected failure: " <> show e) (property False)
Hack for TH splicing
return []
tests :: TestTree
tests = testProperties "Trait.Auth.Basic" $allProperties
| |
1bd49d4d609e106b99592fdef1f3caddcdcf1751e30ac1faecfaf35f9188a284 | ocaml-multicore/ocaml-tsan | test_c_thread_has_lock_systhread.ml | TEST
modules = " test_c_thread_has_lock_cstubs.c "
* hassysthreads
include systhreads
* * bytecode
* * native
modules = "test_c_thread_has_lock_cstubs.c"
* hassysthreads
include systhreads
** bytecode
** native
*)
external test_with_lock : unit -> bool = "with_lock"
external test_without_lock : unit -> bool = "without_lock"
let passed b = Printf.printf (if b then "passed\n" else "failed\n")
let f () =
passed (not (test_without_lock ())) ;
passed (test_with_lock ())
let _ =
f ();
let t = Thread.create f () in
Thread.join t
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/f54002470cc6ab780963cc81b11a85a820a40819/testsuite/tests/c-api/test_c_thread_has_lock_systhread.ml | ocaml | TEST
modules = " test_c_thread_has_lock_cstubs.c "
* hassysthreads
include systhreads
* * bytecode
* * native
modules = "test_c_thread_has_lock_cstubs.c"
* hassysthreads
include systhreads
** bytecode
** native
*)
external test_with_lock : unit -> bool = "with_lock"
external test_without_lock : unit -> bool = "without_lock"
let passed b = Printf.printf (if b then "passed\n" else "failed\n")
let f () =
passed (not (test_without_lock ())) ;
passed (test_with_lock ())
let _ =
f ();
let t = Thread.create f () in
Thread.join t
| |
1e610ecdd25c7d249ee346ebc0626c8cfb60bbc2aad71afa496121a1285acf0c | ocaml-multicore/ocaml-tsan | thread_sanitizer.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, Purdue University
(* *)
Copyright 2022 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
open Asttypes
open Cmm
module V = Backend_var
module VP = Backend_var.With_provenance
type read_or_write = Read | Write
let init_code () =
Cmm_helpers.return_unit Debuginfo.none @@
Cop (Cextcall ("__tsan_init", typ_void, [], false), [], Debuginfo.none)
let bit_size memory_chunk =
match memory_chunk with
| Byte_unsigned
| Byte_signed -> 8
| Sixteen_unsigned
| Sixteen_signed -> 16
| Thirtytwo_unsigned
| Thirtytwo_signed -> 32
| Word_int
| Word_val -> Sys.word_size
| Single -> 32
| Double -> 64
let select_function read_or_write memory_chunk =
let bit_size = bit_size memory_chunk in
let acc_string =
match read_or_write with Read -> "read" | Write -> "write"
in
Printf.sprintf "__tsan_%s%d" acc_string (bit_size / 8)
module TSan_memory_order = struct
(* Constants defined in the LLVM ABI *)
let acquire = Cconst_int (2, Debuginfo.none)
end
let machtype_of_memory_chunk = function
| Byte_unsigned
| Byte_signed
| Sixteen_unsigned
| Sixteen_signed
| Thirtytwo_unsigned
| Thirtytwo_signed
| Word_int -> typ_int
| Word_val -> typ_val
| Single
| Double -> typ_float
let dbg_none = Debuginfo.none
Decides whether an expression { i probably } evaluates to a value of type
[ ] . This is not intended to be foolproof , but only aims to catch the
cases that should happen in practice .
[Addr]. This is not intended to be foolproof, but only aims to catch the
cases that should happen in practice. *)
let rec has_type_addr = function
| Cconst_int (_, _) | Cconst_natint (_, _) | Cconst_float (_, _)
| Cconst_symbol (_, _) | Cassign (_, _) | Ctuple _ | Cswitch (_, _, _, _)
| Ccatch (_, _, _) | Cexit (_, _) | Ctrywith (_, _, _, _) | Creturn_addr
| Cvar _ -> false
| Clet (_, _, body)
| Clet_mut (_, _, _, body)
| Cphantom_let (_, _, body) -> has_type_addr body
| Csequence (_, e) -> has_type_addr e
| Cifthenelse (_, _, e1, _, e2, _) -> has_type_addr e1 || has_type_addr e2
| Cop (op, _, _) ->
begin match op with
| Capply [|Addr|] | Cextcall (_, [|Addr|], _, _) | Cadda -> true
| Capply _ | Cextcall _ | Cload _ | Calloc | Cstore (_, _) | Caddi | Csubi
| Cmuli | Cmulhi | Cdivi | Cmodi | Cand | Cor | Cxor | Clsl | Clsr | Casr
| Ccmpi _ | Caddv | Ccmpa _ | Cnegf | Cabsf | Caddf | Csubf | Cmulf
| Cdivf | Cfloatofint | Cintoffloat | Ccmpf _ | Craise _ | Ccheckbound
| Copaque | Cdls_get -> false
end
type replace_or_not = Keep of Cmm.expression | Replace of VP.t * Cmm.expression
let wrap_entry_exit expr =
let call_entry =
Cmm_helpers.return_unit dbg_none @@
Cop
(Cextcall ("__tsan_func_entry", typ_void, [], false),
[Creturn_addr],
dbg_none)
in
let call_exit = Cmm_helpers.return_unit dbg_none @@ Cop (
Cextcall ("__tsan_func_exit", typ_void, [], false), [], dbg_none)
in
(* [is_tail] is true when the expression is in tail position *)
let rec insert_call_exit is_tail = function
| Clet (v, e, body) -> Clet (v, e, insert_call_exit is_tail body)
| Clet_mut (v, typ, e, body) ->
Clet_mut (v, typ, e, insert_call_exit is_tail body)
| Cphantom_let (v, e, body) ->
Cphantom_let (v, e, insert_call_exit is_tail body)
| Cassign (v, body) -> Cassign (v, insert_call_exit is_tail body)
| Csequence (op1, op2) -> Csequence (op1, insert_call_exit is_tail op2)
| Cifthenelse (cond, t_dbg, t, f_dbg, f, dbg_none) ->
Cifthenelse (cond, t_dbg, insert_call_exit is_tail t, f_dbg,
insert_call_exit is_tail f, dbg_none)
| Cswitch (e, cases, handlers, dbg_none) ->
let handlers = Array.map
(fun (handler, handler_dbg) ->
(insert_call_exit is_tail handler, handler_dbg))
handlers
in
Cswitch (e, cases, handlers, dbg_none)
| Ccatch (isrec, handlers, next) ->
let handlers = List.map
(fun (id, args, e, dbg_none) ->
(id, args, insert_call_exit is_tail e, dbg_none))
handlers
in
Ccatch (isrec, handlers, insert_call_exit is_tail next)
| Cexit (ex, args) ->
(* A [Cexit] is like a goto to the beginning of a handler. Therefore,
it is never the last thing evaluated in a function; there is no need
to insert a call to [__tsan_func_exit] here. *)
Cexit (ex, args)
| Ctrywith (e, v, handler, dbg_none) ->
(* We need to insert a call to [__tsan_func_exit] at the tail of both
the body and the handler. If this is a [try ... with] in tail
position, then the body expression is not in tail position (as code
is inserted at the end of it to pop the exception handler), the
handler expression is. *)
Ctrywith
(insert_call_exit false e,
v,
insert_call_exit is_tail handler,
dbg_none)
| Cop (Capply fn, args, dbg_none) when is_tail ->
This is a tail call . We insert the call to [ _ _ tsan_func_exit ] right
before the call , but after evaluating the arguments . We make an
exception for arguments which evaluate to a value of type [ ] , as
such values should never be live across a function call or
allocation point .
before the call, but after evaluating the arguments. We make an
exception for arguments which evaluate to a value of type [Addr], as
such values should never be live across a function call or
allocation point. *)
let fun_ = List.hd args in
let replace_args =
List.map
(fun e ->
if has_type_addr e
then Keep e
else Replace (VP.create (V.create_local "arg"), e))
(List.tl args)
in
let tail =
Csequence
(call_exit,
(Cop
(Capply fn,
fun_
:: List.map
(function
| Replace (id,_) -> Cvar (VP.var id)
| Keep e -> e)
replace_args,
dbg_none)))
in
List.fold_right
(fun keep_or_replace acc ->
match keep_or_replace with
| Keep _ -> acc
| Replace (id,arg) -> Clet (id, arg, acc))
replace_args
tail
| Cconst_int (_, _) | Cconst_natint (_, _) | Cconst_float (_, _)
| Cconst_symbol (_, _) | Cvar _ | Ctuple _ | Cop (_, _, _)
| Creturn_addr as expr ->
let id = VP.create (V.create_local "res") in
Clet (id, expr, Csequence (call_exit, Cvar (VP.var id)))
in
Csequence (call_entry, insert_call_exit true expr)
let instrument _label body =
let rec aux = function
| Cop (Cload {memory_chunk; mutability=Mutable; is_atomic=false} as load_op,
[loc], dbginfo) ->
(* Emit a call to [__tsan_readN] before the load *)
let loc_id = VP.create (V.create_local "loc") in
let loc_exp = Cvar (VP.var loc_id) in
Clet (loc_id, loc,
Csequence
(Cmm_helpers.return_unit dbg_none (Cop
(Cextcall (select_function Read memory_chunk, typ_void,
[], false),
[loc_exp], dbg_none)),
Cop (load_op, [loc_exp], dbginfo)))
| Cop (Cload {memory_chunk; mutability=Mutable; is_atomic=true},
[loc], dbginfo) ->
Replace the atomic load with a call to [ _ _ ]
let ret_typ = machtype_of_memory_chunk memory_chunk in
Cop (Cextcall
(Printf.sprintf "__tsan_atomic%d_load" (bit_size memory_chunk),
ret_typ, [], false),
[loc; TSan_memory_order.acquire], dbginfo)
| Cop (Cload {memory_chunk=_; mutability=Mutable; is_atomic=_},
_ :: _, _) ->
invalid_arg "instrument: wrong number of arguments for operation Cload"
| Cop (Cstore(memory_chunk, init_or_assn), [loc;v], dbginfo) as c ->
(* Emit a call to [__tsan_writeN] before the store *)
begin match init_or_assn with
| Assignment ->
We make sure that 1 . the location and value expressions are
evaluated before the call to TSan , and 2 . the location
expression is evaluated right before that call , as it might not
be a valid OCaml value ( e.g. a pointer into an array ) , in which
case it must not be live across a function call or allocation
point .
evaluated before the call to TSan, and 2. the location
expression is evaluated right before that call, as it might not
be a valid OCaml value (e.g. a pointer into an array), in which
case it must not be live across a function call or allocation
point. *)
let loc_id = VP.create (V.create_local "loc") in
let loc_exp = Cvar (VP.var loc_id) in
let v_id = VP.create (V.create_local "newval") in
let v_exp = Cvar (VP.var v_id) in
let args = [loc_exp; v_exp] in
Clet (v_id, v,
Clet (loc_id, loc,
Csequence
(Cmm_helpers.return_unit dbg_none (Cop (Cextcall
(select_function Write memory_chunk, typ_void, [],
false),
[loc_exp], dbg_none)),
Cop (Cstore (memory_chunk, init_or_assn), args, dbginfo))))
| Heap_initialization | Root_initialization ->
(* Initializing writes need not be instrumented as they are always
domain-safe *)
c
end
| Cop (Cstore _, _, _) ->
invalid_arg "instrument: wrong number of arguments for operation Cstore"
| Cop (op, es, dbg_none) -> Cop (op, List.map aux es, dbg_none)
| Clet (v, e, body) -> Clet (v, aux e, aux body)
| Clet_mut (v, k, e, body) -> Clet_mut (v, k, aux e, aux body)
| Cphantom_let (v, e, body) -> Cphantom_let (v, e, aux body)
| Cassign (v, e) -> Cassign (v, aux e)
| Ctuple es -> Ctuple (List.map aux es)
| Csequence(c1,c2) -> Csequence(aux c1, aux c2)
| Ccatch (isrec, cases, body) ->
let cases =
List.map (fun (nfail, ids, e, dbg_none) ->
(nfail, ids, aux e, dbg_none))
cases
in
Ccatch (isrec, cases, aux body)
| Cexit (ex, args) -> Cexit (ex, List.map aux args)
| Cifthenelse (cond, t_dbg, t, f_dbg, f, dbg_none) ->
Cifthenelse (aux cond, t_dbg, aux t, f_dbg, aux f, dbg_none)
| Ctrywith (e, ex, handler, dbg_none) ->
Ctrywith (aux e, ex, aux handler, dbg_none)
| Cswitch (e, cases, handlers, dbg_none) ->
let handlers =
handlers |> Array.map (fun (handler, handler_dbg) ->
(aux handler, handler_dbg))
in
Cswitch(aux e, cases, handlers, dbg_none)
(* no instrumentation *)
| Cconst_int _ | Cconst_natint _ | Cconst_float _
| Cconst_symbol _ | Cvar _ | Creturn_addr as c -> c
in
body |> aux |> wrap_entry_exit
| null | https://raw.githubusercontent.com/ocaml-multicore/ocaml-tsan/e5bffcf5bb9835f31bb67cc13e7e1504b4642692/asmcomp/thread_sanitizer.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Constants defined in the LLVM ABI
[is_tail] is true when the expression is in tail position
A [Cexit] is like a goto to the beginning of a handler. Therefore,
it is never the last thing evaluated in a function; there is no need
to insert a call to [__tsan_func_exit] here.
We need to insert a call to [__tsan_func_exit] at the tail of both
the body and the handler. If this is a [try ... with] in tail
position, then the body expression is not in tail position (as code
is inserted at the end of it to pop the exception handler), the
handler expression is.
Emit a call to [__tsan_readN] before the load
Emit a call to [__tsan_writeN] before the store
Initializing writes need not be instrumented as they are always
domain-safe
no instrumentation | , Purdue University
Copyright 2022 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
open Asttypes
open Cmm
module V = Backend_var
module VP = Backend_var.With_provenance
type read_or_write = Read | Write
let init_code () =
Cmm_helpers.return_unit Debuginfo.none @@
Cop (Cextcall ("__tsan_init", typ_void, [], false), [], Debuginfo.none)
let bit_size memory_chunk =
match memory_chunk with
| Byte_unsigned
| Byte_signed -> 8
| Sixteen_unsigned
| Sixteen_signed -> 16
| Thirtytwo_unsigned
| Thirtytwo_signed -> 32
| Word_int
| Word_val -> Sys.word_size
| Single -> 32
| Double -> 64
let select_function read_or_write memory_chunk =
let bit_size = bit_size memory_chunk in
let acc_string =
match read_or_write with Read -> "read" | Write -> "write"
in
Printf.sprintf "__tsan_%s%d" acc_string (bit_size / 8)
module TSan_memory_order = struct
let acquire = Cconst_int (2, Debuginfo.none)
end
let machtype_of_memory_chunk = function
| Byte_unsigned
| Byte_signed
| Sixteen_unsigned
| Sixteen_signed
| Thirtytwo_unsigned
| Thirtytwo_signed
| Word_int -> typ_int
| Word_val -> typ_val
| Single
| Double -> typ_float
let dbg_none = Debuginfo.none
Decides whether an expression { i probably } evaluates to a value of type
[ ] . This is not intended to be foolproof , but only aims to catch the
cases that should happen in practice .
[Addr]. This is not intended to be foolproof, but only aims to catch the
cases that should happen in practice. *)
let rec has_type_addr = function
| Cconst_int (_, _) | Cconst_natint (_, _) | Cconst_float (_, _)
| Cconst_symbol (_, _) | Cassign (_, _) | Ctuple _ | Cswitch (_, _, _, _)
| Ccatch (_, _, _) | Cexit (_, _) | Ctrywith (_, _, _, _) | Creturn_addr
| Cvar _ -> false
| Clet (_, _, body)
| Clet_mut (_, _, _, body)
| Cphantom_let (_, _, body) -> has_type_addr body
| Csequence (_, e) -> has_type_addr e
| Cifthenelse (_, _, e1, _, e2, _) -> has_type_addr e1 || has_type_addr e2
| Cop (op, _, _) ->
begin match op with
| Capply [|Addr|] | Cextcall (_, [|Addr|], _, _) | Cadda -> true
| Capply _ | Cextcall _ | Cload _ | Calloc | Cstore (_, _) | Caddi | Csubi
| Cmuli | Cmulhi | Cdivi | Cmodi | Cand | Cor | Cxor | Clsl | Clsr | Casr
| Ccmpi _ | Caddv | Ccmpa _ | Cnegf | Cabsf | Caddf | Csubf | Cmulf
| Cdivf | Cfloatofint | Cintoffloat | Ccmpf _ | Craise _ | Ccheckbound
| Copaque | Cdls_get -> false
end
type replace_or_not = Keep of Cmm.expression | Replace of VP.t * Cmm.expression
let wrap_entry_exit expr =
let call_entry =
Cmm_helpers.return_unit dbg_none @@
Cop
(Cextcall ("__tsan_func_entry", typ_void, [], false),
[Creturn_addr],
dbg_none)
in
let call_exit = Cmm_helpers.return_unit dbg_none @@ Cop (
Cextcall ("__tsan_func_exit", typ_void, [], false), [], dbg_none)
in
let rec insert_call_exit is_tail = function
| Clet (v, e, body) -> Clet (v, e, insert_call_exit is_tail body)
| Clet_mut (v, typ, e, body) ->
Clet_mut (v, typ, e, insert_call_exit is_tail body)
| Cphantom_let (v, e, body) ->
Cphantom_let (v, e, insert_call_exit is_tail body)
| Cassign (v, body) -> Cassign (v, insert_call_exit is_tail body)
| Csequence (op1, op2) -> Csequence (op1, insert_call_exit is_tail op2)
| Cifthenelse (cond, t_dbg, t, f_dbg, f, dbg_none) ->
Cifthenelse (cond, t_dbg, insert_call_exit is_tail t, f_dbg,
insert_call_exit is_tail f, dbg_none)
| Cswitch (e, cases, handlers, dbg_none) ->
let handlers = Array.map
(fun (handler, handler_dbg) ->
(insert_call_exit is_tail handler, handler_dbg))
handlers
in
Cswitch (e, cases, handlers, dbg_none)
| Ccatch (isrec, handlers, next) ->
let handlers = List.map
(fun (id, args, e, dbg_none) ->
(id, args, insert_call_exit is_tail e, dbg_none))
handlers
in
Ccatch (isrec, handlers, insert_call_exit is_tail next)
| Cexit (ex, args) ->
Cexit (ex, args)
| Ctrywith (e, v, handler, dbg_none) ->
Ctrywith
(insert_call_exit false e,
v,
insert_call_exit is_tail handler,
dbg_none)
| Cop (Capply fn, args, dbg_none) when is_tail ->
This is a tail call . We insert the call to [ _ _ tsan_func_exit ] right
before the call , but after evaluating the arguments . We make an
exception for arguments which evaluate to a value of type [ ] , as
such values should never be live across a function call or
allocation point .
before the call, but after evaluating the arguments. We make an
exception for arguments which evaluate to a value of type [Addr], as
such values should never be live across a function call or
allocation point. *)
let fun_ = List.hd args in
let replace_args =
List.map
(fun e ->
if has_type_addr e
then Keep e
else Replace (VP.create (V.create_local "arg"), e))
(List.tl args)
in
let tail =
Csequence
(call_exit,
(Cop
(Capply fn,
fun_
:: List.map
(function
| Replace (id,_) -> Cvar (VP.var id)
| Keep e -> e)
replace_args,
dbg_none)))
in
List.fold_right
(fun keep_or_replace acc ->
match keep_or_replace with
| Keep _ -> acc
| Replace (id,arg) -> Clet (id, arg, acc))
replace_args
tail
| Cconst_int (_, _) | Cconst_natint (_, _) | Cconst_float (_, _)
| Cconst_symbol (_, _) | Cvar _ | Ctuple _ | Cop (_, _, _)
| Creturn_addr as expr ->
let id = VP.create (V.create_local "res") in
Clet (id, expr, Csequence (call_exit, Cvar (VP.var id)))
in
Csequence (call_entry, insert_call_exit true expr)
let instrument _label body =
let rec aux = function
| Cop (Cload {memory_chunk; mutability=Mutable; is_atomic=false} as load_op,
[loc], dbginfo) ->
let loc_id = VP.create (V.create_local "loc") in
let loc_exp = Cvar (VP.var loc_id) in
Clet (loc_id, loc,
Csequence
(Cmm_helpers.return_unit dbg_none (Cop
(Cextcall (select_function Read memory_chunk, typ_void,
[], false),
[loc_exp], dbg_none)),
Cop (load_op, [loc_exp], dbginfo)))
| Cop (Cload {memory_chunk; mutability=Mutable; is_atomic=true},
[loc], dbginfo) ->
Replace the atomic load with a call to [ _ _ ]
let ret_typ = machtype_of_memory_chunk memory_chunk in
Cop (Cextcall
(Printf.sprintf "__tsan_atomic%d_load" (bit_size memory_chunk),
ret_typ, [], false),
[loc; TSan_memory_order.acquire], dbginfo)
| Cop (Cload {memory_chunk=_; mutability=Mutable; is_atomic=_},
_ :: _, _) ->
invalid_arg "instrument: wrong number of arguments for operation Cload"
| Cop (Cstore(memory_chunk, init_or_assn), [loc;v], dbginfo) as c ->
begin match init_or_assn with
| Assignment ->
We make sure that 1 . the location and value expressions are
evaluated before the call to TSan , and 2 . the location
expression is evaluated right before that call , as it might not
be a valid OCaml value ( e.g. a pointer into an array ) , in which
case it must not be live across a function call or allocation
point .
evaluated before the call to TSan, and 2. the location
expression is evaluated right before that call, as it might not
be a valid OCaml value (e.g. a pointer into an array), in which
case it must not be live across a function call or allocation
point. *)
let loc_id = VP.create (V.create_local "loc") in
let loc_exp = Cvar (VP.var loc_id) in
let v_id = VP.create (V.create_local "newval") in
let v_exp = Cvar (VP.var v_id) in
let args = [loc_exp; v_exp] in
Clet (v_id, v,
Clet (loc_id, loc,
Csequence
(Cmm_helpers.return_unit dbg_none (Cop (Cextcall
(select_function Write memory_chunk, typ_void, [],
false),
[loc_exp], dbg_none)),
Cop (Cstore (memory_chunk, init_or_assn), args, dbginfo))))
| Heap_initialization | Root_initialization ->
c
end
| Cop (Cstore _, _, _) ->
invalid_arg "instrument: wrong number of arguments for operation Cstore"
| Cop (op, es, dbg_none) -> Cop (op, List.map aux es, dbg_none)
| Clet (v, e, body) -> Clet (v, aux e, aux body)
| Clet_mut (v, k, e, body) -> Clet_mut (v, k, aux e, aux body)
| Cphantom_let (v, e, body) -> Cphantom_let (v, e, aux body)
| Cassign (v, e) -> Cassign (v, aux e)
| Ctuple es -> Ctuple (List.map aux es)
| Csequence(c1,c2) -> Csequence(aux c1, aux c2)
| Ccatch (isrec, cases, body) ->
let cases =
List.map (fun (nfail, ids, e, dbg_none) ->
(nfail, ids, aux e, dbg_none))
cases
in
Ccatch (isrec, cases, aux body)
| Cexit (ex, args) -> Cexit (ex, List.map aux args)
| Cifthenelse (cond, t_dbg, t, f_dbg, f, dbg_none) ->
Cifthenelse (aux cond, t_dbg, aux t, f_dbg, aux f, dbg_none)
| Ctrywith (e, ex, handler, dbg_none) ->
Ctrywith (aux e, ex, aux handler, dbg_none)
| Cswitch (e, cases, handlers, dbg_none) ->
let handlers =
handlers |> Array.map (fun (handler, handler_dbg) ->
(aux handler, handler_dbg))
in
Cswitch(aux e, cases, handlers, dbg_none)
| Cconst_int _ | Cconst_natint _ | Cconst_float _
| Cconst_symbol _ | Cvar _ | Creturn_addr as c -> c
in
body |> aux |> wrap_entry_exit
|
d90cc4bc45c3a8a19c9bf8b2ecf5c99734996310619db63fd82c5d15d5af532a | imandra-ai/catapult | backend.ml | open Catapult_utils
module P = Catapult
module Tracing = P.Tracing
module Atomic = P.Atomic_shim_
type event = P.Ser.Event.t
module type ARG = sig
val writer : Writer.t
end
module Make (A : ARG) : P.BACKEND = struct
let writer = A.writer
type local_buf = {
t_id: int;
buf: Buffer.t;
mutable evs: string list; (* batch *)
mutable n_evs: int;
}
let batch_size =
try int_of_string @@ Sys.getenv "TRACE_BATCH_SIZE" with _ -> 100
max time between 2 flushes
let last_batch_flush = Atomic.make (P.Clock.now_us ())
(* send current batch to the writer *)
let flush_batch (self : local_buf) : unit =
if self.n_evs > 0 then (
let b = List.rev self.evs in
self.evs <- [];
self.n_evs <- 0;
Writer.write_string_l writer b
)
(* check if we need to flush the batch *)
let check_batch (self : local_buf) ~now : unit =
if
self.n_evs > batch_size
|| self.n_evs > 0
&& now -. Atomic.get last_batch_flush > max_batch_interval_us
then (
Atomic.set last_batch_flush now;
flush_batch self
)
(* per-thread buffer *)
let buf : local_buf Thread_local.t =
Thread_local.create
~init:(fun ~t_id ->
{ t_id; buf = Buffer.create 1024; n_evs = 0; evs = [] })
~close:flush_batch ()
let teardown () =
Thread_local.clear buf;
Writer.close writer
let tick () =
let now = P.Clock.now_us () in
Thread_local.iter buf ~f:(check_batch ~now)
module Out = Catapult_utils.Json_out
let[@inline] field_col oc = Out.char oc ':'
let[@inline] field_sep oc = Out.char oc ','
let any_val oc (j : string) = Out.raw_string oc j
(* emit [k:v] using printer [f] for the value *)
let field oc k f v : unit =
Out.raw_string oc k;
field_col oc;
f oc v
let[@inline] opt_iter o f =
match o with
| None -> ()
| Some x -> f x
let emit ~id ~name ~ph ~tid ~pid ~cat ~ts_us ~args ~stack ~dur ?extra () :
unit =
(* access local buffer to write and add to batch *)
let lbuf = Thread_local.get_or_create buf in
let j =
let buf = lbuf.buf in
Buffer.clear buf;
Out.char buf '{';
field buf {|"name"|} Out.str_val name;
field_sep buf;
field buf {|"ph"|} Out.char_val (P.Event_type.to_char ph);
field_sep buf;
field buf {|"tid"|} any_val (string_of_int tid);
field_sep buf;
field buf {|"ts"|} Out.float ts_us;
field_sep buf;
opt_iter dur (fun dur ->
field buf {|"dur"|} Out.float dur;
field_sep buf);
opt_iter id (fun i ->
field buf {|"id"|} Out.str_val i;
field_sep buf);
opt_iter stack (fun s ->
Out.raw_string buf {|"stack"|};
field_col buf;
Out.char buf '[';
List.iteri
(fun i x ->
if i > 0 then field_sep buf;
any_val buf x)
s;
Out.char buf ']';
field_sep buf);
opt_iter cat (fun cs ->
Out.raw_string buf {|"cat"|};
field_col buf;
Out.char buf '"';
List.iteri
(fun i x ->
if i > 0 then field_sep buf;
Out.raw_string buf x)
cs;
Out.char buf '"';
field_sep buf);
opt_iter args (fun args ->
Out.raw_string buf {|"args"|};
field_col buf;
Out.char buf '{';
List.iteri
(fun i (k, v) ->
if i > 0 then field_sep buf;
Out.str_val buf k;
field_col buf;
Out.arg buf (v : P.Arg.t))
args;
Out.char buf '}';
field_sep buf);
opt_iter extra (fun l ->
List.iter
(fun (x, y) ->
Out.str_val buf x;
field_col buf;
Out.str_val buf y;
field_sep buf)
l);
field buf {|"pid"|} Out.int pid;
Out.char buf '}';
Buffer.contents buf
in
lbuf.evs <- j :: lbuf.evs;
lbuf.n_evs <- 1 + lbuf.n_evs;
see if we need to flush batch or emit GC counters
check_batch lbuf ~now:ts_us;
Gc_stats.maybe_emit ~now:ts_us ~pid ();
()
end
| null | https://raw.githubusercontent.com/imandra-ai/catapult/4bc5444a8471c5d0d7cb9a376a5a895c0ab042e6/src/sqlite/backend.ml | ocaml | batch
send current batch to the writer
check if we need to flush the batch
per-thread buffer
emit [k:v] using printer [f] for the value
access local buffer to write and add to batch | open Catapult_utils
module P = Catapult
module Tracing = P.Tracing
module Atomic = P.Atomic_shim_
type event = P.Ser.Event.t
module type ARG = sig
val writer : Writer.t
end
module Make (A : ARG) : P.BACKEND = struct
let writer = A.writer
type local_buf = {
t_id: int;
buf: Buffer.t;
mutable n_evs: int;
}
let batch_size =
try int_of_string @@ Sys.getenv "TRACE_BATCH_SIZE" with _ -> 100
max time between 2 flushes
let last_batch_flush = Atomic.make (P.Clock.now_us ())
let flush_batch (self : local_buf) : unit =
if self.n_evs > 0 then (
let b = List.rev self.evs in
self.evs <- [];
self.n_evs <- 0;
Writer.write_string_l writer b
)
let check_batch (self : local_buf) ~now : unit =
if
self.n_evs > batch_size
|| self.n_evs > 0
&& now -. Atomic.get last_batch_flush > max_batch_interval_us
then (
Atomic.set last_batch_flush now;
flush_batch self
)
let buf : local_buf Thread_local.t =
Thread_local.create
~init:(fun ~t_id ->
{ t_id; buf = Buffer.create 1024; n_evs = 0; evs = [] })
~close:flush_batch ()
let teardown () =
Thread_local.clear buf;
Writer.close writer
let tick () =
let now = P.Clock.now_us () in
Thread_local.iter buf ~f:(check_batch ~now)
module Out = Catapult_utils.Json_out
let[@inline] field_col oc = Out.char oc ':'
let[@inline] field_sep oc = Out.char oc ','
let any_val oc (j : string) = Out.raw_string oc j
let field oc k f v : unit =
Out.raw_string oc k;
field_col oc;
f oc v
let[@inline] opt_iter o f =
match o with
| None -> ()
| Some x -> f x
let emit ~id ~name ~ph ~tid ~pid ~cat ~ts_us ~args ~stack ~dur ?extra () :
unit =
let lbuf = Thread_local.get_or_create buf in
let j =
let buf = lbuf.buf in
Buffer.clear buf;
Out.char buf '{';
field buf {|"name"|} Out.str_val name;
field_sep buf;
field buf {|"ph"|} Out.char_val (P.Event_type.to_char ph);
field_sep buf;
field buf {|"tid"|} any_val (string_of_int tid);
field_sep buf;
field buf {|"ts"|} Out.float ts_us;
field_sep buf;
opt_iter dur (fun dur ->
field buf {|"dur"|} Out.float dur;
field_sep buf);
opt_iter id (fun i ->
field buf {|"id"|} Out.str_val i;
field_sep buf);
opt_iter stack (fun s ->
Out.raw_string buf {|"stack"|};
field_col buf;
Out.char buf '[';
List.iteri
(fun i x ->
if i > 0 then field_sep buf;
any_val buf x)
s;
Out.char buf ']';
field_sep buf);
opt_iter cat (fun cs ->
Out.raw_string buf {|"cat"|};
field_col buf;
Out.char buf '"';
List.iteri
(fun i x ->
if i > 0 then field_sep buf;
Out.raw_string buf x)
cs;
Out.char buf '"';
field_sep buf);
opt_iter args (fun args ->
Out.raw_string buf {|"args"|};
field_col buf;
Out.char buf '{';
List.iteri
(fun i (k, v) ->
if i > 0 then field_sep buf;
Out.str_val buf k;
field_col buf;
Out.arg buf (v : P.Arg.t))
args;
Out.char buf '}';
field_sep buf);
opt_iter extra (fun l ->
List.iter
(fun (x, y) ->
Out.str_val buf x;
field_col buf;
Out.str_val buf y;
field_sep buf)
l);
field buf {|"pid"|} Out.int pid;
Out.char buf '}';
Buffer.contents buf
in
lbuf.evs <- j :: lbuf.evs;
lbuf.n_evs <- 1 + lbuf.n_evs;
see if we need to flush batch or emit GC counters
check_batch lbuf ~now:ts_us;
Gc_stats.maybe_emit ~now:ts_us ~pid ();
()
end
|
43d31810aac9f2b803aa1c078efd4122d0f20718b3035148d3a91121782a4139 | kawasima/darzana | mapper_test.clj | (ns darzana.command.mapper-test
(:require [integrant.core :as ig]
[duct.core :as duct]
[darzana.command.mapper :as sut]
[darzana.api-spec.swagger]
[darzana.validator.hibernate-validator]
[darzana.runtime :as runtime]
[clojure.test :refer :all]))
(duct/load-hierarchy)
(deftest mapper
(let [config {:darzana.api-spec/swagger {:swagger-path "dev/resources/darzana"}
:darzana.validator/hibernate-validator {}
:darzana/runtime {:routes-path "dev/resources/scripts"
:commands [['darzana.command.api :as 'api]
['darzana.command.control :as 'control]
['darzana.command.mapper :as 'mapper]
['darzana.command.renderer :as 'renderer]]
:validator (ig/ref :darzana/validator)
:api-spec (ig/ref :darzana/api-spec)}}
system (ig/init config)
runtime (:darzana/runtime system)
ctx (runtime/create-context runtime {:params {:id "1" :name "I'm cat"}})
api {:id "petstore" :path "/pet" :method :post}]
(let [pet (-> (sut/read-value ctx {:scope :params} {:var :pet :type io.swagger.model.Pet})
(get-in [:scope :page :pet]))]
(is (= 1 (.getId pet)) "ID of the pet is 1")
(is (= "I'm cat" (.getName pet)) ))))
| null | https://raw.githubusercontent.com/kawasima/darzana/4b37c8556f74219b707d23cb2d6dce70509a0c1b/test/darzana/command/mapper_test.clj | clojure | (ns darzana.command.mapper-test
(:require [integrant.core :as ig]
[duct.core :as duct]
[darzana.command.mapper :as sut]
[darzana.api-spec.swagger]
[darzana.validator.hibernate-validator]
[darzana.runtime :as runtime]
[clojure.test :refer :all]))
(duct/load-hierarchy)
(deftest mapper
(let [config {:darzana.api-spec/swagger {:swagger-path "dev/resources/darzana"}
:darzana.validator/hibernate-validator {}
:darzana/runtime {:routes-path "dev/resources/scripts"
:commands [['darzana.command.api :as 'api]
['darzana.command.control :as 'control]
['darzana.command.mapper :as 'mapper]
['darzana.command.renderer :as 'renderer]]
:validator (ig/ref :darzana/validator)
:api-spec (ig/ref :darzana/api-spec)}}
system (ig/init config)
runtime (:darzana/runtime system)
ctx (runtime/create-context runtime {:params {:id "1" :name "I'm cat"}})
api {:id "petstore" :path "/pet" :method :post}]
(let [pet (-> (sut/read-value ctx {:scope :params} {:var :pet :type io.swagger.model.Pet})
(get-in [:scope :page :pet]))]
(is (= 1 (.getId pet)) "ID of the pet is 1")
(is (= "I'm cat" (.getName pet)) ))))
| |
8fe7148b8aa75d534bb49254417d5f4bc3a48022aed099f9a92154ab51e844a5 | RobBlackwell/cl-azure | media.lisp | ;;;; media.lisp
Copyright ( c ) 2012 , . All rights reserved .
(in-package #:cl-azure)
See Windows Azure Media Services REST API Reference
;;; See -us/library/windowsazure/hh973618.aspx
(defconstant +media-oauth-url+ "-13")
(defconstant +media-api-url+ "-hs.cloudapp.net/api/")
Define a protocol for dealing with Windows Azure Media Services credentials
(defgeneric media-account-name (account))
(defgeneric media-account-key (account))
(defgeneric media-oauth-url (account))
(defgeneric media-api-url (account))
(defgeneric media-access-token (account))
;;; and a default implementation
(defparameter *media-account* (list :media-account-name "YOUR_ACCOUNT"
:media-account-key "YOUR_KEY"
:media-oauth-url +media-oauth-url+
:media-api-url +media-api-url+))
(defun make-media-account (name key)
""
(list :media-account-name name
:media-account-key key
:media-oauth-url +media-oauth-url+
:media-api-url +media-api-url+))
(defmethod media-account-name ((media-account cons))
(getf media-account :media-account-name))
(defmethod media-account-key ((media-account cons))
(getf media-account :media-account-key))
(defmethod media-oauth-url ((media-account cons))
(getf media-account :media-oauth-url))
(defmethod media-api-url ((media-account cons))
(getf media-account :media-api-url))
(defun json-handler (response)
"Handles and decodes an HTTP response in JSON format."
(if (eq (response-status response) +HTTP-OK+)
(json:decode-json-from-string (my-utf8-bytes-to-string (response-body response)))
response))
;;; The REST API
(defparameter *get-media-token-template*
"grant_type=client_credentials&client_id=~a&client_secret=~a&scope=urn%3aWindowsAzureMediaServices")
(defun get-media-token (&key (account *media-account*)(handler #'json-handler))
"Requests a token from the OAuth v2 endpoint of ACS."
(let ((content (format nil *get-media-token-template* (media-account-name account) (drakma::url-encode (media-account-key account) :utf-8))))
(funcall handler
(web-request
(list :method :post
:uri (media-oauth-url account)
:headers (list (cons "Content-Type" "application/x-www-form-urlencoded")
(cons "Expect" "100-continue")
(cons "Connection" "Keep-Alive"))
:body content)))))
(defmethod media-access-token ((media-account cons))
(let ((token (getf media-account :media-token)))
(if token
(assoc :access--token token)
(rest (assoc :access--token (get-media-token :account media-account))))))
(defun media-request (method resource &key (media-account *media-account*)
(content nil)
(handler #'json-handler))
"Makes an HTTP request to the Media Services REST API."
(let ((token (media-access-token media-account)))
(funcall handler
(web-request
(list :method method
:uri (format nil "~a~a" (media-api-url media-account) resource)
:headers (list (cons "Content-Type" "application/json;odata=verbose")
(cons "Accept" "application/json;odata=verbose")
(cons "DataServiceVersion" "3.0")
(cons "MaxDataServiceVersion" "3.0")
(cons "x-ms-version" "1.0")
(cons "Authorization" (format nil "Bearer ~a" token)))
:body content)))))
(defun get-media-processors(&key (media-account *media-account*) (handler #'json-handler))
(media-request :get "MediaProcessors" :media-account media-account :handler handler))
(defun get-media-assets (&key (media-account *media-account*) (handler #'json-handler))
(media-request :get "Assets" :media-account media-account :handler handler))
(defun get-media-jobs(&key (media-account *media-account*) (handler #'json-handler))
(media-request :get "Jobs" :media-account media-account :handler handler))
| null | https://raw.githubusercontent.com/RobBlackwell/cl-azure/03b097256d85ea09f090987c0c833c61eb7b9b5d/media.lisp | lisp | media.lisp
See -us/library/windowsazure/hh973618.aspx
and a default implementation
The REST API | Copyright ( c ) 2012 , . All rights reserved .
(in-package #:cl-azure)
See Windows Azure Media Services REST API Reference
(defconstant +media-oauth-url+ "-13")
(defconstant +media-api-url+ "-hs.cloudapp.net/api/")
Define a protocol for dealing with Windows Azure Media Services credentials
(defgeneric media-account-name (account))
(defgeneric media-account-key (account))
(defgeneric media-oauth-url (account))
(defgeneric media-api-url (account))
(defgeneric media-access-token (account))
(defparameter *media-account* (list :media-account-name "YOUR_ACCOUNT"
:media-account-key "YOUR_KEY"
:media-oauth-url +media-oauth-url+
:media-api-url +media-api-url+))
(defun make-media-account (name key)
""
(list :media-account-name name
:media-account-key key
:media-oauth-url +media-oauth-url+
:media-api-url +media-api-url+))
(defmethod media-account-name ((media-account cons))
(getf media-account :media-account-name))
(defmethod media-account-key ((media-account cons))
(getf media-account :media-account-key))
(defmethod media-oauth-url ((media-account cons))
(getf media-account :media-oauth-url))
(defmethod media-api-url ((media-account cons))
(getf media-account :media-api-url))
(defun json-handler (response)
"Handles and decodes an HTTP response in JSON format."
(if (eq (response-status response) +HTTP-OK+)
(json:decode-json-from-string (my-utf8-bytes-to-string (response-body response)))
response))
(defparameter *get-media-token-template*
"grant_type=client_credentials&client_id=~a&client_secret=~a&scope=urn%3aWindowsAzureMediaServices")
(defun get-media-token (&key (account *media-account*)(handler #'json-handler))
"Requests a token from the OAuth v2 endpoint of ACS."
(let ((content (format nil *get-media-token-template* (media-account-name account) (drakma::url-encode (media-account-key account) :utf-8))))
(funcall handler
(web-request
(list :method :post
:uri (media-oauth-url account)
:headers (list (cons "Content-Type" "application/x-www-form-urlencoded")
(cons "Expect" "100-continue")
(cons "Connection" "Keep-Alive"))
:body content)))))
(defmethod media-access-token ((media-account cons))
(let ((token (getf media-account :media-token)))
(if token
(assoc :access--token token)
(rest (assoc :access--token (get-media-token :account media-account))))))
(defun media-request (method resource &key (media-account *media-account*)
(content nil)
(handler #'json-handler))
"Makes an HTTP request to the Media Services REST API."
(let ((token (media-access-token media-account)))
(funcall handler
(web-request
(list :method method
:uri (format nil "~a~a" (media-api-url media-account) resource)
:headers (list (cons "Content-Type" "application/json;odata=verbose")
(cons "Accept" "application/json;odata=verbose")
(cons "DataServiceVersion" "3.0")
(cons "MaxDataServiceVersion" "3.0")
(cons "x-ms-version" "1.0")
(cons "Authorization" (format nil "Bearer ~a" token)))
:body content)))))
(defun get-media-processors(&key (media-account *media-account*) (handler #'json-handler))
(media-request :get "MediaProcessors" :media-account media-account :handler handler))
(defun get-media-assets (&key (media-account *media-account*) (handler #'json-handler))
(media-request :get "Assets" :media-account media-account :handler handler))
(defun get-media-jobs(&key (media-account *media-account*) (handler #'json-handler))
(media-request :get "Jobs" :media-account media-account :handler handler))
|
8f5e07b9ab700f04841129651ba45b3fa3a84034fc418b2b5e5423c8b0cbd3dc | poroh/ersip | ersip_reply.erl | %%
Copyright ( c ) 2018 Dmitry Poroh
%% All rights reserved.
Distributed under the terms of the MIT License . See the LICENSE file .
%%
%% Defines ways of replying on the SIP request
%%
-module(ersip_reply).
-export([new/1,
new/2,
status/1,
reason/1,
to_tag/1
]).
-export_type([options/0,
params_list/0
]).
%%%===================================================================
%%% Types
%%%===================================================================
-record(options, {status :: ersip_status:code(),
reason = undefined :: undefined | ersip_status:reason(),
to_tag = auto :: auto | ersip_hdr_fromto:tag()
}).
-type options() :: #options{}.
-type param_pair() :: {know_param(), term()}.
-type params_list() :: [param_pair()].
-type know_param() :: reason
| to_tag.
%%%===================================================================
%%% API
%%%===================================================================
-spec new(ersip_status:code()) -> options().
new(Status) when is_integer(Status)
andalso Status >= 100
andalso Status =< 699 ->
#options{status = Status}.
-spec new(ersip_status:code(), params_list()) -> options().
new(Status, Params) when is_integer(Status)
andalso Status >= 100
andalso Status =< 699 ->
Opts0 = #options{status = Status},
lists:foldl(fun add_param/2,
Opts0,
Params).
-spec status(#options{}) -> ersip_status:code().
status(#options{status = Status}) ->
Status.
-spec reason(#options{}) -> binary().
reason(#options{reason = undefined, status = Status}) ->
ersip_status:reason_phrase(Status);
reason(#options{reason = Reason}) ->
Reason.
-spec to_tag(options()) -> auto | ersip_hdr_fromto:tag().
to_tag(#options{to_tag = Tag}) ->
Tag.
%%%===================================================================
%%% Internal Implementation
%%%===================================================================
add_param({to_tag, Tag}, #options{} = Opts) ->
Opts#options{to_tag = Tag};
add_param({reason, Reason}, #options{} = Opts) ->
Opts#options{reason = Reason}.
| null | https://raw.githubusercontent.com/poroh/ersip/f1b0d3c5713fb063a6cc327ea493f06cff6a6e5e/src/ersip_reply.erl | erlang |
All rights reserved.
Defines ways of replying on the SIP request
===================================================================
Types
===================================================================
===================================================================
API
===================================================================
===================================================================
Internal Implementation
=================================================================== | Copyright ( c ) 2018 Dmitry Poroh
Distributed under the terms of the MIT License . See the LICENSE file .
-module(ersip_reply).
-export([new/1,
new/2,
status/1,
reason/1,
to_tag/1
]).
-export_type([options/0,
params_list/0
]).
-record(options, {status :: ersip_status:code(),
reason = undefined :: undefined | ersip_status:reason(),
to_tag = auto :: auto | ersip_hdr_fromto:tag()
}).
-type options() :: #options{}.
-type param_pair() :: {know_param(), term()}.
-type params_list() :: [param_pair()].
-type know_param() :: reason
| to_tag.
-spec new(ersip_status:code()) -> options().
new(Status) when is_integer(Status)
andalso Status >= 100
andalso Status =< 699 ->
#options{status = Status}.
-spec new(ersip_status:code(), params_list()) -> options().
new(Status, Params) when is_integer(Status)
andalso Status >= 100
andalso Status =< 699 ->
Opts0 = #options{status = Status},
lists:foldl(fun add_param/2,
Opts0,
Params).
-spec status(#options{}) -> ersip_status:code().
status(#options{status = Status}) ->
Status.
-spec reason(#options{}) -> binary().
reason(#options{reason = undefined, status = Status}) ->
ersip_status:reason_phrase(Status);
reason(#options{reason = Reason}) ->
Reason.
-spec to_tag(options()) -> auto | ersip_hdr_fromto:tag().
to_tag(#options{to_tag = Tag}) ->
Tag.
add_param({to_tag, Tag}, #options{} = Opts) ->
Opts#options{to_tag = Tag};
add_param({reason, Reason}, #options{} = Opts) ->
Opts#options{reason = Reason}.
|
0dc34dd68c1e04ffbc44354481bbf1515293c72a505404293afbc72bcbbfc9e2 | mit-pdos/mcqc | Bool.hs | {-# LANGUAGE OverloadedStrings #-}
module Sema.Bool where
import Data.MonoTraversable
import CIR.Expr
-- TODO: add more bool expression semantics
boolSemantics :: CExpr -> CExpr
-- Semantics for True and False
boolSemantics CExprCall { _cd = CDef { _nm = "coq_true" }, _cparams = [] } = CExprBool True
boolSemantics CExprCall { _cd = CDef { _nm = "coq_false" }, _cparams = [] } = CExprBool False
boolSemantics other = omap boolSemantics other
| null | https://raw.githubusercontent.com/mit-pdos/mcqc/85b5a65f1750ffb7c2336fa4c9266cc238aeeb5e/src/Sema/Bool.hs | haskell | # LANGUAGE OverloadedStrings #
TODO: add more bool expression semantics
Semantics for True and False | module Sema.Bool where
import Data.MonoTraversable
import CIR.Expr
boolSemantics :: CExpr -> CExpr
boolSemantics CExprCall { _cd = CDef { _nm = "coq_true" }, _cparams = [] } = CExprBool True
boolSemantics CExprCall { _cd = CDef { _nm = "coq_false" }, _cparams = [] } = CExprBool False
boolSemantics other = omap boolSemantics other
|
e2c5ac222fc9f4395dce9507732b7798f88b793933f313aaa0c0eb49f157e801 | NetComposer/nksip | nksip_refer_plugin.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2019 . 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.
%%
%% -------------------------------------------------------------------
%% @doc NkSIP REFER Plugin Callbacks
-module(nksip_refer_plugin).
-author('Carlos Gonzalez <>').
-include("nksip.hrl").
-include("nksip_call.hrl").
-include_lib("nkserver/include/nkserver.hrl").
-export([plugin_deps/0]).
%% ===================================================================
%% Plugin
%% ===================================================================
plugin_deps() ->
[nksip].
| null | https://raw.githubusercontent.com/NetComposer/nksip/7fbcc66806635dc8ecc5d11c30322e4d1df36f0a/src/plugins/nksip_refer_plugin.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc NkSIP REFER Plugin Callbacks
===================================================================
Plugin
=================================================================== | Copyright ( c ) 2019 . 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(nksip_refer_plugin).
-author('Carlos Gonzalez <>').
-include("nksip.hrl").
-include("nksip_call.hrl").
-include_lib("nkserver/include/nkserver.hrl").
-export([plugin_deps/0]).
plugin_deps() ->
[nksip].
|
04798bf2a61450cde16a306119a04d0446575add8effef617bb9e9ad9e11918b | McMasterU/HashedExpression | State.hs | -- |
-- Module : HashedExpression.Differentiation.Reverse.State
-- Copyright : (c) OCA 2020
License : MIT ( see the LICENSE file )
-- Maintainer :
-- Stability : provisional
-- Portability : unportable
--
-- Helper for reverse accumulation method
module HashedExpression.Differentiation.Reverse.State
( from,
addDerivative,
setPartialDerivative,
ComputeReverseM,
ComputeDState (..),
)
where
import Control.Monad.State.Strict
import qualified Data.IntMap.Strict as IM
import Data.List (foldl')
import Data.List.HT (removeEach)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import GHC.Stack (HasCallStack)
import HashedExpression.Internal.Base
import HashedExpression.Internal.Hash
import HashedExpression.Internal.MonadExpression
import Prelude hiding ((^))
data ComputeDState = ComputeDState
{ contextMap :: ExpressionMap,
cumulativeDerivatives :: Map NodeID [NodeID], -- cumulative derivatives incurred by parents
partialDerivativeMap :: Map String NodeID
}
-- |
addDerivative :: NodeID -> NodeID -> ComputeReverseM ()
addDerivative x dx = modify' $ \s -> s {cumulativeDerivatives = Map.insertWith (++) x [dx] (cumulativeDerivatives s)}
-- |
setPartialDerivative :: (Map String NodeID -> Map String NodeID) -> ComputeReverseM ()
setPartialDerivative f = modify' $ \s -> s {partialDerivativeMap = f (partialDerivativeMap s)}
-- |
type ComputeReverseM a = State ComputeDState a
instance MonadExpression (State ComputeDState) where
introduceNode node = do
mp <- gets contextMap
let nID = hashNode (checkCollisionMap mp) node
modify' $ \s -> s {contextMap = IM.insert nID node (contextMap s)}
return $ NodeID nID
getContextMap = gets contextMap
-- |
from :: NodeID -> ComputeReverseM NodeID
from = return
| null | https://raw.githubusercontent.com/McMasterU/HashedExpression/cfe9f21165f1f3fc6d59ec27fb962c29e67a9bbb/src/HashedExpression/Differentiation/Reverse/State.hs | haskell | |
Module : HashedExpression.Differentiation.Reverse.State
Copyright : (c) OCA 2020
Maintainer :
Stability : provisional
Portability : unportable
Helper for reverse accumulation method
cumulative derivatives incurred by parents
|
|
|
| | License : MIT ( see the LICENSE file )
module HashedExpression.Differentiation.Reverse.State
( from,
addDerivative,
setPartialDerivative,
ComputeReverseM,
ComputeDState (..),
)
where
import Control.Monad.State.Strict
import qualified Data.IntMap.Strict as IM
import Data.List (foldl')
import Data.List.HT (removeEach)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import GHC.Stack (HasCallStack)
import HashedExpression.Internal.Base
import HashedExpression.Internal.Hash
import HashedExpression.Internal.MonadExpression
import Prelude hiding ((^))
data ComputeDState = ComputeDState
{ contextMap :: ExpressionMap,
partialDerivativeMap :: Map String NodeID
}
addDerivative :: NodeID -> NodeID -> ComputeReverseM ()
addDerivative x dx = modify' $ \s -> s {cumulativeDerivatives = Map.insertWith (++) x [dx] (cumulativeDerivatives s)}
setPartialDerivative :: (Map String NodeID -> Map String NodeID) -> ComputeReverseM ()
setPartialDerivative f = modify' $ \s -> s {partialDerivativeMap = f (partialDerivativeMap s)}
type ComputeReverseM a = State ComputeDState a
instance MonadExpression (State ComputeDState) where
introduceNode node = do
mp <- gets contextMap
let nID = hashNode (checkCollisionMap mp) node
modify' $ \s -> s {contextMap = IM.insert nID node (contextMap s)}
return $ NodeID nID
getContextMap = gets contextMap
from :: NodeID -> ComputeReverseM NodeID
from = return
|
24d0e5385320289a0dc7c5c5da88d781a15f0b9c35ffffb9948dc61440a735c8 | mstksg/typelits-printf | Internal.hs | # LANGUAGE AllowAmbiguousTypes #
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DefaultSignatures #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE KindSignatures #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PatternSynonyms #
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeApplications #
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
# OPTIONS_HADDOCK not - home #
-- |
Module : . Printf . Internal
Copyright : ( c ) 2019
-- License : BSD3
--
Maintainer :
-- Stability : experimental
-- Portability : non-portable
--
Internal workings of the printf mechanisms , exposed for potential
-- debugging purposes.
--
-- Please do not use this module for anything besides debugging, as is
-- definitely very unstable and might go away or change dramatically
-- between versions.
module GHC.TypeLits.Printf.Internal (
ParseFmtStr
, ParseFmtStr_
, ParseFmt
, ParseFmt_
, FormatAdjustment(..)
, ShowFormat
, FormatSign(..)
, WidthMod(..)
, Flags(..)
, EmptyFlags
, FieldFormat(..)
, SChar
, Demote
, Reflect(..)
, FormatType(..)
, Printf(..)
, FormatFun(..)
, PFmt(..)
, pfmt
, mkPFmt, mkPFmt_
, PHelp(..)
) where
import Data.Int
import Data.Proxy
import Data.Symbol.Utils
import Data.Word
import GHC.OverloadedLabels
import GHC.TypeLits
import GHC.TypeLits.Printf.Parse
import Numeric.Natural
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Text.Printf as P
| Typeclass associating format types ( @d@ , , etc . ) with the types
-- that can be formatted by them.
--
-- You can extend the printf methods here for your own types by writing
-- your instances here.
class FormatType (t :: SChar) a where
formatArg :: p t -> a -> P.FieldFormat -> ShowS
default formatArg :: P.PrintfArg a => p t -> a -> P.FieldFormat -> ShowS
formatArg _ = P.formatArg
instance FormatType "c" Char
instance FormatType "c" Word8
instance FormatType "c" Word16
instance FormatType "d" Char
instance FormatType "d" Int
instance FormatType "d" Int8
instance FormatType "d" Int16
instance FormatType "d" Int32
instance FormatType "d" Int64
instance FormatType "d" Integer
instance FormatType "d" Natural
instance FormatType "d" Word
instance FormatType "d" Word8
instance FormatType "d" Word16
instance FormatType "d" Word32
instance FormatType "d" Word64
instance FormatType "o" Char
instance FormatType "o" Int
instance FormatType "o" Int8
instance FormatType "o" Int16
instance FormatType "o" Int32
instance FormatType "o" Int64
instance FormatType "o" Integer
instance FormatType "o" Natural
instance FormatType "o" Word
instance FormatType "o" Word8
instance FormatType "o" Word16
instance FormatType "o" Word32
instance FormatType "o" Word64
instance FormatType "x" Int
instance FormatType "x" Int8
instance FormatType "x" Int16
instance FormatType "x" Int32
instance FormatType "x" Int64
instance FormatType "x" Integer
instance FormatType "x" Natural
instance FormatType "x" Word
instance FormatType "x" Word8
instance FormatType "x" Word16
instance FormatType "x" Word32
instance FormatType "x" Word64
instance FormatType "X" Char
instance FormatType "X" Int
instance FormatType "X" Int8
instance FormatType "X" Int16
instance FormatType "X" Int32
instance FormatType "X" Int64
instance FormatType "X" Integer
instance FormatType "X" Natural
instance FormatType "X" Word
instance FormatType "X" Word8
instance FormatType "X" Word16
instance FormatType "X" Word32
instance FormatType "X" Word64
instance FormatType "b" Char
instance FormatType "b" Int
instance FormatType "b" Int8
instance FormatType "b" Int16
instance FormatType "b" Int32
instance FormatType "b" Int64
instance FormatType "b" Integer
instance FormatType "b" Natural
instance FormatType "b" Word
instance FormatType "b" Word8
instance FormatType "b" Word16
instance FormatType "b" Word32
instance FormatType "b" Word64
instance FormatType "u" Char
instance FormatType "u" Int
instance FormatType "u" Int8
instance FormatType "u" Int16
instance FormatType "u" Int32
instance FormatType "u" Int64
instance FormatType "u" Integer
instance FormatType "u" Natural
instance FormatType "u" Word
instance FormatType "u" Word8
instance FormatType "u" Word16
instance FormatType "u" Word32
instance FormatType "u" Word64
instance FormatType "f" Double
instance FormatType "f" Float
instance FormatType "F" Double
instance FormatType "F" Float
instance FormatType "g" Double
instance FormatType "g" Float
instance FormatType "G" Double
instance FormatType "G" Float
instance FormatType "e" Double
instance FormatType "e" Float
instance FormatType "E" Double
instance FormatType "E" Float
instance FormatType "s" String
instance FormatType "s" T.Text where
formatArg _ = P.formatArg . T.unpack
instance FormatType "s" TL.Text where
formatArg _ = P.formatArg . TL.unpack
-- | Treats as @c@
instance FormatType "v" Char
-- | Treats as @d@
instance FormatType "v" Int
-- | Treats as @d@
instance FormatType "v" Int8
-- | Treats as @d@
instance FormatType "v" Int16
-- | Treats as @d@
instance FormatType "v" Int32
-- | Treats as @d@
instance FormatType "v" Int64
-- | Treats as @d@
instance FormatType "v" Integer
| Treats as @u@
instance FormatType "v" Natural
| Treats as @u@
instance FormatType "v" Word
| Treats as @u@
instance FormatType "v" Word8
| Treats as @u@
instance FormatType "v" Word16
| Treats as @u@
instance FormatType "v" Word32
| Treats as @u@
instance FormatType "v" Word64
-- | Treats as @g@
instance FormatType "v" Double
-- | Treats as @g@
instance FormatType "v" Float
-- | Treats as @s@
instance FormatType "v" String
-- | Treats as @s@
instance FormatType "v" T.Text where
formatArg _ = P.formatArg . T.unpack
-- | Treats as @s@
instance FormatType "v" TL.Text where
formatArg _ = P.formatArg . TL.unpack
-- | The typeclass supporting polyarity used by
-- 'GHC.TypeLits.Printf.printf'. It works in mostly the same way as
-- 'P.PrintfType' from "Text.Printf", and similar the same as
' Data . Symbol . Examples . . FormatF ' . Ideally , you will never have to
-- run into this typeclass or have to deal with it directly.
--
Every item in the first argument of ' FormatFun ' is a chunk of the
-- formatting string, split between format holes ('Right') and string
-- chunks ('Left').
--
If you want to see some useful error messages for feedback , ' ' can
-- be useful:
--
> > > pHelp $ printf @"You have % .2f dollars , % s " 3.62
-- -- ERROR: Call to printf missing argument fulfilling "%s"
-- -- Either provide an argument or rewrite the format string to not expect
-- -- one.
class FormatFun (ffs :: [Either Symbol FieldFormat]) fun where
formatFun :: p ffs -> String -> fun
-- | A useful tool for helping the type system give useful errors for
-- 'GHC.TypeLits.Printf.printf':
--
> > > printf @"You have " .2f " dollars , % s " 3.26 : : PHelp
-- -- ERROR: Call to printf missing argument fulfilling "%s"
-- -- Either provide an argument or rewrite the format string to not expect
-- -- one.
--
-- Mostly useful if you want to force a useful type error to help see what
-- is going on.
--
-- See also 'pHelp'
newtype PHelp = PHelp {
-- | A useful helper function for helping the type system give useful
-- errors for 'printf':
--
> > > pHelp $ printf @"You have % .2f dollars , % s " 3.62
-- -- ERROR: Call to printf missing argument fulfilling "%s"
-- -- Either provide an argument or rewrite the format string to not expect
-- -- one.
--
-- Mostly useful if you want to force a useful type error to help see
-- what is going on.
pHelp :: String
}
# INCOHERENT #
formatFun _ = id
instance (a ~ Char) => FormatFun '[] PHelp where
formatFun _ = PHelp
instance (a ~ Char) => FormatFun '[] T.Text where
formatFun _ = T.pack
instance (a ~ Char) => FormatFun '[] TL.Text where
formatFun _ = TL.pack
instance (a ~ ()) => FormatFun '[] (IO a) where
formatFun _ = putStr
instance TypeError ( 'Text "Result type of a call to printf not sufficiently inferred."
':$$: 'Text "Please provide an explicit type annotation or other way to help inference."
)
=> FormatFun '[] () where
formatFun _ = error
instance TypeError ( 'Text "An extra argument of type "
':<>: 'ShowType a
':<>: 'Text " was given to a call to printf."
':$$: 'Text "Either remove the argument, or rewrite the format string to include the appropriate hole"
)
=> FormatFun '[] (a -> b) where
formatFun _ = error
instance (KnownSymbol str, FormatFun ffs fun) => FormatFun ('Left str ': ffs) fun where
formatFun _ str = formatFun (Proxy @ffs) (str ++ symbolVal (Proxy @str))
# INCOHERENT #
formatFun _ str x = formatFun (Proxy @ffs) (str ++ formatArg (Proxy @c) x ff "")
where
ff = reflect (Proxy @ff)
type family MissingError ff where
MissingError ff = 'Text "Call to printf missing an argument fulfilling \"%"
':<>: 'Text (ShowFormat ff)
':<>: 'Text "\""
':$$: 'Text "Either provide an argument or rewrite the format string to not expect one."
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) String where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) () where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) T.Text where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) TL.Text where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) PHelp where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) (IO a) where
formatFun _ = error
class Printf (str :: Symbol) fun where
-- | A version of 'GHC.TypeLits.Printf.printf' taking an explicit
-- proxy, which allows usage without /TypeApplications/
--
> > > putStrLn $ printf _ ( Proxy : : Proxy " You have % .2f dollars , % s " ) 3.62 " "
You have 3.62 dollars ,
printf_ :: p str -> fun
instance (Listify str lst, ffs ~ ParseFmtStr_ lst, FormatFun ffs fun) => Printf str fun where
printf_ _ = formatFun (Proxy @ffs) ""
-- | Utility type powering 'pfmt'. See documentation for 'pfmt' for more
-- information on usage.
--
-- Using /OverloadedLabels/, you never need to construct this directly
can just write and a @'PFmt ' " f"@ will be generated . You can also
create this using ' mkPFmt ' or ' mkPFmt _ ' , in the situations where
-- /OverloadedLabels/ doesn't work or is not wanted.
newtype PFmt c = PFmt P.FieldFormat
| A version of ' mkPFmt ' that takes an explicit proxy input .
--
> > > pfmt ( mkPFmt _ ( Proxy : : Proxy " .2f " ) ) 3.6234124
" 3.62 "
mkPFmt_
:: forall str lst ff f w q m c p. (Listify str lst, ff ~ ParseFmt_ lst, Reflect ff, ff ~ 'FF f w q m c)
=> p str
-> PFmt c
mkPFmt_ _ = PFmt ff
where
ff = reflect (Proxy @ff)
-- | Useful for using 'pfmt' without /OverloadedLabels/, or also when
-- passing format specifiers that aren't currently allowed with
/OverloadedLabels/ until GHC 8.10 + ( like @#.2f@ ) .
--
> > > pfmt ( mkPFmt @".2f " ) 3.6234124
" 3.62 "
mkPFmt
:: forall str lst ff f w q m c. (Listify str lst, ff ~ ParseFmt_ lst, Reflect ff, ff ~ 'FF f w q m c)
=> PFmt c
mkPFmt = mkPFmt_ @str @lst (Proxy @str)
instance (Listify str lst, ff ~ ParseFmt_ lst, Reflect ff, ff ~ 'FF f w p m c) => IsLabel str (PFmt c) where
fromLabel = mkPFmt @str @lst
| Parse and run a /single/ format hole on a single vale . Can be useful
-- for formatting individual items or for testing your own custom instances of
' FormatType ' .
--
-- Usually meant to be used with /OverloadedLabels/:
--
> > > pfmt # f 3.62
" 3.62 "
--
However , current versions of GHC disallow labels that are n't valid
identifier names , disallowing things like @'pfmt ' # .2f 3.62@. While
-- there is an
-- <-proposals/ghc-proposals/blob/master/proposals/0170-unrestricted-overloadedlabels.rst
approved proposal > that allows this , if you are using an earlier GHC
-- version, you can get around this using 'mkPFmt':
--
> > > pfmt ( mkPFmt @".2f " ) 3.6234124
" 3.62 "
--
-- Ideally we'd want to be able to write
--
> > > pfmt # .2f 3.6234124
" 3.62 "
--
( which should be possible in GHC 8.10 + )
--
Note that the format string should not include the leading @%@.
pfmt :: forall c a. FormatType c a => PFmt c -> a -> String
pfmt (PFmt ff) x = formatArg (Proxy @c) x ff ""
| null | https://raw.githubusercontent.com/mstksg/typelits-printf/c0cd3d5da3696c80c4d630bafda36ffc403a1d10/src/GHC/TypeLits/Printf/Internal.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE DefaultSignatures #
# LANGUAGE GADTs #
# LANGUAGE RankNTypes #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeInType #
# LANGUAGE TypeOperators #
|
License : BSD3
Stability : experimental
Portability : non-portable
debugging purposes.
Please do not use this module for anything besides debugging, as is
definitely very unstable and might go away or change dramatically
between versions.
that can be formatted by them.
You can extend the printf methods here for your own types by writing
your instances here.
| Treats as @c@
| Treats as @d@
| Treats as @d@
| Treats as @d@
| Treats as @d@
| Treats as @d@
| Treats as @d@
| Treats as @g@
| Treats as @g@
| Treats as @s@
| Treats as @s@
| Treats as @s@
| The typeclass supporting polyarity used by
'GHC.TypeLits.Printf.printf'. It works in mostly the same way as
'P.PrintfType' from "Text.Printf", and similar the same as
run into this typeclass or have to deal with it directly.
formatting string, split between format holes ('Right') and string
chunks ('Left').
be useful:
-- ERROR: Call to printf missing argument fulfilling "%s"
-- Either provide an argument or rewrite the format string to not expect
-- one.
| A useful tool for helping the type system give useful errors for
'GHC.TypeLits.Printf.printf':
-- ERROR: Call to printf missing argument fulfilling "%s"
-- Either provide an argument or rewrite the format string to not expect
-- one.
Mostly useful if you want to force a useful type error to help see what
is going on.
See also 'pHelp'
| A useful helper function for helping the type system give useful
errors for 'printf':
-- ERROR: Call to printf missing argument fulfilling "%s"
-- Either provide an argument or rewrite the format string to not expect
-- one.
Mostly useful if you want to force a useful type error to help see
what is going on.
| A version of 'GHC.TypeLits.Printf.printf' taking an explicit
proxy, which allows usage without /TypeApplications/
| Utility type powering 'pfmt'. See documentation for 'pfmt' for more
information on usage.
Using /OverloadedLabels/, you never need to construct this directly
/OverloadedLabels/ doesn't work or is not wanted.
| Useful for using 'pfmt' without /OverloadedLabels/, or also when
passing format specifiers that aren't currently allowed with
for formatting individual items or for testing your own custom instances of
Usually meant to be used with /OverloadedLabels/:
there is an
<-proposals/ghc-proposals/blob/master/proposals/0170-unrestricted-overloadedlabels.rst
version, you can get around this using 'mkPFmt':
Ideally we'd want to be able to write
| # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE KindSignatures #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PatternSynonyms #
# LANGUAGE TypeApplications #
# LANGUAGE UndecidableInstances #
# OPTIONS_HADDOCK not - home #
Module : . Printf . Internal
Copyright : ( c ) 2019
Maintainer :
Internal workings of the printf mechanisms , exposed for potential
module GHC.TypeLits.Printf.Internal (
ParseFmtStr
, ParseFmtStr_
, ParseFmt
, ParseFmt_
, FormatAdjustment(..)
, ShowFormat
, FormatSign(..)
, WidthMod(..)
, Flags(..)
, EmptyFlags
, FieldFormat(..)
, SChar
, Demote
, Reflect(..)
, FormatType(..)
, Printf(..)
, FormatFun(..)
, PFmt(..)
, pfmt
, mkPFmt, mkPFmt_
, PHelp(..)
) where
import Data.Int
import Data.Proxy
import Data.Symbol.Utils
import Data.Word
import GHC.OverloadedLabels
import GHC.TypeLits
import GHC.TypeLits.Printf.Parse
import Numeric.Natural
import qualified Data.Text as T
import qualified Data.Text.Lazy as TL
import qualified Text.Printf as P
| Typeclass associating format types ( @d@ , , etc . ) with the types
class FormatType (t :: SChar) a where
formatArg :: p t -> a -> P.FieldFormat -> ShowS
default formatArg :: P.PrintfArg a => p t -> a -> P.FieldFormat -> ShowS
formatArg _ = P.formatArg
instance FormatType "c" Char
instance FormatType "c" Word8
instance FormatType "c" Word16
instance FormatType "d" Char
instance FormatType "d" Int
instance FormatType "d" Int8
instance FormatType "d" Int16
instance FormatType "d" Int32
instance FormatType "d" Int64
instance FormatType "d" Integer
instance FormatType "d" Natural
instance FormatType "d" Word
instance FormatType "d" Word8
instance FormatType "d" Word16
instance FormatType "d" Word32
instance FormatType "d" Word64
instance FormatType "o" Char
instance FormatType "o" Int
instance FormatType "o" Int8
instance FormatType "o" Int16
instance FormatType "o" Int32
instance FormatType "o" Int64
instance FormatType "o" Integer
instance FormatType "o" Natural
instance FormatType "o" Word
instance FormatType "o" Word8
instance FormatType "o" Word16
instance FormatType "o" Word32
instance FormatType "o" Word64
instance FormatType "x" Int
instance FormatType "x" Int8
instance FormatType "x" Int16
instance FormatType "x" Int32
instance FormatType "x" Int64
instance FormatType "x" Integer
instance FormatType "x" Natural
instance FormatType "x" Word
instance FormatType "x" Word8
instance FormatType "x" Word16
instance FormatType "x" Word32
instance FormatType "x" Word64
instance FormatType "X" Char
instance FormatType "X" Int
instance FormatType "X" Int8
instance FormatType "X" Int16
instance FormatType "X" Int32
instance FormatType "X" Int64
instance FormatType "X" Integer
instance FormatType "X" Natural
instance FormatType "X" Word
instance FormatType "X" Word8
instance FormatType "X" Word16
instance FormatType "X" Word32
instance FormatType "X" Word64
instance FormatType "b" Char
instance FormatType "b" Int
instance FormatType "b" Int8
instance FormatType "b" Int16
instance FormatType "b" Int32
instance FormatType "b" Int64
instance FormatType "b" Integer
instance FormatType "b" Natural
instance FormatType "b" Word
instance FormatType "b" Word8
instance FormatType "b" Word16
instance FormatType "b" Word32
instance FormatType "b" Word64
instance FormatType "u" Char
instance FormatType "u" Int
instance FormatType "u" Int8
instance FormatType "u" Int16
instance FormatType "u" Int32
instance FormatType "u" Int64
instance FormatType "u" Integer
instance FormatType "u" Natural
instance FormatType "u" Word
instance FormatType "u" Word8
instance FormatType "u" Word16
instance FormatType "u" Word32
instance FormatType "u" Word64
instance FormatType "f" Double
instance FormatType "f" Float
instance FormatType "F" Double
instance FormatType "F" Float
instance FormatType "g" Double
instance FormatType "g" Float
instance FormatType "G" Double
instance FormatType "G" Float
instance FormatType "e" Double
instance FormatType "e" Float
instance FormatType "E" Double
instance FormatType "E" Float
instance FormatType "s" String
instance FormatType "s" T.Text where
formatArg _ = P.formatArg . T.unpack
instance FormatType "s" TL.Text where
formatArg _ = P.formatArg . TL.unpack
instance FormatType "v" Char
instance FormatType "v" Int
instance FormatType "v" Int8
instance FormatType "v" Int16
instance FormatType "v" Int32
instance FormatType "v" Int64
instance FormatType "v" Integer
| Treats as @u@
instance FormatType "v" Natural
| Treats as @u@
instance FormatType "v" Word
| Treats as @u@
instance FormatType "v" Word8
| Treats as @u@
instance FormatType "v" Word16
| Treats as @u@
instance FormatType "v" Word32
| Treats as @u@
instance FormatType "v" Word64
instance FormatType "v" Double
instance FormatType "v" Float
instance FormatType "v" String
instance FormatType "v" T.Text where
formatArg _ = P.formatArg . T.unpack
instance FormatType "v" TL.Text where
formatArg _ = P.formatArg . TL.unpack
' Data . Symbol . Examples . . FormatF ' . Ideally , you will never have to
Every item in the first argument of ' FormatFun ' is a chunk of the
If you want to see some useful error messages for feedback , ' ' can
> > > pHelp $ printf @"You have % .2f dollars , % s " 3.62
class FormatFun (ffs :: [Either Symbol FieldFormat]) fun where
formatFun :: p ffs -> String -> fun
> > > printf @"You have " .2f " dollars , % s " 3.26 : : PHelp
newtype PHelp = PHelp {
> > > pHelp $ printf @"You have % .2f dollars , % s " 3.62
pHelp :: String
}
# INCOHERENT #
formatFun _ = id
instance (a ~ Char) => FormatFun '[] PHelp where
formatFun _ = PHelp
instance (a ~ Char) => FormatFun '[] T.Text where
formatFun _ = T.pack
instance (a ~ Char) => FormatFun '[] TL.Text where
formatFun _ = TL.pack
instance (a ~ ()) => FormatFun '[] (IO a) where
formatFun _ = putStr
instance TypeError ( 'Text "Result type of a call to printf not sufficiently inferred."
':$$: 'Text "Please provide an explicit type annotation or other way to help inference."
)
=> FormatFun '[] () where
formatFun _ = error
instance TypeError ( 'Text "An extra argument of type "
':<>: 'ShowType a
':<>: 'Text " was given to a call to printf."
':$$: 'Text "Either remove the argument, or rewrite the format string to include the appropriate hole"
)
=> FormatFun '[] (a -> b) where
formatFun _ = error
instance (KnownSymbol str, FormatFun ffs fun) => FormatFun ('Left str ': ffs) fun where
formatFun _ str = formatFun (Proxy @ffs) (str ++ symbolVal (Proxy @str))
# INCOHERENT #
formatFun _ str x = formatFun (Proxy @ffs) (str ++ formatArg (Proxy @c) x ff "")
where
ff = reflect (Proxy @ff)
type family MissingError ff where
MissingError ff = 'Text "Call to printf missing an argument fulfilling \"%"
':<>: 'Text (ShowFormat ff)
':<>: 'Text "\""
':$$: 'Text "Either provide an argument or rewrite the format string to not expect one."
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) String where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) () where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) T.Text where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) TL.Text where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) PHelp where
formatFun _ = error
instance TypeError (MissingError ff) => FormatFun ('Right ff ': ffs) (IO a) where
formatFun _ = error
class Printf (str :: Symbol) fun where
> > > putStrLn $ printf _ ( Proxy : : Proxy " You have % .2f dollars , % s " ) 3.62 " "
You have 3.62 dollars ,
printf_ :: p str -> fun
instance (Listify str lst, ffs ~ ParseFmtStr_ lst, FormatFun ffs fun) => Printf str fun where
printf_ _ = formatFun (Proxy @ffs) ""
can just write and a @'PFmt ' " f"@ will be generated . You can also
create this using ' mkPFmt ' or ' mkPFmt _ ' , in the situations where
newtype PFmt c = PFmt P.FieldFormat
| A version of ' mkPFmt ' that takes an explicit proxy input .
> > > pfmt ( mkPFmt _ ( Proxy : : Proxy " .2f " ) ) 3.6234124
" 3.62 "
mkPFmt_
:: forall str lst ff f w q m c p. (Listify str lst, ff ~ ParseFmt_ lst, Reflect ff, ff ~ 'FF f w q m c)
=> p str
-> PFmt c
mkPFmt_ _ = PFmt ff
where
ff = reflect (Proxy @ff)
/OverloadedLabels/ until GHC 8.10 + ( like @#.2f@ ) .
> > > pfmt ( mkPFmt @".2f " ) 3.6234124
" 3.62 "
mkPFmt
:: forall str lst ff f w q m c. (Listify str lst, ff ~ ParseFmt_ lst, Reflect ff, ff ~ 'FF f w q m c)
=> PFmt c
mkPFmt = mkPFmt_ @str @lst (Proxy @str)
instance (Listify str lst, ff ~ ParseFmt_ lst, Reflect ff, ff ~ 'FF f w p m c) => IsLabel str (PFmt c) where
fromLabel = mkPFmt @str @lst
| Parse and run a /single/ format hole on a single vale . Can be useful
' FormatType ' .
> > > pfmt # f 3.62
" 3.62 "
However , current versions of GHC disallow labels that are n't valid
identifier names , disallowing things like @'pfmt ' # .2f 3.62@. While
approved proposal > that allows this , if you are using an earlier GHC
> > > pfmt ( mkPFmt @".2f " ) 3.6234124
" 3.62 "
> > > pfmt # .2f 3.6234124
" 3.62 "
( which should be possible in GHC 8.10 + )
Note that the format string should not include the leading @%@.
pfmt :: forall c a. FormatType c a => PFmt c -> a -> String
pfmt (PFmt ff) x = formatArg (Proxy @c) x ff ""
|
a9980b4f2a3c113321a0c20827e58eb4b102940b170f0a701426aabda7177a2d | basho/basho_bench | basho_bench.erl | %% -------------------------------------------------------------------
%%
%% basho_bench: Benchmarking Suite
%%
Copyright ( c ) 2009 - 2012 Basho Techonologies
%%
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(basho_bench).
-export([main/1, md5/1]).
-include("basho_bench.hrl").
%% ====================================================================
%% API
%% ====================================================================
cli_options() ->
[
{help, $h, "help", undefined, "Print usage"},
{results_dir, $d, "results-dir", string, "Base directory to store test results, defaults to ./tests"},
{bench_name, $n, "bench-name", string, "Name to identify the run, defaults to timestamp"},
{net_node, $N, "node", atom, "Erlang long node name of local node (initiating basho_bench)"},
{net_cookie, $C, "cookie", {atom, benchmark}, "Erlang network distribution magic cookie"},
{net_join, $J, "join", atom, "Erlang long node name of remote node (to join to)"}
].
main(Args) ->
{Opts, Configs} = check_args(getopt:parse(cli_options(), Args)),
ok = maybe_show_usage(Opts),
ok = maybe_net_node(Opts),
ok = maybe_join(Opts),
BenchName = bench_name(Opts),
TestDir = test_dir(Opts, BenchName),
%% Load baseline configs
case application:load(basho_bench) of
ok -> ok;
{error, {already_loaded, basho_bench}} -> ok
end,
register(basho_bench, self()),
%% TODO: Move into a proper supervision tree, janky for now
{ok, _Pid} = basho_bench_config:start_link(),
basho_bench_config:set(test_id, BenchName),
application:load(lager),
ConsoleLagerLevel = basho_bench_config:get(log_level, debug),
ErrorLog = filename:join([TestDir, "error.log"]),
ConsoleLog = filename:join([TestDir, "console.log"]),
CrashLog = filename:join([TestDir, "crash.log"]),
application:set_env(lager,
handlers,
[{lager_console_backend, ConsoleLagerLevel},
{lager_file_backend, [{file, ErrorLog}, {level, error}, {size, 10485760}, {date, "$D0"}, {count, 5}]},
{lager_file_backend, [{file, ConsoleLog}, {level, debug}, {size, 10485760}, {date, "$D0"}, {count, 5}]}
]),
application:set_env(lager, crash_log, CrashLog),
lager:start(),
%% Make sure this happens after starting lager or failures wont
%% show.
basho_bench_config:load(Configs),
%% Log level can be overriden by the config files
CustomLagerLevel = basho_bench_config:get(log_level),
lager:set_loglevel(lager_console_backend, CustomLagerLevel),
lager:set_loglevel(lager_file_backend, ConsoleLog, CustomLagerLevel),
Init code path
add_code_paths(basho_bench_config:get(code_paths, [])),
%% If a source directory is specified, compile and load all .erl files found
%% there.
case basho_bench_config:get(source_dir, []) of
[] ->
ok;
SourceDir ->
load_source_files(SourceDir)
end,
%% Copy the config into the test dir for posterity
[ begin {ok, _} = file:copy(Config, filename:join(TestDir, filename:basename(Config))) end
|| Config <- Configs ],
case basho_bench_config:get(distribute_work, false) of
true -> setup_distributed_work();
false -> ok
end,
Set our CWD to the test dir
ok = file:set_cwd(TestDir),
log_dimensions(),
%% Run pre_hook for user code preconditions
run_pre_hook(),
%% Spin up the application
ok = basho_bench_app:start(),
%% Pull the runtime duration from the config and sleep until that's passed OR
%% the supervisor process exits
Mref = erlang:monitor(process, whereis(basho_bench_sup)),
DurationMins = basho_bench_config:get(duration),
wait_for_stop(Mref, DurationMins).
%% ====================================================================
Internal functions
%% ====================================================================
print_usage() ->
getopt:usage(cli_options(), escript:script_name(), "CONFIG_FILE").
check_args({ok, {Opts, Args}}) ->
{Opts, Args};
check_args({error, {Reason, _Data}}) ->
?STD_ERR("Failed to parse arguments: ~p~n", [Reason]),
print_usage(),
halt(1).
maybe_show_usage(Opts) ->
case lists:member(help, Opts) of
true ->
print_usage(),
halt(0);
false ->
ok
end.
maybe_net_node(Opts) ->
case lists:keyfind(net_node, 1, Opts) of
{_, Node} ->
{_, Cookie} = lists:keyfind(net_cookie, 1, Opts),
os:cmd("epmd -daemon"),
net_kernel:start([Node, longnames]),
erlang:set_cookie(Node, Cookie),
ok;
false ->
ok
end.
maybe_join(Opts) ->
case lists:keyfind(net_join, 1, Opts) of
{_, Host} ->
case net_adm:ping(Host) of
pong -> global:sync();
_ -> throw({no_host, Host})
end;
false ->
ok
end.
bench_name(Opts) ->
case proplists:get_value(bench_name, Opts, id()) of
"current" ->
?STD_ERR("Cannot use name 'current'~n", []),
halt(1);
Name ->
Name
end.
test_dir(Opts, Name) ->
{ok, CWD} = file:get_cwd(),
DefaultResultsDir = filename:join([CWD, "tests"]),
ResultsDir = proplists:get_value(results_dir, Opts, DefaultResultsDir),
ResultsDirAbs = filename:absname(ResultsDir),
TestDir = filename:join([ResultsDirAbs, Name]),
{ok, TestDir} = {filelib:ensure_dir(filename:join(TestDir, "foobar")), TestDir},
Link = filename:join([ResultsDir, "current"]),
[] = os:cmd(?FMT("rm -f ~s; ln -sf ~s ~s", [Link, TestDir, Link])),
TestDir.
wait_for_stop(Mref, infinity) ->
receive
{'DOWN', Mref, _, _, Info} ->
run_post_hook(),
?CONSOLE("Test stopped: ~p\n", [Info])
end;
wait_for_stop(Mref, DurationMins) ->
Duration = timer:minutes(DurationMins) + timer:seconds(1),
receive
{'DOWN', Mref, _, _, Info} ->
run_post_hook(),
?CONSOLE("Test stopped: ~p\n", [Info]);
{shutdown, Reason, Exit} ->
run_post_hook(),
basho_bench_app:stop(),
?CONSOLE("Test shutdown: ~s~n", [Reason]),
halt(Exit)
after Duration ->
run_post_hook(),
basho_bench_app:stop(),
?CONSOLE("Test completed after ~p mins.\n", [DurationMins])
end.
%%
Construct a string suitable for use as a unique ID for this test run
%%
id() ->
{{Y, M, D}, {H, Min, S}} = calendar:local_time(),
?FMT("~w~2..0w~2..0w_~2..0w~2..0w~2..0w", [Y, M, D, H, Min, S]).
add_code_paths([]) ->
ok;
add_code_paths([Path | Rest]) ->
Absname = filename:absname(Path),
CodePath = case filename:basename(Absname) of
"ebin" ->
Absname;
_ ->
filename:join(Absname, "ebin")
end,
case code:add_path(CodePath) of
true ->
add_code_paths(Rest);
Error ->
?FAIL_MSG("Failed to add ~p to code_path: ~p\n", [CodePath, Error])
end.
%%
%% Convert a number of bytes into a more user-friendly representation
%%
user_friendly_bytes(Size) ->
lists:foldl(fun(Desc, {Sz, SzDesc}) ->
case Sz > 1000 of
true ->
{Sz / 1024, Desc};
false ->
{Sz, SzDesc}
end
end,
{Size, bytes}, ['KB', 'MB', 'GB']).
log_dimensions() ->
case basho_bench_keygen:dimension(basho_bench_config:get(key_generator)) of
undefined ->
ok;
Keyspace ->
Valspace = basho_bench_valgen:dimension(basho_bench_config:get(value_generator), Keyspace),
{Size, Desc} = user_friendly_bytes(Valspace),
?INFO("Est. data size: ~.2f ~s\n", [Size, Desc])
end.
load_source_files(Dir) ->
CompileFn = fun(F, _Acc) ->
case compile:file(F, [report, binary]) of
{ok, Mod, Bin} ->
{module, Mod} = code:load_binary(Mod, F, Bin),
deploy_module(Mod),
?INFO("Loaded ~p (~s)\n", [Mod, F]),
ok;
Error ->
io:format("Failed to compile ~s: ~p\n", [F, Error])
end
end,
filelib:fold_files(Dir, ".*.erl", false, CompileFn, ok).
run_pre_hook() ->
run_hook(basho_bench_config:get(pre_hook, no_op)).
run_post_hook() ->
run_hook(basho_bench_config:get(post_hook, no_op)).
run_hook({Module, Function}) ->
Module:Function();
run_hook(no_op) ->
no_op.
get_addr_args() ->
{ok, IfAddrs} = inet:getifaddrs(),
FlattAttrib = lists:flatten([IfAttrib || {_Ifname, IfAttrib} <- IfAddrs]),
Addrs = proplists:get_all_values(addr, FlattAttrib),
If inet : ntoa is unavailable , it probably means that you 're running < R16
StrAddrs = [inet:ntoa(Addr) || Addr <- Addrs],
string:join(StrAddrs, " ").
setup_distributed_work() ->
case node() of
'nonode@nohost' ->
?STD_ERR("Basho bench not started in distributed mode, and distribute_work = true~n", []),
halt(1);
_ -> ok
end,
{ok, _Pid} = erl_boot_server:start([]),
%% Allow anyone to boot from me...I might want to lock this down this down at some point
erl_boot_server:add_subnet({0,0,0,0}, {0,0,0,0}),
%% This is cheating, horribly, but it's the only simple way to bypass net_adm:host_file()
gen_server:start({global, pool_master}, pool, [], []),
RemoteSpec = basho_bench_config:get(remote_nodes, []),
Cookie = lists:flatten(erlang:atom_to_list(erlang:get_cookie())),
Args = "-setcookie " ++ Cookie ++ " -loader inet -hosts " ++ get_addr_args(),
Slaves = [ slave:start_link(Host, Name, Args) || {Host, Name} <- RemoteSpec],
SlaveNames = [SlaveName || {ok, SlaveName} <- Slaves],
[pool:attach(SlaveName) || SlaveName <- SlaveNames],
CodePaths = code:get_path(),
rpc:multicall(SlaveNames, code, set_path, [CodePaths]),
Apps = [lager, basho_bench, getopt, bear, folsom, ibrowse, riakc, riak_pb, mochiweb, protobuffs, goldrush],
[distribute_app(App) || App <- Apps].
deploy_module(Module) ->
case basho_bench_config:get(distribute_work, false) of
true ->
Nodes = nodes(),
{Module, Binary, Filename} = code:get_object_code(Module),
rpc:multicall(Nodes, code, load_binary, [Module, Filename, Binary]);
false -> ok
end.
distribute_app(App) ->
% :(. This is super hackish, it depends on a bunch of assumptions
But , unfortunately there are negative interactions with escript and slave nodes
CodeExtension = code:objfile_extension(),
LibDir = code:lib_dir(App),
Get what paths are in the code path that start with LibDir
LibDirLen = string:len(LibDir),
EbinsDir = lists:filter(fun(CodePathDir) -> string:substr(CodePathDir, 1, LibDirLen) == LibDir end, code:get_path()),
StripEndFun = fun(Path) ->
PathLen = string:len(Path),
case string:substr(Path, PathLen - string:len(CodeExtension) + 1, string:len(Path)) of
CodeExtension ->
{true, string:substr(Path, 1, PathLen - string:len(CodeExtension))};
_ -> false
end
end,
EbinDirDistributeFun = fun(EbinDir) ->
{ok, Beams} = erl_prim_loader:list_dir(EbinDir),
Modules = lists:filtermap(StripEndFun, Beams),
ModulesLoaded = [code:load_abs(filename:join(EbinDir, ModFileName)) || ModFileName <- Modules],
lists:foreach(fun({module, Module}) -> deploy_module(Module) end, ModulesLoaded)
end,
lists:foreach(EbinDirDistributeFun, EbinsDir),
ok.
%% just a utility, should be in basho_bench_utils.erl
%% but 's' is for multiple utilities, and so far this
%% is the only one.
-ifdef(new_hash).
md5(Bin) -> crypto:hash(md5, Bin).
-else.
md5(Bin) -> crypto:md5(Bin).
-endif.
| null | https://raw.githubusercontent.com/basho/basho_bench/aa66398bb6a91645dbb97e91a236f3cdcd1f188f/src/basho_bench.erl | erlang | -------------------------------------------------------------------
basho_bench: Benchmarking Suite
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
====================================================================
Load baseline configs
TODO: Move into a proper supervision tree, janky for now
Make sure this happens after starting lager or failures wont
show.
Log level can be overriden by the config files
If a source directory is specified, compile and load all .erl files found
there.
Copy the config into the test dir for posterity
Run pre_hook for user code preconditions
Spin up the application
Pull the runtime duration from the config and sleep until that's passed OR
the supervisor process exits
====================================================================
====================================================================
Convert a number of bytes into a more user-friendly representation
Allow anyone to boot from me...I might want to lock this down this down at some point
This is cheating, horribly, but it's the only simple way to bypass net_adm:host_file()
:(. This is super hackish, it depends on a bunch of assumptions
just a utility, should be in basho_bench_utils.erl
but 's' is for multiple utilities, and so far this
is the only one. | Copyright ( c ) 2009 - 2012 Basho Techonologies
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(basho_bench).
-export([main/1, md5/1]).
-include("basho_bench.hrl").
cli_options() ->
[
{help, $h, "help", undefined, "Print usage"},
{results_dir, $d, "results-dir", string, "Base directory to store test results, defaults to ./tests"},
{bench_name, $n, "bench-name", string, "Name to identify the run, defaults to timestamp"},
{net_node, $N, "node", atom, "Erlang long node name of local node (initiating basho_bench)"},
{net_cookie, $C, "cookie", {atom, benchmark}, "Erlang network distribution magic cookie"},
{net_join, $J, "join", atom, "Erlang long node name of remote node (to join to)"}
].
main(Args) ->
{Opts, Configs} = check_args(getopt:parse(cli_options(), Args)),
ok = maybe_show_usage(Opts),
ok = maybe_net_node(Opts),
ok = maybe_join(Opts),
BenchName = bench_name(Opts),
TestDir = test_dir(Opts, BenchName),
case application:load(basho_bench) of
ok -> ok;
{error, {already_loaded, basho_bench}} -> ok
end,
register(basho_bench, self()),
{ok, _Pid} = basho_bench_config:start_link(),
basho_bench_config:set(test_id, BenchName),
application:load(lager),
ConsoleLagerLevel = basho_bench_config:get(log_level, debug),
ErrorLog = filename:join([TestDir, "error.log"]),
ConsoleLog = filename:join([TestDir, "console.log"]),
CrashLog = filename:join([TestDir, "crash.log"]),
application:set_env(lager,
handlers,
[{lager_console_backend, ConsoleLagerLevel},
{lager_file_backend, [{file, ErrorLog}, {level, error}, {size, 10485760}, {date, "$D0"}, {count, 5}]},
{lager_file_backend, [{file, ConsoleLog}, {level, debug}, {size, 10485760}, {date, "$D0"}, {count, 5}]}
]),
application:set_env(lager, crash_log, CrashLog),
lager:start(),
basho_bench_config:load(Configs),
CustomLagerLevel = basho_bench_config:get(log_level),
lager:set_loglevel(lager_console_backend, CustomLagerLevel),
lager:set_loglevel(lager_file_backend, ConsoleLog, CustomLagerLevel),
Init code path
add_code_paths(basho_bench_config:get(code_paths, [])),
case basho_bench_config:get(source_dir, []) of
[] ->
ok;
SourceDir ->
load_source_files(SourceDir)
end,
[ begin {ok, _} = file:copy(Config, filename:join(TestDir, filename:basename(Config))) end
|| Config <- Configs ],
case basho_bench_config:get(distribute_work, false) of
true -> setup_distributed_work();
false -> ok
end,
Set our CWD to the test dir
ok = file:set_cwd(TestDir),
log_dimensions(),
run_pre_hook(),
ok = basho_bench_app:start(),
Mref = erlang:monitor(process, whereis(basho_bench_sup)),
DurationMins = basho_bench_config:get(duration),
wait_for_stop(Mref, DurationMins).
Internal functions
print_usage() ->
getopt:usage(cli_options(), escript:script_name(), "CONFIG_FILE").
check_args({ok, {Opts, Args}}) ->
{Opts, Args};
check_args({error, {Reason, _Data}}) ->
?STD_ERR("Failed to parse arguments: ~p~n", [Reason]),
print_usage(),
halt(1).
maybe_show_usage(Opts) ->
case lists:member(help, Opts) of
true ->
print_usage(),
halt(0);
false ->
ok
end.
maybe_net_node(Opts) ->
case lists:keyfind(net_node, 1, Opts) of
{_, Node} ->
{_, Cookie} = lists:keyfind(net_cookie, 1, Opts),
os:cmd("epmd -daemon"),
net_kernel:start([Node, longnames]),
erlang:set_cookie(Node, Cookie),
ok;
false ->
ok
end.
maybe_join(Opts) ->
case lists:keyfind(net_join, 1, Opts) of
{_, Host} ->
case net_adm:ping(Host) of
pong -> global:sync();
_ -> throw({no_host, Host})
end;
false ->
ok
end.
bench_name(Opts) ->
case proplists:get_value(bench_name, Opts, id()) of
"current" ->
?STD_ERR("Cannot use name 'current'~n", []),
halt(1);
Name ->
Name
end.
test_dir(Opts, Name) ->
{ok, CWD} = file:get_cwd(),
DefaultResultsDir = filename:join([CWD, "tests"]),
ResultsDir = proplists:get_value(results_dir, Opts, DefaultResultsDir),
ResultsDirAbs = filename:absname(ResultsDir),
TestDir = filename:join([ResultsDirAbs, Name]),
{ok, TestDir} = {filelib:ensure_dir(filename:join(TestDir, "foobar")), TestDir},
Link = filename:join([ResultsDir, "current"]),
[] = os:cmd(?FMT("rm -f ~s; ln -sf ~s ~s", [Link, TestDir, Link])),
TestDir.
wait_for_stop(Mref, infinity) ->
receive
{'DOWN', Mref, _, _, Info} ->
run_post_hook(),
?CONSOLE("Test stopped: ~p\n", [Info])
end;
wait_for_stop(Mref, DurationMins) ->
Duration = timer:minutes(DurationMins) + timer:seconds(1),
receive
{'DOWN', Mref, _, _, Info} ->
run_post_hook(),
?CONSOLE("Test stopped: ~p\n", [Info]);
{shutdown, Reason, Exit} ->
run_post_hook(),
basho_bench_app:stop(),
?CONSOLE("Test shutdown: ~s~n", [Reason]),
halt(Exit)
after Duration ->
run_post_hook(),
basho_bench_app:stop(),
?CONSOLE("Test completed after ~p mins.\n", [DurationMins])
end.
Construct a string suitable for use as a unique ID for this test run
id() ->
{{Y, M, D}, {H, Min, S}} = calendar:local_time(),
?FMT("~w~2..0w~2..0w_~2..0w~2..0w~2..0w", [Y, M, D, H, Min, S]).
add_code_paths([]) ->
ok;
add_code_paths([Path | Rest]) ->
Absname = filename:absname(Path),
CodePath = case filename:basename(Absname) of
"ebin" ->
Absname;
_ ->
filename:join(Absname, "ebin")
end,
case code:add_path(CodePath) of
true ->
add_code_paths(Rest);
Error ->
?FAIL_MSG("Failed to add ~p to code_path: ~p\n", [CodePath, Error])
end.
user_friendly_bytes(Size) ->
lists:foldl(fun(Desc, {Sz, SzDesc}) ->
case Sz > 1000 of
true ->
{Sz / 1024, Desc};
false ->
{Sz, SzDesc}
end
end,
{Size, bytes}, ['KB', 'MB', 'GB']).
log_dimensions() ->
case basho_bench_keygen:dimension(basho_bench_config:get(key_generator)) of
undefined ->
ok;
Keyspace ->
Valspace = basho_bench_valgen:dimension(basho_bench_config:get(value_generator), Keyspace),
{Size, Desc} = user_friendly_bytes(Valspace),
?INFO("Est. data size: ~.2f ~s\n", [Size, Desc])
end.
load_source_files(Dir) ->
CompileFn = fun(F, _Acc) ->
case compile:file(F, [report, binary]) of
{ok, Mod, Bin} ->
{module, Mod} = code:load_binary(Mod, F, Bin),
deploy_module(Mod),
?INFO("Loaded ~p (~s)\n", [Mod, F]),
ok;
Error ->
io:format("Failed to compile ~s: ~p\n", [F, Error])
end
end,
filelib:fold_files(Dir, ".*.erl", false, CompileFn, ok).
run_pre_hook() ->
run_hook(basho_bench_config:get(pre_hook, no_op)).
run_post_hook() ->
run_hook(basho_bench_config:get(post_hook, no_op)).
run_hook({Module, Function}) ->
Module:Function();
run_hook(no_op) ->
no_op.
get_addr_args() ->
{ok, IfAddrs} = inet:getifaddrs(),
FlattAttrib = lists:flatten([IfAttrib || {_Ifname, IfAttrib} <- IfAddrs]),
Addrs = proplists:get_all_values(addr, FlattAttrib),
If inet : ntoa is unavailable , it probably means that you 're running < R16
StrAddrs = [inet:ntoa(Addr) || Addr <- Addrs],
string:join(StrAddrs, " ").
setup_distributed_work() ->
case node() of
'nonode@nohost' ->
?STD_ERR("Basho bench not started in distributed mode, and distribute_work = true~n", []),
halt(1);
_ -> ok
end,
{ok, _Pid} = erl_boot_server:start([]),
erl_boot_server:add_subnet({0,0,0,0}, {0,0,0,0}),
gen_server:start({global, pool_master}, pool, [], []),
RemoteSpec = basho_bench_config:get(remote_nodes, []),
Cookie = lists:flatten(erlang:atom_to_list(erlang:get_cookie())),
Args = "-setcookie " ++ Cookie ++ " -loader inet -hosts " ++ get_addr_args(),
Slaves = [ slave:start_link(Host, Name, Args) || {Host, Name} <- RemoteSpec],
SlaveNames = [SlaveName || {ok, SlaveName} <- Slaves],
[pool:attach(SlaveName) || SlaveName <- SlaveNames],
CodePaths = code:get_path(),
rpc:multicall(SlaveNames, code, set_path, [CodePaths]),
Apps = [lager, basho_bench, getopt, bear, folsom, ibrowse, riakc, riak_pb, mochiweb, protobuffs, goldrush],
[distribute_app(App) || App <- Apps].
deploy_module(Module) ->
case basho_bench_config:get(distribute_work, false) of
true ->
Nodes = nodes(),
{Module, Binary, Filename} = code:get_object_code(Module),
rpc:multicall(Nodes, code, load_binary, [Module, Filename, Binary]);
false -> ok
end.
distribute_app(App) ->
But , unfortunately there are negative interactions with escript and slave nodes
CodeExtension = code:objfile_extension(),
LibDir = code:lib_dir(App),
Get what paths are in the code path that start with LibDir
LibDirLen = string:len(LibDir),
EbinsDir = lists:filter(fun(CodePathDir) -> string:substr(CodePathDir, 1, LibDirLen) == LibDir end, code:get_path()),
StripEndFun = fun(Path) ->
PathLen = string:len(Path),
case string:substr(Path, PathLen - string:len(CodeExtension) + 1, string:len(Path)) of
CodeExtension ->
{true, string:substr(Path, 1, PathLen - string:len(CodeExtension))};
_ -> false
end
end,
EbinDirDistributeFun = fun(EbinDir) ->
{ok, Beams} = erl_prim_loader:list_dir(EbinDir),
Modules = lists:filtermap(StripEndFun, Beams),
ModulesLoaded = [code:load_abs(filename:join(EbinDir, ModFileName)) || ModFileName <- Modules],
lists:foreach(fun({module, Module}) -> deploy_module(Module) end, ModulesLoaded)
end,
lists:foreach(EbinDirDistributeFun, EbinsDir),
ok.
-ifdef(new_hash).
md5(Bin) -> crypto:hash(md5, Bin).
-else.
md5(Bin) -> crypto:md5(Bin).
-endif.
|
db6066d75bbde7ccbdb6274c24bfad6c63eeeac0550370ca03cbc11ca8bbf8a2 | alvatar/spheres | test-fmt.scm |
(cond-expand
(chicken
(load "fmt-chicken.scm"))
(else))
(cond-expand
(chicken
(use test)
(import fmt))
(gauche
(use gauche.test)
(use text.fmt)
(define test-begin test-start)
(define orig-test (with-module gauche.test test))
(define-syntax test
(syntax-rules ()
((test name expected expr)
(guard (e (else #f))
(orig-test name expected (lambda () expr))))
((test expected expr)
(test (let ((s (with-output-to-string (lambda () (write 'expr)))))
(substring s 0 (min 60 (string-length s))))
expected expr)))))
(else))
(test-begin "fmt")
;; basic data types
(test "hi" (fmt #f "hi"))
(test "\"hi\"" (fmt #f (wrt "hi")))
(test "\"hi \\\"bob\\\"\"" (fmt #f (wrt "hi \"bob\"")))
(test "\"hello\\nworld\"" (fmt #f (wrt "hello\nworld")))
(test "ABC" (fmt #f (upcase "abc")))
(test "abc" (fmt #f (downcase "ABC")))
(test "Abc" (fmt #f (titlecase "abc")))
(test "abc def" (fmt #f "abc" (tab-to) "def"))
(test "abc def" (fmt #f "abc" (tab-to 5) "def"))
(test "abcdef" (fmt #f "abc" (tab-to 3) "def"))
(test "-1" (fmt #f -1))
(test "0" (fmt #f 0))
(test "1" (fmt #f 1))
(test "10" (fmt #f 10))
(test "100" (fmt #f 100))
(test "-1" (fmt #f (num -1)))
(test "0" (fmt #f (num 0)))
(test "1" (fmt #f (num 1)))
(test "10" (fmt #f (num 10)))
(test "100" (fmt #f (num 100)))
( test " 1e+15 " ( fmt # f ( num 1e+15 ) ) )
;; (test "1e+23" (fmt #f (num 1e+23)))
( test " 1.2e+23 " ( fmt # f ( num 1.2e+23 ) ) )
( test " 1e-5 " ( fmt # f ( num 1e-5 ) ) )
( test " 1e-6 " ( fmt # f ( num 1e-6 ) ) )
( test " 1e-7 " ( fmt # f ( num 1e-7 ) ) )
( test " 2e-6 " ( fmt # f ( num 2e-6 ) ) )
(test "57005" (fmt #f #xDEAD))
(test "#xDEAD" (fmt #f (radix 16 #xDEAD)))
(test "#xDEAD1234" (fmt #f (radix 16 #xDEAD) 1234))
(test "#xDE.AD" (fmt #f (radix 16 (exact->inexact (/ #xDEAD #x100)))))
(test "#xD.EAD" (fmt #f (radix 16 (exact->inexact (/ #xDEAD #x1000)))))
(test "#x0.DEAD" (fmt #f (radix 16 (exact->inexact (/ #xDEAD #x10000)))))
(test "1G" (fmt #f (radix 17 (num 33))))
(test "1G" (fmt #f (num 33 17)))
(test "3.14159" (fmt #f 3.14159))
(test "3.14" (fmt #f (fix 2 3.14159)))
(test "3.14" (fmt #f (fix 2 3.14)))
(test "3.00" (fmt #f (fix 2 3.)))
(test "1.10" (fmt #f (num 1.099 10 2)))
(test "0.00" (fmt #f (fix 2 1e-17)))
(test "0.0000000000" (fmt #f (fix 10 1e-17)))
(test "0.00000000000000001000" (fmt #f (fix 20 1e-17)))
( test - error ( fmt # f ( num 1e-17 0 ) ) )
(test "0.000004" (fmt #f (num 0.000004 10 6)))
(test "0.0000040" (fmt #f (num 0.000004 10 7)))
(test "0.00000400" (fmt #f (num 0.000004 10 8)))
( test " 0.000004 " ( fmt # f ( num 0.000004 ) ) )
(test " 3.14159" (fmt #f (decimal-align 5 (num 3.14159))))
(test " 31.4159" (fmt #f (decimal-align 5 (num 31.4159))))
(test " 314.159" (fmt #f (decimal-align 5 (num 314.159))))
(test "3141.59" (fmt #f (decimal-align 5 (num 3141.59))))
(test "31415.9" (fmt #f (decimal-align 5 (num 31415.9))))
(test " -3.14159" (fmt #f (decimal-align 5 (num -3.14159))))
(test " -31.4159" (fmt #f (decimal-align 5 (num -31.4159))))
(test "-314.159" (fmt #f (decimal-align 5 (num -314.159))))
(test "-3141.59" (fmt #f (decimal-align 5 (num -3141.59))))
(test "-31415.9" (fmt #f (decimal-align 5 (num -31415.9))))
(cond
((exact? (/ 1 3)) ;; exact rationals
(test "333.333333333333333333333333333333" (fmt #f (fix 30 1000/3)))
(test "33.333333333333333333333333333333" (fmt #f (fix 30 100/3)))
(test "3.333333333333333333333333333333" (fmt #f (fix 30 10/3)))
(test "0.333333333333333333333333333333" (fmt #f (fix 30 1/3)))
(test "0.033333333333333333333333333333" (fmt #f (fix 30 1/30)))
(test "0.003333333333333333333333333333" (fmt #f (fix 30 1/300)))
(test "0.000333333333333333333333333333" (fmt #f (fix 30 1/3000)))
(test "0.666666666666666666666666666667" (fmt #f (fix 30 2/3)))
(test "0.090909090909090909090909090909" (fmt #f (fix 30 1/11)))
(test "1.428571428571428571428571428571" (fmt #f (fix 30 10/7)))
(test "0.123456789012345678901234567890"
(fmt #f (fix 30 (/ 123456789012345678901234567890
1000000000000000000000000000000))))
(test " 333.333333333333333333333333333333" (fmt #f (decimal-align 5 (fix 30 1000/3))))
(test " 33.333333333333333333333333333333" (fmt #f (decimal-align 5 (fix 30 100/3))))
(test " 3.333333333333333333333333333333" (fmt #f (decimal-align 5 (fix 30 10/3))))
(test " 0.333333333333333333333333333333" (fmt #f (decimal-align 5 (fix 30 1/3))))
))
(test "11.75" (fmt #f (num (/ 47 4) 10 2)))
(test "-11.75" (fmt #f (num (/ -47 4) 10 2)))
(test "(#x11 #x22 #x33)" (fmt #f (radix 16 '(#x11 #x22 #x33))))
(test "299,792,458" (fmt #f (num 299792458 10 #f #f #t)))
(test "299,792,458" (fmt #f (num/comma 299792458)))
(test "299.792.458" (fmt #f (comma-char #\. (num/comma 299792458))))
(test "299.792.458,0" (fmt #f (comma-char #\. (num/comma 299792458.0))))
(test "100,000" (fmt #f (num 100000 10 0 #f 3)))
(test "100,000.0" (fmt #f (num 100000 10 1 #f 3)))
(test "100,000.00" (fmt #f (num 100000 10 2 #f 3)))
(test "1.23" (fmt #f (fix 2 (num/fit 4 1.2345))))
(test "1.00" (fmt #f (fix 2 (num/fit 4 1))))
(test "#.##" (fmt #f (fix 2 (num/fit 4 12.345))))
;; (cond
;; ((feature? 'full-numeric-tower)
;; (test "1+2i" (fmt #f (string->number "1+2i")))
;; (test "1+2i" (fmt #f (num (string->number "1+2i"))))
( test " 1.00 + 2.00i " ( fmt # f ( fix 2 ( num ( string->number " 1 + 2i " ) ) ) ) )
( test " 3.14 + 2.00i " ( fmt # f ( fix 2 ( num ( string->number " 3.14159 + 2i " ) ) ) ) ) ) )
(test "3.9Ki" (fmt #f (num/si 3986)))
(test "4k" (fmt #f (num/si 3986 1000)))
(test "608" (fmt #f (num/si 608)))
(test "3G" (fmt #f (num/si 12345.12355 16)))
;; padding/trimming
(test "abc " (fmt #f (pad 5 "abc")))
(test " abc" (fmt #f (pad/left 5 "abc")))
(test " abc " (fmt #f (pad/both 5 "abc")))
(test "abcde" (fmt #f (pad 5 "abcde")))
(test "abcdef" (fmt #f (pad 5 "abcdef")))
(test "abc" (fmt #f (trim 3 "abcde")))
(test "abc" (fmt #f (trim/length 3 "abcde")))
(test "abc" (fmt #f (trim/length 3 "abc\nde")))
(test "cde" (fmt #f (trim/left 3 "abcde")))
(test "bcd" (fmt #f (trim/both 3 "abcde")))
(test "prefix: abc" (fmt #f "prefix: " (trim 3 "abcde")))
(test "prefix: abc" (fmt #f "prefix: " (trim/length 3 "abcde")))
(test "prefix: abc" (fmt #f "prefix: " (trim/length 3 "abc\nde")))
(test "prefix: cde" (fmt #f "prefix: " (trim/left 3 "abcde")))
(test "prefix: bcd" (fmt #f "prefix: " (trim/both 3 "abcde")))
(test "abcde" (fmt #f (ellipses "..." (trim 5 "abcde"))))
(test "ab..." (fmt #f (ellipses "..." (trim 5 "abcdef"))))
(test "abc..." (fmt #f (ellipses "..." (trim 6 "abcdefg"))))
(test "abcde" (fmt #f (ellipses "..." (trim/left 5 "abcde"))))
(test "...ef" (fmt #f (ellipses "..." (trim/left 5 "abcdef"))))
(test "...efg" (fmt #f (ellipses "..." (trim/left 6 "abcdefg"))))
(test "abcdefg" (fmt #f (ellipses "..." (trim/both 7 "abcdefg"))))
(test "...d..." (fmt #f (ellipses "..." (trim/both 7 "abcdefgh"))))
(test "...e..." (fmt #f (ellipses "..." (trim/both 7 "abcdefghi"))))
(test "abc " (fmt #f (fit 5 "abc")))
(test " abc" (fmt #f (fit/left 5 "abc")))
(test " abc " (fmt #f (fit/both 5 "abc")))
(test "abcde" (fmt #f (fit 5 "abcde")))
(test "abcde" (fmt #f (fit/left 5 "abcde")))
(test "abcde" (fmt #f (fit/both 5 "abcde")))
(test "abcde" (fmt #f (fit 5 "abcdefgh")))
(test "defgh" (fmt #f (fit/left 5 "abcdefgh")))
(test "cdefg" (fmt #f (fit/both 5 "abcdefgh")))
(test "prefix: abc " (fmt #f "prefix: " (fit 5 "abc")))
(test "prefix: abc" (fmt #f "prefix: " (fit/left 5 "abc")))
(test "prefix: abc " (fmt #f "prefix: " (fit/both 5 "abc")))
(test "prefix: abcde" (fmt #f "prefix: " (fit 5 "abcde")))
(test "prefix: abcde" (fmt #f "prefix: " (fit/left 5 "abcde")))
(test "prefix: abcde" (fmt #f "prefix: " (fit/both 5 "abcde")))
(test "prefix: abcde" (fmt #f "prefix: " (fit 5 "abcdefgh")))
(test "prefix: defgh" (fmt #f "prefix: " (fit/left 5 "abcdefgh")))
(test "prefix: cdefg" (fmt #f "prefix: " (fit/both 5 "abcdefgh")))
(test "abc\n123\n" (fmt #f (fmt-join/suffix (cut trim 3 <>) (string-split "abcdef\n123456\n" "\n") nl)))
;; utilities
(test "1 2 3" (fmt #f (fmt-join dsp '(1 2 3) " ")))
;; shared structures
(test "#0=(1 . #0#)"
(fmt #f (wrt (let ((ones (list 1))) (set-cdr! ones ones) ones))))
(test "(0 . #0=(1 . #0#))"
(fmt #f (wrt (let ((ones (list 1)))
(set-cdr! ones ones)
(cons 0 ones)))))
(test "(sym . #0=(sym . #0#))"
(fmt #f (wrt (let ((syms (list 'sym)))
(set-cdr! syms syms)
(cons 'sym syms)))))
(test "(#0=(1 . #0#) #1=(2 . #1#))"
(fmt #f (wrt (let ((ones (list 1))
(twos (list 2)))
(set-cdr! ones ones)
(set-cdr! twos twos)
(list ones twos)))))
;; without shared detection
(test "(1 1 1 1 1"
(fmt #f (trim/length
10
(wrt/unshared
(let ((ones (list 1))) (set-cdr! ones ones) ones)))))
(test "(1 1 1 1 1 "
(fmt #f (trim/length
11
(wrt/unshared
(let ((ones (list 1))) (set-cdr! ones ones) ones)))))
;; pretty printing
;; (define-macro (test-pretty str)
;; (let ((sexp (with-input-from-string str read)))
;; `(test ,str (fmt #f (pretty ',sexp)))))
(define-syntax test-pretty
(syntax-rules ()
((test-pretty str)
(let ((sexp (with-input-from-string str read)))
(test str (fmt #f (pretty sexp)))))))
(test-pretty "(foo bar)\n")
(test-pretty
"((self . aquanet-paper-1991)
(type . paper)
(title . \"Aquanet: a hypertext tool to hold your\"))
")
(test-pretty
"(abracadabra xylophone
bananarama
yellowstonepark
cryptoanalysis
zebramania
delightful
wubbleflubbery)\n")
(test-pretty
"#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32 33 34 35 36 37)\n")
(test-pretty
"(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32 33 34 35 36 37)\n")
(test-pretty
"(define (fold kons knil ls)
(define (loop ls acc)
(if (null? ls) acc (loop (cdr ls) (kons (car ls) acc))))
(loop ls knil))\n")
(test-pretty
"(do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec) (vector-set! vec i i))\n")
(test-pretty
"(do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec)
(vector-set! vec i 'supercalifrajalisticexpialidocious))\n")
(test-pretty
"(do ((my-vector (make-vector 5)) (index 0 (+ index 1)))
((= index 5) my-vector)
(vector-set! my-vector index index))\n")
(test-pretty
"(define (fold kons knil ls)
(let loop ((ls ls) (acc knil))
(if (null? ls) acc (loop (cdr ls) (kons (car ls) acc)))))\n")
(test-pretty
"(define (file->sexp-list pathname)
(call-with-input-file pathname
(lambda (port)
(let loop ((res '()))
(let ((line (read port)))
(if (eof-object? line) (reverse res) (loop (cons line res))))))))\n")
(test "(let ((ones '#0=(1 . #0#))) ones)\n"
(fmt #f (pretty (let ((ones (list 1))) (set-cdr! ones ones) `(let ((ones ',ones)) ones)))))
'(test
"(let ((zeros '(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
(ones '#0=(1 . #0#)))
(append zeros ones))\n"
(fmt #f (pretty
(let ((ones (list 1)))
(set-cdr! ones ones)
`(let ((zeros '(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
(ones ',ones))
(append zeros ones))))))
;; slashify
(test "\"note\",\"very simple\",\"csv\",\"writer\",\"\"\"yay!\"\"\""
(fmt #f (fmt-join (lambda (x) (cat "\"" (slashified x #\" #f) "\""))
'("note" "very simple" "csv" "writer" "\"yay!\"")
",")))
(test "note,\"very simple\",csv,writer,\"\"\"yay!\"\"\""
(fmt #f (fmt-join (cut maybe-slashified <> char-whitespace? #\" #f)
'("note" "very simple" "csv" "writer" "\"yay!\"")
",")))
;; columnar formatting
(test "abc\ndef\n" (fmt #f (fmt-columns (list dsp "abc\ndef\n"))))
(test "abc123\ndef456\n" (fmt #f (fmt-columns (list dsp "abc\ndef\n") (list dsp "123\n456\n"))))
(test "abc123\ndef456\n" (fmt #f (fmt-columns (list dsp "abc\ndef\n") (list dsp "123\n456"))))
(test "abc123\ndef456\n" (fmt #f (fmt-columns (list dsp "abc\ndef") (list dsp "123\n456\n"))))
(test "abc123\ndef456\nghi789\n"
(fmt #f (fmt-columns (list dsp "abc\ndef\nghi\n") (list dsp "123\n456\n789\n"))))
(test "abc123wuv\ndef456xyz\n"
(fmt #f (fmt-columns (list dsp "abc\ndef\n") (list dsp "123\n456\n") (list dsp "wuv\nxyz\n"))))
(test "abc 123\ndef 456\n"
(fmt #f (fmt-columns (list (cut pad/right 5 <>) "abc\ndef\n") (list dsp "123\n456\n"))))
(test "ABC 123\nDEF 456\n"
(fmt #f (fmt-columns (list (compose upcase (cut pad/right 5 <>)) "abc\ndef\n")
(list dsp "123\n456\n"))))
(test "ABC 123\nDEF 456\n"
(fmt #f (fmt-columns (list (compose (cut pad/right 5 <>) upcase) "abc\ndef\n")
(list dsp "123\n456\n"))))
(test "hello\nworld\n" (fmt #f (with-width 8 (wrap-lines "hello world"))))
(test "\n" (fmt #f (wrap-lines " ")))
test divide by zero error
"The quick
brown fox
jumped
over the
lazy dog
"
(fmt #f (with-width 10 (justify "The quick brown fox jumped over the lazy dog"))))
(test "his message
(-users/2010-10/msg00171.html)
to the chicken-users
(-users)\n"
(fmt #f (with-width 67 (wrap-lines "his message (-users/2010-10/msg00171.html) to the chicken-users (-users)"))))
(test "The fundamental list iterator.
Applies KONS to each element of
LS and the result of the previous
application, beginning with KNIL.
With KONS as CONS and KNIL as '(),
equivalent to REVERSE.
"
(fmt #f (with-width 36 (wrap-lines "The fundamental list iterator. Applies KONS to each element of LS and the result of the previous application, beginning with KNIL. With KONS as CONS and KNIL as '(), equivalent to REVERSE."))))
(test
"The fundamental list iterator.
Applies KONS to each element of
LS and the result of the previous
application, beginning with KNIL.
With KONS as CONS and KNIL as '(),
equivalent to REVERSE.
"
(fmt #f (with-width 36 (justify "The fundamental list iterator. Applies KONS to each element of LS and the result of the previous application, beginning with KNIL. With KONS as CONS and KNIL as '(), equivalent to REVERSE."))))
(test
"(define (fold kons knil ls) ; The fundamental list iterator.
(let lp ((ls ls) (acc knil)) ; Applies KONS to each element of
LS and the result of the previous
application , beginning with KNIL .
With KONS as CONS and KNIL as ' ( ) ,
(kons (car ls) acc))))) ; equivalent to REVERSE.
"
(fmt #f (fmt-columns
(list
(cut pad/right 36 <>)
(with-width 36
(pretty '(define (fold kons knil ls)
(let lp ((ls ls) (acc knil))
(if (null? ls)
acc
(lp (cdr ls)
(kons (car ls) acc))))))))
(list
(cut cat " ; " <>)
(with-width 36
(wrap-lines "The fundamental list iterator. Applies KONS to each element of LS and the result of the previous application, beginning with KNIL. With KONS as CONS and KNIL as '(), equivalent to REVERSE."))))))
(test
"(define (fold kons knil ls) ; The fundamental list iterator.
(let lp ((ls ls) (acc knil)) ; Applies KONS to each element of
LS and the result of the previous
application , beginning with KNIL .
With KONS as CONS and KNIL as ' ( ) ,
(kons (car ls) acc))))) ; equivalent to REVERSE.
"
(fmt #f (with-width 76
(columnar
(pretty '(define (fold kons knil ls)
(let lp ((ls ls) (acc knil))
(if (null? ls)
acc
(lp (cdr ls)
(kons (car ls) acc))))))
" ; "
(wrap-lines "The fundamental list iterator. Applies KONS to each element of LS and the result of the previous application, beginning with KNIL. With KONS as CONS and KNIL as '(), equivalent to REVERSE.")))))
(test
"- Item 1: The text here is
indented according
to the space \"Item
1\" takes, and one
does not known what
goes here.
"
(fmt #f (columnar 9 (dsp "- Item 1:") " " (with-width 20 (wrap-lines "The text here is indented according to the space \"Item 1\" takes, and one does not known what goes here.")))))
(test
"- Item 1: The text here is
indented according
to the space \"Item
1\" takes, and one
does not known what
goes here.
"
(fmt #f (columnar 9 (dsp "- Item 1:\n") " " (with-width 20 (wrap-lines "The text here is indented according to the space \"Item 1\" takes, and one does not known what goes here.")))))
(test
"- Item 1: The text here is----------------------------------------------------
--------- indented according--------------------------------------------------
--------- to the space \"Item--------------------------------------------------
--------- 1\" takes, and one---------------------------------------------------
--------- does not known what-------------------------------------------------
--------- goes here.----------------------------------------------------------
"
(fmt #f (pad-char #\- (columnar 9 (dsp "- Item 1:\n") " " (with-width 20 (wrap-lines "The text here is indented according to the space \"Item 1\" takes, and one does not known what goes here."))))))
(test
"a | 123
bc | 45
def | 6
"
(fmt #f (with-width
20
(tabular (dsp "a\nbc\ndef\n") " | " (dsp "123\n45\n6\n")))))
;; misc extras
(define (string-hide-passwords str)
(string-substitute (regexp "(pass(?:w(?:or)?d)?\\s?[:=>]\\s+)\\S+" #t)
"\\1******"
str
#t))
(define hide-passwords
(make-string-fmt-transformer string-hide-passwords))
(define (string-mangle-email str)
(string-substitute
(regexp "\\b([-+.\\w]+)@((?:[-+\\w]+\\.)+[a-z]{2,4})\\b" #t)
"\\1 _at_ \\2"
str
#t))
(define mangle-email
(make-string-fmt-transformer string-mangle-email))
(test-end)
| null | https://raw.githubusercontent.com/alvatar/spheres/568836f234a469ef70c69f4a2d9b56d41c3fc5bd/spheres/string/fmt/test/test-fmt.scm | scheme | basic data types
(test "1e+23" (fmt #f (num 1e+23)))
exact rationals
(cond
((feature? 'full-numeric-tower)
(test "1+2i" (fmt #f (string->number "1+2i")))
(test "1+2i" (fmt #f (num (string->number "1+2i"))))
padding/trimming
utilities
shared structures
without shared detection
pretty printing
(define-macro (test-pretty str)
(let ((sexp (with-input-from-string str read)))
`(test ,str (fmt #f (pretty ',sexp)))))
slashify
columnar formatting
The fundamental list iterator.
Applies KONS to each element of
equivalent to REVERSE.
The fundamental list iterator.
Applies KONS to each element of
equivalent to REVERSE.
misc extras |
(cond-expand
(chicken
(load "fmt-chicken.scm"))
(else))
(cond-expand
(chicken
(use test)
(import fmt))
(gauche
(use gauche.test)
(use text.fmt)
(define test-begin test-start)
(define orig-test (with-module gauche.test test))
(define-syntax test
(syntax-rules ()
((test name expected expr)
(guard (e (else #f))
(orig-test name expected (lambda () expr))))
((test expected expr)
(test (let ((s (with-output-to-string (lambda () (write 'expr)))))
(substring s 0 (min 60 (string-length s))))
expected expr)))))
(else))
(test-begin "fmt")
(test "hi" (fmt #f "hi"))
(test "\"hi\"" (fmt #f (wrt "hi")))
(test "\"hi \\\"bob\\\"\"" (fmt #f (wrt "hi \"bob\"")))
(test "\"hello\\nworld\"" (fmt #f (wrt "hello\nworld")))
(test "ABC" (fmt #f (upcase "abc")))
(test "abc" (fmt #f (downcase "ABC")))
(test "Abc" (fmt #f (titlecase "abc")))
(test "abc def" (fmt #f "abc" (tab-to) "def"))
(test "abc def" (fmt #f "abc" (tab-to 5) "def"))
(test "abcdef" (fmt #f "abc" (tab-to 3) "def"))
(test "-1" (fmt #f -1))
(test "0" (fmt #f 0))
(test "1" (fmt #f 1))
(test "10" (fmt #f 10))
(test "100" (fmt #f 100))
(test "-1" (fmt #f (num -1)))
(test "0" (fmt #f (num 0)))
(test "1" (fmt #f (num 1)))
(test "10" (fmt #f (num 10)))
(test "100" (fmt #f (num 100)))
( test " 1e+15 " ( fmt # f ( num 1e+15 ) ) )
( test " 1.2e+23 " ( fmt # f ( num 1.2e+23 ) ) )
( test " 1e-5 " ( fmt # f ( num 1e-5 ) ) )
( test " 1e-6 " ( fmt # f ( num 1e-6 ) ) )
( test " 1e-7 " ( fmt # f ( num 1e-7 ) ) )
( test " 2e-6 " ( fmt # f ( num 2e-6 ) ) )
(test "57005" (fmt #f #xDEAD))
(test "#xDEAD" (fmt #f (radix 16 #xDEAD)))
(test "#xDEAD1234" (fmt #f (radix 16 #xDEAD) 1234))
(test "#xDE.AD" (fmt #f (radix 16 (exact->inexact (/ #xDEAD #x100)))))
(test "#xD.EAD" (fmt #f (radix 16 (exact->inexact (/ #xDEAD #x1000)))))
(test "#x0.DEAD" (fmt #f (radix 16 (exact->inexact (/ #xDEAD #x10000)))))
(test "1G" (fmt #f (radix 17 (num 33))))
(test "1G" (fmt #f (num 33 17)))
(test "3.14159" (fmt #f 3.14159))
(test "3.14" (fmt #f (fix 2 3.14159)))
(test "3.14" (fmt #f (fix 2 3.14)))
(test "3.00" (fmt #f (fix 2 3.)))
(test "1.10" (fmt #f (num 1.099 10 2)))
(test "0.00" (fmt #f (fix 2 1e-17)))
(test "0.0000000000" (fmt #f (fix 10 1e-17)))
(test "0.00000000000000001000" (fmt #f (fix 20 1e-17)))
( test - error ( fmt # f ( num 1e-17 0 ) ) )
(test "0.000004" (fmt #f (num 0.000004 10 6)))
(test "0.0000040" (fmt #f (num 0.000004 10 7)))
(test "0.00000400" (fmt #f (num 0.000004 10 8)))
( test " 0.000004 " ( fmt # f ( num 0.000004 ) ) )
(test " 3.14159" (fmt #f (decimal-align 5 (num 3.14159))))
(test " 31.4159" (fmt #f (decimal-align 5 (num 31.4159))))
(test " 314.159" (fmt #f (decimal-align 5 (num 314.159))))
(test "3141.59" (fmt #f (decimal-align 5 (num 3141.59))))
(test "31415.9" (fmt #f (decimal-align 5 (num 31415.9))))
(test " -3.14159" (fmt #f (decimal-align 5 (num -3.14159))))
(test " -31.4159" (fmt #f (decimal-align 5 (num -31.4159))))
(test "-314.159" (fmt #f (decimal-align 5 (num -314.159))))
(test "-3141.59" (fmt #f (decimal-align 5 (num -3141.59))))
(test "-31415.9" (fmt #f (decimal-align 5 (num -31415.9))))
(cond
(test "333.333333333333333333333333333333" (fmt #f (fix 30 1000/3)))
(test "33.333333333333333333333333333333" (fmt #f (fix 30 100/3)))
(test "3.333333333333333333333333333333" (fmt #f (fix 30 10/3)))
(test "0.333333333333333333333333333333" (fmt #f (fix 30 1/3)))
(test "0.033333333333333333333333333333" (fmt #f (fix 30 1/30)))
(test "0.003333333333333333333333333333" (fmt #f (fix 30 1/300)))
(test "0.000333333333333333333333333333" (fmt #f (fix 30 1/3000)))
(test "0.666666666666666666666666666667" (fmt #f (fix 30 2/3)))
(test "0.090909090909090909090909090909" (fmt #f (fix 30 1/11)))
(test "1.428571428571428571428571428571" (fmt #f (fix 30 10/7)))
(test "0.123456789012345678901234567890"
(fmt #f (fix 30 (/ 123456789012345678901234567890
1000000000000000000000000000000))))
(test " 333.333333333333333333333333333333" (fmt #f (decimal-align 5 (fix 30 1000/3))))
(test " 33.333333333333333333333333333333" (fmt #f (decimal-align 5 (fix 30 100/3))))
(test " 3.333333333333333333333333333333" (fmt #f (decimal-align 5 (fix 30 10/3))))
(test " 0.333333333333333333333333333333" (fmt #f (decimal-align 5 (fix 30 1/3))))
))
(test "11.75" (fmt #f (num (/ 47 4) 10 2)))
(test "-11.75" (fmt #f (num (/ -47 4) 10 2)))
(test "(#x11 #x22 #x33)" (fmt #f (radix 16 '(#x11 #x22 #x33))))
(test "299,792,458" (fmt #f (num 299792458 10 #f #f #t)))
(test "299,792,458" (fmt #f (num/comma 299792458)))
(test "299.792.458" (fmt #f (comma-char #\. (num/comma 299792458))))
(test "299.792.458,0" (fmt #f (comma-char #\. (num/comma 299792458.0))))
(test "100,000" (fmt #f (num 100000 10 0 #f 3)))
(test "100,000.0" (fmt #f (num 100000 10 1 #f 3)))
(test "100,000.00" (fmt #f (num 100000 10 2 #f 3)))
(test "1.23" (fmt #f (fix 2 (num/fit 4 1.2345))))
(test "1.00" (fmt #f (fix 2 (num/fit 4 1))))
(test "#.##" (fmt #f (fix 2 (num/fit 4 12.345))))
( test " 1.00 + 2.00i " ( fmt # f ( fix 2 ( num ( string->number " 1 + 2i " ) ) ) ) )
( test " 3.14 + 2.00i " ( fmt # f ( fix 2 ( num ( string->number " 3.14159 + 2i " ) ) ) ) ) ) )
(test "3.9Ki" (fmt #f (num/si 3986)))
(test "4k" (fmt #f (num/si 3986 1000)))
(test "608" (fmt #f (num/si 608)))
(test "3G" (fmt #f (num/si 12345.12355 16)))
(test "abc " (fmt #f (pad 5 "abc")))
(test " abc" (fmt #f (pad/left 5 "abc")))
(test " abc " (fmt #f (pad/both 5 "abc")))
(test "abcde" (fmt #f (pad 5 "abcde")))
(test "abcdef" (fmt #f (pad 5 "abcdef")))
(test "abc" (fmt #f (trim 3 "abcde")))
(test "abc" (fmt #f (trim/length 3 "abcde")))
(test "abc" (fmt #f (trim/length 3 "abc\nde")))
(test "cde" (fmt #f (trim/left 3 "abcde")))
(test "bcd" (fmt #f (trim/both 3 "abcde")))
(test "prefix: abc" (fmt #f "prefix: " (trim 3 "abcde")))
(test "prefix: abc" (fmt #f "prefix: " (trim/length 3 "abcde")))
(test "prefix: abc" (fmt #f "prefix: " (trim/length 3 "abc\nde")))
(test "prefix: cde" (fmt #f "prefix: " (trim/left 3 "abcde")))
(test "prefix: bcd" (fmt #f "prefix: " (trim/both 3 "abcde")))
(test "abcde" (fmt #f (ellipses "..." (trim 5 "abcde"))))
(test "ab..." (fmt #f (ellipses "..." (trim 5 "abcdef"))))
(test "abc..." (fmt #f (ellipses "..." (trim 6 "abcdefg"))))
(test "abcde" (fmt #f (ellipses "..." (trim/left 5 "abcde"))))
(test "...ef" (fmt #f (ellipses "..." (trim/left 5 "abcdef"))))
(test "...efg" (fmt #f (ellipses "..." (trim/left 6 "abcdefg"))))
(test "abcdefg" (fmt #f (ellipses "..." (trim/both 7 "abcdefg"))))
(test "...d..." (fmt #f (ellipses "..." (trim/both 7 "abcdefgh"))))
(test "...e..." (fmt #f (ellipses "..." (trim/both 7 "abcdefghi"))))
(test "abc " (fmt #f (fit 5 "abc")))
(test " abc" (fmt #f (fit/left 5 "abc")))
(test " abc " (fmt #f (fit/both 5 "abc")))
(test "abcde" (fmt #f (fit 5 "abcde")))
(test "abcde" (fmt #f (fit/left 5 "abcde")))
(test "abcde" (fmt #f (fit/both 5 "abcde")))
(test "abcde" (fmt #f (fit 5 "abcdefgh")))
(test "defgh" (fmt #f (fit/left 5 "abcdefgh")))
(test "cdefg" (fmt #f (fit/both 5 "abcdefgh")))
(test "prefix: abc " (fmt #f "prefix: " (fit 5 "abc")))
(test "prefix: abc" (fmt #f "prefix: " (fit/left 5 "abc")))
(test "prefix: abc " (fmt #f "prefix: " (fit/both 5 "abc")))
(test "prefix: abcde" (fmt #f "prefix: " (fit 5 "abcde")))
(test "prefix: abcde" (fmt #f "prefix: " (fit/left 5 "abcde")))
(test "prefix: abcde" (fmt #f "prefix: " (fit/both 5 "abcde")))
(test "prefix: abcde" (fmt #f "prefix: " (fit 5 "abcdefgh")))
(test "prefix: defgh" (fmt #f "prefix: " (fit/left 5 "abcdefgh")))
(test "prefix: cdefg" (fmt #f "prefix: " (fit/both 5 "abcdefgh")))
(test "abc\n123\n" (fmt #f (fmt-join/suffix (cut trim 3 <>) (string-split "abcdef\n123456\n" "\n") nl)))
(test "1 2 3" (fmt #f (fmt-join dsp '(1 2 3) " ")))
(test "#0=(1 . #0#)"
(fmt #f (wrt (let ((ones (list 1))) (set-cdr! ones ones) ones))))
(test "(0 . #0=(1 . #0#))"
(fmt #f (wrt (let ((ones (list 1)))
(set-cdr! ones ones)
(cons 0 ones)))))
(test "(sym . #0=(sym . #0#))"
(fmt #f (wrt (let ((syms (list 'sym)))
(set-cdr! syms syms)
(cons 'sym syms)))))
(test "(#0=(1 . #0#) #1=(2 . #1#))"
(fmt #f (wrt (let ((ones (list 1))
(twos (list 2)))
(set-cdr! ones ones)
(set-cdr! twos twos)
(list ones twos)))))
(test "(1 1 1 1 1"
(fmt #f (trim/length
10
(wrt/unshared
(let ((ones (list 1))) (set-cdr! ones ones) ones)))))
(test "(1 1 1 1 1 "
(fmt #f (trim/length
11
(wrt/unshared
(let ((ones (list 1))) (set-cdr! ones ones) ones)))))
(define-syntax test-pretty
(syntax-rules ()
((test-pretty str)
(let ((sexp (with-input-from-string str read)))
(test str (fmt #f (pretty sexp)))))))
(test-pretty "(foo bar)\n")
(test-pretty
"((self . aquanet-paper-1991)
(type . paper)
(title . \"Aquanet: a hypertext tool to hold your\"))
")
(test-pretty
"(abracadabra xylophone
bananarama
yellowstonepark
cryptoanalysis
zebramania
delightful
wubbleflubbery)\n")
(test-pretty
"#(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32 33 34 35 36 37)\n")
(test-pretty
"(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32 33 34 35 36 37)\n")
(test-pretty
"(define (fold kons knil ls)
(define (loop ls acc)
(if (null? ls) acc (loop (cdr ls) (kons (car ls) acc))))
(loop ls knil))\n")
(test-pretty
"(do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec) (vector-set! vec i i))\n")
(test-pretty
"(do ((vec (make-vector 5)) (i 0 (+ i 1))) ((= i 5) vec)
(vector-set! vec i 'supercalifrajalisticexpialidocious))\n")
(test-pretty
"(do ((my-vector (make-vector 5)) (index 0 (+ index 1)))
((= index 5) my-vector)
(vector-set! my-vector index index))\n")
(test-pretty
"(define (fold kons knil ls)
(let loop ((ls ls) (acc knil))
(if (null? ls) acc (loop (cdr ls) (kons (car ls) acc)))))\n")
(test-pretty
"(define (file->sexp-list pathname)
(call-with-input-file pathname
(lambda (port)
(let loop ((res '()))
(let ((line (read port)))
(if (eof-object? line) (reverse res) (loop (cons line res))))))))\n")
(test "(let ((ones '#0=(1 . #0#))) ones)\n"
(fmt #f (pretty (let ((ones (list 1))) (set-cdr! ones ones) `(let ((ones ',ones)) ones)))))
'(test
"(let ((zeros '(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
(ones '#0=(1 . #0#)))
(append zeros ones))\n"
(fmt #f (pretty
(let ((ones (list 1)))
(set-cdr! ones ones)
`(let ((zeros '(0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0))
(ones ',ones))
(append zeros ones))))))
(test "\"note\",\"very simple\",\"csv\",\"writer\",\"\"\"yay!\"\"\""
(fmt #f (fmt-join (lambda (x) (cat "\"" (slashified x #\" #f) "\""))
'("note" "very simple" "csv" "writer" "\"yay!\"")
",")))
(test "note,\"very simple\",csv,writer,\"\"\"yay!\"\"\""
(fmt #f (fmt-join (cut maybe-slashified <> char-whitespace? #\" #f)
'("note" "very simple" "csv" "writer" "\"yay!\"")
",")))
(test "abc\ndef\n" (fmt #f (fmt-columns (list dsp "abc\ndef\n"))))
(test "abc123\ndef456\n" (fmt #f (fmt-columns (list dsp "abc\ndef\n") (list dsp "123\n456\n"))))
(test "abc123\ndef456\n" (fmt #f (fmt-columns (list dsp "abc\ndef\n") (list dsp "123\n456"))))
(test "abc123\ndef456\n" (fmt #f (fmt-columns (list dsp "abc\ndef") (list dsp "123\n456\n"))))
(test "abc123\ndef456\nghi789\n"
(fmt #f (fmt-columns (list dsp "abc\ndef\nghi\n") (list dsp "123\n456\n789\n"))))
(test "abc123wuv\ndef456xyz\n"
(fmt #f (fmt-columns (list dsp "abc\ndef\n") (list dsp "123\n456\n") (list dsp "wuv\nxyz\n"))))
(test "abc 123\ndef 456\n"
(fmt #f (fmt-columns (list (cut pad/right 5 <>) "abc\ndef\n") (list dsp "123\n456\n"))))
(test "ABC 123\nDEF 456\n"
(fmt #f (fmt-columns (list (compose upcase (cut pad/right 5 <>)) "abc\ndef\n")
(list dsp "123\n456\n"))))
(test "ABC 123\nDEF 456\n"
(fmt #f (fmt-columns (list (compose (cut pad/right 5 <>) upcase) "abc\ndef\n")
(list dsp "123\n456\n"))))
(test "hello\nworld\n" (fmt #f (with-width 8 (wrap-lines "hello world"))))
(test "\n" (fmt #f (wrap-lines " ")))
test divide by zero error
"The quick
brown fox
jumped
over the
lazy dog
"
(fmt #f (with-width 10 (justify "The quick brown fox jumped over the lazy dog"))))
(test "his message
(-users/2010-10/msg00171.html)
to the chicken-users
(-users)\n"
(fmt #f (with-width 67 (wrap-lines "his message (-users/2010-10/msg00171.html) to the chicken-users (-users)"))))
(test "The fundamental list iterator.
Applies KONS to each element of
LS and the result of the previous
application, beginning with KNIL.
With KONS as CONS and KNIL as '(),
equivalent to REVERSE.
"
(fmt #f (with-width 36 (wrap-lines "The fundamental list iterator. Applies KONS to each element of LS and the result of the previous application, beginning with KNIL. With KONS as CONS and KNIL as '(), equivalent to REVERSE."))))
(test
"The fundamental list iterator.
Applies KONS to each element of
LS and the result of the previous
application, beginning with KNIL.
With KONS as CONS and KNIL as '(),
equivalent to REVERSE.
"
(fmt #f (with-width 36 (justify "The fundamental list iterator. Applies KONS to each element of LS and the result of the previous application, beginning with KNIL. With KONS as CONS and KNIL as '(), equivalent to REVERSE."))))
(test
LS and the result of the previous
application , beginning with KNIL .
With KONS as CONS and KNIL as ' ( ) ,
"
(fmt #f (fmt-columns
(list
(cut pad/right 36 <>)
(with-width 36
(pretty '(define (fold kons knil ls)
(let lp ((ls ls) (acc knil))
(if (null? ls)
acc
(lp (cdr ls)
(kons (car ls) acc))))))))
(list
(cut cat " ; " <>)
(with-width 36
(wrap-lines "The fundamental list iterator. Applies KONS to each element of LS and the result of the previous application, beginning with KNIL. With KONS as CONS and KNIL as '(), equivalent to REVERSE."))))))
(test
LS and the result of the previous
application , beginning with KNIL .
With KONS as CONS and KNIL as ' ( ) ,
"
(fmt #f (with-width 76
(columnar
(pretty '(define (fold kons knil ls)
(let lp ((ls ls) (acc knil))
(if (null? ls)
acc
(lp (cdr ls)
(kons (car ls) acc))))))
" ; "
(wrap-lines "The fundamental list iterator. Applies KONS to each element of LS and the result of the previous application, beginning with KNIL. With KONS as CONS and KNIL as '(), equivalent to REVERSE.")))))
(test
"- Item 1: The text here is
indented according
to the space \"Item
1\" takes, and one
does not known what
goes here.
"
(fmt #f (columnar 9 (dsp "- Item 1:") " " (with-width 20 (wrap-lines "The text here is indented according to the space \"Item 1\" takes, and one does not known what goes here.")))))
(test
"- Item 1: The text here is
indented according
to the space \"Item
1\" takes, and one
does not known what
goes here.
"
(fmt #f (columnar 9 (dsp "- Item 1:\n") " " (with-width 20 (wrap-lines "The text here is indented according to the space \"Item 1\" takes, and one does not known what goes here.")))))
(test
"- Item 1: The text here is----------------------------------------------------
--------- indented according--------------------------------------------------
--------- to the space \"Item--------------------------------------------------
--------- 1\" takes, and one---------------------------------------------------
--------- does not known what-------------------------------------------------
--------- goes here.----------------------------------------------------------
"
(fmt #f (pad-char #\- (columnar 9 (dsp "- Item 1:\n") " " (with-width 20 (wrap-lines "The text here is indented according to the space \"Item 1\" takes, and one does not known what goes here."))))))
(test
"a | 123
bc | 45
def | 6
"
(fmt #f (with-width
20
(tabular (dsp "a\nbc\ndef\n") " | " (dsp "123\n45\n6\n")))))
(define (string-hide-passwords str)
(string-substitute (regexp "(pass(?:w(?:or)?d)?\\s?[:=>]\\s+)\\S+" #t)
"\\1******"
str
#t))
(define hide-passwords
(make-string-fmt-transformer string-hide-passwords))
(define (string-mangle-email str)
(string-substitute
(regexp "\\b([-+.\\w]+)@((?:[-+\\w]+\\.)+[a-z]{2,4})\\b" #t)
"\\1 _at_ \\2"
str
#t))
(define mangle-email
(make-string-fmt-transformer string-mangle-email))
(test-end)
|
00a66a8f85bc3ce718930a3690834385fcbbc2bc2ee1ad8ae1e2d1c99355a703 | mirage/alcotest | pp_intf.ml |
* Copyright ( c ) 2013 - 2016 < >
* Copyright ( c ) 2019 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2013-2016 Thomas Gazagnaire <>
* Copyright (c) 2019 Craig Ferguson <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Model
type theta = Format.formatter -> unit
(** Type corresponding to a [%t] placeholder. *)
module Types = struct
type event = [ `Result of Test_name.t * Run_result.t | `Start of Test_name.t ]
type result = {
success : int;
failures : int;
time : float;
errors : unit Fmt.t list;
}
end
module type Make_arg = sig
val stdout_columns : unit -> int option
end
module type S = sig
include module type of Types
val info :
?available_width:int ->
max_label:int ->
doc_of_test_name:(Test_name.t -> string) ->
Test_name.t Fmt.t
val rresult_error : Run_result.t Fmt.t
val event_line :
margins:int ->
max_label:int ->
doc_of_test_name:(Test_name.t -> string) ->
[ `Result of Test_name.t * [< Run_result.t ] | `Start of Test_name.t ] Fmt.t
val event :
isatty:bool ->
compact:bool ->
max_label:int ->
doc_of_test_name:(Test_name.t -> string) ->
selector_on_failure:bool ->
tests_so_far:int ->
event Fmt.t
val suite_results :
log_dir:theta ->
< verbose : bool ; show_errors : bool ; json : bool ; compact : bool ; .. > ->
result Fmt.t
val quoted : 'a Fmt.t -> 'a Fmt.t
(** Wraps a formatter with `GNU-style quotation marks'. *)
val with_surrounding_box : 'a Fmt.t -> 'a Fmt.t
* Wraps a formatter with a Unicode box with width given by
{ ! _ .stdout_columns } . Uses box - drawing characters from code page 437 .
{!_.stdout_columns}. Uses box-drawing characters from code page 437. *)
val horizontal_rule : _ Fmt.t
* Horizontal rule of length { ! _ .stdout_columns } . Uses box - drawing characters
from code page 437 .
from code page 437. *)
val user_error : string -> _
(** Raise a user error, then fail. *)
end
module type Pp = sig
val tag : [ `Ok | `Fail | `Skip | `Todo | `Assert ] Fmt.t
val map_theta : theta -> f:(unit Fmt.t -> unit Fmt.t) -> theta
val pp_plural : int Fmt.t
* This is for adding an 's ' to words that should be pluralized , e.g.
{ [
let n = List.length items in
Fmt.pr " Found % i item%a . " n pp_plural n
] }
{[
let n = List.length items in
Fmt.pr "Found %i item%a." n pp_plural n
]} *)
module Make (_ : Make_arg) : S
end
| null | https://raw.githubusercontent.com/mirage/alcotest/e2d5ddf31594e0f9c3bcef98ca4859856b281efc/src/alcotest-engine/pp_intf.ml | ocaml | * Type corresponding to a [%t] placeholder.
* Wraps a formatter with `GNU-style quotation marks'.
* Raise a user error, then fail. |
* Copyright ( c ) 2013 - 2016 < >
* Copyright ( c ) 2019 < >
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (c) 2013-2016 Thomas Gazagnaire <>
* Copyright (c) 2019 Craig Ferguson <>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
open Model
type theta = Format.formatter -> unit
module Types = struct
type event = [ `Result of Test_name.t * Run_result.t | `Start of Test_name.t ]
type result = {
success : int;
failures : int;
time : float;
errors : unit Fmt.t list;
}
end
module type Make_arg = sig
val stdout_columns : unit -> int option
end
module type S = sig
include module type of Types
val info :
?available_width:int ->
max_label:int ->
doc_of_test_name:(Test_name.t -> string) ->
Test_name.t Fmt.t
val rresult_error : Run_result.t Fmt.t
val event_line :
margins:int ->
max_label:int ->
doc_of_test_name:(Test_name.t -> string) ->
[ `Result of Test_name.t * [< Run_result.t ] | `Start of Test_name.t ] Fmt.t
val event :
isatty:bool ->
compact:bool ->
max_label:int ->
doc_of_test_name:(Test_name.t -> string) ->
selector_on_failure:bool ->
tests_so_far:int ->
event Fmt.t
val suite_results :
log_dir:theta ->
< verbose : bool ; show_errors : bool ; json : bool ; compact : bool ; .. > ->
result Fmt.t
val quoted : 'a Fmt.t -> 'a Fmt.t
val with_surrounding_box : 'a Fmt.t -> 'a Fmt.t
* Wraps a formatter with a Unicode box with width given by
{ ! _ .stdout_columns } . Uses box - drawing characters from code page 437 .
{!_.stdout_columns}. Uses box-drawing characters from code page 437. *)
val horizontal_rule : _ Fmt.t
* Horizontal rule of length { ! _ .stdout_columns } . Uses box - drawing characters
from code page 437 .
from code page 437. *)
val user_error : string -> _
end
module type Pp = sig
val tag : [ `Ok | `Fail | `Skip | `Todo | `Assert ] Fmt.t
val map_theta : theta -> f:(unit Fmt.t -> unit Fmt.t) -> theta
val pp_plural : int Fmt.t
* This is for adding an 's ' to words that should be pluralized , e.g.
{ [
let n = List.length items in
Fmt.pr " Found % i item%a . " n pp_plural n
] }
{[
let n = List.length items in
Fmt.pr "Found %i item%a." n pp_plural n
]} *)
module Make (_ : Make_arg) : S
end
|
307f00ef5e3a7024932dcdedb5c68c2cc3f1b02906ab8d93200a23377982124a | duo-lang/duo-lang | BenchRunner.hs | module Main where
import Criterion.Main
import Control.Monad.Except
import Data.List.NonEmpty (NonEmpty)
import Driver.Definition (defaultDriverState, parseAndCheckModule)
import Driver.Driver (inferProgramIO)
import Errors
import Syntax.CST.Program qualified as CST
import Syntax.CST.Names
import Syntax.TST.Program qualified as TST
import Utils (listRecursiveDuoFiles, moduleNameToFullPath)
import GHC.IO.Encoding (setLocaleEncoding)
import System.IO (utf8)
excluded :: [ModuleName]
excluded = []
getAvailableExamples :: IO [(FilePath, ModuleName)]
getAvailableExamples = do
let examplesFp = "examples/"
let examplesFp' = "std/"
examples <- listRecursiveDuoFiles examplesFp
examples' <- listRecursiveDuoFiles examplesFp'
let examplesFiltered = filter filterFun examples
let examplesFiltered' = filter filterFun examples'
return $ zip (repeat examplesFp) examplesFiltered ++ zip (repeat examplesFp') examplesFiltered'
where
filterFun s = s `notElem` excluded
getParsedDeclarations :: FilePath -> ModuleName -> IO (Either (NonEmpty Error) CST.Module)
getParsedDeclarations fp mn = do
let fullFp = moduleNameToFullPath mn fp
runExceptT (parseAndCheckModule fullFp mn fp)
getTypecheckedDecls :: FilePath -> ModuleName -> IO (Either (NonEmpty Error) TST.Module)
getTypecheckedDecls fp mn = do
decls <- getParsedDeclarations fp mn
case decls of
Right decls -> do
fmap snd <$> (fst <$> inferProgramIO defaultDriverState decls)
Left err -> return (Left err)
typeInferenceBenchmarks :: [(FilePath, ModuleName)] -> Benchmark
typeInferenceBenchmarks fps = bgroup "Type inference" (uncurry inferType <$> fps)
inferType :: FilePath -> ModuleName -> Benchmark
inferType fp mn = bench (" Example: " <> moduleNameToFullPath mn fp) $ whnfIO (getTypecheckedDecls fp mn)
main :: IO ()
main = do
setLocaleEncoding utf8
examples <- getAvailableExamples
defaultMain [typeInferenceBenchmarks examples]
| null | https://raw.githubusercontent.com/duo-lang/duo-lang/ee1dfcfc2aba1011ffd7880debaa17ac9e645dcd/bench/BenchRunner.hs | haskell | module Main where
import Criterion.Main
import Control.Monad.Except
import Data.List.NonEmpty (NonEmpty)
import Driver.Definition (defaultDriverState, parseAndCheckModule)
import Driver.Driver (inferProgramIO)
import Errors
import Syntax.CST.Program qualified as CST
import Syntax.CST.Names
import Syntax.TST.Program qualified as TST
import Utils (listRecursiveDuoFiles, moduleNameToFullPath)
import GHC.IO.Encoding (setLocaleEncoding)
import System.IO (utf8)
excluded :: [ModuleName]
excluded = []
getAvailableExamples :: IO [(FilePath, ModuleName)]
getAvailableExamples = do
let examplesFp = "examples/"
let examplesFp' = "std/"
examples <- listRecursiveDuoFiles examplesFp
examples' <- listRecursiveDuoFiles examplesFp'
let examplesFiltered = filter filterFun examples
let examplesFiltered' = filter filterFun examples'
return $ zip (repeat examplesFp) examplesFiltered ++ zip (repeat examplesFp') examplesFiltered'
where
filterFun s = s `notElem` excluded
getParsedDeclarations :: FilePath -> ModuleName -> IO (Either (NonEmpty Error) CST.Module)
getParsedDeclarations fp mn = do
let fullFp = moduleNameToFullPath mn fp
runExceptT (parseAndCheckModule fullFp mn fp)
getTypecheckedDecls :: FilePath -> ModuleName -> IO (Either (NonEmpty Error) TST.Module)
getTypecheckedDecls fp mn = do
decls <- getParsedDeclarations fp mn
case decls of
Right decls -> do
fmap snd <$> (fst <$> inferProgramIO defaultDriverState decls)
Left err -> return (Left err)
typeInferenceBenchmarks :: [(FilePath, ModuleName)] -> Benchmark
typeInferenceBenchmarks fps = bgroup "Type inference" (uncurry inferType <$> fps)
inferType :: FilePath -> ModuleName -> Benchmark
inferType fp mn = bench (" Example: " <> moduleNameToFullPath mn fp) $ whnfIO (getTypecheckedDecls fp mn)
main :: IO ()
main = do
setLocaleEncoding utf8
examples <- getAvailableExamples
defaultMain [typeInferenceBenchmarks examples]
| |
3df61a152e6bc8653d0282718aca2b4276114a69cb9b6c75865d2eff1c61b530 | BitGameEN/bitgamex | erlcloud_ec2_meta.erl | -module(erlcloud_ec2_meta).
-include("erlcloud.hrl").
-include("erlcloud_aws.hrl").
-export([get_instance_metadata/0, get_instance_metadata/1, get_instance_metadata/2,
get_instance_user_data/0, get_instance_user_data/1,
get_instance_dynamic_data/0, get_instance_dynamic_data/1, get_instance_dynamic_data/2]).
-spec get_instance_metadata() -> {ok, binary()} | {error, tuple()}.
get_instance_metadata() ->
get_instance_metadata(erlcloud_aws:default_config()).
-spec get_instance_metadata(Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
get_instance_metadata(Config) ->
get_instance_metadata("", Config).
%%%---------------------------------------------------------------------------
-spec get_instance_metadata( ItemPath :: string(), Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
%%%---------------------------------------------------------------------------
%% @doc Retrieve the instance meta data for the instance this code is running on. Will fail if not an EC2 instance.
%%
%% This convenience function will retrieve the instance id from the AWS metadata available at
%% -data/*
%% ItemPath allows fetching specific pieces of metadata.
%%
%%
get_instance_metadata(ItemPath, Config) ->
MetaDataPath = "-data/" ++ ItemPath,
erlcloud_aws:http_body(erlcloud_httpc:request(MetaDataPath, get, [], <<>>, erlcloud_aws:get_timeout(Config), Config)).
-spec get_instance_user_data() -> {ok, binary()} | {error, tuple()}.
get_instance_user_data() ->
get_instance_user_data(erlcloud_aws:default_config()).
%%%---------------------------------------------------------------------------
-spec get_instance_user_data( Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
%%%---------------------------------------------------------------------------
%% @doc Retrieve the user data for the instance this code is running on. Will fail if not an EC2 instance.
%%
%% This convenience function will retrieve the user data the instance was started with, i.e. what's available at
%% -data
%%
%%
get_instance_user_data(Config) ->
UserDataPath = "-data/",
erlcloud_aws:http_body(erlcloud_httpc:request(UserDataPath, get, [], <<>>, erlcloud_aws:get_timeout(Config), Config)).
-spec get_instance_dynamic_data() -> {ok, binary()} | {error, tuple()}.
get_instance_dynamic_data() ->
get_instance_dynamic_data(erlcloud_aws:default_config()).
-spec get_instance_dynamic_data(Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
get_instance_dynamic_data(Config) ->
get_instance_dynamic_data("", Config).
%%%---------------------------------------------------------------------------
-spec get_instance_dynamic_data( ItemPath :: string(), Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
%%%---------------------------------------------------------------------------
get_instance_dynamic_data(ItemPath, Config) ->
DynamicDataPath = "/" ++ ItemPath,
erlcloud_aws:http_body(erlcloud_httpc:request(DynamicDataPath, get, [], <<>>, erlcloud_aws:get_timeout(Config), Config)).
| null | https://raw.githubusercontent.com/BitGameEN/bitgamex/151ba70a481615379f9648581a5d459b503abe19/src/deps/erlcloud/src/erlcloud_ec2_meta.erl | erlang | ---------------------------------------------------------------------------
---------------------------------------------------------------------------
@doc Retrieve the instance meta data for the instance this code is running on. Will fail if not an EC2 instance.
This convenience function will retrieve the instance id from the AWS metadata available at
-data/*
ItemPath allows fetching specific pieces of metadata.
---------------------------------------------------------------------------
---------------------------------------------------------------------------
@doc Retrieve the user data for the instance this code is running on. Will fail if not an EC2 instance.
This convenience function will retrieve the user data the instance was started with, i.e. what's available at
-data
---------------------------------------------------------------------------
--------------------------------------------------------------------------- | -module(erlcloud_ec2_meta).
-include("erlcloud.hrl").
-include("erlcloud_aws.hrl").
-export([get_instance_metadata/0, get_instance_metadata/1, get_instance_metadata/2,
get_instance_user_data/0, get_instance_user_data/1,
get_instance_dynamic_data/0, get_instance_dynamic_data/1, get_instance_dynamic_data/2]).
-spec get_instance_metadata() -> {ok, binary()} | {error, tuple()}.
get_instance_metadata() ->
get_instance_metadata(erlcloud_aws:default_config()).
-spec get_instance_metadata(Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
get_instance_metadata(Config) ->
get_instance_metadata("", Config).
-spec get_instance_metadata( ItemPath :: string(), Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
get_instance_metadata(ItemPath, Config) ->
MetaDataPath = "-data/" ++ ItemPath,
erlcloud_aws:http_body(erlcloud_httpc:request(MetaDataPath, get, [], <<>>, erlcloud_aws:get_timeout(Config), Config)).
-spec get_instance_user_data() -> {ok, binary()} | {error, tuple()}.
get_instance_user_data() ->
get_instance_user_data(erlcloud_aws:default_config()).
-spec get_instance_user_data( Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
get_instance_user_data(Config) ->
UserDataPath = "-data/",
erlcloud_aws:http_body(erlcloud_httpc:request(UserDataPath, get, [], <<>>, erlcloud_aws:get_timeout(Config), Config)).
-spec get_instance_dynamic_data() -> {ok, binary()} | {error, tuple()}.
get_instance_dynamic_data() ->
get_instance_dynamic_data(erlcloud_aws:default_config()).
-spec get_instance_dynamic_data(Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
get_instance_dynamic_data(Config) ->
get_instance_dynamic_data("", Config).
-spec get_instance_dynamic_data( ItemPath :: string(), Config :: aws_config() ) -> {ok, binary()} | {error, tuple()}.
get_instance_dynamic_data(ItemPath, Config) ->
DynamicDataPath = "/" ++ ItemPath,
erlcloud_aws:http_body(erlcloud_httpc:request(DynamicDataPath, get, [], <<>>, erlcloud_aws:get_timeout(Config), Config)).
|
4e45f8b9b37631f84b0eda30de986a28ff38999bf961a48799891db5d92ece98 | solita/mnt-teet | filename_metadata_test.clj | (ns teet.file.filename-metadata-test
(:require [teet.file.filename-metadata :refer [filename->metadata
metadata->filename]]
[clojure.test :refer [deftest is]]
[teet.util.string :as string]))
(def example-filenames
["MA14658_EP_TL_PT_00_Projekt tingimused.pdf"
"MA14658_EP_TL_GL_00_Aruanne.pdf"
"MA14658_EP_TL_GL_00_3-1_puurauk2.pdf"
"MA14658_EP_TL_GL_00_3-2_puurauk3.pdf"
"MA14658_EP_TL_CL_01_3-1_mahud.xls"
"MA14658_EP_TL_CL_02_3-2_mahud.pdf"
"MA14658_EP_TL_TL_01_1-01_AP-Vinso.dwg"
"MA14658_EP_TL_TL_01_1-02_AP-Leevi.dwg"
"MA14658_EP_TL_TS_02_1_Uskuna.dwg"
"MA14658_EP_TL_KY_00_1_Uskuna.pdf"
"MA14658_EP_TL_AA_00_0-101_esimesed100m_plaan.pdf"
"MA14658_EP_TL_AA_00_0-102_keskmine jupp.pdf"
"MA14658_EP_TL_AA_00_0-103_esimesed 100 m-pikiprofiil.pdf"
"MA14658_EH_TL_CL_00_kululoend.xls"
"MA14658_EH_TL_TL_00_1-01_teostusjoonis.dwg"])
(deftest filename-metadata-roundtrip
(doseq [filename1 example-filenames
:let [metadata (filename->metadata filename1)
filename2 (metadata->filename metadata)]]
(is (= (string/strip-leading-zeroes filename1)
(string/strip-leading-zeroes filename2))
"filename generated from parsed metadata is the same")))
| null | https://raw.githubusercontent.com/solita/mnt-teet/7a5124975ce1c7f3e7a7c55fe23257ca3f7b6411/app/backend/test/teet/file/filename_metadata_test.clj | clojure | (ns teet.file.filename-metadata-test
(:require [teet.file.filename-metadata :refer [filename->metadata
metadata->filename]]
[clojure.test :refer [deftest is]]
[teet.util.string :as string]))
(def example-filenames
["MA14658_EP_TL_PT_00_Projekt tingimused.pdf"
"MA14658_EP_TL_GL_00_Aruanne.pdf"
"MA14658_EP_TL_GL_00_3-1_puurauk2.pdf"
"MA14658_EP_TL_GL_00_3-2_puurauk3.pdf"
"MA14658_EP_TL_CL_01_3-1_mahud.xls"
"MA14658_EP_TL_CL_02_3-2_mahud.pdf"
"MA14658_EP_TL_TL_01_1-01_AP-Vinso.dwg"
"MA14658_EP_TL_TL_01_1-02_AP-Leevi.dwg"
"MA14658_EP_TL_TS_02_1_Uskuna.dwg"
"MA14658_EP_TL_KY_00_1_Uskuna.pdf"
"MA14658_EP_TL_AA_00_0-101_esimesed100m_plaan.pdf"
"MA14658_EP_TL_AA_00_0-102_keskmine jupp.pdf"
"MA14658_EP_TL_AA_00_0-103_esimesed 100 m-pikiprofiil.pdf"
"MA14658_EH_TL_CL_00_kululoend.xls"
"MA14658_EH_TL_TL_00_1-01_teostusjoonis.dwg"])
(deftest filename-metadata-roundtrip
(doseq [filename1 example-filenames
:let [metadata (filename->metadata filename1)
filename2 (metadata->filename metadata)]]
(is (= (string/strip-leading-zeroes filename1)
(string/strip-leading-zeroes filename2))
"filename generated from parsed metadata is the same")))
| |
cd15fd3f89a4242e3aabaeb50674441e3684104894049a6eeed1ebbb96045be5 | racket/racket7 | atomic.rkt | #lang racket/base
(require '#%unsafe
(for-syntax racket/base))
(provide (protect-out in-atomic-mode?
start-atomic
end-atomic
start-breakable-atomic
end-breakable-atomic
call-as-atomic
call-as-nonatomic))
(define (start-atomic)
(unsafe-start-atomic))
(define (end-atomic)
(unsafe-end-atomic))
(define (start-breakable-atomic)
(unsafe-start-breakable-atomic))
(define (end-breakable-atomic)
(unsafe-end-breakable-atomic))
(define (in-atomic-mode?)
(unsafe-in-atomic?))
;; ----------------------------------------
(define monitor-owner #f)
;; An exception may be constructed while we're entered:
(define entered-err-string-handler
(lambda (s n)
(call-as-nonatomic
(lambda ()
((error-value->string-handler) s n)))))
(define old-paramz #f)
(define old-break-paramz #f)
(define extra-atomic-depth 0)
(define exited-key (gensym 'as-exit))
(define lock-tag (make-continuation-prompt-tag 'lock))
(define (call-as-atomic f)
(unless (and (procedure? f)
(procedure-arity-includes? f 0))
(raise-type-error 'call-as-atomic "procedure (arity 0)" f))
(cond
[(eq? monitor-owner (current-thread))
;; Increment atomicity level for cooperation with anything
;; that is sensitive to the current depth of atomicity.
(dynamic-wind (lambda ()
(start-breakable-atomic)
(set! extra-atomic-depth (add1 extra-atomic-depth)))
f
(lambda ()
(set! extra-atomic-depth (sub1 extra-atomic-depth))
(end-breakable-atomic)))]
[else
(with-continuation-mark
exited-key
#f
(call-with-continuation-prompt
(lambda ()
(dynamic-wind
(lambda ()
(start-breakable-atomic)
(set! monitor-owner (current-thread)))
(lambda ()
(set! old-paramz (current-parameterization))
(set! old-break-paramz (current-break-parameterization))
(parameterize ([error-value->string-handler entered-err-string-handler])
(parameterize-break
#f
(call-with-exception-handler
(lambda (exn)
;; Get out of atomic region before letting
;; an exception handler work
(if (continuation-mark-set-first #f exited-key)
exn ; defer to previous exn handler
(abort-current-continuation
lock-tag
(lambda () (raise exn)))))
f))))
(lambda ()
(set! monitor-owner #f)
(set! old-paramz #f)
(set! old-break-paramz #f)
(end-breakable-atomic))))
lock-tag
(lambda (t) (t))))]))
(define (call-as-nonatomic f)
(unless (and (procedure? f)
(procedure-arity-includes? f 0))
(raise-type-error 'call-as-nonatomic "procedure (arity 0)" f))
(unless (eq? monitor-owner (current-thread))
(error 'call-as-nonatomic "not in atomic area for ~e" f))
(let ([paramz old-paramz]
[break-paramz old-break-paramz]
[extra-depth extra-atomic-depth])
(with-continuation-mark
exited-key
#t ; disables special exception handling
(call-with-parameterization
paramz
(lambda ()
(call-with-break-parameterization
break-paramz
(lambda ()
(dynamic-wind
(lambda ()
(set! monitor-owner #f)
(set! extra-atomic-depth 0)
(end-breakable-atomic)
(let loop ([i extra-depth])
(unless (zero? i)
(end-breakable-atomic)
(loop (sub1 i)))))
f
(lambda ()
(start-breakable-atomic)
(set! old-paramz paramz)
(set! old-break-paramz break-paramz)
(let loop ([i extra-depth])
(unless (zero? i)
(start-breakable-atomic)
(loop (sub1 i))))
(set! extra-atomic-depth extra-depth)
(set! monitor-owner (current-thread)))))))))))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/collects/ffi/unsafe/atomic.rkt | racket | ----------------------------------------
An exception may be constructed while we're entered:
Increment atomicity level for cooperation with anything
that is sensitive to the current depth of atomicity.
Get out of atomic region before letting
an exception handler work
defer to previous exn handler
disables special exception handling | #lang racket/base
(require '#%unsafe
(for-syntax racket/base))
(provide (protect-out in-atomic-mode?
start-atomic
end-atomic
start-breakable-atomic
end-breakable-atomic
call-as-atomic
call-as-nonatomic))
(define (start-atomic)
(unsafe-start-atomic))
(define (end-atomic)
(unsafe-end-atomic))
(define (start-breakable-atomic)
(unsafe-start-breakable-atomic))
(define (end-breakable-atomic)
(unsafe-end-breakable-atomic))
(define (in-atomic-mode?)
(unsafe-in-atomic?))
(define monitor-owner #f)
(define entered-err-string-handler
(lambda (s n)
(call-as-nonatomic
(lambda ()
((error-value->string-handler) s n)))))
(define old-paramz #f)
(define old-break-paramz #f)
(define extra-atomic-depth 0)
(define exited-key (gensym 'as-exit))
(define lock-tag (make-continuation-prompt-tag 'lock))
(define (call-as-atomic f)
(unless (and (procedure? f)
(procedure-arity-includes? f 0))
(raise-type-error 'call-as-atomic "procedure (arity 0)" f))
(cond
[(eq? monitor-owner (current-thread))
(dynamic-wind (lambda ()
(start-breakable-atomic)
(set! extra-atomic-depth (add1 extra-atomic-depth)))
f
(lambda ()
(set! extra-atomic-depth (sub1 extra-atomic-depth))
(end-breakable-atomic)))]
[else
(with-continuation-mark
exited-key
#f
(call-with-continuation-prompt
(lambda ()
(dynamic-wind
(lambda ()
(start-breakable-atomic)
(set! monitor-owner (current-thread)))
(lambda ()
(set! old-paramz (current-parameterization))
(set! old-break-paramz (current-break-parameterization))
(parameterize ([error-value->string-handler entered-err-string-handler])
(parameterize-break
#f
(call-with-exception-handler
(lambda (exn)
(if (continuation-mark-set-first #f exited-key)
(abort-current-continuation
lock-tag
(lambda () (raise exn)))))
f))))
(lambda ()
(set! monitor-owner #f)
(set! old-paramz #f)
(set! old-break-paramz #f)
(end-breakable-atomic))))
lock-tag
(lambda (t) (t))))]))
(define (call-as-nonatomic f)
(unless (and (procedure? f)
(procedure-arity-includes? f 0))
(raise-type-error 'call-as-nonatomic "procedure (arity 0)" f))
(unless (eq? monitor-owner (current-thread))
(error 'call-as-nonatomic "not in atomic area for ~e" f))
(let ([paramz old-paramz]
[break-paramz old-break-paramz]
[extra-depth extra-atomic-depth])
(with-continuation-mark
exited-key
(call-with-parameterization
paramz
(lambda ()
(call-with-break-parameterization
break-paramz
(lambda ()
(dynamic-wind
(lambda ()
(set! monitor-owner #f)
(set! extra-atomic-depth 0)
(end-breakable-atomic)
(let loop ([i extra-depth])
(unless (zero? i)
(end-breakable-atomic)
(loop (sub1 i)))))
f
(lambda ()
(start-breakable-atomic)
(set! old-paramz paramz)
(set! old-break-paramz break-paramz)
(let loop ([i extra-depth])
(unless (zero? i)
(start-breakable-atomic)
(loop (sub1 i))))
(set! extra-atomic-depth extra-depth)
(set! monitor-owner (current-thread)))))))))))
|
31795b0df738883a65ed33081b001a4982c8bdb1267e16fcc489db3df28e3c2d | avras/nsime | nsime_droptail_queue_SUITE.erl | %%
Copyright ( C ) 2012 < >
%%
%% This file is part of nsime.
%%
nsime 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.
%%
%% nsime 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 nsime. If not, see </>.
%%
%% Purpose : Test module for nsime_droptail_queue
Author :
-module(nsime_droptail_queue_SUITE).
-author("Saravanan Vijayakumaran").
-compile(export_all).
-include("ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include("nsime_types.hrl").
-include("nsime_packet.hrl").
-include("nsime_droptail_queue_state.hrl").
all() -> [
test_creation,
test_enqueue_dequeue,
test_drop_packet,
test_dequeue_all_packets,
test_reset_statistics
].
init_per_suite(Config) ->
Config.
end_per_suite(Config) ->
Config.
test_creation(_) ->
QueueState = nsime_droptail_queue:create(),
?assert(is_record(QueueState, nsime_droptail_queue_state)),
?assert(nsime_droptail_queue:is_empty(QueueState)),
QueueStats = nsime_droptail_queue:get_statistics(QueueState),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_packet_count, infinity),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_byte_count, infinity),
?assert(queue:is_empty(QueueStats#nsime_droptail_queue_state.packets)).
test_enqueue_dequeue(_) ->
MaxPackets = 2,
MaxBytes = 2000,
QueueState = #nsime_droptail_queue_state{max_packet_count = MaxPackets, max_byte_count = MaxBytes},
?assert(nsime_droptail_queue:is_empty(QueueState)),
Size = 1000,
Packet1 = create_packet(Size),
QueueState1 = nsime_droptail_queue:enqueue_packet(QueueState, Packet1),
?assert(is_record(QueueState1, nsime_droptail_queue_state)),
?assertNot(nsime_droptail_queue:is_empty(QueueState1)),
QueueStats1 = nsime_droptail_queue:get_statistics(QueueState1),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_packet_count, 1),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_byte_count, Size),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_packet_count, 1),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_byte_count, Size),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_byte_count, MaxBytes),
Packet2 = create_packet(1000),
QueueState2 = nsime_droptail_queue:enqueue_packet(QueueState1, Packet2),
?assert(is_record(QueueState2, nsime_droptail_queue_state)),
?assertNot(nsime_droptail_queue:is_empty(QueueState2)),
QueueStats2 = nsime_droptail_queue:get_statistics(QueueState2),
?assertEqual(QueueStats2#nsime_droptail_queue_state.current_packet_count, 2),
?assertEqual(QueueStats2#nsime_droptail_queue_state.current_byte_count, 2*Size),
?assertEqual(QueueStats2#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats2#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats2#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats2#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats2#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats2#nsime_droptail_queue_state.max_byte_count, MaxBytes),
QueueState3 = nsime_droptail_queue:enqueue_packet(QueueState2, create_packet(1000)),
?assert(is_record(QueueState3, nsime_droptail_queue_state)),
?assertNot(nsime_droptail_queue:is_empty(QueueState3)),
QueueStats3 = nsime_droptail_queue:get_statistics(QueueState3),
?assertEqual(QueueStats3#nsime_droptail_queue_state.current_packet_count, 2),
?assertEqual(QueueStats3#nsime_droptail_queue_state.current_byte_count, 2*Size),
?assertEqual(QueueStats3#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats3#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats3#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats3#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats3#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats3#nsime_droptail_queue_state.max_byte_count, MaxBytes),
{Packet1, QueueState4} = nsime_droptail_queue:dequeue_packet(QueueState3),
?assertNot(nsime_droptail_queue:is_empty(QueueState4)),
QueueStats4 = nsime_droptail_queue:get_statistics(QueueState4),
?assertEqual(QueueStats4#nsime_droptail_queue_state.current_packet_count, 1),
?assertEqual(QueueStats4#nsime_droptail_queue_state.current_byte_count, Size),
?assertEqual(QueueStats4#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats4#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats4#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats4#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats4#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats4#nsime_droptail_queue_state.max_byte_count, MaxBytes),
{Packet2, QueueState5} = nsime_droptail_queue:dequeue_packet(QueueState4),
?assert(nsime_droptail_queue:is_empty(QueueState5)),
QueueStats5 = nsime_droptail_queue:get_statistics(QueueState5),
?assertEqual(QueueStats5#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats5#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats5#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats5#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats5#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats5#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats5#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats5#nsime_droptail_queue_state.max_byte_count, MaxBytes),
?assertEqual(nsime_droptail_queue:dequeue_packet(QueueState5), {none, QueueState5}),
?assert(nsime_droptail_queue:is_empty(QueueState5)),
QueueStats6 = nsime_droptail_queue:get_statistics(QueueState5),
?assertEqual(QueueStats6#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats6#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats6#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats6#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats6#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats6#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats6#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats6#nsime_droptail_queue_state.max_byte_count, MaxBytes).
test_drop_packet(_) ->
MaxPackets = 3,
MaxBytes = 3000,
QueueState = #nsime_droptail_queue_state{max_packet_count = MaxPackets, max_byte_count = MaxBytes},
?assert(is_record(QueueState, nsime_droptail_queue_state)),
Size = 1000,
Packet1 = create_packet(Size),
PacketId1 = Packet1#nsime_packet.id,
Packet2 = create_packet(Size),
QueueState1 = nsime_droptail_queue:enqueue_packet(QueueState, Packet1),
?assert(is_record(QueueState1, nsime_droptail_queue_state)),
QueueState2 = nsime_droptail_queue:enqueue_packet(QueueState1, Packet2),
?assert(is_record(QueueState2, nsime_droptail_queue_state)),
QueueState3 = nsime_droptail_queue:drop_packet(QueueState2, PacketId1),
?assert(is_record(QueueState3, nsime_droptail_queue_state)),
QueueStats = nsime_droptail_queue:get_statistics(QueueState3),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_packet_count, 1),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_byte_count, Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_byte_count, MaxBytes),
QueueState3 = nsime_droptail_queue:drop_packet(QueueState3, PacketId1),
QueueState4 = nsime_droptail_queue:enqueue_packet(QueueState3, Packet1),
?assert(is_record(QueueState4, nsime_droptail_queue_state)),
QueueState5 = nsime_droptail_queue:enqueue_packet(QueueState4, Packet1),
?assert(is_record(QueueState5, nsime_droptail_queue_state)),
QueueState5 = nsime_droptail_queue:drop_packet(QueueState5, PacketId1),
{Packet2, QueueState6} = nsime_droptail_queue:dequeue_packet(QueueState5),
?assert(is_record(QueueState6, nsime_droptail_queue_state)),
{Packet1, QueueState7} = nsime_droptail_queue:dequeue_packet(QueueState6),
?assert(is_record(QueueState7, nsime_droptail_queue_state)),
{Packet1, QueueState8} = nsime_droptail_queue:dequeue_packet(QueueState7),
?assert(is_record(QueueState8, nsime_droptail_queue_state)).
test_dequeue_all_packets(_) ->
MaxPackets = 3,
MaxBytes = 3000,
QueueState = #nsime_droptail_queue_state{max_packet_count = MaxPackets, max_byte_count = MaxBytes},
?assert(is_record(QueueState, nsime_droptail_queue_state)),
Size = 1000,
Packet1 = create_packet(Size),
Packet2 = create_packet(Size),
QueueState1 = nsime_droptail_queue:enqueue_packet(QueueState, Packet1),
?assert(is_record(QueueState1, nsime_droptail_queue_state)),
QueueState2 = nsime_droptail_queue:enqueue_packet(QueueState1, Packet2),
?assert(is_record(QueueState2, nsime_droptail_queue_state)),
QueueStats = nsime_droptail_queue:get_statistics(QueueState2),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_byte_count, MaxBytes),
QueueState3 = nsime_droptail_queue:dequeue_all_packets(QueueState2),
QueueStats1 = nsime_droptail_queue:get_statistics(QueueState3),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_byte_count, MaxBytes).
test_reset_statistics(_) ->
MaxPackets = 3,
MaxBytes = 3000,
QueueState = #nsime_droptail_queue_state{max_packet_count = MaxPackets, max_byte_count = MaxBytes},
?assert(is_record(QueueState, nsime_droptail_queue_state)),
Size = 1000,
Packet1 = create_packet(Size),
Packet2 = create_packet(Size),
QueueState1 = nsime_droptail_queue:enqueue_packet(QueueState, Packet1),
?assert(is_record(QueueState1, nsime_droptail_queue_state)),
QueueState2 = nsime_droptail_queue:enqueue_packet(QueueState1, Packet2),
?assert(is_record(QueueState2, nsime_droptail_queue_state)),
QueueStats = nsime_droptail_queue:get_statistics(QueueState2),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_byte_count, MaxBytes),
QueueState3 = nsime_droptail_queue:reset_statistics(QueueState2),
?assertNot(nsime_droptail_queue:is_empty(QueueState3)),
QueueStats1 = nsime_droptail_queue:get_statistics(QueueState3),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_byte_count, MaxBytes).
create_packet(Size) ->
#nsime_packet{
id = make_ref(),
size = Size
}.
| null | https://raw.githubusercontent.com/avras/nsime/fc5c164272aa649541bb3895d9f4bea34f45beec/test/nsime_droptail_queue_SUITE.erl | erlang |
This file is part of nsime.
(at your option) any later version.
nsime 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 nsime. If not, see </>.
Purpose : Test module for nsime_droptail_queue | Copyright ( C ) 2012 < >
nsime 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
You should have received a copy of the GNU General Public License
Author :
-module(nsime_droptail_queue_SUITE).
-author("Saravanan Vijayakumaran").
-compile(export_all).
-include("ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include("nsime_types.hrl").
-include("nsime_packet.hrl").
-include("nsime_droptail_queue_state.hrl").
all() -> [
test_creation,
test_enqueue_dequeue,
test_drop_packet,
test_dequeue_all_packets,
test_reset_statistics
].
init_per_suite(Config) ->
Config.
end_per_suite(Config) ->
Config.
test_creation(_) ->
QueueState = nsime_droptail_queue:create(),
?assert(is_record(QueueState, nsime_droptail_queue_state)),
?assert(nsime_droptail_queue:is_empty(QueueState)),
QueueStats = nsime_droptail_queue:get_statistics(QueueState),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_packet_count, infinity),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_byte_count, infinity),
?assert(queue:is_empty(QueueStats#nsime_droptail_queue_state.packets)).
test_enqueue_dequeue(_) ->
MaxPackets = 2,
MaxBytes = 2000,
QueueState = #nsime_droptail_queue_state{max_packet_count = MaxPackets, max_byte_count = MaxBytes},
?assert(nsime_droptail_queue:is_empty(QueueState)),
Size = 1000,
Packet1 = create_packet(Size),
QueueState1 = nsime_droptail_queue:enqueue_packet(QueueState, Packet1),
?assert(is_record(QueueState1, nsime_droptail_queue_state)),
?assertNot(nsime_droptail_queue:is_empty(QueueState1)),
QueueStats1 = nsime_droptail_queue:get_statistics(QueueState1),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_packet_count, 1),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_byte_count, Size),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_packet_count, 1),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_byte_count, Size),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_byte_count, MaxBytes),
Packet2 = create_packet(1000),
QueueState2 = nsime_droptail_queue:enqueue_packet(QueueState1, Packet2),
?assert(is_record(QueueState2, nsime_droptail_queue_state)),
?assertNot(nsime_droptail_queue:is_empty(QueueState2)),
QueueStats2 = nsime_droptail_queue:get_statistics(QueueState2),
?assertEqual(QueueStats2#nsime_droptail_queue_state.current_packet_count, 2),
?assertEqual(QueueStats2#nsime_droptail_queue_state.current_byte_count, 2*Size),
?assertEqual(QueueStats2#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats2#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats2#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats2#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats2#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats2#nsime_droptail_queue_state.max_byte_count, MaxBytes),
QueueState3 = nsime_droptail_queue:enqueue_packet(QueueState2, create_packet(1000)),
?assert(is_record(QueueState3, nsime_droptail_queue_state)),
?assertNot(nsime_droptail_queue:is_empty(QueueState3)),
QueueStats3 = nsime_droptail_queue:get_statistics(QueueState3),
?assertEqual(QueueStats3#nsime_droptail_queue_state.current_packet_count, 2),
?assertEqual(QueueStats3#nsime_droptail_queue_state.current_byte_count, 2*Size),
?assertEqual(QueueStats3#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats3#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats3#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats3#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats3#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats3#nsime_droptail_queue_state.max_byte_count, MaxBytes),
{Packet1, QueueState4} = nsime_droptail_queue:dequeue_packet(QueueState3),
?assertNot(nsime_droptail_queue:is_empty(QueueState4)),
QueueStats4 = nsime_droptail_queue:get_statistics(QueueState4),
?assertEqual(QueueStats4#nsime_droptail_queue_state.current_packet_count, 1),
?assertEqual(QueueStats4#nsime_droptail_queue_state.current_byte_count, Size),
?assertEqual(QueueStats4#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats4#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats4#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats4#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats4#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats4#nsime_droptail_queue_state.max_byte_count, MaxBytes),
{Packet2, QueueState5} = nsime_droptail_queue:dequeue_packet(QueueState4),
?assert(nsime_droptail_queue:is_empty(QueueState5)),
QueueStats5 = nsime_droptail_queue:get_statistics(QueueState5),
?assertEqual(QueueStats5#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats5#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats5#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats5#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats5#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats5#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats5#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats5#nsime_droptail_queue_state.max_byte_count, MaxBytes),
?assertEqual(nsime_droptail_queue:dequeue_packet(QueueState5), {none, QueueState5}),
?assert(nsime_droptail_queue:is_empty(QueueState5)),
QueueStats6 = nsime_droptail_queue:get_statistics(QueueState5),
?assertEqual(QueueStats6#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats6#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats6#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats6#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats6#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats6#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats6#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats6#nsime_droptail_queue_state.max_byte_count, MaxBytes).
test_drop_packet(_) ->
MaxPackets = 3,
MaxBytes = 3000,
QueueState = #nsime_droptail_queue_state{max_packet_count = MaxPackets, max_byte_count = MaxBytes},
?assert(is_record(QueueState, nsime_droptail_queue_state)),
Size = 1000,
Packet1 = create_packet(Size),
PacketId1 = Packet1#nsime_packet.id,
Packet2 = create_packet(Size),
QueueState1 = nsime_droptail_queue:enqueue_packet(QueueState, Packet1),
?assert(is_record(QueueState1, nsime_droptail_queue_state)),
QueueState2 = nsime_droptail_queue:enqueue_packet(QueueState1, Packet2),
?assert(is_record(QueueState2, nsime_droptail_queue_state)),
QueueState3 = nsime_droptail_queue:drop_packet(QueueState2, PacketId1),
?assert(is_record(QueueState3, nsime_droptail_queue_state)),
QueueStats = nsime_droptail_queue:get_statistics(QueueState3),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_packet_count, 1),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_byte_count, Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_packet_count, 1),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_byte_count, Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_byte_count, MaxBytes),
QueueState3 = nsime_droptail_queue:drop_packet(QueueState3, PacketId1),
QueueState4 = nsime_droptail_queue:enqueue_packet(QueueState3, Packet1),
?assert(is_record(QueueState4, nsime_droptail_queue_state)),
QueueState5 = nsime_droptail_queue:enqueue_packet(QueueState4, Packet1),
?assert(is_record(QueueState5, nsime_droptail_queue_state)),
QueueState5 = nsime_droptail_queue:drop_packet(QueueState5, PacketId1),
{Packet2, QueueState6} = nsime_droptail_queue:dequeue_packet(QueueState5),
?assert(is_record(QueueState6, nsime_droptail_queue_state)),
{Packet1, QueueState7} = nsime_droptail_queue:dequeue_packet(QueueState6),
?assert(is_record(QueueState7, nsime_droptail_queue_state)),
{Packet1, QueueState8} = nsime_droptail_queue:dequeue_packet(QueueState7),
?assert(is_record(QueueState8, nsime_droptail_queue_state)).
test_dequeue_all_packets(_) ->
MaxPackets = 3,
MaxBytes = 3000,
QueueState = #nsime_droptail_queue_state{max_packet_count = MaxPackets, max_byte_count = MaxBytes},
?assert(is_record(QueueState, nsime_droptail_queue_state)),
Size = 1000,
Packet1 = create_packet(Size),
Packet2 = create_packet(Size),
QueueState1 = nsime_droptail_queue:enqueue_packet(QueueState, Packet1),
?assert(is_record(QueueState1, nsime_droptail_queue_state)),
QueueState2 = nsime_droptail_queue:enqueue_packet(QueueState1, Packet2),
?assert(is_record(QueueState2, nsime_droptail_queue_state)),
QueueStats = nsime_droptail_queue:get_statistics(QueueState2),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_byte_count, MaxBytes),
QueueState3 = nsime_droptail_queue:dequeue_all_packets(QueueState2),
QueueStats1 = nsime_droptail_queue:get_statistics(QueueState3),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_byte_count, MaxBytes).
test_reset_statistics(_) ->
MaxPackets = 3,
MaxBytes = 3000,
QueueState = #nsime_droptail_queue_state{max_packet_count = MaxPackets, max_byte_count = MaxBytes},
?assert(is_record(QueueState, nsime_droptail_queue_state)),
Size = 1000,
Packet1 = create_packet(Size),
Packet2 = create_packet(Size),
QueueState1 = nsime_droptail_queue:enqueue_packet(QueueState, Packet1),
?assert(is_record(QueueState1, nsime_droptail_queue_state)),
QueueState2 = nsime_droptail_queue:enqueue_packet(QueueState1, Packet2),
?assert(is_record(QueueState2, nsime_droptail_queue_state)),
QueueStats = nsime_droptail_queue:get_statistics(QueueState2),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.current_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_packet_count, 2),
?assertEqual(QueueStats#nsime_droptail_queue_state.received_byte_count, 2*Size),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats#nsime_droptail_queue_state.max_byte_count, MaxBytes),
QueueState3 = nsime_droptail_queue:reset_statistics(QueueState2),
?assertNot(nsime_droptail_queue:is_empty(QueueState3)),
QueueStats1 = nsime_droptail_queue:get_statistics(QueueState3),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.current_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.received_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_packet_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.dropped_byte_count, 0),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_packet_count, MaxPackets),
?assertEqual(QueueStats1#nsime_droptail_queue_state.max_byte_count, MaxBytes).
create_packet(Size) ->
#nsime_packet{
id = make_ref(),
size = Size
}.
|
2855800db3e281e89d478eee10ac58ad871c84ae909ebf90ceb19c983887d96f | emqx/emqx-exproto | emqx_exproto.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 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(emqx_exproto).
-compile({no_auto_import, [register/1]}).
-include("emqx_exproto.hrl").
-export([ start_listeners/0
, stop_listeners/0
]).
%% APIs: Connection level
-export([ send/2
, close/1
]).
%% APIs: Protocol/Session level
-export([ register/2
, publish/2
, subscribe/3
, unsubscribe/2
]).
%%--------------------------------------------------------------------
%% APIs
%%--------------------------------------------------------------------
-spec(start_listeners() -> ok).
start_listeners() ->
lists:foreach(fun start_listener/1, application:get_env(?APP, listeners, [])).
-spec(stop_listeners() -> ok).
stop_listeners() ->
lists:foreach(fun stop_listener/1, application:get_env(?APP, listeners, [])).
%%--------------------------------------------------------------------
%% APIs - Connection level
%%--------------------------------------------------------------------
-spec(send(pid(), binary()) -> ok).
send(Conn, Data) when is_pid(Conn), is_binary(Data) ->
emqx_exproto_conn:cast(Conn, {send, Data}).
-spec(close(pid()) -> ok).
close(Conn) when is_pid(Conn) ->
emqx_exproto_conn:cast(Conn, close).
%%--------------------------------------------------------------------
%% APIs - Protocol/Session level
%%--------------------------------------------------------------------
-spec(register(pid(), list()) -> ok | {error, any()}).
register(Conn, ClientInfo0) ->
case emqx_exproto_types:parse(clientinfo, ClientInfo0) of
{error, Reason} ->
{error, Reason};
ClientInfo ->
emqx_exproto_conn:cast(Conn, {register, ClientInfo})
end.
-spec(publish(pid(), list()) -> ok | {error, any()}).
publish(Conn, Msg0) when is_pid(Conn), is_list(Msg0) ->
case emqx_exproto_types:parse(message, Msg0) of
{error, Reason} ->
{error, Reason};
Msg ->
emqx_exproto_conn:cast(Conn, {publish, Msg})
end.
-spec(subscribe(pid(), binary(), emqx_types:qos()) -> ok | {error, any()}).
subscribe(Conn, Topic, Qos)
when is_pid(Conn), is_binary(Topic),
(Qos =:= 0 orelse Qos =:= 1 orelse Qos =:= 2) ->
emqx_exproto_conn:cast(Conn, {subscribe, Topic, Qos}).
-spec(unsubscribe(pid(), binary()) -> ok | {error, any()}).
unsubscribe(Conn, Topic)
when is_pid(Conn), is_binary(Topic) ->
emqx_exproto_conn:cast(Conn, {unsubscribe, Topic}).
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
start_listener({Proto, LisType, ListenOn, Opts}) ->
Name = name(Proto, LisType),
{value, {_, DriverOpts}, LisOpts} = lists:keytake(driver, 1, Opts),
case emqx_exproto_driver_mngr:ensure_driver(Name, DriverOpts) of
{ok, _DriverPid}->
case start_listener(LisType, Name, ListenOn, [{driver, Name} |LisOpts]) of
{ok, _} ->
io:format("Start ~s listener on ~s successfully.~n",
[Name, format(ListenOn)]);
{error, Reason} ->
io:format(standard_error, "Failed to start ~s listener on ~s - ~0p~n!",
[Name, format(ListenOn), Reason]),
error(Reason)
end;
{error, Reason} ->
io:format(standard_error, "Failed to start ~s's driver - ~0p~n!",
[Name, Reason]),
error(Reason)
end.
@private
start_listener(LisType, Name, ListenOn, LisOpts)
when LisType =:= tcp;
LisType =:= ssl ->
SockOpts = esockd:parse_opt(LisOpts),
esockd:open(Name, ListenOn, merge_tcp_default(SockOpts),
{emqx_exproto_conn, start_link, [LisOpts-- SockOpts]});
start_listener(udp, Name, ListenOn, LisOpts) ->
SockOpts = esockd:parse_opt(LisOpts),
esockd:open_udp(Name, ListenOn, merge_udp_default(SockOpts),
{emqx_exproto_conn, start_link, [LisOpts-- SockOpts]});
start_listener(dtls, Name, ListenOn, LisOpts) ->
SockOpts = esockd:parse_opt(LisOpts),
esockd:open_dtls(Name, ListenOn, merge_udp_default(SockOpts),
{emqx_exproto_conn, start_link, [LisOpts-- SockOpts]}).
stop_listener({Proto, LisType, ListenOn, Opts}) ->
Name = name(Proto, LisType),
_ = emqx_exproto_driver_mngr:stop_driver(Name),
StopRet = stop_listener(LisType, Name, ListenOn, Opts),
case StopRet of
ok -> io:format("Stop ~s listener on ~s successfully.~n",
[Name, format(ListenOn)]);
{error, Reason} ->
io:format(standard_error, "Failed to stop ~s listener on ~s - ~p~n.",
[Name, format(ListenOn), Reason])
end,
StopRet.
@private
stop_listener(_LisType, Name, ListenOn, _Opts) ->
esockd:close(Name, ListenOn).
@private
name(Proto, LisType) ->
list_to_atom(lists:flatten(io_lib:format("~s:~s", [Proto, LisType]))).
@private
format({Addr, Port}) when is_list(Addr) ->
io_lib:format("~s:~w", [Addr, Port]).
@private
merge_tcp_default(Opts) ->
case lists:keytake(tcp_options, 1, Opts) of
{value, {tcp_options, TcpOpts}, Opts1} ->
[{tcp_options, emqx_misc:merge_opts(?TCP_SOCKOPTS, TcpOpts)} | Opts1];
false ->
[{tcp_options, ?TCP_SOCKOPTS} | Opts]
end.
merge_udp_default(Opts) ->
case lists:keytake(udp_options, 1, Opts) of
{value, {udp_options, TcpOpts}, Opts1} ->
[{udp_options, emqx_misc:merge_opts(?UDP_SOCKOPTS, TcpOpts)} | Opts1];
false ->
[{udp_options, ?UDP_SOCKOPTS} | Opts]
end.
| null | https://raw.githubusercontent.com/emqx/emqx-exproto/7aff2dae106302fdcdcd0d5ce31fe90df4861013/src/emqx_exproto.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.
--------------------------------------------------------------------
APIs: Connection level
APIs: Protocol/Session level
--------------------------------------------------------------------
APIs
--------------------------------------------------------------------
--------------------------------------------------------------------
APIs - Connection level
--------------------------------------------------------------------
--------------------------------------------------------------------
APIs - Protocol/Session level
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | Copyright ( c ) 2020 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(emqx_exproto).
-compile({no_auto_import, [register/1]}).
-include("emqx_exproto.hrl").
-export([ start_listeners/0
, stop_listeners/0
]).
-export([ send/2
, close/1
]).
-export([ register/2
, publish/2
, subscribe/3
, unsubscribe/2
]).
-spec(start_listeners() -> ok).
start_listeners() ->
lists:foreach(fun start_listener/1, application:get_env(?APP, listeners, [])).
-spec(stop_listeners() -> ok).
stop_listeners() ->
lists:foreach(fun stop_listener/1, application:get_env(?APP, listeners, [])).
-spec(send(pid(), binary()) -> ok).
send(Conn, Data) when is_pid(Conn), is_binary(Data) ->
emqx_exproto_conn:cast(Conn, {send, Data}).
-spec(close(pid()) -> ok).
close(Conn) when is_pid(Conn) ->
emqx_exproto_conn:cast(Conn, close).
-spec(register(pid(), list()) -> ok | {error, any()}).
register(Conn, ClientInfo0) ->
case emqx_exproto_types:parse(clientinfo, ClientInfo0) of
{error, Reason} ->
{error, Reason};
ClientInfo ->
emqx_exproto_conn:cast(Conn, {register, ClientInfo})
end.
-spec(publish(pid(), list()) -> ok | {error, any()}).
publish(Conn, Msg0) when is_pid(Conn), is_list(Msg0) ->
case emqx_exproto_types:parse(message, Msg0) of
{error, Reason} ->
{error, Reason};
Msg ->
emqx_exproto_conn:cast(Conn, {publish, Msg})
end.
-spec(subscribe(pid(), binary(), emqx_types:qos()) -> ok | {error, any()}).
subscribe(Conn, Topic, Qos)
when is_pid(Conn), is_binary(Topic),
(Qos =:= 0 orelse Qos =:= 1 orelse Qos =:= 2) ->
emqx_exproto_conn:cast(Conn, {subscribe, Topic, Qos}).
-spec(unsubscribe(pid(), binary()) -> ok | {error, any()}).
unsubscribe(Conn, Topic)
when is_pid(Conn), is_binary(Topic) ->
emqx_exproto_conn:cast(Conn, {unsubscribe, Topic}).
Internal functions
start_listener({Proto, LisType, ListenOn, Opts}) ->
Name = name(Proto, LisType),
{value, {_, DriverOpts}, LisOpts} = lists:keytake(driver, 1, Opts),
case emqx_exproto_driver_mngr:ensure_driver(Name, DriverOpts) of
{ok, _DriverPid}->
case start_listener(LisType, Name, ListenOn, [{driver, Name} |LisOpts]) of
{ok, _} ->
io:format("Start ~s listener on ~s successfully.~n",
[Name, format(ListenOn)]);
{error, Reason} ->
io:format(standard_error, "Failed to start ~s listener on ~s - ~0p~n!",
[Name, format(ListenOn), Reason]),
error(Reason)
end;
{error, Reason} ->
io:format(standard_error, "Failed to start ~s's driver - ~0p~n!",
[Name, Reason]),
error(Reason)
end.
@private
start_listener(LisType, Name, ListenOn, LisOpts)
when LisType =:= tcp;
LisType =:= ssl ->
SockOpts = esockd:parse_opt(LisOpts),
esockd:open(Name, ListenOn, merge_tcp_default(SockOpts),
{emqx_exproto_conn, start_link, [LisOpts-- SockOpts]});
start_listener(udp, Name, ListenOn, LisOpts) ->
SockOpts = esockd:parse_opt(LisOpts),
esockd:open_udp(Name, ListenOn, merge_udp_default(SockOpts),
{emqx_exproto_conn, start_link, [LisOpts-- SockOpts]});
start_listener(dtls, Name, ListenOn, LisOpts) ->
SockOpts = esockd:parse_opt(LisOpts),
esockd:open_dtls(Name, ListenOn, merge_udp_default(SockOpts),
{emqx_exproto_conn, start_link, [LisOpts-- SockOpts]}).
stop_listener({Proto, LisType, ListenOn, Opts}) ->
Name = name(Proto, LisType),
_ = emqx_exproto_driver_mngr:stop_driver(Name),
StopRet = stop_listener(LisType, Name, ListenOn, Opts),
case StopRet of
ok -> io:format("Stop ~s listener on ~s successfully.~n",
[Name, format(ListenOn)]);
{error, Reason} ->
io:format(standard_error, "Failed to stop ~s listener on ~s - ~p~n.",
[Name, format(ListenOn), Reason])
end,
StopRet.
@private
stop_listener(_LisType, Name, ListenOn, _Opts) ->
esockd:close(Name, ListenOn).
@private
name(Proto, LisType) ->
list_to_atom(lists:flatten(io_lib:format("~s:~s", [Proto, LisType]))).
@private
format({Addr, Port}) when is_list(Addr) ->
io_lib:format("~s:~w", [Addr, Port]).
@private
merge_tcp_default(Opts) ->
case lists:keytake(tcp_options, 1, Opts) of
{value, {tcp_options, TcpOpts}, Opts1} ->
[{tcp_options, emqx_misc:merge_opts(?TCP_SOCKOPTS, TcpOpts)} | Opts1];
false ->
[{tcp_options, ?TCP_SOCKOPTS} | Opts]
end.
merge_udp_default(Opts) ->
case lists:keytake(udp_options, 1, Opts) of
{value, {udp_options, TcpOpts}, Opts1} ->
[{udp_options, emqx_misc:merge_opts(?UDP_SOCKOPTS, TcpOpts)} | Opts1];
false ->
[{udp_options, ?UDP_SOCKOPTS} | Opts]
end.
|
541da9bd60f4faab9b509e107b9a6f12321dcd0fae7eced6ba315f606f23cdaf | NorfairKing/smos | ClockSpec.hs | module Smos.Report.ClockSpec where
import Data.GenValidity.Path ()
import Smos.Data.Gen ()
import Smos.Report.Clock
import Smos.Report.Clock.Gen ()
import Smos.Report.Filter.Gen ()
import Test.Syd
import Test.Syd.Validity
spec :: Spec
spec = do
describe "zeroOutByFilter" $
it "produces valid smos files" $
producesValid3 zeroOutByFilter
describe "trimLogbookEntry" $
it "produces valid logbook entries" $
producesValid3 trimLogbookEntry
describe "trimLogbookEntryTo" $
it "produces valid logbook entries" $
forAllValid $
\tz -> producesValid3 $ trimLogbookEntryTo tz
describe "sumLogbookEntryTime" $
it "produces valid difftimes" $
producesValid sumLogbookEntryTime
| null | https://raw.githubusercontent.com/NorfairKing/smos/489f5b510c9a30a3c79fef0a0d1a796464705923/smos-report-gen/test/Smos/Report/ClockSpec.hs | haskell | module Smos.Report.ClockSpec where
import Data.GenValidity.Path ()
import Smos.Data.Gen ()
import Smos.Report.Clock
import Smos.Report.Clock.Gen ()
import Smos.Report.Filter.Gen ()
import Test.Syd
import Test.Syd.Validity
spec :: Spec
spec = do
describe "zeroOutByFilter" $
it "produces valid smos files" $
producesValid3 zeroOutByFilter
describe "trimLogbookEntry" $
it "produces valid logbook entries" $
producesValid3 trimLogbookEntry
describe "trimLogbookEntryTo" $
it "produces valid logbook entries" $
forAllValid $
\tz -> producesValid3 $ trimLogbookEntryTo tz
describe "sumLogbookEntryTime" $
it "produces valid difftimes" $
producesValid sumLogbookEntryTime
| |
e700d672187cefe151a7cc9eaefd3ba95e3426fcd16584e94f809a58e78dfc72 | cabol/cross_db | person.erl | -module(person).
-export([
new/2,
new/3,
new/4,
changeset/2,
all/2,
list_to_map/1
]).
-include_lib("cross_db/include/xdb.hrl").
-schema({people, [
{id, integer, [primary_key]},
{first_name, string},
{last_name, string},
{age, integer},
{address, string},
{birthdate, date},
{created_at, datetime, [{setter, false}]},
{height, float},
{description, string},
{profile_image, binary, [{getter, false}]},
{is_blocked, boolean},
{status, string},
{weird_field1, custom},
{weird_field2, custom},
{weird_field3, custom}
]}).
-define(PERMITTED, xdb_schema_spec:field_names(schema_spec())).
%% @equiv new(FirstName, LastName, undefined)
new(FirstName, LastName) ->
new(FirstName, LastName, undefined).
%% @equiv new(FirstName, LastName, Age, undefined)
new(FirstName, LastName, Age) ->
new(FirstName, LastName, Age, undefined).
-spec new(binary(), binary(), integer() | undefined, binary() | undefined) -> xdb_schema:fields().
new(FirstName, LastName, Age, Address) ->
{BirthDate, _} = calendar:universal_time(),
Datetime = calendar:universal_time(),
#{
first_name => FirstName,
last_name => LastName,
age => Age,
address => Address,
birthdate => BirthDate,
created_at => Datetime,
height => undefined,
description => undefined,
profile_image => undefined,
is_blocked => undefined,
weird_field1 => undefined,
weird_field2 => undefined,
weird_field3 => undefined,
missing => undefined
}.
-spec changeset(t(), xdb_schema:fields()) -> xdb_changeset:t().
changeset(Person, Params) ->
xdb_ct:pipe(Person, [
{fun xdb_changeset:cast/3, [Params, ?PERMITTED]},
{fun xdb_changeset:validate_required/2, [[id, first_name, last_name, age]]},
{fun xdb_changeset:validate_inclusion/3, [status, [<<"active">>, <<"blocked">>]]},
{fun xdb_changeset:validate_number/3, [age, [{less_than_or_equal_to, 33}]]},
{fun xdb_changeset:validate_length/3, [last_name, [{min, 3}]]},
{fun xdb_changeset:validate_format/3, [last_name, <<"^oth">>]}
]).
-spec all(xdb_repo:t(), xdb_query:conditions()) -> {integer(), #{any() => t()}} | no_return().
all(Repo, Conditions) ->
Records = list_to_map(Repo:all(xdb_query:from(person, [{where, Conditions}]))),
{maps:size(Records), Records}.
-spec list_to_map([t()]) -> #{any() => t()}.
list_to_map(People) ->
lists:foldl(fun(#{id := Id} = P, Acc) ->
Acc#{Id => P}
end, #{}, People).
| null | https://raw.githubusercontent.com/cabol/cross_db/365bb3b6cffde1b4da7109ed2594a0a3f1a4a949/src/test/models/person.erl | erlang | @equiv new(FirstName, LastName, undefined)
@equiv new(FirstName, LastName, Age, undefined) | -module(person).
-export([
new/2,
new/3,
new/4,
changeset/2,
all/2,
list_to_map/1
]).
-include_lib("cross_db/include/xdb.hrl").
-schema({people, [
{id, integer, [primary_key]},
{first_name, string},
{last_name, string},
{age, integer},
{address, string},
{birthdate, date},
{created_at, datetime, [{setter, false}]},
{height, float},
{description, string},
{profile_image, binary, [{getter, false}]},
{is_blocked, boolean},
{status, string},
{weird_field1, custom},
{weird_field2, custom},
{weird_field3, custom}
]}).
-define(PERMITTED, xdb_schema_spec:field_names(schema_spec())).
new(FirstName, LastName) ->
new(FirstName, LastName, undefined).
new(FirstName, LastName, Age) ->
new(FirstName, LastName, Age, undefined).
-spec new(binary(), binary(), integer() | undefined, binary() | undefined) -> xdb_schema:fields().
new(FirstName, LastName, Age, Address) ->
{BirthDate, _} = calendar:universal_time(),
Datetime = calendar:universal_time(),
#{
first_name => FirstName,
last_name => LastName,
age => Age,
address => Address,
birthdate => BirthDate,
created_at => Datetime,
height => undefined,
description => undefined,
profile_image => undefined,
is_blocked => undefined,
weird_field1 => undefined,
weird_field2 => undefined,
weird_field3 => undefined,
missing => undefined
}.
-spec changeset(t(), xdb_schema:fields()) -> xdb_changeset:t().
changeset(Person, Params) ->
xdb_ct:pipe(Person, [
{fun xdb_changeset:cast/3, [Params, ?PERMITTED]},
{fun xdb_changeset:validate_required/2, [[id, first_name, last_name, age]]},
{fun xdb_changeset:validate_inclusion/3, [status, [<<"active">>, <<"blocked">>]]},
{fun xdb_changeset:validate_number/3, [age, [{less_than_or_equal_to, 33}]]},
{fun xdb_changeset:validate_length/3, [last_name, [{min, 3}]]},
{fun xdb_changeset:validate_format/3, [last_name, <<"^oth">>]}
]).
-spec all(xdb_repo:t(), xdb_query:conditions()) -> {integer(), #{any() => t()}} | no_return().
all(Repo, Conditions) ->
Records = list_to_map(Repo:all(xdb_query:from(person, [{where, Conditions}]))),
{maps:size(Records), Records}.
-spec list_to_map([t()]) -> #{any() => t()}.
list_to_map(People) ->
lists:foldl(fun(#{id := Id} = P, Acc) ->
Acc#{Id => P}
end, #{}, People).
|
07ec773e557ab2ec4d20783271dd585d9a042953640ea1284b517e430195f8b2 | kelamg/HtDP2e-workthrough | ex48.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 ex48) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define (reward s)
(cond
[(<= 0 s 10) "bronze"]
[(and (< 10 s) (<= s 20)) "silver"]
[else "gold"]))
(reward 18)
| null | https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Fixed-size-Data/ex48.rkt | racket | about the language level of this file in a form that our tools can easily process. | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname ex48) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
(define (reward s)
(cond
[(<= 0 s 10) "bronze"]
[(and (< 10 s) (<= s 20)) "silver"]
[else "gold"]))
(reward 18)
|
6c7cbdbbca1100f6f8cf95425ce4a67da86902173c1827f2f84318f3c796f7e7 | argp/bap | unicode.ml |
let say x = IO.nwrite IO.stdout x; IO.write IO.stdout '\n'
let usay = IO.write_uline IO.stdout
let s1 = "Simple ASCII string"
and s2 = "Complex: á é í ó ú"
let u1 = UTF8.of_string s1
let rope1 = Rope.of_ustring u1
and rope2 = Rope.of_latin1 s2
let rec exp_dup n r = if n <= 0 then r else exp_dup (n-1) (Rope.append r r)
let r16 = exp_dup 4 rope2
let () = usay rope1; usay rope2
let () = usay r16
let r3 = Rope.sub r16 15 36
let () = say "Characters 15 to 41 of r16: "; usay r3
let c11 = Rope.get rope2 11
let () =
say "Character 11: ";
IO.write_uchar IO.stdout c11; say "\n"
let bad_rope =
try
usay (Rope.of_ustring (UTF8.of_string s2))
with UTF8.Malformed_code -> say "Non-utf8 input -- caught Malformed_code\n (don't worry, that's part of the example)\n"
| null | https://raw.githubusercontent.com/argp/bap/2f60a35e822200a1ec50eea3a947a322b45da363/batteries/examples/snippets/unicode.ml | ocaml |
let say x = IO.nwrite IO.stdout x; IO.write IO.stdout '\n'
let usay = IO.write_uline IO.stdout
let s1 = "Simple ASCII string"
and s2 = "Complex: á é í ó ú"
let u1 = UTF8.of_string s1
let rope1 = Rope.of_ustring u1
and rope2 = Rope.of_latin1 s2
let rec exp_dup n r = if n <= 0 then r else exp_dup (n-1) (Rope.append r r)
let r16 = exp_dup 4 rope2
let () = usay rope1; usay rope2
let () = usay r16
let r3 = Rope.sub r16 15 36
let () = say "Characters 15 to 41 of r16: "; usay r3
let c11 = Rope.get rope2 11
let () =
say "Character 11: ";
IO.write_uchar IO.stdout c11; say "\n"
let bad_rope =
try
usay (Rope.of_ustring (UTF8.of_string s2))
with UTF8.Malformed_code -> say "Non-utf8 input -- caught Malformed_code\n (don't worry, that's part of the example)\n"
| |
2a8ec20a9fa18b858df073e0e7e410beaad27908d25db2376bb3ef5c4ec07b17 | arttuka/reagent-material-ui | card_actions.cljs | (ns reagent-mui.material.card-actions
"Imports @mui/material/CardActions as a Reagent component.
Original documentation is at -ui/api/card-actions/ ."
(:require [reagent.core :as r]
["@mui/material/CardActions" :as MuiCardActions]))
(def card-actions (r/adapt-react-class (.-default MuiCardActions)))
| null | https://raw.githubusercontent.com/arttuka/reagent-material-ui/14103a696c41c0eb67fc07fc67cd8799efd88cb9/src/core/reagent_mui/material/card_actions.cljs | clojure | (ns reagent-mui.material.card-actions
"Imports @mui/material/CardActions as a Reagent component.
Original documentation is at -ui/api/card-actions/ ."
(:require [reagent.core :as r]
["@mui/material/CardActions" :as MuiCardActions]))
(def card-actions (r/adapt-react-class (.-default MuiCardActions)))
| |
f508aa63b1c29682111b887295f05fd54f6978e9c6b5ad94578131b68cf06a99 | wireless-net/erlang-nommu | release_handler.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2013 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
-module(release_handler).
-behaviour(gen_server).
-include_lib("kernel/include/file.hrl").
%% External exports
-export([start_link/0,
create_RELEASES/1, create_RELEASES/2, create_RELEASES/4,
unpack_release/1,
check_install_release/1, check_install_release/2,
install_release/1, install_release/2, new_emulator_upgrade/2,
remove_release/1, which_releases/0, which_releases/1,
make_permanent/1, reboot_old_release/1,
set_unpacked/2, set_removed/1, install_file/2]).
-export([upgrade_app/2, downgrade_app/2, downgrade_app/3,
upgrade_script/2, downgrade_script/3,
eval_appup_script/4]).
%% Internal exports
-export([init/1, handle_call/3, handle_info/2, terminate/2,
handle_cast/2, code_change/3]).
%% Internal exports, a client release_handler may call this functions.
-export([do_write_release/3, do_copy_file/2, do_copy_files/2,
do_copy_files/1, do_rename_files/1, do_remove_files/1,
remove_file/1, do_write_file/2, do_write_file/3,
do_ensure_RELEASES/1]).
-record(state, {unpurged = [],
root,
rel_dir,
releases,
timer,
start_prg,
masters = false,
client_dir = false,
static_emulator = false,
pre_sync_nodes = []}).
%%-----------------------------------------------------------------
status action next_status
%% =============================================
%% - unpack unpacked
%% unpacked install current
%% remove -
%% current make_permanent permanent
%% install other old
%% restart node unpacked
%% remove -
%% permanent make other permanent old
%% install permanent
%% old reboot_old permanent
%% install current
%% remove -
%%-----------------------------------------------------------------
libs = [ { Lib , Vsn , Dir } ]
-record(release, {name, vsn, erts_vsn, libs = [], status}).
-define(timeout, 10000).
%%-----------------------------------------------------------------
%% The version set on the temporary release that will be used when the
%% emulator is upgraded.
-define(tmp_vsn(__BaseVsn__), "__new_emulator__"++__BaseVsn__).
%%-----------------------------------------------------------------
%% Assumes the following file structure:
%% root --- lib --- Appl-Vsn1 --- <src>
%% | | |- ebin
%% | | |_ priv
%% | |_ Appl-Vsn2
%% |
--- start ( default ; { sasl , start_prg } overrides
%% | |- run_erl
| |- start_erl ( reads start_erl.data )
%% | |_ <to_erl>
%% |
%% |- erts-EVsn1 --- bin --- <jam44>
%% | |- <epmd>
%% | |_ erl
%% |- erts-EVsn2
%% |
|- clients --- -- start
%% <clients use same lib and erts as master>
%% | | |_ releases --- start_erl.data
%% | | |_ Vsn1 -- start.boot
%% | |_ ClientName2
%% |
%% |- clients --- Type1 --- lib
%% <clients use own lib and erts>
%% | | |- erts-EVsn
| | -- start
| | | _ -- releases -- start_erl.data
%% | | |_ start.boot (static)
%% | | |_ Vsn1
%% | |_ Type2
%% |
%% |- releases --- RELEASES
| | _ < Vsn1.tar . Z >
%% | |
%% | |- start_erl.data (generated by rh)
%% | |
%% | |_ Vsn1 --- start.boot
%% | | |- <sys.config>
| | | _ relup
%% | |_ Vsn2
%% |
%% |- log --- erlang.log.N (1 .. 5)
%%
%% where <Name> means 'for example Name', and root is
%% init:get_argument(root)
%%
%% It is configurable where the start file is located, and what it
%% is called.
The paramater is { sasl , start_prg } = File
%% It is also configurable where the releases directory is located.
%% Default is $ROOT/releases. $RELDIR overrids, and
{ sasl , } overrides both .
%%-----------------------------------------------------------------
start_link() ->
gen_server:start_link({local, release_handler}, ?MODULE, [], []).
%%-----------------------------------------------------------------
: is the name of the package file
%% (without .tar.Z (.tar on non unix systems))
%% Purpose: Copies all files in the release package to their
directories . Checks that all required libs and erts
%% files are present.
%% Returns: {ok, Vsn} | {error, Reason}
%% Reason = {existing_release, Vsn} |
%% {no_such_file, File} |
%% {bad_rel_file, RelFile} |
%% {file_missing, FileName} | (in the tar package)
%% exit_reason()
%%-----------------------------------------------------------------
unpack_release(ReleaseName) ->
call({unpack_release, ReleaseName}).
%%-----------------------------------------------------------------
Purpose : Checks the relup script for the specified version .
%% The release must be unpacked.
%% Options = [purge] - all old code that can be soft purged
%% will be purged if all checks succeeds. This can be usefull
%% in order to reduce time needed in the following call to
%% install_release.
Returns : { ok , FromVsn , } | { error , Reason }
%% Reason = {illegal_option, IllegalOpt} |
%% {already_installed, Vsn} |
{ bad_relup_file , RelFile } |
{ no_such_release ,
%% {no_such_from_vsn, Vsn} |
%% exit_reason()
%%-----------------------------------------------------------------
check_install_release(Vsn) ->
check_install_release(Vsn, []).
check_install_release(Vsn, Opts) ->
case check_check_install_options(Opts, false) of
{ok,Purge} ->
call({check_install_release, Vsn, Purge});
Error ->
Error
end.
check_check_install_options([purge|Opts], _) ->
check_check_install_options(Opts, true);
check_check_install_options([Illegal|_],_Purge) ->
{error,{illegal_option,Illegal}};
check_check_install_options([],Purge) ->
{ok,Purge}.
%%-----------------------------------------------------------------
Purpose : Executes the relup script for the specified version .
%% The release must be unpacked.
Returns : { ok , FromVsn , } |
{ continue_after_restart , FromVsn , } |
%% {error, Reason}
%% Reason = {already_installed, Vsn} |
{ bad_relup_file , RelFile } |
{ no_such_release ,
%% {no_such_from_vsn, Vsn} |
%% {could_not_create_hybrid_boot,Why} |
%% {missing_base_app,Vsn,App} |
%% {illegal_option, Opt}} |
%% exit_reason()
%%-----------------------------------------------------------------
install_release(Vsn) ->
call({install_release, Vsn, restart, []}).
install_release(Vsn, Opt) ->
case check_install_options(Opt, restart, []) of
{ok, ErrorAction, InstallOpt} ->
call({install_release, Vsn, ErrorAction, InstallOpt});
Error ->
Error
end.
check_install_options([Opt | Opts], ErrAct, InstOpts) ->
case install_option(Opt) of
{error_action, EAct} ->
check_install_options(Opts, EAct, InstOpts);
true ->
check_install_options(Opts, ErrAct, [Opt | InstOpts]);
false ->
{error, {illegal_option, Opt}}
end;
check_install_options([], ErrAct, InstOpts) ->
{ok, ErrAct, InstOpts}.
install_option(Opt = {error_action, reboot}) -> Opt;
install_option(Opt = {error_action, restart}) -> Opt;
install_option({code_change_timeout, TimeOut}) ->
check_timeout(TimeOut);
install_option({suspend_timeout, TimeOut}) ->
check_timeout(TimeOut);
install_option({update_paths, Bool}) when Bool==true; Bool==false ->
true;
install_option(_Opt) -> false.
check_timeout(infinity) -> true;
check_timeout(Int) when is_integer(Int), Int > 0 -> true;
check_timeout(_Else) -> false.
%%-----------------------------------------------------------------
%% Purpose: Called by boot script after emulator is restarted due to
%% new erts version.
%% Returns: Same as install_release/2
%% If this crashes, the emulator restart will fail
%% (since the function is called from the boot script)
%% and there will be a rollback.
%%-----------------------------------------------------------------
new_emulator_upgrade(Vsn, Opts) ->
Result = call({install_release, Vsn, reboot, Opts}),
error_logger:info_msg(
"~w:install_release(~p,~p) completed after node restart "
"with new emulator version~nResult: ~p~n",[?MODULE,Vsn,Opts,Result]),
Result.
%%-----------------------------------------------------------------
%% Purpose: Makes the specified release version be the one that is
%% used when the system starts (or restarts).
%% The release must be installed (not unpacked).
%% Returns: ok | {error, Reason}
%% Reason = {bad_status, Status} |
{ no_such_release ,
%% exit_reason()
%%-----------------------------------------------------------------
make_permanent(Vsn) ->
call({make_permanent, Vsn}).
%%-----------------------------------------------------------------
%% Purpose: Reboots the system from an old release.
%%-----------------------------------------------------------------
reboot_old_release(Vsn) ->
call({reboot_old_release, Vsn}).
%%-----------------------------------------------------------------
%% Purpose: Deletes all files and directories used by the release
%% version, that are not used by any other release.
%% The release must not be permanent.
%% Returns: ok | {error, Reason}
%% Reason = {permanent, Vsn} |
%%-----------------------------------------------------------------
remove_release(Vsn) ->
call({remove_release, Vsn}).
%%-----------------------------------------------------------------
: RelFile = string ( )
Libs = [ { Lib , , } ]
Lib = = string ( )
%% Purpose: Tells the release handler that a release has been
%% unpacked, without using the function unpack_release/1.
%% RelFile is an absolute file name including the extension
%% .rel.
%% The release dir will be created. The necessary files can
%% be installed by calling install_file/2.
The release_handler remebers where all libs are located .
%% If remove_release is called later,
those libs are removed as well ( if no other releases uses
%% them).
%% Returns: ok | {error, Reason}
%%-----------------------------------------------------------------
set_unpacked(RelFile, LibDirs) ->
call({set_unpacked, RelFile, LibDirs}).
%%-----------------------------------------------------------------
: Vsn = string ( )
%% Purpose: Makes it possible to handle removal of releases
%% outside the release_handler.
%% This function won't delete any files at all.
%% Returns: ok | {error, Reason}
%%-----------------------------------------------------------------
set_removed(Vsn) ->
call({set_removed, Vsn}).
%%-----------------------------------------------------------------
%% Purpose: Makes it possible to install the start.boot,
sys.config and relup files if they are not part of a
standard release package . May be used to
%% install files that are generated, before install_release
%% is called.
%% Returns: ok | {error, {no_such_release, Vsn}}
%%-----------------------------------------------------------------
install_file(Vsn, File) when is_list(File) ->
call({install_file, File, Vsn}).
%%-----------------------------------------------------------------
Returns : [ { Name , , [ LibName ] , Status } ]
%% Status = unpacked | current | permanent | old
%%-----------------------------------------------------------------
which_releases() ->
call(which_releases).
%%-----------------------------------------------------------------
Returns : [ { Name , , [ LibName ] , Status } ]
%% Status = unpacked | current | permanent | old
%%-----------------------------------------------------------------
which_releases(Status) ->
Releases = which_releases(),
get_releases_with_status(Releases, Status, []).
%%-----------------------------------------------------------------
check_script(Script , LibDirs ) - > ok | { error , Reason }
%%-----------------------------------------------------------------
check_script(Script, LibDirs) ->
release_handler_1:check_script(Script, LibDirs).
%%-----------------------------------------------------------------
eval_script(Script , Apps , LibDirs , NewLibs , Opts ) - >
{ ok , } |
%% restart_emulator |
%% {error, Error}
{ ' EXIT ' , Reason }
%% If sync_nodes is present, the calling process must have called
net_kernel : monitor_nodes(true ) before calling this function .
%% No! No other process than the release_handler can ever call this
%% function, if sync_nodes is used.
%%
LibDirs is a list of all applications , while NewLibs is a list of
%% applications that have changed version between the current and the
%% new release.
%% -----------------------------------------------------------------
eval_script(Script, Apps, LibDirs, NewLibs, Opts) ->
catch release_handler_1:eval_script(Script, Apps, LibDirs, NewLibs, Opts).
%%-----------------------------------------------------------------
Func : create_RELEASES(Root , RelFile , LibDirs ) - > ok | { error , Reason }
%% Types: Root = RelFile = string()
%% Purpose: Creates an initial RELEASES file.
%%-----------------------------------------------------------------
create_RELEASES([Root, RelFile | LibDirs]) ->
create_RELEASES(Root, filename:join(Root, "releases"), RelFile, LibDirs).
create_RELEASES(Root, RelFile) ->
create_RELEASES(Root, filename:join(Root, "releases"), RelFile, []).
create_RELEASES(Root, RelDir, RelFile, LibDirs) ->
case catch check_rel(Root, RelFile, LibDirs, false) of
{error, Reason } ->
{error, Reason};
Rel ->
Rel2 = Rel#release{status = permanent},
catch write_releases(RelDir, [Rel2], false)
end.
%%-----------------------------------------------------------------
Func : upgrade_app(App , ) - > { ok , }
%% | restart_emulator
%% | {error, Error}
%% Types:
%% App = atom()
%% Dir = string() assumed to be application directory, the code
%% located under Dir/ebin
Purpose : Upgrade to the version in according to an appup file
%%-----------------------------------------------------------------
upgrade_app(App, NewDir) ->
try upgrade_script(App, NewDir) of
{ok, NewVsn, Script} ->
eval_appup_script(App, NewVsn, NewDir, Script)
catch
throw:Reason ->
{error, Reason}
end.
%%-----------------------------------------------------------------
%% Func: downgrade_app(App, Dir)
downgrade_app(App , Vsn , Dir ) - > { ok , }
%% | restart_emulator
%% | {error, Error}
%% Types:
%% App = atom()
Vsn = string ( ) , may be omitted if = = App - Vsn
%% Dir = string() assumed to be application directory, the code
%% located under Dir/ebin
Purpose : Downgrade from the version in according to an appup file
%% located in the ebin dir of the _current_ version
%%-----------------------------------------------------------------
downgrade_app(App, OldDir) ->
case string:tokens(filename:basename(OldDir), "-") of
[_AppS, OldVsn] ->
downgrade_app(App, OldVsn, OldDir);
_ ->
{error, {unknown_version, App}}
end.
downgrade_app(App, OldVsn, OldDir) ->
try downgrade_script(App, OldVsn, OldDir) of
{ok, Script} ->
eval_appup_script(App, OldVsn, OldDir, Script)
catch
throw:Reason ->
{error, Reason}
end.
upgrade_script(App, NewDir) ->
OldVsn = ensure_running(App),
OldDir = code:lib_dir(App),
{NewVsn, Script} = find_script(App, NewDir, OldVsn, up),
OldAppl = read_app(App, OldVsn, OldDir),
NewAppl = read_app(App, NewVsn, NewDir),
case systools_rc:translate_scripts(up,
[Script],[NewAppl],[OldAppl]) of
{ok, LowLevelScript} ->
{ok, NewVsn, LowLevelScript};
{error, _SystoolsRC, Reason} ->
throw(Reason)
end.
downgrade_script(App, OldVsn, OldDir) ->
NewVsn = ensure_running(App),
NewDir = code:lib_dir(App),
{NewVsn, Script} = find_script(App, NewDir, OldVsn, down),
OldAppl = read_app(App, OldVsn, OldDir),
NewAppl = read_app(App, NewVsn, NewDir),
case systools_rc:translate_scripts(dn,
[Script],[OldAppl],[NewAppl]) of
{ok, LowLevelScript} ->
{ok, LowLevelScript};
{error, _SystoolsRC, Reason} ->
throw(Reason)
end.
eval_appup_script(App, ToVsn, ToDir, Script) ->
EnvBefore = application_controller:prep_config_change(),
AppSpecL = read_appspec(App, ToDir),
Res = release_handler_1:eval_script(Script,
[ AppSpec ]
[{App, ToVsn, ToDir}],
[{App, ToVsn, ToDir}],
[]), % [Opt]
case Res of
{ok, _Unpurged} ->
application_controller:change_application_data(AppSpecL,[]),
application_controller:config_change(EnvBefore);
_Res ->
ignore
end,
Res.
ensure_running(App) ->
case lists:keysearch(App, 1, application:which_applications()) of
{value, {_App, _Descr, Vsn}} ->
Vsn;
false ->
throw({app_not_running, App})
end.
find_script(App, Dir, OldVsn, UpOrDown) ->
Appup = filename:join([Dir, "ebin", atom_to_list(App)++".appup"]),
case file:consult(Appup) of
{ok, [{NewVsn, UpFromScripts, DownToScripts}]} ->
Scripts = case UpOrDown of
up -> UpFromScripts;
down -> DownToScripts
end,
case systools_relup:appup_search_for_version(OldVsn,Scripts) of
{ok,Script} ->
{NewVsn,Script};
error ->
throw({version_not_in_appup, OldVsn})
end;
{error, enoent} ->
throw(no_appup_found);
{error, Reason} ->
throw(Reason)
end.
read_app(App, Vsn, Dir) ->
AppS = atom_to_list(App),
Path = [filename:join(Dir, "ebin")],
case systools_make:read_application(AppS, Vsn, Path, []) of
{ok, Appl} ->
Appl;
{error, {not_found, _AppFile}} ->
throw({no_app_found, Vsn, Dir});
{error, Reason} ->
throw(Reason)
end.
read_appspec(App, Dir) ->
AppS = atom_to_list(App),
Path = [filename:join(Dir, "ebin")],
case file:path_consult(Path, AppS++".app") of
{ok, AppSpecL, _File} ->
AppSpecL;
{error, Reason} ->
throw(Reason)
end.
%%-----------------------------------------------------------------
%% call(Request) -> Term
%%-----------------------------------------------------------------
call(Req) ->
gen_server:call(release_handler, Req, infinity).
%%-----------------------------------------------------------------
%% Call-back functions from gen_server
%%-----------------------------------------------------------------
init([]) ->
{ok, [[Root]]} = init:get_argument(root),
{CliDir, Masters} = is_client(),
ReleaseDir =
case application:get_env(sasl, releases_dir) of
undefined ->
case os:getenv("RELDIR") of
false ->
if
CliDir == false ->
filename:join([Root, "releases"]);
true ->
filename:join([CliDir, "releases"])
end;
RELDIR ->
RELDIR
end;
{ok, Dir} ->
Dir
end,
Releases =
case consult(filename:join(ReleaseDir, "RELEASES"), Masters) of
{ok, [Term]} ->
transform_release(ReleaseDir, Term, Masters);
_ ->
{Name, Vsn} = init:script_id(),
[#release{name = Name, vsn = Vsn, status = permanent}]
end,
StartPrg =
case application:get_env(start_prg) of
{ok, Found2} when is_list(Found2) ->
{do_check, Found2};
_ ->
{no_check, filename:join([Root, "bin", "start"])}
end,
Static =
case application:get_env(static_emulator) of
{ok, SFlag} when is_atom(SFlag) -> SFlag;
_ -> false
end,
{ok, #state{root = Root, rel_dir = ReleaseDir, releases = Releases,
start_prg = StartPrg, masters = Masters,
client_dir = CliDir, static_emulator = Static}}.
handle_call({unpack_release, ReleaseName}, _From, S)
when S#state.masters == false ->
case catch do_unpack_release(S#state.root, S#state.rel_dir,
ReleaseName, S#state.releases) of
{ok, NewReleases, Vsn} ->
{reply, {ok, Vsn}, S#state{releases = NewReleases}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({unpack_release, _ReleaseName}, _From, S) ->
{reply, {error, client_node}, S};
handle_call({check_install_release, Vsn, Purge}, _From, S) ->
case catch do_check_install_release(S#state.rel_dir,
Vsn,
S#state.releases,
S#state.masters,
Purge) of
{ok, CurrentVsn, Descr} ->
{reply, {ok, CurrentVsn, Descr}, S};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({install_release, Vsn, ErrorAction, Opts}, From, S) ->
NS = resend_sync_nodes(S),
case catch do_install_release(S, Vsn, Opts) of
{ok, NewReleases, [], CurrentVsn, Descr} ->
{reply, {ok, CurrentVsn, Descr}, NS#state{releases=NewReleases}};
{ok, NewReleases, Unpurged, CurrentVsn, Descr} ->
Timer =
case S#state.timer of
undefined ->
{ok, Ref} = timer:send_interval(?timeout, timeout),
Ref;
Ref -> Ref
end,
NewS = NS#state{releases = NewReleases, unpurged = Unpurged,
timer = Timer},
{reply, {ok, CurrentVsn, Descr}, NewS};
{error, Reason} ->
{reply, {error, Reason}, NS};
{restart_emulator, CurrentVsn, Descr} ->
gen_server:reply(From, {ok, CurrentVsn, Descr}),
init:reboot(),
{noreply, NS};
{restart_new_emulator, CurrentVsn, Descr} ->
gen_server:reply(From, {continue_after_restart, CurrentVsn, Descr}),
init:reboot(),
{noreply, NS};
{'EXIT', Reason} ->
io:format("release_handler:"
"install_release(Vsn=~p Opts=~p) failed, "
"Reason=~p~n", [Vsn, Opts, Reason]),
gen_server:reply(From, {error, Reason}),
case ErrorAction of
restart ->
init:restart();
reboot ->
init:reboot()
end,
{noreply, NS}
end;
handle_call({make_permanent, Vsn}, _From, S) ->
case catch do_make_permanent(S, Vsn) of
{ok, Releases, Unpurged} ->
{reply, ok, S#state{releases = Releases, unpurged = Unpurged}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({reboot_old_release, Vsn}, From, S) ->
case catch do_reboot_old_release(S, Vsn) of
ok ->
gen_server:reply(From, ok),
init:reboot(),
{noreply, S};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({remove_release, Vsn}, _From, S)
when S#state.masters == false ->
case catch do_remove_release(S#state.root, S#state.rel_dir,
Vsn, S#state.releases) of
{ok, NewReleases} ->
{reply, ok, S#state{releases = NewReleases}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({remove_release, _Vsn}, _From, S) ->
{reply, {error, client_node}, S};
handle_call({set_unpacked, RelFile, LibDirs}, _From, S) ->
Root = S#state.root,
case catch do_set_unpacked(Root, S#state.rel_dir, RelFile,
LibDirs, S#state.releases,
S#state.masters) of
{ok, NewReleases, Vsn} ->
{reply, {ok, Vsn}, S#state{releases = NewReleases}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({set_removed, Vsn}, _From, S) ->
case catch do_set_removed(S#state.rel_dir, Vsn,
S#state.releases,
S#state.masters) of
{ok, NewReleases} ->
{reply, ok, S#state{releases = NewReleases}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({install_file, File, Vsn}, _From, S) ->
Reply =
case lists:keysearch(Vsn, #release.vsn, S#state.releases) of
{value, _} ->
Dir = filename:join([S#state.rel_dir, Vsn]),
catch copy_file(File, Dir, S#state.masters);
_ ->
{error, {no_such_release, Vsn}}
end,
{reply, Reply, S};
handle_call(which_releases, _From, S) ->
Reply = lists:map(fun(#release{name = Name, vsn = Vsn, libs = Libs,
status = Status}) ->
{Name, Vsn, mk_lib_name(Libs), Status}
end, S#state.releases),
{reply, Reply, S}.
mk_lib_name([{LibName, Vsn, _Dir} | T]) ->
[lists:concat([LibName, "-", Vsn]) | mk_lib_name(T)];
mk_lib_name([]) -> [].
handle_info(timeout, S) ->
case soft_purge(S#state.unpurged) of
[] ->
_ = timer:cancel(S#state.timer),
{noreply, S#state{unpurged = [], timer = undefined}};
Unpurged ->
{noreply, S#state{unpurged = Unpurged}}
end;
handle_info({sync_nodes, Id, Node}, S) ->
PSN = S#state.pre_sync_nodes,
{noreply, S#state{pre_sync_nodes = [{sync_nodes, Id, Node} | PSN]}};
handle_info(Msg, State) ->
error_logger:info_msg("release_handler: got unknown message: ~p~n", [Msg]),
{noreply, State}.
terminate(_Reason, _State) ->
ok.
handle_cast(_Msg, State) ->
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%-----------------------------------------------------------------
Internal functions
%%%-----------------------------------------------------------------
is_client() ->
case application:get_env(masters) of
{ok, Masters} ->
Alive = is_alive(),
case atom_list(Masters) of
true when Alive == true ->
case application:get_env(client_directory) of
{ok, ClientDir} ->
case int_list(ClientDir) of
true ->
{ClientDir, Masters};
_ ->
exit({bad_parameter, client_directory,
ClientDir})
end;
_ ->
{false, false}
end;
_ ->
exit({bad_parameter, masters, Masters})
end;
_ ->
{false, false}
end.
atom_list([A|T]) when is_atom(A) -> atom_list(T);
atom_list([]) -> true;
atom_list(_) -> false.
int_list([I|T]) when is_integer(I) -> int_list(T);
int_list([]) -> true;
int_list(_) -> false.
resend_sync_nodes(S) ->
lists:foreach(fun(Msg) -> self() ! Msg end, S#state.pre_sync_nodes),
S#state{pre_sync_nodes = []}.
soft_purge(Unpurged) ->
lists:filter(fun({Mod, _PostPurgeMethod}) ->
case code:soft_purge(Mod) of
No proc left , do n't remember
false -> true % Still proc left, remember it
end
end,
Unpurged).
brutal_purge(Unpurged) ->
lists:filter(fun({Mod, brutal_purge}) -> code:purge(Mod), false;
(_) -> true
end,
Unpurged).
%%-----------------------------------------------------------------
%% The release package is a RelName.tar.Z (.tar on non unix) file
%% with the following contents:
- RelName.rel = = { release , { Name , , { erts , EVsn } , [ lib ( ) ] }
%% - <files> according to [lib()]
- lib ( ) = { LibName , }
%% In the Dir, there exists a file called RELEASES, which contains
a [ { Vsn , { erts , EVsn } , { libs , [ { LibName , , } ] } } ] .
%% Note that RelDir is an absolute directory name !
%% Note that this function is not executed by a client
%% release_handler.
%%-----------------------------------------------------------------
do_unpack_release(Root, RelDir, ReleaseName, Releases) ->
Tar = filename:join(RelDir, ReleaseName ++ ".tar.gz"),
do_check_file(Tar, regular),
Rel = ReleaseName ++ ".rel",
extract_rel_file(filename:join("releases", Rel), Tar, Root),
RelFile = filename:join(RelDir, Rel),
Release = check_rel(Root, RelFile, false),
#release{vsn = Vsn} = Release,
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, _} -> throw({error, {existing_release, Vsn}});
_ -> ok
end,
extract_tar(Root, Tar),
NewReleases = [Release#release{status = unpacked} | Releases],
write_releases(RelDir, NewReleases, false),
%% Keeping this for backwards compatibility reasons with older
systools : make_tar , where there is no copy of the .rel file in
the releases/<vsn > dir . See OTP-9746 .
Dir = filename:join([RelDir, Vsn]),
copy_file(RelFile, Dir, false),
%% Clean release
_ = file:delete(Tar),
_ = file:delete(RelFile),
{ok, NewReleases, Vsn}.
check_rel(Root, RelFile, Masters) ->
check_rel(Root, RelFile, [], Masters).
check_rel(Root, RelFile, LibDirs, Masters) ->
case consult(RelFile, Masters) of
{ok, [RelData]} ->
check_rel_data(RelData, Root, LibDirs, Masters);
{ok, _} ->
throw({error, {bad_rel_file, RelFile}});
{error, Reason} when is_tuple(Reason) ->
throw({error, {bad_rel_file, RelFile}});
FileError is posix atom | no_master
throw({error, {FileError, RelFile}})
end.
check_rel_data({release, {Name, Vsn}, {erts, EVsn}, Libs}, Root, LibDirs,
Masters) ->
Libs2 =
lists:map(fun(LibSpec) ->
Lib = element(1, LibSpec),
LibVsn = element(2, LibSpec),
LibName = lists:concat([Lib, "-", LibVsn]),
LibDir =
case lists:keysearch(Lib, 1, LibDirs) of
{value, {_Lib, _Vsn, Dir}} ->
Path = filename:join(Dir,LibName),
check_path(Path, Masters),
Path;
_ ->
filename:join([Root, "lib", LibName])
end,
{Lib, LibVsn, LibDir}
end,
Libs),
#release{name = Name, vsn = Vsn, erts_vsn = EVsn,
libs = Libs2, status = unpacking};
check_rel_data(RelData, _Root, _LibDirs, _Masters) ->
throw({error, {bad_rel_data, RelData}}).
check_path(Path) ->
check_path_response(Path, file:read_file_info(Path)).
check_path(Path, false) -> check_path(Path);
check_path(Path, Masters) -> check_path_master(Masters, Path).
%%-----------------------------------------------------------------
%% check_path at any master node.
%% If the path does not exist or is not a directory
at one node it should not exist at any other node either .
%%-----------------------------------------------------------------
check_path_master([Master|Ms], Path) ->
case rpc:call(Master, file, read_file_info, [Path]) of
{badrpc, _} -> consult_master(Ms, Path);
Res -> check_path_response(Path, Res)
end;
check_path_master([], _Path) ->
{error, no_master}.
check_path_response(_Path, {ok, Info}) when Info#file_info.type==directory ->
ok;
check_path_response(Path, {ok, _Info}) ->
throw({error, {not_a_directory, Path}});
check_path_response(Path, {error, _Reason}) ->
throw({error, {no_such_directory, Path}}).
do_check_install_release(RelDir, Vsn, Releases, Masters, Purge) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{status = current}} ->
{error, {already_installed, Vsn}};
{value, Release} ->
LatestRelease = get_latest_release(Releases),
VsnDir = filename:join([RelDir, Vsn]),
check_file(filename:join(VsnDir, "start.boot"), regular, Masters),
IsRelup = check_opt_file(filename:join(VsnDir, "relup"), regular, Masters),
check_opt_file(filename:join(VsnDir, "sys.config"), regular, Masters),
Check that all required libs are present
Libs = Release#release.libs,
lists:foreach(fun({_Lib, _LibVsn, LibDir}) ->
check_file(LibDir, directory, Masters),
Ebin = filename:join(LibDir, "ebin"),
check_file(Ebin, directory, Masters)
end,
Libs),
if
IsRelup ->
case get_rh_script(LatestRelease, Release, RelDir, Masters) of
{ok, {CurrentVsn, Descr, Script}} ->
case catch check_script(Script, Libs) of
{ok,SoftPurgeMods} when Purge=:=true ->
%% Get modules with brutal_purge
%% instructions, but that can be
%% soft purged
{ok,BrutalPurgeMods} =
release_handler_1:check_old_processes(
Script,brutal_purge),
lists:foreach(
fun(Mod) ->
catch erlang:purge_module(Mod)
end,
SoftPurgeMods ++ BrutalPurgeMods),
{ok, CurrentVsn, Descr};
{ok,_} ->
{ok, CurrentVsn, Descr};
Else ->
Else
end;
Error ->
Error
end;
true ->
{ok, Vsn, ""}
end;
_ ->
{error, {no_such_release, Vsn}}
end.
do_install_release(#state{start_prg = StartPrg,
root = RootDir,
rel_dir = RelDir, releases = Releases,
masters = Masters,
static_emulator = Static},
Vsn, Opts) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{status = current}} ->
{error, {already_installed, Vsn}};
{value, Release} ->
LatestRelease = get_latest_release(Releases),
case get_rh_script(LatestRelease, Release, RelDir, Masters) of
{ok, {_CurrentVsn, _Descr, [restart_new_emulator|_Script]}}
when Static == true ->
throw(static_emulator);
{ok, {CurrentVsn, Descr, [restart_new_emulator|_Script]}} ->
%% This will only happen if the upgrade includes
%% an emulator upgrade (and it is not a downgrade)
%% - then the new emulator must be started before
%% new code can be loaded.
%% Create a temporary release which includes new
%% emulator, kernel, stdlib and sasl - and old
%% versions of other applications.
{TmpVsn,TmpRelease} =
new_emulator_make_tmp_release(LatestRelease,Release,
RelDir,Opts,Masters),
NReleases = [TmpRelease|Releases],
%% Then uppgrade to the temporary release.
%% The rest of the upgrade will continue after the restart
prepare_restart_new_emulator(StartPrg, RootDir,
RelDir, TmpVsn, TmpRelease,
NReleases, Masters),
{restart_new_emulator, CurrentVsn, Descr};
{ok, {CurrentVsn, Descr, Script}} ->
%% In case there has been an emulator upgrade,
%% remove the temporary release
NReleases =
new_emulator_rm_tmp_release(
LatestRelease#release.vsn,
LatestRelease#release.erts_vsn,
Vsn,RelDir,Releases,Masters),
Then execute the relup script
mon_nodes(true),
EnvBefore = application_controller:prep_config_change(),
Apps = change_appl_data(RelDir, Release, Masters),
LibDirs = Release#release.libs,
NewLibs = get_new_libs(LatestRelease#release.libs,
Release#release.libs),
case eval_script(Script, Apps, LibDirs, NewLibs, Opts) of
{ok, Unpurged} ->
application_controller:config_change(EnvBefore),
mon_nodes(false),
NReleases1 = set_status(Vsn, current, NReleases),
{ok, NReleases1, Unpurged, CurrentVsn, Descr};
restart_emulator when Static == true ->
throw(static_emulator);
restart_emulator ->
mon_nodes(false),
prepare_restart_new_emulator(StartPrg, RootDir,
RelDir, Vsn, Release,
NReleases, Masters),
{restart_emulator, CurrentVsn, Descr};
Else ->
application_controller:config_change(EnvBefore),
mon_nodes(false),
Else
end;
Error ->
Error
end;
_ ->
{error, {no_such_release, Vsn}}
end.
new_emulator_make_tmp_release(CurrentRelease,ToRelease,RelDir,Opts,Masters) ->
CurrentVsn = CurrentRelease#release.vsn,
ToVsn = ToRelease#release.vsn,
TmpVsn = ?tmp_vsn(CurrentVsn),
case get_base_libs(ToRelease#release.libs) of
{ok,{Kernel,Stdlib,Sasl}=BaseLibs,_} ->
case get_base_libs(ToRelease#release.libs) of
{ok,_,RestLibs} ->
TmpErtsVsn = ToRelease#release.erts_vsn,
TmpLibs = [Kernel,Stdlib,Sasl|RestLibs],
TmpRelease = CurrentRelease#release{vsn=TmpVsn,
erts_vsn=TmpErtsVsn,
libs = TmpLibs,
status = unpacked},
new_emulator_make_hybrid_boot(CurrentVsn,ToVsn,TmpVsn,
BaseLibs,RelDir,Opts,Masters),
new_emulator_make_hybrid_config(CurrentVsn,ToVsn,TmpVsn,
RelDir,Masters),
{TmpVsn,TmpRelease};
{error,{missing,Missing}} ->
throw({error,{missing_base_app,CurrentVsn,Missing}})
end;
{error,{missing,Missing}} ->
throw({error,{missing_base_app,ToVsn,Missing}})
end.
Get kernel , stdlib and sasl libs ,
and also return the rest of the libs as a list .
Return error if any of kernel , stdlib or sasl does not exist .
get_base_libs(Libs) ->
get_base_libs(Libs,undefined,undefined,undefined,[]).
get_base_libs([{kernel,_,_}=Kernel|Libs],undefined,Stdlib,Sasl,Rest) ->
get_base_libs(Libs,Kernel,Stdlib,Sasl,Rest);
get_base_libs([{stdlib,_,_}=Stdlib|Libs],Kernel,undefined,Sasl,Rest) ->
get_base_libs(Libs,Kernel,Stdlib,Sasl,Rest);
get_base_libs([{sasl,_,_}=Sasl|Libs],Kernel,Stdlib,undefined,Rest) ->
get_base_libs(Libs,Kernel,Stdlib,Sasl,Rest);
get_base_libs([Lib|Libs],Kernel,Stdlib,Sasl,Rest) ->
get_base_libs(Libs,Kernel,Stdlib,Sasl,[Lib|Rest]);
get_base_libs([],undefined,_Stdlib,_Sasl,_Rest) ->
{error,{missing,kernel}};
get_base_libs([],_Kernel,undefined,_Sasl,_Rest) ->
{error,{missing,stdlib}};
get_base_libs([],_Kernel,_Stdlib,undefined,_Rest) ->
{error,{missing,sasl}};
get_base_libs([],Kernel,Stdlib,Sasl,Rest) ->
{ok,{Kernel,Stdlib,Sasl},lists:reverse(Rest)}.
new_emulator_make_hybrid_boot(CurrentVsn,ToVsn,TmpVsn,BaseLibs,RelDir,Opts,Masters) ->
FromBootFile = filename:join([RelDir,CurrentVsn,"start.boot"]),
ToBootFile = filename:join([RelDir,ToVsn,"start.boot"]),
TmpBootFile = filename:join([RelDir,TmpVsn,"start.boot"]),
ensure_dir(TmpBootFile,Masters),
Args = [ToVsn,Opts],
{ok,FromBoot} = read_file(FromBootFile,Masters),
{ok,ToBoot} = read_file(ToBootFile,Masters),
{{_,_,KernelPath},{_,_,StdlibPath},{_,_,SaslPath}} = BaseLibs,
Paths = {filename:join(KernelPath,"ebin"),
filename:join(StdlibPath,"ebin"),
filename:join(SaslPath,"ebin")},
case systools_make:make_hybrid_boot(TmpVsn,FromBoot,ToBoot,Paths,Args) of
{ok,TmpBoot} ->
write_file(TmpBootFile,TmpBoot,Masters);
{error,Reason} ->
throw({error,{could_not_create_hybrid_boot,Reason}})
end.
new_emulator_make_hybrid_config(CurrentVsn,ToVsn,TmpVsn,RelDir,Masters) ->
FromFile = filename:join([RelDir,CurrentVsn,"sys.config"]),
ToFile = filename:join([RelDir,ToVsn,"sys.config"]),
TmpFile = filename:join([RelDir,TmpVsn,"sys.config"]),
FromConfig =
case consult(FromFile,Masters) of
{ok,[FC]} ->
FC;
{error,Error1} ->
io:format("Warning: ~w can not read ~p: ~p~n",
[?MODULE,FromFile,Error1]),
[]
end,
[Kernel,Stdlib,Sasl] =
case consult(ToFile,Masters) of
{ok,[ToConfig]} ->
[lists:keyfind(App,1,ToConfig) || App <- [kernel,stdlib,sasl]];
{error,Error2} ->
io:format("Warning: ~w can not read ~p: ~p~n",
[?MODULE,ToFile,Error2]),
[false,false,false]
end,
Config1 = replace_config(kernel,FromConfig,Kernel),
Config2 = replace_config(stdlib,Config1,Stdlib),
Config3 = replace_config(sasl,Config2,Sasl),
ConfigStr = io_lib:format("~p.~n",[Config3]),
write_file(TmpFile,ConfigStr,Masters).
Take the configuration for application App from the new config and
%% insert in the old config.
%% If no entry exists in the new config, then delete the entry (if it exists)
%% from the old config.
%% If entry exists in the new config, but not in the old config, then
%% add the entry.
replace_config(App,Config,false) ->
lists:keydelete(App,1,Config);
replace_config(App,Config,AppConfig) ->
lists:keystore(App,1,Config,AppConfig).
%% Remove all files related to the temporary release
new_emulator_rm_tmp_release(?tmp_vsn(_)=TmpVsn,EVsn,NewVsn,
RelDir,Releases,Masters) ->
case os:type() of
{win32, nt} ->
rename_tmp_service(EVsn,TmpVsn,NewVsn);
_ ->
ok
end,
remove_dir(filename:join(RelDir,TmpVsn),Masters),
lists:keydelete(TmpVsn,#release.vsn,Releases);
new_emulator_rm_tmp_release(_,_,_,_,Releases,_) ->
Releases.
Rename the tempoarary service ( for erts ugprade ) to the real ToVsn
rename_tmp_service(EVsn,TmpVsn,NewVsn) ->
FromName = hd(string:tokens(atom_to_list(node()),"@")) ++ "_" ++ TmpVsn,
ToName = hd(string:tokens(atom_to_list(node()),"@")) ++ "_" ++ NewVsn,
case erlsrv:get_service(EVsn,ToName) of
{error, _Error} ->
ok;
_Data ->
{ok,_} = erlsrv:remove_service(ToName),
ok
end,
rename_service(EVsn,FromName,ToName).
%% Rename a service and check that it succeeded
rename_service(EVsn,FromName,ToName) ->
case erlsrv:rename_service(EVsn,FromName,ToName) of
{ok,_} ->
case erlsrv:get_service(EVsn,ToName) of
{error,Error1} ->
throw({error,Error1});
_Data2 ->
ok
end;
Error2 ->
throw({error,{service_rename_failed, Error2}})
end.
This code chunk updates the services in one of two ways ,
%%% Either the emulator is restarted, in which case the old service
%%% is to be removed and the new enabled, or the emulator is NOT restarted
%%% in which case we try to rename the old service to the new name and try
%%% to update heart's view of what service we are really running.
do_make_services_permanent(PermanentVsn,Vsn, PermanentEVsn, EVsn) ->
PermName = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ PermanentVsn,
Name = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ Vsn,
case erlsrv:get_service(EVsn,Name) of
{error, _Error} ->
%% We probably do not need to replace services, just
%% rename.
case os:getenv("ERLSRV_SERVICE_NAME") == PermName of
true ->
rename_service(EVsn,PermName,Name),
%% The interfaces for doing this are
%% NOT published and may be subject to
%% change. Do NOT do this anywhere else!
os:putenv("ERLSRV_SERVICE_NAME", Name),
%% Restart heart port program, this
%% function is only to be used here.
heart:cycle();
false ->
throw({error,service_name_missmatch})
end;
Data ->
UpdData = erlsrv:new_service(Name, Data, []),
case erlsrv:store_service(EVsn,UpdData) of
ok ->
{ok,_} = erlsrv:disable_service(PermanentEVsn, PermName),
{ok,_} = erlsrv:enable_service(EVsn, Name),
{ok,_} = erlsrv:remove_service(PermName),
%%% Read comments about these above...
os:putenv("ERLSRV_SERVICE_NAME", Name),
ok = heart:cycle();
Error4 ->
throw(Error4)
end
end.
do_make_permanent(#state{releases = Releases,
rel_dir = RelDir, unpurged = Unpurged,
masters = Masters,
static_emulator = Static},
Vsn) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{erts_vsn = EVsn, status = Status}}
when Status /= unpacked, Status /= old, Status /= permanent ->
Dir = filename:join([RelDir, Vsn]),
Sys =
case catch check_file(filename:join(Dir, "sys.config"),
regular, Masters) of
ok -> filename:join(Dir, "sys");
_ -> false
end,
Boot = filename:join(Dir, "start.boot"),
check_file(Boot, regular, Masters),
set_permanent_files(RelDir, EVsn, Vsn, Masters, Static),
NewReleases = set_status(Vsn, permanent, Releases),
write_releases(RelDir, NewReleases, Masters),
case os:type() of
{win32, nt} ->
{value, PermanentRelease} =
lists:keysearch(permanent, #release.status,
Releases),
PermanentVsn = PermanentRelease#release.vsn,
PermanentEVsn = PermanentRelease#release.erts_vsn,
case catch do_make_services_permanent(PermanentVsn,
Vsn,
PermanentEVsn,
EVsn) of
{error,Reason} ->
throw({error,{service_update_failed, Reason}});
_ ->
ok
end;
_ ->
ok
end,
ok = init:make_permanent(filename:join(Dir, "start"), Sys),
{ok, NewReleases, brutal_purge(Unpurged)};
{value, #release{status = permanent}} ->
{ok, Releases, Unpurged};
{value, #release{status = Status}} ->
{error, {bad_status, Status}};
false ->
{error, {no_such_release, Vsn}}
end.
do_back_service(OldVersion, CurrentVersion,OldEVsn,CurrentEVsn) ->
NN = hd(string:tokens(atom_to_list(node()),"@")),
OldName = NN ++ "_" ++ OldVersion,
CurrentName = NN ++ "_" ++ CurrentVersion,
UpdData = case erlsrv:get_service(CurrentEVsn,CurrentName) of
{error, Error} ->
throw({error,Error});
Data ->
erlsrv:new_service(OldName, Data, [])
end,
_ = case erlsrv:store_service(OldEVsn,UpdData) of
ok ->
{ok,_} = erlsrv:disable_service(CurrentEVsn,CurrentName),
{ok,_} = erlsrv:enable_service(OldEVsn,OldName);
Error2 ->
throw(Error2)
end,
OldErlSrv = filename:nativename(erlsrv:erlsrv(OldEVsn)),
CurrentErlSrv = filename:nativename(erlsrv:erlsrv(CurrentEVsn)),
case heart:set_cmd(CurrentErlSrv ++ " remove " ++ CurrentName ++
" & " ++ OldErlSrv ++ " start " ++ OldName) of
ok ->
ok;
Error3 ->
throw({error, {'heart:set_cmd() error', Error3}})
end.
do_reboot_old_release(#state{releases = Releases,
rel_dir = RelDir, masters = Masters,
static_emulator = Static},
Vsn) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{erts_vsn = EVsn, status = old}} ->
CurrentRunning = case os:type() of
{win32,nt} ->
%% Get the current release on NT
case lists:keysearch(permanent,
#release.status,
Releases) of
false ->
lists:keysearch(current,
#release.status,
Releases);
{value,CR} ->
CR
end;
_ ->
false
end,
set_permanent_files(RelDir, EVsn, Vsn, Masters, Static),
NewReleases = set_status(Vsn, permanent, Releases),
write_releases(RelDir, NewReleases, Masters),
case os:type() of
{win32,nt} ->
%% Edit up the services and set a reasonable heart
%% command
do_back_service(Vsn,CurrentRunning#release.vsn,EVsn,
CurrentRunning#release.erts_vsn);
_ ->
ok
end,
ok;
{value, #release{status = Status}} ->
{error, {bad_status, Status}};
false ->
{error, {no_such_release, Vsn}}
end.
%%-----------------------------------------------------------------
%% Depending of if the release_handler is running in normal, client or
%% client with static emulator the new system version is made permanent
%% in different ways.
%%-----------------------------------------------------------------
set_permanent_files(RelDir, EVsn, Vsn, false, _) ->
write_start(filename:join([RelDir, "start_erl.data"]),
EVsn ++ " " ++ Vsn,
false);
set_permanent_files(RelDir, EVsn, Vsn, Masters, false) ->
write_start(filename:join([RelDir, "start_erl.data"]),
EVsn ++ " " ++ Vsn,
Masters);
set_permanent_files(RelDir, _EVsn, Vsn, Masters, _Static) ->
VsnDir = filename:join([RelDir, Vsn]),
set_static_files(VsnDir, RelDir, Masters).
do_remove_service(Vsn) ->
%% Very unconditionally remove the service.
%% Note that the service could already have been removed when
%% making another release permanent.
ServiceName = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ Vsn,
case erlsrv:get_service(ServiceName) of
{error, _Error} ->
ok;
_Data ->
{ok,_} = erlsrv:remove_service(ServiceName),
ok
end.
do_remove_release(Root, RelDir, Vsn, Releases) ->
Decide which libs should be removed
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{status = permanent}} ->
{error, {permanent, Vsn}};
{value, #release{libs = RemoveLibs, vsn = Vsn, erts_vsn = EVsn}} ->
case os:type() of
{win32, nt} ->
do_remove_service(Vsn);
_ ->
ok
end,
NewReleases = lists:keydelete(Vsn, #release.vsn, Releases),
RemoveThese =
lists:foldl(fun(#release{libs = Libs}, Remove) ->
diff_dir(Remove, Libs)
end, RemoveLibs, NewReleases),
lists:foreach(fun({_Lib, _LVsn, LDir}) ->
remove_file(LDir)
end, RemoveThese),
remove_file(filename:join([RelDir, Vsn])),
case lists:keysearch(EVsn, #release.erts_vsn, NewReleases) of
{value, _} -> ok;
false -> % Remove erts library, no more references to it
remove_file(filename:join(Root, "erts-" ++ EVsn))
end,
write_releases(RelDir, NewReleases, false),
{ok, NewReleases};
false ->
{error, {no_such_release, Vsn}}
end.
do_set_unpacked(Root, RelDir, RelFile, LibDirs, Releases, Masters) ->
Release = check_rel(Root, RelFile, LibDirs, Masters),
#release{vsn = Vsn} = Release,
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, _} -> throw({error, {existing_release, Vsn}});
false -> ok
end,
NewReleases = [Release#release{status = unpacked} | Releases],
VsnDir = filename:join([RelDir, Vsn]),
make_dir(VsnDir, Masters),
write_releases(RelDir, NewReleases, Masters),
{ok, NewReleases, Vsn}.
do_set_removed(RelDir, Vsn, Releases, Masters) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{status = permanent}} ->
{error, {permanent, Vsn}};
{value, _} ->
NewReleases = lists:keydelete(Vsn, #release.vsn, Releases),
write_releases(RelDir, NewReleases, Masters),
{ok, NewReleases};
false ->
{error, {no_such_release, Vsn}}
end.
%%-----------------------------------------------------------------
A relup file consists of :
{ Vsn , [ { FromVsn , , RhScript } ] , [ { ToVsn , , RhScript } ] } .
%% It describes how to get to this release from previous releases,
%% and how to get from this release to previous releases.
We can get from a FromVsn that 's a substring of CurrentVsn ( e.g.
1.1 is a substring of 1.1.1 , but not 1.2 ) , but when we get to
ToVsn , we must have an exact match .
%%
%% We do not put any semantics into the version strings, i.e. we
do n't know if going from Vsn1 to Vsn2 represents a upgrade or
a downgrade . For both upgrades and downgrades , the relup file
%% is located in the directory of the latest version. Since we
do not which version is latest , we first suppose that ToVsn >
CurrentVsn , i.e. we perform an upgrade . If we do n't find the
corresponding relup instructions , we check if it 's possible to
downgrade from CurrentVsn to ToVsn .
%%-----------------------------------------------------------------
get_rh_script(#release{vsn = ?tmp_vsn(CurrentVsn)},
#release{vsn = ToVsn},
RelDir,
Masters) ->
{ok,{Vsn,Descr,[restart_new_emulator|Script]}} =
do_get_rh_script(CurrentVsn,ToVsn,RelDir,Masters),
{ok,{Vsn,Descr,Script}};
get_rh_script(#release{vsn = CurrentVsn},
#release{vsn = ToVsn},
RelDir,
Masters) ->
do_get_rh_script(CurrentVsn,ToVsn,RelDir,Masters).
do_get_rh_script(CurrentVsn, ToVsn, RelDir, Masters) ->
Relup = filename:join([RelDir, ToVsn, "relup"]),
case try_upgrade(ToVsn, CurrentVsn, Relup, Masters) of
{ok, RhScript} ->
{ok, RhScript};
_ ->
Relup2 = filename:join([RelDir, CurrentVsn,"relup"]),
case try_downgrade(ToVsn, CurrentVsn, Relup2, Masters) of
{ok, RhScript} ->
{ok, RhScript};
_ ->
throw({error, {no_matching_relup, ToVsn, CurrentVsn}})
end
end.
try_upgrade(ToVsn, CurrentVsn, Relup, Masters) ->
case consult(Relup, Masters) of
{ok, [{ToVsn, ListOfRhScripts, _}]} ->
case lists:keysearch(CurrentVsn, 1, ListOfRhScripts) of
{value, RhScript} ->
{ok, RhScript};
_ ->
error
end;
{ok, _} ->
throw({error, {bad_relup_file, Relup}});
{error, Reason} when is_tuple(Reason) ->
throw({error, {bad_relup_file, Relup}});
{error, enoent} ->
error;
FileError is posix atom | no_master
throw({error, {FileError, Relup}})
end.
try_downgrade(ToVsn, CurrentVsn, Relup, Masters) ->
case consult(Relup, Masters) of
{ok, [{CurrentVsn, _, ListOfRhScripts}]} ->
case lists:keysearch(ToVsn, 1, ListOfRhScripts) of
{value, RhScript} ->
{ok, RhScript};
_ ->
error
end;
{ok, _} ->
throw({error, {bad_relup_file, Relup}});
{error, Reason} when is_tuple(Reason) ->
throw({error, {bad_relup_file, Relup}});
FileError is posix atom | no_master
throw({error, {FileError, Relup}})
end.
Status = current | tmp_current | permanent
set_status(Vsn, Status, Releases) ->
lists:zf(fun(Release) when Release#release.vsn == Vsn,
Release#release.status == permanent ->
%% If a permanent rel is installed, it keeps its
%% permanent status (not changed to current).
%% The current becomes old though.
true;
(Release) when Release#release.vsn == Vsn ->
{true, Release#release{status = Status}};
(Release) when Release#release.status == Status ->
{true, Release#release{status = old}};
(_) ->
true
end, Releases).
get_latest_release(Releases) ->
case lists:keysearch(current, #release.status, Releases) of
{value, Release} ->
Release;
false ->
{value, Release} =
lists:keysearch(permanent, #release.status, Releases),
Release
end.
Returns : [ { Lib , Vsn , Dir } ] to be removed
diff_dir([H | T], L) ->
case memlib(H, L) of
true -> diff_dir(T, L);
false -> [H | diff_dir(T, L)]
end;
diff_dir([], _) -> [].
memlib({Lib, Vsn, _Dir}, [{Lib, Vsn, _Dir2} | _T]) -> true;
memlib(Lib, [_H | T]) -> memlib(Lib, T);
memlib(_Lib, []) -> false.
%% recursively remove file or directory
remove_file(File) ->
case file:read_link_info(File) of
{ok, Info} when Info#file_info.type==directory ->
case file:list_dir(File) of
{ok, Files} ->
lists:foreach(fun(File2) ->
remove_file(filename:join(File,File2))
end, Files),
case file:del_dir(File) of
ok -> ok;
{error, Reason} -> throw({error, Reason})
end;
{error, Reason} ->
throw({error, Reason})
end;
{ok, _Info} ->
case file:delete(File) of
ok -> ok;
{error, Reason} -> throw({error, Reason})
end;
{error, _Reason} ->
throw({error, {no_such_file, File}})
end.
do_write_file(File, Str) ->
do_write_file(File, Str, []).
do_write_file(File, Str, FileOpts) ->
case file:open(File, [write | FileOpts]) of
{ok, Fd} ->
io:put_chars(Fd, Str),
ok = file:close(Fd);
{error, Reason} ->
{error, {Reason, File}}
end.
%%-----------------------------------------------------------------
%% Change current applications (specifically, update their version,
%% description and env.)
%%-----------------------------------------------------------------
change_appl_data(RelDir, #release{vsn = Vsn}, Masters) ->
Dir = filename:join([RelDir, Vsn]),
BootFile = filename:join(Dir, "start.boot"),
case read_file(BootFile, Masters) of
{ok, Bin} ->
Config = case consult(filename:join(Dir, "sys.config"), Masters) of
{ok, [Conf]} -> Conf;
_ -> []
end,
Appls = get_appls(binary_to_term(Bin)),
case application_controller:change_application_data(Appls,Config) of
ok -> Appls;
{error, Reason} -> exit({change_appl_data, Reason})
end;
{error, _Reason} ->
throw({error, {no_such_file, BootFile}})
end.
%%-----------------------------------------------------------------
%% This function is dependent on the application functions and
%% the start script syntax.
%%-----------------------------------------------------------------
get_appls({script, _, Script}) -> get_appls(Script, []).
%% kernel is taken care of separately
get_appls([{kernelProcess, application_controller,
{application_controller, start, [App]}} |T], Res) ->
get_appls(T, [App | Res]);
%% other applications but kernel
get_appls([{apply, {application, load, [App]}} |T], Res) ->
get_appls(T, [App | Res]);
get_appls([_ | T], Res) ->
get_appls(T, Res);
get_appls([], Res) ->
Res.
mon_nodes(true) ->
ok = net_kernel:monitor_nodes(true);
mon_nodes(false) ->
ok = net_kernel:monitor_nodes(false),
flush().
flush() ->
receive
{nodedown, _} -> flush();
{nodeup, _} -> flush()
after
0 -> ok
end.
prepare_restart_nt(#release{erts_vsn = EVsn, vsn = Vsn},
#release{erts_vsn = PermEVsn, vsn = PermVsn},
DataFileName) ->
CurrentServiceName = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ PermVsn,
FutureServiceName = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ Vsn,
CurrentService = case erlsrv:get_service(PermEVsn,CurrentServiceName) of
{error, _} = Error1 ->
throw(Error1);
CS ->
CS
end,
FutureService = erlsrv:new_service(FutureServiceName,
CurrentService,
filename:nativename(DataFileName),
%% This is rather icky... On a
%% non permanent service, the
ERLSRV_SERVICE_NAME is
%% actually that of an old service,
%% to make heart commands work...
CurrentServiceName),
case erlsrv:store_service(EVsn, FutureService) of
{error, _} = Error2 ->
throw(Error2);
_X ->
{ok,_} = erlsrv:disable_service(EVsn, FutureServiceName),
ErlSrv = filename:nativename(erlsrv:erlsrv(EVsn)),
StartDisabled = ErlSrv ++ " start_disabled " ++ FutureServiceName,
case heart:set_cmd(StartDisabled) of
ok ->
ok;
Error3 ->
throw({error, {'heart:set_cmd() error', Error3}})
end
end.
%%-----------------------------------------------------------------
%% Set things up for restarting the new emulator. The actual
%% restart is performed by calling init:reboot() higher up.
%%-----------------------------------------------------------------
prepare_restart_new_emulator(StartPrg, RootDir, RelDir,
Vsn, Release, Releases, Masters) ->
{value, PRelease} = lists:keysearch(permanent, #release.status,Releases),
NReleases1 = set_status(Vsn, current, Releases),
NReleases2 = set_status(Vsn,tmp_current,NReleases1),
write_releases(RelDir, NReleases2, Masters),
prepare_restart_new_emulator(StartPrg, RootDir, RelDir,
Release, PRelease, Masters).
prepare_restart_new_emulator(StartPrg, RootDir, RelDir,
Release, PRelease, Masters) ->
#release{erts_vsn = EVsn, vsn = Vsn} = Release,
Data = EVsn ++ " " ++ Vsn,
DataFile = write_new_start_erl(Data, RelDir, Masters),
Tell heart to use DataFile instead of start_erl.data
case os:type() of
{win32,nt} ->
write_ini_file(RootDir,EVsn,Masters),
prepare_restart_nt(Release,PRelease,DataFile);
{unix,_} ->
StartP = check_start_prg(StartPrg, Masters),
case heart:set_cmd(StartP ++ " " ++ DataFile) of
ok ->
ok;
Error ->
throw({error, {'heart:set_cmd() error', Error}})
end
end.
check_start_prg({do_check, StartPrg}, Masters) ->
check_file(StartPrg, regular, Masters),
StartPrg;
check_start_prg({_, StartPrg}, _) ->
StartPrg.
write_new_start_erl(Data, RelDir, Masters) ->
DataFile = filename:join([RelDir, "new_start_erl.data"]),
write_file(DataFile, Data, Masters),
DataFile.
%%-----------------------------------------------------------------
%% When a new emulator shall be restarted, the current release
%% is written with status tmp_current. When the new emulator
%% is started, this function is called. The tmp_current release
%% gets status unpacked on disk, and current in memory. If a reboot
%% is made (due to a crash), the release is just unpacked. If a crash
occurs before a call to is made , the old emulator
is started , and is called for it . The tmp_current
%% release is changed to unpacked.
%% If the release is made permanent, this is written to disk.
%%-----------------------------------------------------------------
transform_release(ReleaseDir, Releases, Masters) ->
case init:script_id() of
{Name, ?tmp_vsn(_)=TmpVsn} ->
%% This is was a reboot due to a new emulator version. The
%% current release is a temporary internal release, which
%% must be removed. It is the "real new release" that is
%% set to unpacked on disk and current in memory.
DReleases = lists:keydelete(TmpVsn,#release.vsn,Releases),
write_releases(ReleaseDir, DReleases, Masters),
set_current({Name,TmpVsn},Releases);
ScriptId ->
F = fun(Release) when Release#release.status == tmp_current ->
Release#release{status = unpacked};
(Release) -> Release
end,
case lists:map(F, Releases) of
Releases ->
Releases;
DReleases ->
write_releases(ReleaseDir, DReleases, Masters),
set_current(ScriptId, Releases)
end
end.
set_current(ScriptId, Releases) ->
F1 = fun(Release) when Release#release.status == tmp_current ->
case ScriptId of
{_Name,Vsn} when Release#release.vsn == Vsn ->
Release#release{status = current};
_ ->
Release#release{status = unpacked}
end;
(Release) -> Release
end,
lists:map(F1, Releases).
%%-----------------------------------------------------------------
Functions handling files , RELEASES , start_erl.data etc .
%% This functions consider if the release_handler is a client and
%% in that case performs the operations at all master nodes or at
%% none (in case of failure).
%%-----------------------------------------------------------------
check_opt_file(FileName, Type, Masters) ->
case catch check_file(FileName, Type, Masters) of
ok ->
true;
_Error ->
io:format("Warning: ~p missing (optional)~n", [FileName]),
false
end.
check_file(FileName, Type, false) ->
do_check_file(FileName, Type);
check_file(FileName, Type, Masters) ->
check_file_masters(FileName, Type, Masters).
%% Check that file exists at all masters.
check_file_masters(FileName, Type, [Master|Masters]) ->
do_check_file(Master, FileName, Type),
check_file_masters(FileName, Type, Masters);
check_file_masters(_FileName, _Type, []) ->
ok.
%% Type == regular | directory
do_check_file(FileName, Type) ->
case file:read_file_info(FileName) of
{ok, Info} when Info#file_info.type==Type -> ok;
{error, _Reason} -> throw({error, {no_such_file, FileName}})
end.
do_check_file(Master, FileName, Type) ->
case rpc:call(Master, file, read_file_info, [FileName]) of
{ok, Info} when Info#file_info.type==Type -> ok;
_ -> throw({error, {no_such_file, {Master, FileName}}})
end.
%%-----------------------------------------------------------------
If does n't exists in tar it could have been created
%% by the user in another way, i.e. ignore this here.
%%-----------------------------------------------------------------
extract_rel_file(Rel, Tar, Root) ->
erl_tar:extract(Tar, [{files, [Rel]}, {cwd, Root}, compressed]).
extract_tar(Root, Tar) ->
case erl_tar:extract(Tar, [keep_old_files, {cwd, Root}, compressed]) of
ok ->
ok;
{error, Reason, Name} -> % Old erl_tar.
throw({error, {cannot_extract_file, Name, Reason}});
New erl_tar ( ) .
throw({error, {cannot_extract_file, Name, Reason}})
end.
write_releases(Dir, Releases, Masters) ->
%% We must never write 'current' to disk, since this will confuse
%% us after a node restart - since we would then have a permanent
%% release running, but state set to current for a non-running
%% release.
NewReleases = lists:zf(fun(Release) when Release#release.status == current ->
{true, Release#release{status = unpacked}};
(_) ->
true
end, Releases),
write_releases_1(Dir, NewReleases, Masters).
write_releases_1(Dir, NewReleases, false) ->
case do_write_release(Dir, "RELEASES", NewReleases) of
ok -> ok;
Error -> throw(Error)
end;
write_releases_1(Dir, NewReleases, Masters) ->
all_masters(Masters),
write_releases_m(Dir, NewReleases, Masters).
do_write_release(Dir, RELEASES, NewReleases) ->
case file:open(filename:join(Dir, RELEASES), [write]) of
{ok, Fd} ->
ok = io:format(Fd, "~p.~n", [NewReleases]),
ok = file:close(Fd);
{error, Reason} ->
{error, Reason}
end.
%%-----------------------------------------------------------------
%% Write the "RELEASES" file at all master nodes.
1 . Save " RELEASES.backup " at all nodes .
%% 2. Save "RELEASES.change" at all nodes.
%% 3. Update the "RELEASES.change" file at all nodes.
%% 4. Move "RELEASES.change" to "RELEASES".
5 . Remove " RELEASES.backup " at all nodes .
%%
If one of the steps above fails , all steps is recovered from
( as long as possible ) , except for 5 which is allowed to fail .
%%-----------------------------------------------------------------
write_releases_m(Dir, NewReleases, Masters) ->
RelFile = filename:join(Dir, "RELEASES"),
Backup = filename:join(Dir, "RELEASES.backup"),
Change = filename:join(Dir, "RELEASES.change"),
ensure_RELEASES_exists(Masters, RelFile),
case at_all_masters(Masters, ?MODULE, do_copy_files,
[RelFile, [Backup, Change]]) of
ok ->
case at_all_masters(Masters, ?MODULE, do_write_release,
[Dir, "RELEASES.change", NewReleases]) of
ok ->
case at_all_masters(Masters, file, rename,
[Change, RelFile]) of
ok ->
remove_files(all, [Backup, Change], Masters),
ok;
{error, {Master, R}} ->
takewhile(Master, Masters, file, rename,
[Backup, RelFile]),
remove_files(all, [Backup, Change], Masters),
throw({error, {Master, R, move_releases}})
end;
{error, {Master, R}} ->
remove_files(all, [Backup, Change], Masters),
throw({error, {Master, R, update_releases}})
end;
{error, {Master, R}} ->
remove_files(Master, [Backup, Change], Masters),
throw({error, {Master, R, backup_releases}})
end.
ensure_RELEASES_exists(Masters, RelFile) ->
case at_all_masters(Masters, ?MODULE, do_ensure_RELEASES, [RelFile]) of
ok ->
ok;
{error, {Master, R}} ->
throw({error, {Master, R, ensure_RELEASES_exists}})
end.
copy_file(File, Dir, false) ->
case do_copy_file(File, Dir) of
ok -> ok;
Error -> throw(Error)
end;
copy_file(File, Dir, Masters) ->
all_masters(Masters),
copy_file_m(File, Dir, Masters).
%%-----------------------------------------------------------------
copy at every master node .
%% If an error occurs at a node, the total copy failed.
%% We do not have to cleanup in case of failure as this
%% copy_file is harmless.
%%-----------------------------------------------------------------
copy_file_m(File, Dir, [Master|Masters]) ->
case rpc:call(Master, ?MODULE, do_copy_file, [File, Dir]) of
ok -> copy_file_m(File, Dir, Masters);
{error, {Reason, F}} -> throw({error, {Master, Reason, F}});
Other -> throw({error, {Master, Other, File}})
end;
copy_file_m(_File, _Dir, []) ->
ok.
do_copy_file(File, Dir) ->
File2 = filename:join(Dir, filename:basename(File)),
do_copy_file1(File, File2).
do_copy_file1(File, File2) ->
case file:read_file(File) of
{ok, Bin} ->
case file:write_file(File2, Bin) of
ok -> ok;
{error, Reason} ->
{error, {Reason, File2}}
end;
{error, Reason} ->
{error, {Reason, File}}
end.
%%-----------------------------------------------------------------
%% Copy File to a list of files.
%%-----------------------------------------------------------------
do_copy_files(File, [ToFile|ToFiles]) ->
case do_copy_file1(File, ToFile) of
ok -> do_copy_files(File, ToFiles);
Error -> Error
end;
do_copy_files(_, []) ->
ok.
%%-----------------------------------------------------------------
%% Copy each Src file to Dest file in the list of files.
%%-----------------------------------------------------------------
do_copy_files([{Src, Dest}|Files]) ->
case do_copy_file1(Src, Dest) of
ok -> do_copy_files(Files);
Error -> Error
end;
do_copy_files([]) ->
ok.
%%-----------------------------------------------------------------
%% Rename each Src file to Dest file in the list of files.
%%-----------------------------------------------------------------
do_rename_files([{Src, Dest}|Files]) ->
case file:rename(Src, Dest) of
ok -> do_rename_files(Files);
Error -> Error
end;
do_rename_files([]) ->
ok.
%%-----------------------------------------------------------------
%% Remove a list of files. Ignore failure.
%%-----------------------------------------------------------------
do_remove_files([File|Files]) ->
_ = file:delete(File),
do_remove_files(Files);
do_remove_files([]) ->
ok.
%%-----------------------------------------------------------------
%% Ensure that the RELEASES file exists.
%% If not create an empty RELEASES file.
%%-----------------------------------------------------------------
do_ensure_RELEASES(RelFile) ->
case file:read_file_info(RelFile) of
{ok, _} -> ok;
_ -> do_write_file(RelFile, "[]. ")
end.
%%-----------------------------------------------------------------
%% Make a directory, ignore failures (captured later).
%%-----------------------------------------------------------------
make_dir(Dir, false) ->
_ = file:make_dir(Dir),
ok;
make_dir(Dir, Masters) ->
lists:foreach(fun(Master) -> rpc:call(Master, file, make_dir, [Dir]) end,
Masters).
%%-----------------------------------------------------------------
%% Check that all masters are alive.
%%-----------------------------------------------------------------
all_masters(Masters) ->
case rpc:multicall(Masters, erlang, info, [version]) of
{_, []} -> ok;
{_, BadNodes} -> throw({error, {bad_masters, BadNodes}})
end.
%%-----------------------------------------------------------------
%% Evaluate {M,F,A} at all masters.
%% {M,F,A} is supposed to return ok. Otherwise at_all_masters
%% returns {error, {Master, Other}}.
%%-----------------------------------------------------------------
at_all_masters([Master|Masters], M, F, A) ->
case rpc:call(Master, M, F, A) of
ok -> at_all_masters(Masters, M, F, A);
Error -> {error, {Master, Error}}
end;
at_all_masters([], _, _, _) ->
ok.
%%-----------------------------------------------------------------
%% Evaluate {M,F,A} at all masters until Master is found.
%% Ignore {M,F,A} return value.
%%-----------------------------------------------------------------
takewhile(Master, Masters, M, F, A) ->
_ = lists:takewhile(fun(Ma) when Ma == Master ->
false;
(Ma) ->
rpc:call(Ma, M, F, A),
true
end, Masters),
ok.
consult(File, false) -> file:consult(File);
consult(File, Masters) -> consult_master(Masters, File).
%%-----------------------------------------------------------------
%% consult the File at any master node.
If the file does not exist at one node it should
%% not exist at any other node either.
%%-----------------------------------------------------------------
consult_master([Master|Ms], File) ->
case rpc:call(Master, file, consult, [File]) of
{badrpc, _} -> consult_master(Ms, File);
Res -> Res
end;
consult_master([], _File) ->
{error, no_master}.
read_file(File, false) ->
file:read_file(File);
read_file(File, Masters) ->
read_master(Masters, File).
write_file(File, Data, false) ->
case file:write_file(File, Data) of
ok -> ok;
Error -> throw(Error)
end;
write_file(File, Data, Masters) ->
case at_all_masters(Masters, file, write_file, [File, Data]) of
ok -> ok;
Error -> throw(Error)
end.
ensure_dir(File, false) ->
case filelib:ensure_dir(File) of
ok -> ok;
Error -> throw(Error)
end;
ensure_dir(File, Masters) ->
case at_all_masters(Masters,filelib,ensure_dir,[File]) of
ok -> ok;
Error -> throw(Error)
end.
remove_dir(Dir, false) ->
remove_file(Dir);
remove_dir(Dir, Masters) ->
case at_all_masters(Masters,?MODULE,remove_file,[Dir]) of
ok -> ok;
Error -> throw(Error)
end.
%% Ignore status of each delete !
remove_files(Master, Files, Masters) ->
takewhile(Master, Masters, ?MODULE, do_remove_files, [Files]).
%%-----------------------------------------------------------------
%% read the File at any master node.
If the file does not exist at one node it should
%% not exist at any other node either.
%%-----------------------------------------------------------------
read_master([Master|Ms], File) ->
case rpc:call(Master, file, read_file, [File]) of
{badrpc, _} -> read_master(Ms, File);
Res -> Res
end;
read_master([], _File) ->
{error, no_master}.
%%-----------------------------------------------------------------
%% Write start_erl.data.
%%-----------------------------------------------------------------
write_start(File, Data, false) ->
case do_write_file(File, Data) of
ok -> ok;
Error -> throw(Error)
end;
write_start(File, Data, Masters) ->
all_masters(Masters),
safe_write_file_m(File, Data, Masters).
%%-----------------------------------------------------------------
Copy the " start.boot " and " sys.config " from SrcDir to DestDir at all
%% master nodes.
1 . Save DestDir/"start.backup " and " at all nodes .
%% 2. Copy files at all nodes.
%% 3. Remove backup files at all nodes.
%%
If one of the steps above fails , all steps is recovered from
( as long as possible ) , except for 3 which is allowed to fail .
%%-----------------------------------------------------------------
set_static_files(SrcDir, DestDir, Masters) ->
all_masters(Masters),
Boot = "start.boot",
Config = "sys.config",
SrcBoot = filename:join(SrcDir, Boot),
DestBoot = filename:join(DestDir, Boot),
BackupBoot = filename:join(DestDir, "start.backup"),
SrcConf = filename:join(SrcDir, Config),
DestConf = filename:join(DestDir, Config),
BackupConf = filename:join(DestDir, "sys.backup"),
case at_all_masters(Masters, ?MODULE, do_copy_files,
[[{DestBoot, BackupBoot},
{DestConf, BackupConf}]]) of
ok ->
case at_all_masters(Masters, ?MODULE, do_copy_files,
[[{SrcBoot, DestBoot},
{SrcConf, DestConf}]]) of
ok ->
remove_files(all, [BackupBoot, BackupConf], Masters),
ok;
{error, {Master, R}} ->
takewhile(Master, Masters, ?MODULE, do_rename_files,
[{BackupBoot, DestBoot},
{BackupConf, DestConf}]),
remove_files(all, [BackupBoot, BackupConf], Masters),
throw({error, {Master, R, copy_start_config}})
end;
{error, {Master, R}} ->
remove_files(Master, [BackupBoot, BackupConf], Masters),
throw({error, {Master, R, backup_start_config}})
end.
%%-----------------------------------------------------------------
%% Write erl.ini
Writes the erl.ini file used by erl.exe when ( re)starting the erlang node .
At first installation , this is done by Install.exe , which means that if
%% the format of this file for some reason is changed, then Install.c must
%% also be updated (and probably some other c-files which read erl.ini)
%%-----------------------------------------------------------------
write_ini_file(RootDir,EVsn,Masters) ->
BinDir = filename:join([RootDir,"erts-"++EVsn,"bin"]),
Str0 = io_lib:format("[erlang]~n"
"Bindir=~ts~n"
"Progname=erl~n"
"Rootdir=~ts~n",
[filename:nativename(BinDir),
filename:nativename(RootDir)]),
Str = re:replace(Str0,"\\\\","\\\\\\\\",[{return,list},global,unicode]),
IniFile = filename:join(BinDir,"erl.ini"),
do_write_ini_file(IniFile,Str,Masters).
do_write_ini_file(File,Data,false) ->
case do_write_file(File, Data, [{encoding,utf8}]) of
ok -> ok;
Error -> throw(Error)
end;
do_write_ini_file(File,Data,Masters) ->
all_masters(Masters),
safe_write_file_m(File, Data, [{encoding,utf8}], Masters).
%%-----------------------------------------------------------------
%% Write the given file at all master nodes.
%% 1. Save <File>.backup at all nodes.
%% 2. Write <File>.change at all nodes.
3 . Move < File>.change to < File >
%% 4. Remove <File>.backup at all nodes.
%%
If one of the steps above fails , all steps are recovered from
( as long as possible ) , except for 4 which is allowed to fail .
%%-----------------------------------------------------------------
safe_write_file_m(File, Data, Masters) ->
safe_write_file_m(File, Data, [], Masters).
safe_write_file_m(File, Data, FileOpts, Masters) ->
Backup = File ++ ".backup",
Change = File ++ ".change",
case at_all_masters(Masters, ?MODULE, do_copy_files,
[File, [Backup]]) of
ok ->
case at_all_masters(Masters, ?MODULE, do_write_file,
[Change, Data, FileOpts]) of
ok ->
case at_all_masters(Masters, file, rename,
[Change, File]) of
ok ->
remove_files(all, [Backup, Change], Masters),
ok;
{error, {Master, R}} ->
takewhile(Master, Masters, file, rename,
[Backup, File]),
remove_files(all, [Backup, Change], Masters),
throw({error, {Master, R, rename,
filename:basename(Change),
filename:basename(File)}})
end;
{error, {Master, R}} ->
remove_files(all, [Backup, Change], Masters),
throw({error, {Master, R, write, filename:basename(Change)}})
end;
{error, {Master, R}} ->
remove_files(Master, [Backup], Masters),
throw({error, {Master, R, backup,
filename:basename(File),
filename:basename(Backup)}})
end.
%%-----------------------------------------------------------------
%% Figure out which applications that have changed version between the
two releases . The paths for these applications must always be
updated , even if the relup script does not load any modules . See
OTP-9402 .
%%
%% A different situation is when the same application version is used
%% in old and new release, but the path has changed. This is not
%% handled here - instead it must be explicitely indicated by the
%% 'update_paths' option to release_handler:install_release/2 if the
%% code path shall be updated then.
%% -----------------------------------------------------------------
get_new_libs([{App,Vsn,_LibDir}|CurrentLibs], NewLibs) ->
case lists:keyfind(App,1,NewLibs) of
{App,NewVsn,_} = LibInfo when NewVsn =/= Vsn ->
[LibInfo | get_new_libs(CurrentLibs,NewLibs)];
_ ->
get_new_libs(CurrentLibs,NewLibs)
end;
get_new_libs([],_) ->
[].
%%-----------------------------------------------------------------
%% Return a list of releases witch a specific status
%%-----------------------------------------------------------------
get_releases_with_status([], _, Acc) ->
Acc;
get_releases_with_status([ {_, _, _, ReleaseStatus } = Head | Tail],
Status, Acc) when ReleaseStatus == Status ->
get_releases_with_status(Tail, Status, [Head | Acc]);
get_releases_with_status([_ | Tail], Status, Acc) ->
get_releases_with_status(Tail, Status, Acc).
| null | https://raw.githubusercontent.com/wireless-net/erlang-nommu/79f32f81418e022d8ad8e0e447deaea407289926/lib/sasl/src/release_handler.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%
External exports
Internal exports
Internal exports, a client release_handler may call this functions.
-----------------------------------------------------------------
=============================================
- unpack unpacked
unpacked install current
remove -
current make_permanent permanent
install other old
restart node unpacked
remove -
permanent make other permanent old
install permanent
old reboot_old permanent
install current
remove -
-----------------------------------------------------------------
-----------------------------------------------------------------
The version set on the temporary release that will be used when the
emulator is upgraded.
-----------------------------------------------------------------
Assumes the following file structure:
root --- lib --- Appl-Vsn1 --- <src>
| | |- ebin
| | |_ priv
| |_ Appl-Vsn2
|
| |- run_erl
| |_ <to_erl>
|
|- erts-EVsn1 --- bin --- <jam44>
| |- <epmd>
| |_ erl
|- erts-EVsn2
|
<clients use same lib and erts as master>
| | |_ releases --- start_erl.data
| | |_ Vsn1 -- start.boot
| |_ ClientName2
|
|- clients --- Type1 --- lib
<clients use own lib and erts>
| | |- erts-EVsn
| | |_ start.boot (static)
| | |_ Vsn1
| |_ Type2
|
|- releases --- RELEASES
| |
| |- start_erl.data (generated by rh)
| |
| |_ Vsn1 --- start.boot
| | |- <sys.config>
| |_ Vsn2
|
|- log --- erlang.log.N (1 .. 5)
where <Name> means 'for example Name', and root is
init:get_argument(root)
It is configurable where the start file is located, and what it
is called.
It is also configurable where the releases directory is located.
Default is $ROOT/releases. $RELDIR overrids, and
-----------------------------------------------------------------
-----------------------------------------------------------------
(without .tar.Z (.tar on non unix systems))
Purpose: Copies all files in the release package to their
files are present.
Returns: {ok, Vsn} | {error, Reason}
Reason = {existing_release, Vsn} |
{no_such_file, File} |
{bad_rel_file, RelFile} |
{file_missing, FileName} | (in the tar package)
exit_reason()
-----------------------------------------------------------------
-----------------------------------------------------------------
The release must be unpacked.
Options = [purge] - all old code that can be soft purged
will be purged if all checks succeeds. This can be usefull
in order to reduce time needed in the following call to
install_release.
Reason = {illegal_option, IllegalOpt} |
{already_installed, Vsn} |
{no_such_from_vsn, Vsn} |
exit_reason()
-----------------------------------------------------------------
-----------------------------------------------------------------
The release must be unpacked.
{error, Reason}
Reason = {already_installed, Vsn} |
{no_such_from_vsn, Vsn} |
{could_not_create_hybrid_boot,Why} |
{missing_base_app,Vsn,App} |
{illegal_option, Opt}} |
exit_reason()
-----------------------------------------------------------------
-----------------------------------------------------------------
Purpose: Called by boot script after emulator is restarted due to
new erts version.
Returns: Same as install_release/2
If this crashes, the emulator restart will fail
(since the function is called from the boot script)
and there will be a rollback.
-----------------------------------------------------------------
-----------------------------------------------------------------
Purpose: Makes the specified release version be the one that is
used when the system starts (or restarts).
The release must be installed (not unpacked).
Returns: ok | {error, Reason}
Reason = {bad_status, Status} |
exit_reason()
-----------------------------------------------------------------
-----------------------------------------------------------------
Purpose: Reboots the system from an old release.
-----------------------------------------------------------------
-----------------------------------------------------------------
Purpose: Deletes all files and directories used by the release
version, that are not used by any other release.
The release must not be permanent.
Returns: ok | {error, Reason}
Reason = {permanent, Vsn} |
-----------------------------------------------------------------
-----------------------------------------------------------------
Purpose: Tells the release handler that a release has been
unpacked, without using the function unpack_release/1.
RelFile is an absolute file name including the extension
.rel.
The release dir will be created. The necessary files can
be installed by calling install_file/2.
If remove_release is called later,
them).
Returns: ok | {error, Reason}
-----------------------------------------------------------------
-----------------------------------------------------------------
Purpose: Makes it possible to handle removal of releases
outside the release_handler.
This function won't delete any files at all.
Returns: ok | {error, Reason}
-----------------------------------------------------------------
-----------------------------------------------------------------
Purpose: Makes it possible to install the start.boot,
install files that are generated, before install_release
is called.
Returns: ok | {error, {no_such_release, Vsn}}
-----------------------------------------------------------------
-----------------------------------------------------------------
Status = unpacked | current | permanent | old
-----------------------------------------------------------------
-----------------------------------------------------------------
Status = unpacked | current | permanent | old
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
restart_emulator |
{error, Error}
If sync_nodes is present, the calling process must have called
No! No other process than the release_handler can ever call this
function, if sync_nodes is used.
applications that have changed version between the current and the
new release.
-----------------------------------------------------------------
-----------------------------------------------------------------
Types: Root = RelFile = string()
Purpose: Creates an initial RELEASES file.
-----------------------------------------------------------------
-----------------------------------------------------------------
| restart_emulator
| {error, Error}
Types:
App = atom()
Dir = string() assumed to be application directory, the code
located under Dir/ebin
-----------------------------------------------------------------
-----------------------------------------------------------------
Func: downgrade_app(App, Dir)
| restart_emulator
| {error, Error}
Types:
App = atom()
Dir = string() assumed to be application directory, the code
located under Dir/ebin
located in the ebin dir of the _current_ version
-----------------------------------------------------------------
[Opt]
-----------------------------------------------------------------
call(Request) -> Term
-----------------------------------------------------------------
-----------------------------------------------------------------
Call-back functions from gen_server
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
Still proc left, remember it
-----------------------------------------------------------------
The release package is a RelName.tar.Z (.tar on non unix) file
with the following contents:
- <files> according to [lib()]
In the Dir, there exists a file called RELEASES, which contains
Note that RelDir is an absolute directory name !
Note that this function is not executed by a client
release_handler.
-----------------------------------------------------------------
Keeping this for backwards compatibility reasons with older
Clean release
-----------------------------------------------------------------
check_path at any master node.
If the path does not exist or is not a directory
-----------------------------------------------------------------
Get modules with brutal_purge
instructions, but that can be
soft purged
This will only happen if the upgrade includes
an emulator upgrade (and it is not a downgrade)
- then the new emulator must be started before
new code can be loaded.
Create a temporary release which includes new
emulator, kernel, stdlib and sasl - and old
versions of other applications.
Then uppgrade to the temporary release.
The rest of the upgrade will continue after the restart
In case there has been an emulator upgrade,
remove the temporary release
insert in the old config.
If no entry exists in the new config, then delete the entry (if it exists)
from the old config.
If entry exists in the new config, but not in the old config, then
add the entry.
Remove all files related to the temporary release
Rename a service and check that it succeeded
Either the emulator is restarted, in which case the old service
is to be removed and the new enabled, or the emulator is NOT restarted
in which case we try to rename the old service to the new name and try
to update heart's view of what service we are really running.
We probably do not need to replace services, just
rename.
The interfaces for doing this are
NOT published and may be subject to
change. Do NOT do this anywhere else!
Restart heart port program, this
function is only to be used here.
Read comments about these above...
Get the current release on NT
Edit up the services and set a reasonable heart
command
-----------------------------------------------------------------
Depending of if the release_handler is running in normal, client or
client with static emulator the new system version is made permanent
in different ways.
-----------------------------------------------------------------
Very unconditionally remove the service.
Note that the service could already have been removed when
making another release permanent.
Remove erts library, no more references to it
-----------------------------------------------------------------
It describes how to get to this release from previous releases,
and how to get from this release to previous releases.
We do not put any semantics into the version strings, i.e. we
is located in the directory of the latest version. Since we
-----------------------------------------------------------------
If a permanent rel is installed, it keeps its
permanent status (not changed to current).
The current becomes old though.
recursively remove file or directory
-----------------------------------------------------------------
Change current applications (specifically, update their version,
description and env.)
-----------------------------------------------------------------
-----------------------------------------------------------------
This function is dependent on the application functions and
the start script syntax.
-----------------------------------------------------------------
kernel is taken care of separately
other applications but kernel
This is rather icky... On a
non permanent service, the
actually that of an old service,
to make heart commands work...
-----------------------------------------------------------------
Set things up for restarting the new emulator. The actual
restart is performed by calling init:reboot() higher up.
-----------------------------------------------------------------
-----------------------------------------------------------------
When a new emulator shall be restarted, the current release
is written with status tmp_current. When the new emulator
is started, this function is called. The tmp_current release
gets status unpacked on disk, and current in memory. If a reboot
is made (due to a crash), the release is just unpacked. If a crash
release is changed to unpacked.
If the release is made permanent, this is written to disk.
-----------------------------------------------------------------
This is was a reboot due to a new emulator version. The
current release is a temporary internal release, which
must be removed. It is the "real new release" that is
set to unpacked on disk and current in memory.
-----------------------------------------------------------------
This functions consider if the release_handler is a client and
in that case performs the operations at all master nodes or at
none (in case of failure).
-----------------------------------------------------------------
Check that file exists at all masters.
Type == regular | directory
-----------------------------------------------------------------
by the user in another way, i.e. ignore this here.
-----------------------------------------------------------------
Old erl_tar.
We must never write 'current' to disk, since this will confuse
us after a node restart - since we would then have a permanent
release running, but state set to current for a non-running
release.
-----------------------------------------------------------------
Write the "RELEASES" file at all master nodes.
2. Save "RELEASES.change" at all nodes.
3. Update the "RELEASES.change" file at all nodes.
4. Move "RELEASES.change" to "RELEASES".
-----------------------------------------------------------------
-----------------------------------------------------------------
If an error occurs at a node, the total copy failed.
We do not have to cleanup in case of failure as this
copy_file is harmless.
-----------------------------------------------------------------
-----------------------------------------------------------------
Copy File to a list of files.
-----------------------------------------------------------------
-----------------------------------------------------------------
Copy each Src file to Dest file in the list of files.
-----------------------------------------------------------------
-----------------------------------------------------------------
Rename each Src file to Dest file in the list of files.
-----------------------------------------------------------------
-----------------------------------------------------------------
Remove a list of files. Ignore failure.
-----------------------------------------------------------------
-----------------------------------------------------------------
Ensure that the RELEASES file exists.
If not create an empty RELEASES file.
-----------------------------------------------------------------
-----------------------------------------------------------------
Make a directory, ignore failures (captured later).
-----------------------------------------------------------------
-----------------------------------------------------------------
Check that all masters are alive.
-----------------------------------------------------------------
-----------------------------------------------------------------
Evaluate {M,F,A} at all masters.
{M,F,A} is supposed to return ok. Otherwise at_all_masters
returns {error, {Master, Other}}.
-----------------------------------------------------------------
-----------------------------------------------------------------
Evaluate {M,F,A} at all masters until Master is found.
Ignore {M,F,A} return value.
-----------------------------------------------------------------
-----------------------------------------------------------------
consult the File at any master node.
not exist at any other node either.
-----------------------------------------------------------------
Ignore status of each delete !
-----------------------------------------------------------------
read the File at any master node.
not exist at any other node either.
-----------------------------------------------------------------
-----------------------------------------------------------------
Write start_erl.data.
-----------------------------------------------------------------
-----------------------------------------------------------------
master nodes.
2. Copy files at all nodes.
3. Remove backup files at all nodes.
-----------------------------------------------------------------
-----------------------------------------------------------------
Write erl.ini
the format of this file for some reason is changed, then Install.c must
also be updated (and probably some other c-files which read erl.ini)
-----------------------------------------------------------------
-----------------------------------------------------------------
Write the given file at all master nodes.
1. Save <File>.backup at all nodes.
2. Write <File>.change at all nodes.
4. Remove <File>.backup at all nodes.
-----------------------------------------------------------------
-----------------------------------------------------------------
Figure out which applications that have changed version between the
A different situation is when the same application version is used
in old and new release, but the path has changed. This is not
handled here - instead it must be explicitely indicated by the
'update_paths' option to release_handler:install_release/2 if the
code path shall be updated then.
-----------------------------------------------------------------
-----------------------------------------------------------------
Return a list of releases witch a specific status
----------------------------------------------------------------- | Copyright Ericsson AB 1996 - 2013 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(release_handler).
-behaviour(gen_server).
-include_lib("kernel/include/file.hrl").
-export([start_link/0,
create_RELEASES/1, create_RELEASES/2, create_RELEASES/4,
unpack_release/1,
check_install_release/1, check_install_release/2,
install_release/1, install_release/2, new_emulator_upgrade/2,
remove_release/1, which_releases/0, which_releases/1,
make_permanent/1, reboot_old_release/1,
set_unpacked/2, set_removed/1, install_file/2]).
-export([upgrade_app/2, downgrade_app/2, downgrade_app/3,
upgrade_script/2, downgrade_script/3,
eval_appup_script/4]).
-export([init/1, handle_call/3, handle_info/2, terminate/2,
handle_cast/2, code_change/3]).
-export([do_write_release/3, do_copy_file/2, do_copy_files/2,
do_copy_files/1, do_rename_files/1, do_remove_files/1,
remove_file/1, do_write_file/2, do_write_file/3,
do_ensure_RELEASES/1]).
-record(state, {unpurged = [],
root,
rel_dir,
releases,
timer,
start_prg,
masters = false,
client_dir = false,
static_emulator = false,
pre_sync_nodes = []}).
status action next_status
libs = [ { Lib , Vsn , Dir } ]
-record(release, {name, vsn, erts_vsn, libs = [], status}).
-define(timeout, 10000).
-define(tmp_vsn(__BaseVsn__), "__new_emulator__"++__BaseVsn__).
--- start ( default ; { sasl , start_prg } overrides
| |- start_erl ( reads start_erl.data )
|- clients --- -- start
| | -- start
| | | _ -- releases -- start_erl.data
| | _ < Vsn1.tar . Z >
| | | _ relup
The paramater is { sasl , start_prg } = File
{ sasl , } overrides both .
start_link() ->
gen_server:start_link({local, release_handler}, ?MODULE, [], []).
: is the name of the package file
directories . Checks that all required libs and erts
unpack_release(ReleaseName) ->
call({unpack_release, ReleaseName}).
Purpose : Checks the relup script for the specified version .
Returns : { ok , FromVsn , } | { error , Reason }
{ bad_relup_file , RelFile } |
{ no_such_release ,
check_install_release(Vsn) ->
check_install_release(Vsn, []).
check_install_release(Vsn, Opts) ->
case check_check_install_options(Opts, false) of
{ok,Purge} ->
call({check_install_release, Vsn, Purge});
Error ->
Error
end.
check_check_install_options([purge|Opts], _) ->
check_check_install_options(Opts, true);
check_check_install_options([Illegal|_],_Purge) ->
{error,{illegal_option,Illegal}};
check_check_install_options([],Purge) ->
{ok,Purge}.
Purpose : Executes the relup script for the specified version .
Returns : { ok , FromVsn , } |
{ continue_after_restart , FromVsn , } |
{ bad_relup_file , RelFile } |
{ no_such_release ,
install_release(Vsn) ->
call({install_release, Vsn, restart, []}).
install_release(Vsn, Opt) ->
case check_install_options(Opt, restart, []) of
{ok, ErrorAction, InstallOpt} ->
call({install_release, Vsn, ErrorAction, InstallOpt});
Error ->
Error
end.
check_install_options([Opt | Opts], ErrAct, InstOpts) ->
case install_option(Opt) of
{error_action, EAct} ->
check_install_options(Opts, EAct, InstOpts);
true ->
check_install_options(Opts, ErrAct, [Opt | InstOpts]);
false ->
{error, {illegal_option, Opt}}
end;
check_install_options([], ErrAct, InstOpts) ->
{ok, ErrAct, InstOpts}.
install_option(Opt = {error_action, reboot}) -> Opt;
install_option(Opt = {error_action, restart}) -> Opt;
install_option({code_change_timeout, TimeOut}) ->
check_timeout(TimeOut);
install_option({suspend_timeout, TimeOut}) ->
check_timeout(TimeOut);
install_option({update_paths, Bool}) when Bool==true; Bool==false ->
true;
install_option(_Opt) -> false.
check_timeout(infinity) -> true;
check_timeout(Int) when is_integer(Int), Int > 0 -> true;
check_timeout(_Else) -> false.
new_emulator_upgrade(Vsn, Opts) ->
Result = call({install_release, Vsn, reboot, Opts}),
error_logger:info_msg(
"~w:install_release(~p,~p) completed after node restart "
"with new emulator version~nResult: ~p~n",[?MODULE,Vsn,Opts,Result]),
Result.
{ no_such_release ,
make_permanent(Vsn) ->
call({make_permanent, Vsn}).
reboot_old_release(Vsn) ->
call({reboot_old_release, Vsn}).
remove_release(Vsn) ->
call({remove_release, Vsn}).
: RelFile = string ( )
Libs = [ { Lib , , } ]
Lib = = string ( )
The release_handler remebers where all libs are located .
those libs are removed as well ( if no other releases uses
set_unpacked(RelFile, LibDirs) ->
call({set_unpacked, RelFile, LibDirs}).
: Vsn = string ( )
set_removed(Vsn) ->
call({set_removed, Vsn}).
sys.config and relup files if they are not part of a
standard release package . May be used to
install_file(Vsn, File) when is_list(File) ->
call({install_file, File, Vsn}).
Returns : [ { Name , , [ LibName ] , Status } ]
which_releases() ->
call(which_releases).
Returns : [ { Name , , [ LibName ] , Status } ]
which_releases(Status) ->
Releases = which_releases(),
get_releases_with_status(Releases, Status, []).
check_script(Script , LibDirs ) - > ok | { error , Reason }
check_script(Script, LibDirs) ->
release_handler_1:check_script(Script, LibDirs).
eval_script(Script , Apps , LibDirs , NewLibs , Opts ) - >
{ ok , } |
{ ' EXIT ' , Reason }
net_kernel : monitor_nodes(true ) before calling this function .
LibDirs is a list of all applications , while NewLibs is a list of
eval_script(Script, Apps, LibDirs, NewLibs, Opts) ->
catch release_handler_1:eval_script(Script, Apps, LibDirs, NewLibs, Opts).
Func : create_RELEASES(Root , RelFile , LibDirs ) - > ok | { error , Reason }
create_RELEASES([Root, RelFile | LibDirs]) ->
create_RELEASES(Root, filename:join(Root, "releases"), RelFile, LibDirs).
create_RELEASES(Root, RelFile) ->
create_RELEASES(Root, filename:join(Root, "releases"), RelFile, []).
create_RELEASES(Root, RelDir, RelFile, LibDirs) ->
case catch check_rel(Root, RelFile, LibDirs, false) of
{error, Reason } ->
{error, Reason};
Rel ->
Rel2 = Rel#release{status = permanent},
catch write_releases(RelDir, [Rel2], false)
end.
Func : upgrade_app(App , ) - > { ok , }
Purpose : Upgrade to the version in according to an appup file
upgrade_app(App, NewDir) ->
try upgrade_script(App, NewDir) of
{ok, NewVsn, Script} ->
eval_appup_script(App, NewVsn, NewDir, Script)
catch
throw:Reason ->
{error, Reason}
end.
downgrade_app(App , Vsn , Dir ) - > { ok , }
Vsn = string ( ) , may be omitted if = = App - Vsn
Purpose : Downgrade from the version in according to an appup file
downgrade_app(App, OldDir) ->
case string:tokens(filename:basename(OldDir), "-") of
[_AppS, OldVsn] ->
downgrade_app(App, OldVsn, OldDir);
_ ->
{error, {unknown_version, App}}
end.
downgrade_app(App, OldVsn, OldDir) ->
try downgrade_script(App, OldVsn, OldDir) of
{ok, Script} ->
eval_appup_script(App, OldVsn, OldDir, Script)
catch
throw:Reason ->
{error, Reason}
end.
upgrade_script(App, NewDir) ->
OldVsn = ensure_running(App),
OldDir = code:lib_dir(App),
{NewVsn, Script} = find_script(App, NewDir, OldVsn, up),
OldAppl = read_app(App, OldVsn, OldDir),
NewAppl = read_app(App, NewVsn, NewDir),
case systools_rc:translate_scripts(up,
[Script],[NewAppl],[OldAppl]) of
{ok, LowLevelScript} ->
{ok, NewVsn, LowLevelScript};
{error, _SystoolsRC, Reason} ->
throw(Reason)
end.
downgrade_script(App, OldVsn, OldDir) ->
NewVsn = ensure_running(App),
NewDir = code:lib_dir(App),
{NewVsn, Script} = find_script(App, NewDir, OldVsn, down),
OldAppl = read_app(App, OldVsn, OldDir),
NewAppl = read_app(App, NewVsn, NewDir),
case systools_rc:translate_scripts(dn,
[Script],[OldAppl],[NewAppl]) of
{ok, LowLevelScript} ->
{ok, LowLevelScript};
{error, _SystoolsRC, Reason} ->
throw(Reason)
end.
eval_appup_script(App, ToVsn, ToDir, Script) ->
EnvBefore = application_controller:prep_config_change(),
AppSpecL = read_appspec(App, ToDir),
Res = release_handler_1:eval_script(Script,
[ AppSpec ]
[{App, ToVsn, ToDir}],
[{App, ToVsn, ToDir}],
case Res of
{ok, _Unpurged} ->
application_controller:change_application_data(AppSpecL,[]),
application_controller:config_change(EnvBefore);
_Res ->
ignore
end,
Res.
ensure_running(App) ->
case lists:keysearch(App, 1, application:which_applications()) of
{value, {_App, _Descr, Vsn}} ->
Vsn;
false ->
throw({app_not_running, App})
end.
find_script(App, Dir, OldVsn, UpOrDown) ->
Appup = filename:join([Dir, "ebin", atom_to_list(App)++".appup"]),
case file:consult(Appup) of
{ok, [{NewVsn, UpFromScripts, DownToScripts}]} ->
Scripts = case UpOrDown of
up -> UpFromScripts;
down -> DownToScripts
end,
case systools_relup:appup_search_for_version(OldVsn,Scripts) of
{ok,Script} ->
{NewVsn,Script};
error ->
throw({version_not_in_appup, OldVsn})
end;
{error, enoent} ->
throw(no_appup_found);
{error, Reason} ->
throw(Reason)
end.
read_app(App, Vsn, Dir) ->
AppS = atom_to_list(App),
Path = [filename:join(Dir, "ebin")],
case systools_make:read_application(AppS, Vsn, Path, []) of
{ok, Appl} ->
Appl;
{error, {not_found, _AppFile}} ->
throw({no_app_found, Vsn, Dir});
{error, Reason} ->
throw(Reason)
end.
read_appspec(App, Dir) ->
AppS = atom_to_list(App),
Path = [filename:join(Dir, "ebin")],
case file:path_consult(Path, AppS++".app") of
{ok, AppSpecL, _File} ->
AppSpecL;
{error, Reason} ->
throw(Reason)
end.
call(Req) ->
gen_server:call(release_handler, Req, infinity).
init([]) ->
{ok, [[Root]]} = init:get_argument(root),
{CliDir, Masters} = is_client(),
ReleaseDir =
case application:get_env(sasl, releases_dir) of
undefined ->
case os:getenv("RELDIR") of
false ->
if
CliDir == false ->
filename:join([Root, "releases"]);
true ->
filename:join([CliDir, "releases"])
end;
RELDIR ->
RELDIR
end;
{ok, Dir} ->
Dir
end,
Releases =
case consult(filename:join(ReleaseDir, "RELEASES"), Masters) of
{ok, [Term]} ->
transform_release(ReleaseDir, Term, Masters);
_ ->
{Name, Vsn} = init:script_id(),
[#release{name = Name, vsn = Vsn, status = permanent}]
end,
StartPrg =
case application:get_env(start_prg) of
{ok, Found2} when is_list(Found2) ->
{do_check, Found2};
_ ->
{no_check, filename:join([Root, "bin", "start"])}
end,
Static =
case application:get_env(static_emulator) of
{ok, SFlag} when is_atom(SFlag) -> SFlag;
_ -> false
end,
{ok, #state{root = Root, rel_dir = ReleaseDir, releases = Releases,
start_prg = StartPrg, masters = Masters,
client_dir = CliDir, static_emulator = Static}}.
handle_call({unpack_release, ReleaseName}, _From, S)
when S#state.masters == false ->
case catch do_unpack_release(S#state.root, S#state.rel_dir,
ReleaseName, S#state.releases) of
{ok, NewReleases, Vsn} ->
{reply, {ok, Vsn}, S#state{releases = NewReleases}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({unpack_release, _ReleaseName}, _From, S) ->
{reply, {error, client_node}, S};
handle_call({check_install_release, Vsn, Purge}, _From, S) ->
case catch do_check_install_release(S#state.rel_dir,
Vsn,
S#state.releases,
S#state.masters,
Purge) of
{ok, CurrentVsn, Descr} ->
{reply, {ok, CurrentVsn, Descr}, S};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({install_release, Vsn, ErrorAction, Opts}, From, S) ->
NS = resend_sync_nodes(S),
case catch do_install_release(S, Vsn, Opts) of
{ok, NewReleases, [], CurrentVsn, Descr} ->
{reply, {ok, CurrentVsn, Descr}, NS#state{releases=NewReleases}};
{ok, NewReleases, Unpurged, CurrentVsn, Descr} ->
Timer =
case S#state.timer of
undefined ->
{ok, Ref} = timer:send_interval(?timeout, timeout),
Ref;
Ref -> Ref
end,
NewS = NS#state{releases = NewReleases, unpurged = Unpurged,
timer = Timer},
{reply, {ok, CurrentVsn, Descr}, NewS};
{error, Reason} ->
{reply, {error, Reason}, NS};
{restart_emulator, CurrentVsn, Descr} ->
gen_server:reply(From, {ok, CurrentVsn, Descr}),
init:reboot(),
{noreply, NS};
{restart_new_emulator, CurrentVsn, Descr} ->
gen_server:reply(From, {continue_after_restart, CurrentVsn, Descr}),
init:reboot(),
{noreply, NS};
{'EXIT', Reason} ->
io:format("release_handler:"
"install_release(Vsn=~p Opts=~p) failed, "
"Reason=~p~n", [Vsn, Opts, Reason]),
gen_server:reply(From, {error, Reason}),
case ErrorAction of
restart ->
init:restart();
reboot ->
init:reboot()
end,
{noreply, NS}
end;
handle_call({make_permanent, Vsn}, _From, S) ->
case catch do_make_permanent(S, Vsn) of
{ok, Releases, Unpurged} ->
{reply, ok, S#state{releases = Releases, unpurged = Unpurged}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({reboot_old_release, Vsn}, From, S) ->
case catch do_reboot_old_release(S, Vsn) of
ok ->
gen_server:reply(From, ok),
init:reboot(),
{noreply, S};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({remove_release, Vsn}, _From, S)
when S#state.masters == false ->
case catch do_remove_release(S#state.root, S#state.rel_dir,
Vsn, S#state.releases) of
{ok, NewReleases} ->
{reply, ok, S#state{releases = NewReleases}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({remove_release, _Vsn}, _From, S) ->
{reply, {error, client_node}, S};
handle_call({set_unpacked, RelFile, LibDirs}, _From, S) ->
Root = S#state.root,
case catch do_set_unpacked(Root, S#state.rel_dir, RelFile,
LibDirs, S#state.releases,
S#state.masters) of
{ok, NewReleases, Vsn} ->
{reply, {ok, Vsn}, S#state{releases = NewReleases}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({set_removed, Vsn}, _From, S) ->
case catch do_set_removed(S#state.rel_dir, Vsn,
S#state.releases,
S#state.masters) of
{ok, NewReleases} ->
{reply, ok, S#state{releases = NewReleases}};
{error, Reason} ->
{reply, {error, Reason}, S};
{'EXIT', Reason} ->
{reply, {error, Reason}, S}
end;
handle_call({install_file, File, Vsn}, _From, S) ->
Reply =
case lists:keysearch(Vsn, #release.vsn, S#state.releases) of
{value, _} ->
Dir = filename:join([S#state.rel_dir, Vsn]),
catch copy_file(File, Dir, S#state.masters);
_ ->
{error, {no_such_release, Vsn}}
end,
{reply, Reply, S};
handle_call(which_releases, _From, S) ->
Reply = lists:map(fun(#release{name = Name, vsn = Vsn, libs = Libs,
status = Status}) ->
{Name, Vsn, mk_lib_name(Libs), Status}
end, S#state.releases),
{reply, Reply, S}.
mk_lib_name([{LibName, Vsn, _Dir} | T]) ->
[lists:concat([LibName, "-", Vsn]) | mk_lib_name(T)];
mk_lib_name([]) -> [].
handle_info(timeout, S) ->
case soft_purge(S#state.unpurged) of
[] ->
_ = timer:cancel(S#state.timer),
{noreply, S#state{unpurged = [], timer = undefined}};
Unpurged ->
{noreply, S#state{unpurged = Unpurged}}
end;
handle_info({sync_nodes, Id, Node}, S) ->
PSN = S#state.pre_sync_nodes,
{noreply, S#state{pre_sync_nodes = [{sync_nodes, Id, Node} | PSN]}};
handle_info(Msg, State) ->
error_logger:info_msg("release_handler: got unknown message: ~p~n", [Msg]),
{noreply, State}.
terminate(_Reason, _State) ->
ok.
handle_cast(_Msg, State) ->
{noreply, State}.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
is_client() ->
case application:get_env(masters) of
{ok, Masters} ->
Alive = is_alive(),
case atom_list(Masters) of
true when Alive == true ->
case application:get_env(client_directory) of
{ok, ClientDir} ->
case int_list(ClientDir) of
true ->
{ClientDir, Masters};
_ ->
exit({bad_parameter, client_directory,
ClientDir})
end;
_ ->
{false, false}
end;
_ ->
exit({bad_parameter, masters, Masters})
end;
_ ->
{false, false}
end.
atom_list([A|T]) when is_atom(A) -> atom_list(T);
atom_list([]) -> true;
atom_list(_) -> false.
int_list([I|T]) when is_integer(I) -> int_list(T);
int_list([]) -> true;
int_list(_) -> false.
resend_sync_nodes(S) ->
lists:foreach(fun(Msg) -> self() ! Msg end, S#state.pre_sync_nodes),
S#state{pre_sync_nodes = []}.
soft_purge(Unpurged) ->
lists:filter(fun({Mod, _PostPurgeMethod}) ->
case code:soft_purge(Mod) of
No proc left , do n't remember
end
end,
Unpurged).
brutal_purge(Unpurged) ->
lists:filter(fun({Mod, brutal_purge}) -> code:purge(Mod), false;
(_) -> true
end,
Unpurged).
- RelName.rel = = { release , { Name , , { erts , EVsn } , [ lib ( ) ] }
- lib ( ) = { LibName , }
a [ { Vsn , { erts , EVsn } , { libs , [ { LibName , , } ] } } ] .
do_unpack_release(Root, RelDir, ReleaseName, Releases) ->
Tar = filename:join(RelDir, ReleaseName ++ ".tar.gz"),
do_check_file(Tar, regular),
Rel = ReleaseName ++ ".rel",
extract_rel_file(filename:join("releases", Rel), Tar, Root),
RelFile = filename:join(RelDir, Rel),
Release = check_rel(Root, RelFile, false),
#release{vsn = Vsn} = Release,
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, _} -> throw({error, {existing_release, Vsn}});
_ -> ok
end,
extract_tar(Root, Tar),
NewReleases = [Release#release{status = unpacked} | Releases],
write_releases(RelDir, NewReleases, false),
systools : make_tar , where there is no copy of the .rel file in
the releases/<vsn > dir . See OTP-9746 .
Dir = filename:join([RelDir, Vsn]),
copy_file(RelFile, Dir, false),
_ = file:delete(Tar),
_ = file:delete(RelFile),
{ok, NewReleases, Vsn}.
check_rel(Root, RelFile, Masters) ->
check_rel(Root, RelFile, [], Masters).
check_rel(Root, RelFile, LibDirs, Masters) ->
case consult(RelFile, Masters) of
{ok, [RelData]} ->
check_rel_data(RelData, Root, LibDirs, Masters);
{ok, _} ->
throw({error, {bad_rel_file, RelFile}});
{error, Reason} when is_tuple(Reason) ->
throw({error, {bad_rel_file, RelFile}});
FileError is posix atom | no_master
throw({error, {FileError, RelFile}})
end.
check_rel_data({release, {Name, Vsn}, {erts, EVsn}, Libs}, Root, LibDirs,
Masters) ->
Libs2 =
lists:map(fun(LibSpec) ->
Lib = element(1, LibSpec),
LibVsn = element(2, LibSpec),
LibName = lists:concat([Lib, "-", LibVsn]),
LibDir =
case lists:keysearch(Lib, 1, LibDirs) of
{value, {_Lib, _Vsn, Dir}} ->
Path = filename:join(Dir,LibName),
check_path(Path, Masters),
Path;
_ ->
filename:join([Root, "lib", LibName])
end,
{Lib, LibVsn, LibDir}
end,
Libs),
#release{name = Name, vsn = Vsn, erts_vsn = EVsn,
libs = Libs2, status = unpacking};
check_rel_data(RelData, _Root, _LibDirs, _Masters) ->
throw({error, {bad_rel_data, RelData}}).
check_path(Path) ->
check_path_response(Path, file:read_file_info(Path)).
check_path(Path, false) -> check_path(Path);
check_path(Path, Masters) -> check_path_master(Masters, Path).
at one node it should not exist at any other node either .
check_path_master([Master|Ms], Path) ->
case rpc:call(Master, file, read_file_info, [Path]) of
{badrpc, _} -> consult_master(Ms, Path);
Res -> check_path_response(Path, Res)
end;
check_path_master([], _Path) ->
{error, no_master}.
check_path_response(_Path, {ok, Info}) when Info#file_info.type==directory ->
ok;
check_path_response(Path, {ok, _Info}) ->
throw({error, {not_a_directory, Path}});
check_path_response(Path, {error, _Reason}) ->
throw({error, {no_such_directory, Path}}).
do_check_install_release(RelDir, Vsn, Releases, Masters, Purge) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{status = current}} ->
{error, {already_installed, Vsn}};
{value, Release} ->
LatestRelease = get_latest_release(Releases),
VsnDir = filename:join([RelDir, Vsn]),
check_file(filename:join(VsnDir, "start.boot"), regular, Masters),
IsRelup = check_opt_file(filename:join(VsnDir, "relup"), regular, Masters),
check_opt_file(filename:join(VsnDir, "sys.config"), regular, Masters),
Check that all required libs are present
Libs = Release#release.libs,
lists:foreach(fun({_Lib, _LibVsn, LibDir}) ->
check_file(LibDir, directory, Masters),
Ebin = filename:join(LibDir, "ebin"),
check_file(Ebin, directory, Masters)
end,
Libs),
if
IsRelup ->
case get_rh_script(LatestRelease, Release, RelDir, Masters) of
{ok, {CurrentVsn, Descr, Script}} ->
case catch check_script(Script, Libs) of
{ok,SoftPurgeMods} when Purge=:=true ->
{ok,BrutalPurgeMods} =
release_handler_1:check_old_processes(
Script,brutal_purge),
lists:foreach(
fun(Mod) ->
catch erlang:purge_module(Mod)
end,
SoftPurgeMods ++ BrutalPurgeMods),
{ok, CurrentVsn, Descr};
{ok,_} ->
{ok, CurrentVsn, Descr};
Else ->
Else
end;
Error ->
Error
end;
true ->
{ok, Vsn, ""}
end;
_ ->
{error, {no_such_release, Vsn}}
end.
do_install_release(#state{start_prg = StartPrg,
root = RootDir,
rel_dir = RelDir, releases = Releases,
masters = Masters,
static_emulator = Static},
Vsn, Opts) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{status = current}} ->
{error, {already_installed, Vsn}};
{value, Release} ->
LatestRelease = get_latest_release(Releases),
case get_rh_script(LatestRelease, Release, RelDir, Masters) of
{ok, {_CurrentVsn, _Descr, [restart_new_emulator|_Script]}}
when Static == true ->
throw(static_emulator);
{ok, {CurrentVsn, Descr, [restart_new_emulator|_Script]}} ->
{TmpVsn,TmpRelease} =
new_emulator_make_tmp_release(LatestRelease,Release,
RelDir,Opts,Masters),
NReleases = [TmpRelease|Releases],
prepare_restart_new_emulator(StartPrg, RootDir,
RelDir, TmpVsn, TmpRelease,
NReleases, Masters),
{restart_new_emulator, CurrentVsn, Descr};
{ok, {CurrentVsn, Descr, Script}} ->
NReleases =
new_emulator_rm_tmp_release(
LatestRelease#release.vsn,
LatestRelease#release.erts_vsn,
Vsn,RelDir,Releases,Masters),
Then execute the relup script
mon_nodes(true),
EnvBefore = application_controller:prep_config_change(),
Apps = change_appl_data(RelDir, Release, Masters),
LibDirs = Release#release.libs,
NewLibs = get_new_libs(LatestRelease#release.libs,
Release#release.libs),
case eval_script(Script, Apps, LibDirs, NewLibs, Opts) of
{ok, Unpurged} ->
application_controller:config_change(EnvBefore),
mon_nodes(false),
NReleases1 = set_status(Vsn, current, NReleases),
{ok, NReleases1, Unpurged, CurrentVsn, Descr};
restart_emulator when Static == true ->
throw(static_emulator);
restart_emulator ->
mon_nodes(false),
prepare_restart_new_emulator(StartPrg, RootDir,
RelDir, Vsn, Release,
NReleases, Masters),
{restart_emulator, CurrentVsn, Descr};
Else ->
application_controller:config_change(EnvBefore),
mon_nodes(false),
Else
end;
Error ->
Error
end;
_ ->
{error, {no_such_release, Vsn}}
end.
new_emulator_make_tmp_release(CurrentRelease,ToRelease,RelDir,Opts,Masters) ->
CurrentVsn = CurrentRelease#release.vsn,
ToVsn = ToRelease#release.vsn,
TmpVsn = ?tmp_vsn(CurrentVsn),
case get_base_libs(ToRelease#release.libs) of
{ok,{Kernel,Stdlib,Sasl}=BaseLibs,_} ->
case get_base_libs(ToRelease#release.libs) of
{ok,_,RestLibs} ->
TmpErtsVsn = ToRelease#release.erts_vsn,
TmpLibs = [Kernel,Stdlib,Sasl|RestLibs],
TmpRelease = CurrentRelease#release{vsn=TmpVsn,
erts_vsn=TmpErtsVsn,
libs = TmpLibs,
status = unpacked},
new_emulator_make_hybrid_boot(CurrentVsn,ToVsn,TmpVsn,
BaseLibs,RelDir,Opts,Masters),
new_emulator_make_hybrid_config(CurrentVsn,ToVsn,TmpVsn,
RelDir,Masters),
{TmpVsn,TmpRelease};
{error,{missing,Missing}} ->
throw({error,{missing_base_app,CurrentVsn,Missing}})
end;
{error,{missing,Missing}} ->
throw({error,{missing_base_app,ToVsn,Missing}})
end.
Get kernel , stdlib and sasl libs ,
and also return the rest of the libs as a list .
Return error if any of kernel , stdlib or sasl does not exist .
get_base_libs(Libs) ->
get_base_libs(Libs,undefined,undefined,undefined,[]).
get_base_libs([{kernel,_,_}=Kernel|Libs],undefined,Stdlib,Sasl,Rest) ->
get_base_libs(Libs,Kernel,Stdlib,Sasl,Rest);
get_base_libs([{stdlib,_,_}=Stdlib|Libs],Kernel,undefined,Sasl,Rest) ->
get_base_libs(Libs,Kernel,Stdlib,Sasl,Rest);
get_base_libs([{sasl,_,_}=Sasl|Libs],Kernel,Stdlib,undefined,Rest) ->
get_base_libs(Libs,Kernel,Stdlib,Sasl,Rest);
get_base_libs([Lib|Libs],Kernel,Stdlib,Sasl,Rest) ->
get_base_libs(Libs,Kernel,Stdlib,Sasl,[Lib|Rest]);
get_base_libs([],undefined,_Stdlib,_Sasl,_Rest) ->
{error,{missing,kernel}};
get_base_libs([],_Kernel,undefined,_Sasl,_Rest) ->
{error,{missing,stdlib}};
get_base_libs([],_Kernel,_Stdlib,undefined,_Rest) ->
{error,{missing,sasl}};
get_base_libs([],Kernel,Stdlib,Sasl,Rest) ->
{ok,{Kernel,Stdlib,Sasl},lists:reverse(Rest)}.
new_emulator_make_hybrid_boot(CurrentVsn,ToVsn,TmpVsn,BaseLibs,RelDir,Opts,Masters) ->
FromBootFile = filename:join([RelDir,CurrentVsn,"start.boot"]),
ToBootFile = filename:join([RelDir,ToVsn,"start.boot"]),
TmpBootFile = filename:join([RelDir,TmpVsn,"start.boot"]),
ensure_dir(TmpBootFile,Masters),
Args = [ToVsn,Opts],
{ok,FromBoot} = read_file(FromBootFile,Masters),
{ok,ToBoot} = read_file(ToBootFile,Masters),
{{_,_,KernelPath},{_,_,StdlibPath},{_,_,SaslPath}} = BaseLibs,
Paths = {filename:join(KernelPath,"ebin"),
filename:join(StdlibPath,"ebin"),
filename:join(SaslPath,"ebin")},
case systools_make:make_hybrid_boot(TmpVsn,FromBoot,ToBoot,Paths,Args) of
{ok,TmpBoot} ->
write_file(TmpBootFile,TmpBoot,Masters);
{error,Reason} ->
throw({error,{could_not_create_hybrid_boot,Reason}})
end.
new_emulator_make_hybrid_config(CurrentVsn,ToVsn,TmpVsn,RelDir,Masters) ->
FromFile = filename:join([RelDir,CurrentVsn,"sys.config"]),
ToFile = filename:join([RelDir,ToVsn,"sys.config"]),
TmpFile = filename:join([RelDir,TmpVsn,"sys.config"]),
FromConfig =
case consult(FromFile,Masters) of
{ok,[FC]} ->
FC;
{error,Error1} ->
io:format("Warning: ~w can not read ~p: ~p~n",
[?MODULE,FromFile,Error1]),
[]
end,
[Kernel,Stdlib,Sasl] =
case consult(ToFile,Masters) of
{ok,[ToConfig]} ->
[lists:keyfind(App,1,ToConfig) || App <- [kernel,stdlib,sasl]];
{error,Error2} ->
io:format("Warning: ~w can not read ~p: ~p~n",
[?MODULE,ToFile,Error2]),
[false,false,false]
end,
Config1 = replace_config(kernel,FromConfig,Kernel),
Config2 = replace_config(stdlib,Config1,Stdlib),
Config3 = replace_config(sasl,Config2,Sasl),
ConfigStr = io_lib:format("~p.~n",[Config3]),
write_file(TmpFile,ConfigStr,Masters).
Take the configuration for application App from the new config and
replace_config(App,Config,false) ->
lists:keydelete(App,1,Config);
replace_config(App,Config,AppConfig) ->
lists:keystore(App,1,Config,AppConfig).
new_emulator_rm_tmp_release(?tmp_vsn(_)=TmpVsn,EVsn,NewVsn,
RelDir,Releases,Masters) ->
case os:type() of
{win32, nt} ->
rename_tmp_service(EVsn,TmpVsn,NewVsn);
_ ->
ok
end,
remove_dir(filename:join(RelDir,TmpVsn),Masters),
lists:keydelete(TmpVsn,#release.vsn,Releases);
new_emulator_rm_tmp_release(_,_,_,_,Releases,_) ->
Releases.
Rename the tempoarary service ( for erts ugprade ) to the real ToVsn
rename_tmp_service(EVsn,TmpVsn,NewVsn) ->
FromName = hd(string:tokens(atom_to_list(node()),"@")) ++ "_" ++ TmpVsn,
ToName = hd(string:tokens(atom_to_list(node()),"@")) ++ "_" ++ NewVsn,
case erlsrv:get_service(EVsn,ToName) of
{error, _Error} ->
ok;
_Data ->
{ok,_} = erlsrv:remove_service(ToName),
ok
end,
rename_service(EVsn,FromName,ToName).
rename_service(EVsn,FromName,ToName) ->
case erlsrv:rename_service(EVsn,FromName,ToName) of
{ok,_} ->
case erlsrv:get_service(EVsn,ToName) of
{error,Error1} ->
throw({error,Error1});
_Data2 ->
ok
end;
Error2 ->
throw({error,{service_rename_failed, Error2}})
end.
This code chunk updates the services in one of two ways ,
do_make_services_permanent(PermanentVsn,Vsn, PermanentEVsn, EVsn) ->
PermName = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ PermanentVsn,
Name = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ Vsn,
case erlsrv:get_service(EVsn,Name) of
{error, _Error} ->
case os:getenv("ERLSRV_SERVICE_NAME") == PermName of
true ->
rename_service(EVsn,PermName,Name),
os:putenv("ERLSRV_SERVICE_NAME", Name),
heart:cycle();
false ->
throw({error,service_name_missmatch})
end;
Data ->
UpdData = erlsrv:new_service(Name, Data, []),
case erlsrv:store_service(EVsn,UpdData) of
ok ->
{ok,_} = erlsrv:disable_service(PermanentEVsn, PermName),
{ok,_} = erlsrv:enable_service(EVsn, Name),
{ok,_} = erlsrv:remove_service(PermName),
os:putenv("ERLSRV_SERVICE_NAME", Name),
ok = heart:cycle();
Error4 ->
throw(Error4)
end
end.
do_make_permanent(#state{releases = Releases,
rel_dir = RelDir, unpurged = Unpurged,
masters = Masters,
static_emulator = Static},
Vsn) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{erts_vsn = EVsn, status = Status}}
when Status /= unpacked, Status /= old, Status /= permanent ->
Dir = filename:join([RelDir, Vsn]),
Sys =
case catch check_file(filename:join(Dir, "sys.config"),
regular, Masters) of
ok -> filename:join(Dir, "sys");
_ -> false
end,
Boot = filename:join(Dir, "start.boot"),
check_file(Boot, regular, Masters),
set_permanent_files(RelDir, EVsn, Vsn, Masters, Static),
NewReleases = set_status(Vsn, permanent, Releases),
write_releases(RelDir, NewReleases, Masters),
case os:type() of
{win32, nt} ->
{value, PermanentRelease} =
lists:keysearch(permanent, #release.status,
Releases),
PermanentVsn = PermanentRelease#release.vsn,
PermanentEVsn = PermanentRelease#release.erts_vsn,
case catch do_make_services_permanent(PermanentVsn,
Vsn,
PermanentEVsn,
EVsn) of
{error,Reason} ->
throw({error,{service_update_failed, Reason}});
_ ->
ok
end;
_ ->
ok
end,
ok = init:make_permanent(filename:join(Dir, "start"), Sys),
{ok, NewReleases, brutal_purge(Unpurged)};
{value, #release{status = permanent}} ->
{ok, Releases, Unpurged};
{value, #release{status = Status}} ->
{error, {bad_status, Status}};
false ->
{error, {no_such_release, Vsn}}
end.
do_back_service(OldVersion, CurrentVersion,OldEVsn,CurrentEVsn) ->
NN = hd(string:tokens(atom_to_list(node()),"@")),
OldName = NN ++ "_" ++ OldVersion,
CurrentName = NN ++ "_" ++ CurrentVersion,
UpdData = case erlsrv:get_service(CurrentEVsn,CurrentName) of
{error, Error} ->
throw({error,Error});
Data ->
erlsrv:new_service(OldName, Data, [])
end,
_ = case erlsrv:store_service(OldEVsn,UpdData) of
ok ->
{ok,_} = erlsrv:disable_service(CurrentEVsn,CurrentName),
{ok,_} = erlsrv:enable_service(OldEVsn,OldName);
Error2 ->
throw(Error2)
end,
OldErlSrv = filename:nativename(erlsrv:erlsrv(OldEVsn)),
CurrentErlSrv = filename:nativename(erlsrv:erlsrv(CurrentEVsn)),
case heart:set_cmd(CurrentErlSrv ++ " remove " ++ CurrentName ++
" & " ++ OldErlSrv ++ " start " ++ OldName) of
ok ->
ok;
Error3 ->
throw({error, {'heart:set_cmd() error', Error3}})
end.
do_reboot_old_release(#state{releases = Releases,
rel_dir = RelDir, masters = Masters,
static_emulator = Static},
Vsn) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{erts_vsn = EVsn, status = old}} ->
CurrentRunning = case os:type() of
{win32,nt} ->
case lists:keysearch(permanent,
#release.status,
Releases) of
false ->
lists:keysearch(current,
#release.status,
Releases);
{value,CR} ->
CR
end;
_ ->
false
end,
set_permanent_files(RelDir, EVsn, Vsn, Masters, Static),
NewReleases = set_status(Vsn, permanent, Releases),
write_releases(RelDir, NewReleases, Masters),
case os:type() of
{win32,nt} ->
do_back_service(Vsn,CurrentRunning#release.vsn,EVsn,
CurrentRunning#release.erts_vsn);
_ ->
ok
end,
ok;
{value, #release{status = Status}} ->
{error, {bad_status, Status}};
false ->
{error, {no_such_release, Vsn}}
end.
set_permanent_files(RelDir, EVsn, Vsn, false, _) ->
write_start(filename:join([RelDir, "start_erl.data"]),
EVsn ++ " " ++ Vsn,
false);
set_permanent_files(RelDir, EVsn, Vsn, Masters, false) ->
write_start(filename:join([RelDir, "start_erl.data"]),
EVsn ++ " " ++ Vsn,
Masters);
set_permanent_files(RelDir, _EVsn, Vsn, Masters, _Static) ->
VsnDir = filename:join([RelDir, Vsn]),
set_static_files(VsnDir, RelDir, Masters).
do_remove_service(Vsn) ->
ServiceName = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ Vsn,
case erlsrv:get_service(ServiceName) of
{error, _Error} ->
ok;
_Data ->
{ok,_} = erlsrv:remove_service(ServiceName),
ok
end.
do_remove_release(Root, RelDir, Vsn, Releases) ->
Decide which libs should be removed
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{status = permanent}} ->
{error, {permanent, Vsn}};
{value, #release{libs = RemoveLibs, vsn = Vsn, erts_vsn = EVsn}} ->
case os:type() of
{win32, nt} ->
do_remove_service(Vsn);
_ ->
ok
end,
NewReleases = lists:keydelete(Vsn, #release.vsn, Releases),
RemoveThese =
lists:foldl(fun(#release{libs = Libs}, Remove) ->
diff_dir(Remove, Libs)
end, RemoveLibs, NewReleases),
lists:foreach(fun({_Lib, _LVsn, LDir}) ->
remove_file(LDir)
end, RemoveThese),
remove_file(filename:join([RelDir, Vsn])),
case lists:keysearch(EVsn, #release.erts_vsn, NewReleases) of
{value, _} -> ok;
remove_file(filename:join(Root, "erts-" ++ EVsn))
end,
write_releases(RelDir, NewReleases, false),
{ok, NewReleases};
false ->
{error, {no_such_release, Vsn}}
end.
do_set_unpacked(Root, RelDir, RelFile, LibDirs, Releases, Masters) ->
Release = check_rel(Root, RelFile, LibDirs, Masters),
#release{vsn = Vsn} = Release,
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, _} -> throw({error, {existing_release, Vsn}});
false -> ok
end,
NewReleases = [Release#release{status = unpacked} | Releases],
VsnDir = filename:join([RelDir, Vsn]),
make_dir(VsnDir, Masters),
write_releases(RelDir, NewReleases, Masters),
{ok, NewReleases, Vsn}.
do_set_removed(RelDir, Vsn, Releases, Masters) ->
case lists:keysearch(Vsn, #release.vsn, Releases) of
{value, #release{status = permanent}} ->
{error, {permanent, Vsn}};
{value, _} ->
NewReleases = lists:keydelete(Vsn, #release.vsn, Releases),
write_releases(RelDir, NewReleases, Masters),
{ok, NewReleases};
false ->
{error, {no_such_release, Vsn}}
end.
A relup file consists of :
{ Vsn , [ { FromVsn , , RhScript } ] , [ { ToVsn , , RhScript } ] } .
We can get from a FromVsn that 's a substring of CurrentVsn ( e.g.
1.1 is a substring of 1.1.1 , but not 1.2 ) , but when we get to
ToVsn , we must have an exact match .
do n't know if going from Vsn1 to Vsn2 represents a upgrade or
a downgrade . For both upgrades and downgrades , the relup file
do not which version is latest , we first suppose that ToVsn >
CurrentVsn , i.e. we perform an upgrade . If we do n't find the
corresponding relup instructions , we check if it 's possible to
downgrade from CurrentVsn to ToVsn .
get_rh_script(#release{vsn = ?tmp_vsn(CurrentVsn)},
#release{vsn = ToVsn},
RelDir,
Masters) ->
{ok,{Vsn,Descr,[restart_new_emulator|Script]}} =
do_get_rh_script(CurrentVsn,ToVsn,RelDir,Masters),
{ok,{Vsn,Descr,Script}};
get_rh_script(#release{vsn = CurrentVsn},
#release{vsn = ToVsn},
RelDir,
Masters) ->
do_get_rh_script(CurrentVsn,ToVsn,RelDir,Masters).
do_get_rh_script(CurrentVsn, ToVsn, RelDir, Masters) ->
Relup = filename:join([RelDir, ToVsn, "relup"]),
case try_upgrade(ToVsn, CurrentVsn, Relup, Masters) of
{ok, RhScript} ->
{ok, RhScript};
_ ->
Relup2 = filename:join([RelDir, CurrentVsn,"relup"]),
case try_downgrade(ToVsn, CurrentVsn, Relup2, Masters) of
{ok, RhScript} ->
{ok, RhScript};
_ ->
throw({error, {no_matching_relup, ToVsn, CurrentVsn}})
end
end.
try_upgrade(ToVsn, CurrentVsn, Relup, Masters) ->
case consult(Relup, Masters) of
{ok, [{ToVsn, ListOfRhScripts, _}]} ->
case lists:keysearch(CurrentVsn, 1, ListOfRhScripts) of
{value, RhScript} ->
{ok, RhScript};
_ ->
error
end;
{ok, _} ->
throw({error, {bad_relup_file, Relup}});
{error, Reason} when is_tuple(Reason) ->
throw({error, {bad_relup_file, Relup}});
{error, enoent} ->
error;
FileError is posix atom | no_master
throw({error, {FileError, Relup}})
end.
try_downgrade(ToVsn, CurrentVsn, Relup, Masters) ->
case consult(Relup, Masters) of
{ok, [{CurrentVsn, _, ListOfRhScripts}]} ->
case lists:keysearch(ToVsn, 1, ListOfRhScripts) of
{value, RhScript} ->
{ok, RhScript};
_ ->
error
end;
{ok, _} ->
throw({error, {bad_relup_file, Relup}});
{error, Reason} when is_tuple(Reason) ->
throw({error, {bad_relup_file, Relup}});
FileError is posix atom | no_master
throw({error, {FileError, Relup}})
end.
Status = current | tmp_current | permanent
set_status(Vsn, Status, Releases) ->
lists:zf(fun(Release) when Release#release.vsn == Vsn,
Release#release.status == permanent ->
true;
(Release) when Release#release.vsn == Vsn ->
{true, Release#release{status = Status}};
(Release) when Release#release.status == Status ->
{true, Release#release{status = old}};
(_) ->
true
end, Releases).
get_latest_release(Releases) ->
case lists:keysearch(current, #release.status, Releases) of
{value, Release} ->
Release;
false ->
{value, Release} =
lists:keysearch(permanent, #release.status, Releases),
Release
end.
Returns : [ { Lib , Vsn , Dir } ] to be removed
diff_dir([H | T], L) ->
case memlib(H, L) of
true -> diff_dir(T, L);
false -> [H | diff_dir(T, L)]
end;
diff_dir([], _) -> [].
memlib({Lib, Vsn, _Dir}, [{Lib, Vsn, _Dir2} | _T]) -> true;
memlib(Lib, [_H | T]) -> memlib(Lib, T);
memlib(_Lib, []) -> false.
remove_file(File) ->
case file:read_link_info(File) of
{ok, Info} when Info#file_info.type==directory ->
case file:list_dir(File) of
{ok, Files} ->
lists:foreach(fun(File2) ->
remove_file(filename:join(File,File2))
end, Files),
case file:del_dir(File) of
ok -> ok;
{error, Reason} -> throw({error, Reason})
end;
{error, Reason} ->
throw({error, Reason})
end;
{ok, _Info} ->
case file:delete(File) of
ok -> ok;
{error, Reason} -> throw({error, Reason})
end;
{error, _Reason} ->
throw({error, {no_such_file, File}})
end.
do_write_file(File, Str) ->
do_write_file(File, Str, []).
do_write_file(File, Str, FileOpts) ->
case file:open(File, [write | FileOpts]) of
{ok, Fd} ->
io:put_chars(Fd, Str),
ok = file:close(Fd);
{error, Reason} ->
{error, {Reason, File}}
end.
change_appl_data(RelDir, #release{vsn = Vsn}, Masters) ->
Dir = filename:join([RelDir, Vsn]),
BootFile = filename:join(Dir, "start.boot"),
case read_file(BootFile, Masters) of
{ok, Bin} ->
Config = case consult(filename:join(Dir, "sys.config"), Masters) of
{ok, [Conf]} -> Conf;
_ -> []
end,
Appls = get_appls(binary_to_term(Bin)),
case application_controller:change_application_data(Appls,Config) of
ok -> Appls;
{error, Reason} -> exit({change_appl_data, Reason})
end;
{error, _Reason} ->
throw({error, {no_such_file, BootFile}})
end.
get_appls({script, _, Script}) -> get_appls(Script, []).
get_appls([{kernelProcess, application_controller,
{application_controller, start, [App]}} |T], Res) ->
get_appls(T, [App | Res]);
get_appls([{apply, {application, load, [App]}} |T], Res) ->
get_appls(T, [App | Res]);
get_appls([_ | T], Res) ->
get_appls(T, Res);
get_appls([], Res) ->
Res.
mon_nodes(true) ->
ok = net_kernel:monitor_nodes(true);
mon_nodes(false) ->
ok = net_kernel:monitor_nodes(false),
flush().
flush() ->
receive
{nodedown, _} -> flush();
{nodeup, _} -> flush()
after
0 -> ok
end.
prepare_restart_nt(#release{erts_vsn = EVsn, vsn = Vsn},
#release{erts_vsn = PermEVsn, vsn = PermVsn},
DataFileName) ->
CurrentServiceName = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ PermVsn,
FutureServiceName = hd(string:tokens(atom_to_list(node()),"@"))
++ "_" ++ Vsn,
CurrentService = case erlsrv:get_service(PermEVsn,CurrentServiceName) of
{error, _} = Error1 ->
throw(Error1);
CS ->
CS
end,
FutureService = erlsrv:new_service(FutureServiceName,
CurrentService,
filename:nativename(DataFileName),
ERLSRV_SERVICE_NAME is
CurrentServiceName),
case erlsrv:store_service(EVsn, FutureService) of
{error, _} = Error2 ->
throw(Error2);
_X ->
{ok,_} = erlsrv:disable_service(EVsn, FutureServiceName),
ErlSrv = filename:nativename(erlsrv:erlsrv(EVsn)),
StartDisabled = ErlSrv ++ " start_disabled " ++ FutureServiceName,
case heart:set_cmd(StartDisabled) of
ok ->
ok;
Error3 ->
throw({error, {'heart:set_cmd() error', Error3}})
end
end.
prepare_restart_new_emulator(StartPrg, RootDir, RelDir,
Vsn, Release, Releases, Masters) ->
{value, PRelease} = lists:keysearch(permanent, #release.status,Releases),
NReleases1 = set_status(Vsn, current, Releases),
NReleases2 = set_status(Vsn,tmp_current,NReleases1),
write_releases(RelDir, NReleases2, Masters),
prepare_restart_new_emulator(StartPrg, RootDir, RelDir,
Release, PRelease, Masters).
prepare_restart_new_emulator(StartPrg, RootDir, RelDir,
Release, PRelease, Masters) ->
#release{erts_vsn = EVsn, vsn = Vsn} = Release,
Data = EVsn ++ " " ++ Vsn,
DataFile = write_new_start_erl(Data, RelDir, Masters),
Tell heart to use DataFile instead of start_erl.data
case os:type() of
{win32,nt} ->
write_ini_file(RootDir,EVsn,Masters),
prepare_restart_nt(Release,PRelease,DataFile);
{unix,_} ->
StartP = check_start_prg(StartPrg, Masters),
case heart:set_cmd(StartP ++ " " ++ DataFile) of
ok ->
ok;
Error ->
throw({error, {'heart:set_cmd() error', Error}})
end
end.
check_start_prg({do_check, StartPrg}, Masters) ->
check_file(StartPrg, regular, Masters),
StartPrg;
check_start_prg({_, StartPrg}, _) ->
StartPrg.
write_new_start_erl(Data, RelDir, Masters) ->
DataFile = filename:join([RelDir, "new_start_erl.data"]),
write_file(DataFile, Data, Masters),
DataFile.
occurs before a call to is made , the old emulator
is started , and is called for it . The tmp_current
transform_release(ReleaseDir, Releases, Masters) ->
case init:script_id() of
{Name, ?tmp_vsn(_)=TmpVsn} ->
DReleases = lists:keydelete(TmpVsn,#release.vsn,Releases),
write_releases(ReleaseDir, DReleases, Masters),
set_current({Name,TmpVsn},Releases);
ScriptId ->
F = fun(Release) when Release#release.status == tmp_current ->
Release#release{status = unpacked};
(Release) -> Release
end,
case lists:map(F, Releases) of
Releases ->
Releases;
DReleases ->
write_releases(ReleaseDir, DReleases, Masters),
set_current(ScriptId, Releases)
end
end.
set_current(ScriptId, Releases) ->
F1 = fun(Release) when Release#release.status == tmp_current ->
case ScriptId of
{_Name,Vsn} when Release#release.vsn == Vsn ->
Release#release{status = current};
_ ->
Release#release{status = unpacked}
end;
(Release) -> Release
end,
lists:map(F1, Releases).
Functions handling files , RELEASES , start_erl.data etc .
check_opt_file(FileName, Type, Masters) ->
case catch check_file(FileName, Type, Masters) of
ok ->
true;
_Error ->
io:format("Warning: ~p missing (optional)~n", [FileName]),
false
end.
check_file(FileName, Type, false) ->
do_check_file(FileName, Type);
check_file(FileName, Type, Masters) ->
check_file_masters(FileName, Type, Masters).
check_file_masters(FileName, Type, [Master|Masters]) ->
do_check_file(Master, FileName, Type),
check_file_masters(FileName, Type, Masters);
check_file_masters(_FileName, _Type, []) ->
ok.
do_check_file(FileName, Type) ->
case file:read_file_info(FileName) of
{ok, Info} when Info#file_info.type==Type -> ok;
{error, _Reason} -> throw({error, {no_such_file, FileName}})
end.
do_check_file(Master, FileName, Type) ->
case rpc:call(Master, file, read_file_info, [FileName]) of
{ok, Info} when Info#file_info.type==Type -> ok;
_ -> throw({error, {no_such_file, {Master, FileName}}})
end.
If does n't exists in tar it could have been created
extract_rel_file(Rel, Tar, Root) ->
erl_tar:extract(Tar, [{files, [Rel]}, {cwd, Root}, compressed]).
extract_tar(Root, Tar) ->
case erl_tar:extract(Tar, [keep_old_files, {cwd, Root}, compressed]) of
ok ->
ok;
throw({error, {cannot_extract_file, Name, Reason}});
New erl_tar ( ) .
throw({error, {cannot_extract_file, Name, Reason}})
end.
write_releases(Dir, Releases, Masters) ->
NewReleases = lists:zf(fun(Release) when Release#release.status == current ->
{true, Release#release{status = unpacked}};
(_) ->
true
end, Releases),
write_releases_1(Dir, NewReleases, Masters).
write_releases_1(Dir, NewReleases, false) ->
case do_write_release(Dir, "RELEASES", NewReleases) of
ok -> ok;
Error -> throw(Error)
end;
write_releases_1(Dir, NewReleases, Masters) ->
all_masters(Masters),
write_releases_m(Dir, NewReleases, Masters).
do_write_release(Dir, RELEASES, NewReleases) ->
case file:open(filename:join(Dir, RELEASES), [write]) of
{ok, Fd} ->
ok = io:format(Fd, "~p.~n", [NewReleases]),
ok = file:close(Fd);
{error, Reason} ->
{error, Reason}
end.
1 . Save " RELEASES.backup " at all nodes .
5 . Remove " RELEASES.backup " at all nodes .
If one of the steps above fails , all steps is recovered from
( as long as possible ) , except for 5 which is allowed to fail .
write_releases_m(Dir, NewReleases, Masters) ->
RelFile = filename:join(Dir, "RELEASES"),
Backup = filename:join(Dir, "RELEASES.backup"),
Change = filename:join(Dir, "RELEASES.change"),
ensure_RELEASES_exists(Masters, RelFile),
case at_all_masters(Masters, ?MODULE, do_copy_files,
[RelFile, [Backup, Change]]) of
ok ->
case at_all_masters(Masters, ?MODULE, do_write_release,
[Dir, "RELEASES.change", NewReleases]) of
ok ->
case at_all_masters(Masters, file, rename,
[Change, RelFile]) of
ok ->
remove_files(all, [Backup, Change], Masters),
ok;
{error, {Master, R}} ->
takewhile(Master, Masters, file, rename,
[Backup, RelFile]),
remove_files(all, [Backup, Change], Masters),
throw({error, {Master, R, move_releases}})
end;
{error, {Master, R}} ->
remove_files(all, [Backup, Change], Masters),
throw({error, {Master, R, update_releases}})
end;
{error, {Master, R}} ->
remove_files(Master, [Backup, Change], Masters),
throw({error, {Master, R, backup_releases}})
end.
ensure_RELEASES_exists(Masters, RelFile) ->
case at_all_masters(Masters, ?MODULE, do_ensure_RELEASES, [RelFile]) of
ok ->
ok;
{error, {Master, R}} ->
throw({error, {Master, R, ensure_RELEASES_exists}})
end.
copy_file(File, Dir, false) ->
case do_copy_file(File, Dir) of
ok -> ok;
Error -> throw(Error)
end;
copy_file(File, Dir, Masters) ->
all_masters(Masters),
copy_file_m(File, Dir, Masters).
copy at every master node .
copy_file_m(File, Dir, [Master|Masters]) ->
case rpc:call(Master, ?MODULE, do_copy_file, [File, Dir]) of
ok -> copy_file_m(File, Dir, Masters);
{error, {Reason, F}} -> throw({error, {Master, Reason, F}});
Other -> throw({error, {Master, Other, File}})
end;
copy_file_m(_File, _Dir, []) ->
ok.
do_copy_file(File, Dir) ->
File2 = filename:join(Dir, filename:basename(File)),
do_copy_file1(File, File2).
do_copy_file1(File, File2) ->
case file:read_file(File) of
{ok, Bin} ->
case file:write_file(File2, Bin) of
ok -> ok;
{error, Reason} ->
{error, {Reason, File2}}
end;
{error, Reason} ->
{error, {Reason, File}}
end.
do_copy_files(File, [ToFile|ToFiles]) ->
case do_copy_file1(File, ToFile) of
ok -> do_copy_files(File, ToFiles);
Error -> Error
end;
do_copy_files(_, []) ->
ok.
do_copy_files([{Src, Dest}|Files]) ->
case do_copy_file1(Src, Dest) of
ok -> do_copy_files(Files);
Error -> Error
end;
do_copy_files([]) ->
ok.
do_rename_files([{Src, Dest}|Files]) ->
case file:rename(Src, Dest) of
ok -> do_rename_files(Files);
Error -> Error
end;
do_rename_files([]) ->
ok.
do_remove_files([File|Files]) ->
_ = file:delete(File),
do_remove_files(Files);
do_remove_files([]) ->
ok.
do_ensure_RELEASES(RelFile) ->
case file:read_file_info(RelFile) of
{ok, _} -> ok;
_ -> do_write_file(RelFile, "[]. ")
end.
make_dir(Dir, false) ->
_ = file:make_dir(Dir),
ok;
make_dir(Dir, Masters) ->
lists:foreach(fun(Master) -> rpc:call(Master, file, make_dir, [Dir]) end,
Masters).
all_masters(Masters) ->
case rpc:multicall(Masters, erlang, info, [version]) of
{_, []} -> ok;
{_, BadNodes} -> throw({error, {bad_masters, BadNodes}})
end.
at_all_masters([Master|Masters], M, F, A) ->
case rpc:call(Master, M, F, A) of
ok -> at_all_masters(Masters, M, F, A);
Error -> {error, {Master, Error}}
end;
at_all_masters([], _, _, _) ->
ok.
takewhile(Master, Masters, M, F, A) ->
_ = lists:takewhile(fun(Ma) when Ma == Master ->
false;
(Ma) ->
rpc:call(Ma, M, F, A),
true
end, Masters),
ok.
consult(File, false) -> file:consult(File);
consult(File, Masters) -> consult_master(Masters, File).
If the file does not exist at one node it should
consult_master([Master|Ms], File) ->
case rpc:call(Master, file, consult, [File]) of
{badrpc, _} -> consult_master(Ms, File);
Res -> Res
end;
consult_master([], _File) ->
{error, no_master}.
read_file(File, false) ->
file:read_file(File);
read_file(File, Masters) ->
read_master(Masters, File).
write_file(File, Data, false) ->
case file:write_file(File, Data) of
ok -> ok;
Error -> throw(Error)
end;
write_file(File, Data, Masters) ->
case at_all_masters(Masters, file, write_file, [File, Data]) of
ok -> ok;
Error -> throw(Error)
end.
ensure_dir(File, false) ->
case filelib:ensure_dir(File) of
ok -> ok;
Error -> throw(Error)
end;
ensure_dir(File, Masters) ->
case at_all_masters(Masters,filelib,ensure_dir,[File]) of
ok -> ok;
Error -> throw(Error)
end.
remove_dir(Dir, false) ->
remove_file(Dir);
remove_dir(Dir, Masters) ->
case at_all_masters(Masters,?MODULE,remove_file,[Dir]) of
ok -> ok;
Error -> throw(Error)
end.
remove_files(Master, Files, Masters) ->
takewhile(Master, Masters, ?MODULE, do_remove_files, [Files]).
If the file does not exist at one node it should
read_master([Master|Ms], File) ->
case rpc:call(Master, file, read_file, [File]) of
{badrpc, _} -> read_master(Ms, File);
Res -> Res
end;
read_master([], _File) ->
{error, no_master}.
write_start(File, Data, false) ->
case do_write_file(File, Data) of
ok -> ok;
Error -> throw(Error)
end;
write_start(File, Data, Masters) ->
all_masters(Masters),
safe_write_file_m(File, Data, Masters).
Copy the " start.boot " and " sys.config " from SrcDir to DestDir at all
1 . Save DestDir/"start.backup " and " at all nodes .
If one of the steps above fails , all steps is recovered from
( as long as possible ) , except for 3 which is allowed to fail .
set_static_files(SrcDir, DestDir, Masters) ->
all_masters(Masters),
Boot = "start.boot",
Config = "sys.config",
SrcBoot = filename:join(SrcDir, Boot),
DestBoot = filename:join(DestDir, Boot),
BackupBoot = filename:join(DestDir, "start.backup"),
SrcConf = filename:join(SrcDir, Config),
DestConf = filename:join(DestDir, Config),
BackupConf = filename:join(DestDir, "sys.backup"),
case at_all_masters(Masters, ?MODULE, do_copy_files,
[[{DestBoot, BackupBoot},
{DestConf, BackupConf}]]) of
ok ->
case at_all_masters(Masters, ?MODULE, do_copy_files,
[[{SrcBoot, DestBoot},
{SrcConf, DestConf}]]) of
ok ->
remove_files(all, [BackupBoot, BackupConf], Masters),
ok;
{error, {Master, R}} ->
takewhile(Master, Masters, ?MODULE, do_rename_files,
[{BackupBoot, DestBoot},
{BackupConf, DestConf}]),
remove_files(all, [BackupBoot, BackupConf], Masters),
throw({error, {Master, R, copy_start_config}})
end;
{error, {Master, R}} ->
remove_files(Master, [BackupBoot, BackupConf], Masters),
throw({error, {Master, R, backup_start_config}})
end.
Writes the erl.ini file used by erl.exe when ( re)starting the erlang node .
At first installation , this is done by Install.exe , which means that if
write_ini_file(RootDir,EVsn,Masters) ->
BinDir = filename:join([RootDir,"erts-"++EVsn,"bin"]),
Str0 = io_lib:format("[erlang]~n"
"Bindir=~ts~n"
"Progname=erl~n"
"Rootdir=~ts~n",
[filename:nativename(BinDir),
filename:nativename(RootDir)]),
Str = re:replace(Str0,"\\\\","\\\\\\\\",[{return,list},global,unicode]),
IniFile = filename:join(BinDir,"erl.ini"),
do_write_ini_file(IniFile,Str,Masters).
do_write_ini_file(File,Data,false) ->
case do_write_file(File, Data, [{encoding,utf8}]) of
ok -> ok;
Error -> throw(Error)
end;
do_write_ini_file(File,Data,Masters) ->
all_masters(Masters),
safe_write_file_m(File, Data, [{encoding,utf8}], Masters).
3 . Move < File>.change to < File >
If one of the steps above fails , all steps are recovered from
( as long as possible ) , except for 4 which is allowed to fail .
safe_write_file_m(File, Data, Masters) ->
safe_write_file_m(File, Data, [], Masters).
safe_write_file_m(File, Data, FileOpts, Masters) ->
Backup = File ++ ".backup",
Change = File ++ ".change",
case at_all_masters(Masters, ?MODULE, do_copy_files,
[File, [Backup]]) of
ok ->
case at_all_masters(Masters, ?MODULE, do_write_file,
[Change, Data, FileOpts]) of
ok ->
case at_all_masters(Masters, file, rename,
[Change, File]) of
ok ->
remove_files(all, [Backup, Change], Masters),
ok;
{error, {Master, R}} ->
takewhile(Master, Masters, file, rename,
[Backup, File]),
remove_files(all, [Backup, Change], Masters),
throw({error, {Master, R, rename,
filename:basename(Change),
filename:basename(File)}})
end;
{error, {Master, R}} ->
remove_files(all, [Backup, Change], Masters),
throw({error, {Master, R, write, filename:basename(Change)}})
end;
{error, {Master, R}} ->
remove_files(Master, [Backup], Masters),
throw({error, {Master, R, backup,
filename:basename(File),
filename:basename(Backup)}})
end.
two releases . The paths for these applications must always be
updated , even if the relup script does not load any modules . See
OTP-9402 .
get_new_libs([{App,Vsn,_LibDir}|CurrentLibs], NewLibs) ->
case lists:keyfind(App,1,NewLibs) of
{App,NewVsn,_} = LibInfo when NewVsn =/= Vsn ->
[LibInfo | get_new_libs(CurrentLibs,NewLibs)];
_ ->
get_new_libs(CurrentLibs,NewLibs)
end;
get_new_libs([],_) ->
[].
get_releases_with_status([], _, Acc) ->
Acc;
get_releases_with_status([ {_, _, _, ReleaseStatus } = Head | Tail],
Status, Acc) when ReleaseStatus == Status ->
get_releases_with_status(Tail, Status, [Head | Acc]);
get_releases_with_status([_ | Tail], Status, Acc) ->
get_releases_with_status(Tail, Status, Acc).
|
5a1646ec0b0733bda91ff47501689cd84c047c3ca619a49af9370fd0e730c7c6 | yzh44yzh/practical_erlang | chat_user.erl | -module(chat_user).
-behavior(gen_server).
-export([start_link/0, add_message/3, get_messages/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-type(name() :: binary()).
-type(message() :: {name(), binary()}).
-record(state, {
messages = [] :: [message()]
}).
%%% module API
start_link() ->
gen_server:start_link(?MODULE, [], []).
-spec add_message(pid(), name(), binary()) -> ok.
add_message(Pid, UserName, Message) ->
gen_server:cast(Pid, {add_message, {UserName, Message}}), ok.
-spec get_messages(pid()) -> [message()].
get_messages(Pid) ->
gen_server:call(Pid, get_messages).
%%% gen_server API
init([]) ->
{ok, #state{}}.
handle_call(get_messages, _From, #state{messages = Messages} = State) ->
Reply = lists:reverse(Messages),
{reply, Reply, State}.
handle_cast({add_message, Data}, #state{messages = Messages} = State) ->
{noreply, State#state{messages = [Data | Messages]}}.
handle_info(_Request, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVersion, State, _Extra) ->
{ok, State}.
| null | https://raw.githubusercontent.com/yzh44yzh/practical_erlang/c9eec8cf44e152bf50d9bc6d5cb87fee4764f609/10_gen_server_2/solution/chat_user.erl | erlang | module API
gen_server API | -module(chat_user).
-behavior(gen_server).
-export([start_link/0, add_message/3, get_messages/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-type(name() :: binary()).
-type(message() :: {name(), binary()}).
-record(state, {
messages = [] :: [message()]
}).
start_link() ->
gen_server:start_link(?MODULE, [], []).
-spec add_message(pid(), name(), binary()) -> ok.
add_message(Pid, UserName, Message) ->
gen_server:cast(Pid, {add_message, {UserName, Message}}), ok.
-spec get_messages(pid()) -> [message()].
get_messages(Pid) ->
gen_server:call(Pid, get_messages).
init([]) ->
{ok, #state{}}.
handle_call(get_messages, _From, #state{messages = Messages} = State) ->
Reply = lists:reverse(Messages),
{reply, Reply, State}.
handle_cast({add_message, Data}, #state{messages = Messages} = State) ->
{noreply, State#state{messages = [Data | Messages]}}.
handle_info(_Request, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVersion, State, _Extra) ->
{ok, State}.
|
779e67cfbbf863a84ba356f2229ac040609b75b341d84f7c4d87b909efe0f37a | VisionsGlobalEmpowerment/webchange | interactive_read_aloud_import.clj | (ns webchange.dev-templates.interactive-read-aloud-import
(:require [webchange.dev-templates :as t]
[webchange.templates.core :as templates]
[webchange.course.core :as core]))
(comment
(def test-course-slug (-> (t/create-test-course) :slug))
(def scene-slug "test-activity")
(core/update-course-activity-template! test-course-slug scene-slug t/user-id)
(let [data {:activity-name "IRA"
:template-id 45
:characters [{:name "teacher"
:skeleton "senoravaca"}]
:book "sleepy-mr-sloth-english-hjcnzmqz"
:name "Interactive Read Aloud"
:lang "English"
:skills []}
activity (templates/activity-from-template data)
metadata (templates/metadata-from-template data)
[_ {scene-slug :scene-slug}] (core/create-scene! activity metadata test-course-slug scene-slug [] t/user-id)]
(str "/courses/" test-course-slug "/editor-v2/" scene-slug))
;add dialog
(let [data {:action "add-dialog" :data {:dialog "dialog one"}}
scene-data (core/get-scene-latest-version test-course-slug scene-slug)
activity (templates/update-activity-from-template scene-data data)]
(-> (core/save-scene! test-course-slug scene-slug activity t/user-id)
first))
;add question
(let [data {:action "add-question"
:data
{:question-page {:answers [{:text "answer one"}
{:text "answer two"}
{:text "answer three" :checked true}
{:text "answer four"}]
:question "Question one"
:img "/upload/DQHMQLASWJIKMETH.png"}}}
scene-data (core/get-scene-latest-version test-course-slug scene-slug)
activity (templates/update-activity-from-template scene-data data)]
(-> (core/save-scene! test-course-slug scene-slug activity t/user-id)
first)))
(comment
(defn- copy-activity
[course-name-source activity-name]
(let [scene-data (core/get-scene-latest-version course-name-source activity-name)
course-name-source-new (-> (t/create-test-course) :slug)]
(core/save-scene! course-name-source-new activity-name scene-data t/user-id)
[course-name-source-new
(str ":3000/courses/" course-name-source-new "/editor-v2/" activity-name)
(str ":3000/s/" course-name-source-new "/" activity-name)]))
;; Book
(def book-course-slug "amazing-daisy-english-apwoapsx")
(def book-scene-slug "book")
(core/get-scene-latest-version book-course-slug book-scene-slug)
; copy:
(copy-activity book-course-slug book-scene-slug)
(def book-course-slug-copied "test-course-english-fwacvyda")
;; IRA
(def ira-course-slug "english")
(def ira-scene-slug "interactive-read-aloud-amazing-daisy")
(core/get-scene-latest-version ira-course-slug ira-scene-slug)
; copy:
(copy-activity ira-course-slug ira-scene-slug)
(def ira-course-slug-copied "test-course-english-syggwhmo")
;; Fix book-link
(core/save-scene! ira-course-slug-copied
ira-scene-slug
(-> (core/get-scene-latest-version ira-course-slug-copied ira-scene-slug)
(assoc-in [:metadata :saved-props :wizard :book] book-course-slug-copied)
(assoc-in [:metadata :history :created :book] book-course-slug-copied))
t/user-id)
(-> (core/get-scene-latest-version ira-course-slug-copied ira-scene-slug)
(get-in [:objects :book]))
;; sleepy mr sloth
(-> (core/get-activity-current-version 825))
;; ira 1: sleepy mr sloth
(-> (core/get-activity-current-version 834))
(let [user-id 1
course-slug "english"
scene-slug "interactive-read-aloud-newest"
template-options {:action "template-options"
:data {:book-id 825}}]
(core/update-activity! course-slug scene-slug template-options user-id))
(let [user-id 1
course-slug "english"
scene-slug "interactive-read-aloud-newest"]
(core/update-course-activity-template! course-slug scene-slug user-id))
)
| null | https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/118ba5ee407ba1261bac40a6ba5729ccda6e8150/env/dev/clj/webchange/dev_templates/interactive_read_aloud_import.clj | clojure | add dialog
add question
Book
copy:
IRA
copy:
Fix book-link
sleepy mr sloth
ira 1: sleepy mr sloth | (ns webchange.dev-templates.interactive-read-aloud-import
(:require [webchange.dev-templates :as t]
[webchange.templates.core :as templates]
[webchange.course.core :as core]))
(comment
(def test-course-slug (-> (t/create-test-course) :slug))
(def scene-slug "test-activity")
(core/update-course-activity-template! test-course-slug scene-slug t/user-id)
(let [data {:activity-name "IRA"
:template-id 45
:characters [{:name "teacher"
:skeleton "senoravaca"}]
:book "sleepy-mr-sloth-english-hjcnzmqz"
:name "Interactive Read Aloud"
:lang "English"
:skills []}
activity (templates/activity-from-template data)
metadata (templates/metadata-from-template data)
[_ {scene-slug :scene-slug}] (core/create-scene! activity metadata test-course-slug scene-slug [] t/user-id)]
(str "/courses/" test-course-slug "/editor-v2/" scene-slug))
(let [data {:action "add-dialog" :data {:dialog "dialog one"}}
scene-data (core/get-scene-latest-version test-course-slug scene-slug)
activity (templates/update-activity-from-template scene-data data)]
(-> (core/save-scene! test-course-slug scene-slug activity t/user-id)
first))
(let [data {:action "add-question"
:data
{:question-page {:answers [{:text "answer one"}
{:text "answer two"}
{:text "answer three" :checked true}
{:text "answer four"}]
:question "Question one"
:img "/upload/DQHMQLASWJIKMETH.png"}}}
scene-data (core/get-scene-latest-version test-course-slug scene-slug)
activity (templates/update-activity-from-template scene-data data)]
(-> (core/save-scene! test-course-slug scene-slug activity t/user-id)
first)))
(comment
(defn- copy-activity
[course-name-source activity-name]
(let [scene-data (core/get-scene-latest-version course-name-source activity-name)
course-name-source-new (-> (t/create-test-course) :slug)]
(core/save-scene! course-name-source-new activity-name scene-data t/user-id)
[course-name-source-new
(str ":3000/courses/" course-name-source-new "/editor-v2/" activity-name)
(str ":3000/s/" course-name-source-new "/" activity-name)]))
(def book-course-slug "amazing-daisy-english-apwoapsx")
(def book-scene-slug "book")
(core/get-scene-latest-version book-course-slug book-scene-slug)
(copy-activity book-course-slug book-scene-slug)
(def book-course-slug-copied "test-course-english-fwacvyda")
(def ira-course-slug "english")
(def ira-scene-slug "interactive-read-aloud-amazing-daisy")
(core/get-scene-latest-version ira-course-slug ira-scene-slug)
(copy-activity ira-course-slug ira-scene-slug)
(def ira-course-slug-copied "test-course-english-syggwhmo")
(core/save-scene! ira-course-slug-copied
ira-scene-slug
(-> (core/get-scene-latest-version ira-course-slug-copied ira-scene-slug)
(assoc-in [:metadata :saved-props :wizard :book] book-course-slug-copied)
(assoc-in [:metadata :history :created :book] book-course-slug-copied))
t/user-id)
(-> (core/get-scene-latest-version ira-course-slug-copied ira-scene-slug)
(get-in [:objects :book]))
(-> (core/get-activity-current-version 825))
(-> (core/get-activity-current-version 834))
(let [user-id 1
course-slug "english"
scene-slug "interactive-read-aloud-newest"
template-options {:action "template-options"
:data {:book-id 825}}]
(core/update-activity! course-slug scene-slug template-options user-id))
(let [user-id 1
course-slug "english"
scene-slug "interactive-read-aloud-newest"]
(core/update-course-activity-template! course-slug scene-slug user-id))
)
|
1daba4a750dcff6f910e92c689d389aca1bf472dfe93336ad2fe21470b2bd6ae | matsen/pplacer | fig.mli | open Ppatteries
type t
val figs_of_gtree: float -> Newick_gtree.t -> t
val enum_by_score: (int -> float) -> float -> t -> (float * int) Enum.t
val enum_all: t -> int Enum.t
val length: t -> int
val onto_decor_gtree: Decor_gtree.t -> t -> Decor_gtree.t
| null | https://raw.githubusercontent.com/matsen/pplacer/f40a363e962cca7131f1f2d372262e0081ff1190/pplacer_src/fig.mli | ocaml | open Ppatteries
type t
val figs_of_gtree: float -> Newick_gtree.t -> t
val enum_by_score: (int -> float) -> float -> t -> (float * int) Enum.t
val enum_all: t -> int Enum.t
val length: t -> int
val onto_decor_gtree: Decor_gtree.t -> t -> Decor_gtree.t
| |
19df6b68408a55001aee0f87753d006698173cf8d7b23391b7fb29dde91030f9 | rescript-association/doc-tools | Main.ml |
module Config = struct
let runtime_path ~bs_project_dir =
bs_project_dir ^ "/jscomp/runtime"
let belt_path ~bs_project_dir =
bs_project_dir ^ "/jscomp/others"
let odoc_cache_path ~output_dir =
output_dir ^ "/_odoc"
let json_path ~output_dir =
output_dir ^ "/_json"
end
let run cmd =
cmd
|> String.concat " "
|> Unix.system
|> begin function
| Unix.WEXITED 0 -> ()
| Unix.WEXITED e ->
prerr_endline (
"Error while running `" ^ String.concat " " cmd ^ "`:" ^ "\n" ^
"Exited with a non-zero code: " ^ string_of_int e
);
exit (100 + e)
| _ ->
prerr_endline (
"Error while running `" ^ String.concat " " cmd ^ "`:" ^ "\n" ^
"Unexpected termination"
);
exit 100
end
let odoc_compile ~odoc_exe ?odoc_cache_path ~package ~output_dir comp_unit_path =
let comp_unit_name = Filename.remove_extension (Filename.basename comp_unit_path) in
let odoc_file = Config.odoc_cache_path ~output_dir ^ "/" ^ comp_unit_name ^ ".odoc" in
let cmd = [
odoc_exe;
"compile";
"--package=" ^ package;
"-o"; odoc_file;
] in
let cmd =
match odoc_cache_path with
| Some p -> cmd @ ["-I" ^ p]
| None -> cmd in
let cmd = cmd @ [comp_unit_path] in
run cmd;
odoc_file
let odoc_json ~odoc_exe ?odoc_cache_path ~output_dir odoc_file =
let cmd = [
odoc_exe; "json";
"-o"; Config.json_path ~output_dir;
] in
let cmd =
match odoc_cache_path with
| Some p -> cmd @ ["-I" ^ p]
| None -> cmd in
let cmd = cmd @ [odoc_file] in
prerr_endline ("Will generate JSON files for " ^ Filename.basename odoc_file ^
" in " ^ Config.json_path ~output_dir);
run cmd
type package = {
name : string;
path : string;
deps : package list;
comp_units: string list;
}
let runtime ~bs_project_dir = {
name = "runtime";
path = Config.runtime_path ~bs_project_dir;
deps = [];
comp_units = ["js.cmi"]
}
let belt ~bs_project_dir = {
name = "belt";
path = Config.belt_path ~bs_project_dir;
deps = [runtime ~bs_project_dir];
comp_units = [
"belt_Array.cmti";
"belt_Float.cmti";
"belt_HashMap.cmti";
"belt_HashMapInt.cmti";
"belt_HashMapString.cmti";
"belt_HashSet.cmti";
"belt_HashSetInt.cmti";
"belt_HashSetString.cmti";
"belt_Id.cmti";
"belt_Int.cmti";
"belt_internalAVLset.cmti";
"belt_internalAVLtree.cmti";
"belt_internalBuckets.cmti";
"belt_internalBucketsType.cmti";
"belt_internalSetBuckets.cmti";
"belt_List.cmti";
"belt_Map.cmti";
"belt_MapDict.cmti";
"belt_MapInt.cmti";
"belt_MapString.cmti";
"belt_MutableMap.cmti";
"belt_MutableMapInt.cmti";
"belt_MutableMapString.cmti";
"belt_MutableQueue.cmti";
"belt_MutableSet.cmti";
"belt_MutableSetInt.cmti";
"belt_MutableSetString.cmti";
"belt_MutableStack.cmti";
"belt_Option.cmti";
"belt_Range.cmti";
"belt_Result.cmti";
"belt_Set.cmti";
"belt_SetDict.cmti";
"belt_SetInt.cmti";
"belt_SetString.cmti";
"belt_SortArray.cmti";
"belt_SortArrayInt.cmti";
"belt_SortArrayString.cmti";
]
}
(** Given a package compile it and produce JSON files with odoc. *)
let rec process_package ~odoc_exe ~odoc_cache_path ~output_dir pkg : unit =
List.iter (process_package ~odoc_exe ~odoc_cache_path ~output_dir) pkg.deps;
pkg.comp_units
|> List.map (fun comp_units -> pkg.path ^ "/" ^ comp_units)
|> List.iter (fun comp_unit_path ->
let odoc_file = odoc_compile ~odoc_cache_path ~odoc_exe ~package:pkg.name ~output_dir comp_unit_path in
odoc_json ~odoc_exe ~odoc_cache_path ~output_dir odoc_file)
let main odoc_exe bs_project_dir output_dir =
prerr_endline ("Starting...");
run ["mkdir"; "-p"; output_dir];
process_package (belt ~bs_project_dir)
~odoc_exe
~odoc_cache_path:(Config.odoc_cache_path ~output_dir)
~output_dir;
prerr_endline "Done."
open Cmdliner
let odoc_exe =
Arg.(
info ["odoc-exe"] ~docv:"PATH" ~doc:"The path to the odoc executable to be used for doc generation."
|> opt (some string) (Some "odoc")
|> required
)
let bs_project_dir =
Arg.(
info ["bs-project-dir"] ~docv:"PATH" ~doc:"The path to the Bucklescript git repository."
|> opt (some dir) None
|> required
)
let output_dir =
Arg.(
info ["o"; "output-dir"] ~docv:"PATH"
~doc:"The path to directory where generated documentation will be saved."
|> opt (some string) (Some "_output")
|> required
)
let () =
Term.(
(pure(main) $ odoc_exe $ bs_project_dir $ output_dir,
info "bs-doc" ~version:"0.1.0" ~doc:"Generate documentation for Bucklescript libraries")
|> eval
|> exit
)
| null | https://raw.githubusercontent.com/rescript-association/doc-tools/5dfdf4400a617c331409bb94f97f3daf930626b3/src/Main.ml | ocaml | * Given a package compile it and produce JSON files with odoc. |
module Config = struct
let runtime_path ~bs_project_dir =
bs_project_dir ^ "/jscomp/runtime"
let belt_path ~bs_project_dir =
bs_project_dir ^ "/jscomp/others"
let odoc_cache_path ~output_dir =
output_dir ^ "/_odoc"
let json_path ~output_dir =
output_dir ^ "/_json"
end
let run cmd =
cmd
|> String.concat " "
|> Unix.system
|> begin function
| Unix.WEXITED 0 -> ()
| Unix.WEXITED e ->
prerr_endline (
"Error while running `" ^ String.concat " " cmd ^ "`:" ^ "\n" ^
"Exited with a non-zero code: " ^ string_of_int e
);
exit (100 + e)
| _ ->
prerr_endline (
"Error while running `" ^ String.concat " " cmd ^ "`:" ^ "\n" ^
"Unexpected termination"
);
exit 100
end
let odoc_compile ~odoc_exe ?odoc_cache_path ~package ~output_dir comp_unit_path =
let comp_unit_name = Filename.remove_extension (Filename.basename comp_unit_path) in
let odoc_file = Config.odoc_cache_path ~output_dir ^ "/" ^ comp_unit_name ^ ".odoc" in
let cmd = [
odoc_exe;
"compile";
"--package=" ^ package;
"-o"; odoc_file;
] in
let cmd =
match odoc_cache_path with
| Some p -> cmd @ ["-I" ^ p]
| None -> cmd in
let cmd = cmd @ [comp_unit_path] in
run cmd;
odoc_file
let odoc_json ~odoc_exe ?odoc_cache_path ~output_dir odoc_file =
let cmd = [
odoc_exe; "json";
"-o"; Config.json_path ~output_dir;
] in
let cmd =
match odoc_cache_path with
| Some p -> cmd @ ["-I" ^ p]
| None -> cmd in
let cmd = cmd @ [odoc_file] in
prerr_endline ("Will generate JSON files for " ^ Filename.basename odoc_file ^
" in " ^ Config.json_path ~output_dir);
run cmd
type package = {
name : string;
path : string;
deps : package list;
comp_units: string list;
}
let runtime ~bs_project_dir = {
name = "runtime";
path = Config.runtime_path ~bs_project_dir;
deps = [];
comp_units = ["js.cmi"]
}
let belt ~bs_project_dir = {
name = "belt";
path = Config.belt_path ~bs_project_dir;
deps = [runtime ~bs_project_dir];
comp_units = [
"belt_Array.cmti";
"belt_Float.cmti";
"belt_HashMap.cmti";
"belt_HashMapInt.cmti";
"belt_HashMapString.cmti";
"belt_HashSet.cmti";
"belt_HashSetInt.cmti";
"belt_HashSetString.cmti";
"belt_Id.cmti";
"belt_Int.cmti";
"belt_internalAVLset.cmti";
"belt_internalAVLtree.cmti";
"belt_internalBuckets.cmti";
"belt_internalBucketsType.cmti";
"belt_internalSetBuckets.cmti";
"belt_List.cmti";
"belt_Map.cmti";
"belt_MapDict.cmti";
"belt_MapInt.cmti";
"belt_MapString.cmti";
"belt_MutableMap.cmti";
"belt_MutableMapInt.cmti";
"belt_MutableMapString.cmti";
"belt_MutableQueue.cmti";
"belt_MutableSet.cmti";
"belt_MutableSetInt.cmti";
"belt_MutableSetString.cmti";
"belt_MutableStack.cmti";
"belt_Option.cmti";
"belt_Range.cmti";
"belt_Result.cmti";
"belt_Set.cmti";
"belt_SetDict.cmti";
"belt_SetInt.cmti";
"belt_SetString.cmti";
"belt_SortArray.cmti";
"belt_SortArrayInt.cmti";
"belt_SortArrayString.cmti";
]
}
let rec process_package ~odoc_exe ~odoc_cache_path ~output_dir pkg : unit =
List.iter (process_package ~odoc_exe ~odoc_cache_path ~output_dir) pkg.deps;
pkg.comp_units
|> List.map (fun comp_units -> pkg.path ^ "/" ^ comp_units)
|> List.iter (fun comp_unit_path ->
let odoc_file = odoc_compile ~odoc_cache_path ~odoc_exe ~package:pkg.name ~output_dir comp_unit_path in
odoc_json ~odoc_exe ~odoc_cache_path ~output_dir odoc_file)
let main odoc_exe bs_project_dir output_dir =
prerr_endline ("Starting...");
run ["mkdir"; "-p"; output_dir];
process_package (belt ~bs_project_dir)
~odoc_exe
~odoc_cache_path:(Config.odoc_cache_path ~output_dir)
~output_dir;
prerr_endline "Done."
open Cmdliner
let odoc_exe =
Arg.(
info ["odoc-exe"] ~docv:"PATH" ~doc:"The path to the odoc executable to be used for doc generation."
|> opt (some string) (Some "odoc")
|> required
)
let bs_project_dir =
Arg.(
info ["bs-project-dir"] ~docv:"PATH" ~doc:"The path to the Bucklescript git repository."
|> opt (some dir) None
|> required
)
let output_dir =
Arg.(
info ["o"; "output-dir"] ~docv:"PATH"
~doc:"The path to directory where generated documentation will be saved."
|> opt (some string) (Some "_output")
|> required
)
let () =
Term.(
(pure(main) $ odoc_exe $ bs_project_dir $ output_dir,
info "bs-doc" ~version:"0.1.0" ~doc:"Generate documentation for Bucklescript libraries")
|> eval
|> exit
)
|
eed9271dfda4655c1c2a4e58397510d5f9f3b99215852bb3f8551df65854c2e9 | clojure/clojurescript | test.cljs | Copyright ( c ) . All rights reserved .
;; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 ( -1.0.php )
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns repl.test
(:require [clojure.browser.repl :as repl]
;[clojure.reflect :as reflect]
))
(defonce conn
(repl/connect ":9000/repl"))
(comment
;; Note: If you would like for the compiler to be aware of
;; everything in a project then delete the 'out' directory before
;; calling build. This will force the compiler to compile the whole
;; project.
Compile this project to JavaScript
(use 'cljs.closure)
(def opts {:output-to "samples/repl/main.js"
:output-dir "samples/repl/out"})
(build "samples/repl/src" opts)
Start REPL
(do (require '[cljs.repl :as repl])
(require '[cljs.repl.browser :as browser])
(def env (browser/repl-env))
(repl/repl env))
;; Open :9000/ in a browser. When this page is loaded
;; it will connect to the REPL. Alternatively you can serve index.html
;; from your own local webserver.
;; Evaluate some basic forms
(+ 1 1)
(string-print "hello")
(prn "foo")
(prn {:a :b})
(println "hello")
(doseq [next (range 20)] (println next))
{:a :b}
"hello"
(reduce + [1 2 3 4 5])
(time (reduce + (range 10000)))
(js/alert "Hello World!")
(load-file "clojure/string.cljs")
(clojure.string/reverse "Hello")
(defn sum [coll] (reduce + coll))
(sum [2 2 2 2])
;; Create dom elements.
(ns dom.testing (:require [clojure.browser.dom :as dom]))
(dom/append (dom/get-element "content")
(dom/element "Hello World!"))
;; Load something we haven't used yet
(ns test.crypt
(:require [goog.crypt :as c]))
(c/stringToByteArray "ClojureScript")
(load-namespace 'goog.date.Date)
(goog.date.Date.)
(ns test.color (:require [goog.color :as c]))
(js->clj (c/parse "#000000"))
)
| null | https://raw.githubusercontent.com/clojure/clojurescript/a4673b880756531ac5690f7b4721ad76c0810327/samples/repl/src/repl/test.cljs | clojure | The use and distribution terms for this software are covered by the
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
[clojure.reflect :as reflect]
Note: If you would like for the compiler to be aware of
everything in a project then delete the 'out' directory before
calling build. This will force the compiler to compile the whole
project.
Open :9000/ in a browser. When this page is loaded
it will connect to the REPL. Alternatively you can serve index.html
from your own local webserver.
Evaluate some basic forms
Create dom elements.
Load something we haven't used yet | Copyright ( c ) . All rights reserved .
Eclipse Public License 1.0 ( -1.0.php )
(ns repl.test
(:require [clojure.browser.repl :as repl]
))
(defonce conn
(repl/connect ":9000/repl"))
(comment
Compile this project to JavaScript
(use 'cljs.closure)
(def opts {:output-to "samples/repl/main.js"
:output-dir "samples/repl/out"})
(build "samples/repl/src" opts)
Start REPL
(do (require '[cljs.repl :as repl])
(require '[cljs.repl.browser :as browser])
(def env (browser/repl-env))
(repl/repl env))
(+ 1 1)
(string-print "hello")
(prn "foo")
(prn {:a :b})
(println "hello")
(doseq [next (range 20)] (println next))
{:a :b}
"hello"
(reduce + [1 2 3 4 5])
(time (reduce + (range 10000)))
(js/alert "Hello World!")
(load-file "clojure/string.cljs")
(clojure.string/reverse "Hello")
(defn sum [coll] (reduce + coll))
(sum [2 2 2 2])
(ns dom.testing (:require [clojure.browser.dom :as dom]))
(dom/append (dom/get-element "content")
(dom/element "Hello World!"))
(ns test.crypt
(:require [goog.crypt :as c]))
(c/stringToByteArray "ClojureScript")
(load-namespace 'goog.date.Date)
(goog.date.Date.)
(ns test.color (:require [goog.color :as c]))
(js->clj (c/parse "#000000"))
)
|
e2660bc76b5af3ee1451f6b3ad9475a6f4d517dadcc498928bdeb06893657cc4 | gvolpe/musikell | Neo.hs | {-# LANGUAGE OverloadedStrings, RecordWildCards #-}
-- | The Neo4j connection pool.
module Repository.Neo
( mkPipePool
)
where
import Config ( Neo4jConfig(..) )
import Data.Pool ( Pool
, createPool
)
import Data.Text ( unpack )
import Database.Bolt hiding ( unpack )
import GHC.Natural ( naturalToInt )
mkConfig :: Neo4jConfig -> BoltCfg
mkConfig Neo4jConfig {..} = BoltCfg { magic = 1616949271
, version = 1
, userAgent = "hasbolt/1.3"
, maxChunkSize = 65535
, socketTimeout = 5
, host = unpack neo4jHost
, port = naturalToInt neo4jPort
, user = neo4jUser
, password = neo4jPassword
, secure = neo4jSecure
}
mkPipePool :: Neo4jConfig -> IO (Pool Pipe)
mkPipePool c = createPool acquire release 1 3600 10 where
acquire = connect (mkConfig c)
release = close
| null | https://raw.githubusercontent.com/gvolpe/musikell/2ec837b605b87b268e460cd6e13b82e7eea8169b/src/Repository/Neo.hs | haskell | # LANGUAGE OverloadedStrings, RecordWildCards #
| The Neo4j connection pool. |
module Repository.Neo
( mkPipePool
)
where
import Config ( Neo4jConfig(..) )
import Data.Pool ( Pool
, createPool
)
import Data.Text ( unpack )
import Database.Bolt hiding ( unpack )
import GHC.Natural ( naturalToInt )
mkConfig :: Neo4jConfig -> BoltCfg
mkConfig Neo4jConfig {..} = BoltCfg { magic = 1616949271
, version = 1
, userAgent = "hasbolt/1.3"
, maxChunkSize = 65535
, socketTimeout = 5
, host = unpack neo4jHost
, port = naturalToInt neo4jPort
, user = neo4jUser
, password = neo4jPassword
, secure = neo4jSecure
}
mkPipePool :: Neo4jConfig -> IO (Pool Pipe)
mkPipePool c = createPool acquire release 1 3600 10 where
acquire = connect (mkConfig c)
release = close
|
dee90f1745be4ef0007d6bb55cf5a97342bc00ec82ca8263c9263aa050c06755 | auser/hermes | thrift_ambassador.erl | %%%-------------------------------------------------------------------
%%% File :
Author :
%%% Description :
%%%
Created : We d Aug 12 14:19:36 PDT 2009
%%%-------------------------------------------------------------------
-module (thrift_ambassador).
-include ("hermes.hrl").
-include ("poolparty_types.hrl").
-include ("commandInterface_thrift.hrl").
-include ("poolparty_constants.hrl").
-behaviour(gen_server).
%% API
-export([start_link/1]).
-export ([
ask/3,
run/3,
stop/0
]).
-export ([start_thrift_server/1]).
%% gen_server callbacks
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {
start_args, % args to start with
thrift_pid, % thrift client pid
port, % port
retry_times % times to retry
}).
-define(SERVER, ?MODULE).
-define(PORT_OPTIONS, [stream, {line, 1024}, binary, exit_status, hide]).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
%% Description: Starts the server
%%--------------------------------------------------------------------
start_link(Args) ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [Args], []).
ask(CloudName, Func, Msg) -> gen_server:call(?MODULE, {cloud_query, CloudName, Func, Msg}).
run(CloudName, Func, Msg) -> gen_server:cast(?MODULE, {cloud_run, CloudName, Func, Msg}).
%%--------------------------------------------------------------------
%% Function: stop () -> ok
%% Description: Stop ourselves and the socket_server
%%--------------------------------------------------------------------
stop() ->
?INFO("Stopping ~p~n", [?MODULE]),
stop_thrift_client(config:read()),
thrift_socket_server : stop(get_hostname ( ) ) ,
ok.
%%====================================================================
%% gen_server callbacks
%%====================================================================
%%--------------------------------------------------------------------
%% Function: init(Args) -> {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%% Description: Initiates the server
%%--------------------------------------------------------------------
init([Args]) ->
ThriftPort = proplists:get_value(proto_port, Args),
CloudConfig = proplists:get_value(clouds_config, Args),
CloudName = proplists:get_value(cloud_name, Args),
stop_thrift_client(Args),
timer:sleep(500),
Port = start_thrift_cloud_server(Args),
{ok, HostName} = get_hostname(),
BannerArr = [
{"thrift_port", erlang:integer_to_list(ThriftPort)},
{"thrift client hostname", HostName},
{"cloud name", CloudName},
{"cloud config", CloudConfig}
],
loudmouth:banner("Started thrift", BannerArr),
% O = thrift_client:start_link(HostName, ThriftPort, commandInterface_thrift),
timer:sleep(1000),
?INFO("Connecting with thrift_client on ~p:~p~n", [HostName, ThriftPort]),
P = case thrift_client:start_link(HostName, ThriftPort, commandInterface_thrift) of
{error, R} ->
?ERROR("Thrift client could not connect to: ~p, ~p, ~p = ~p~n", [HostName, ThriftPort, commandInterface_thrift, R]),
timer:sleep(1000),
self();
{ok, C} -> C
end,
?INFO("Connected! Ready to go!~n~n", []),
{ok, #state{
start_args = Args,
thrift_pid = P,
port = Port,
retry_times = 0
}}.
%%--------------------------------------------------------------------
Function : % % handle_call(Request , From , State ) - > { reply , Reply , State } |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} |
%% {stop, Reason, State}
%% Description: Handling call messages
%%--------------------------------------------------------------------
handle_call({cloud_query, CloudName, Fun, [Args]}, _From, #state{thrift_pid = P, start_args = StartArgs} = State) ->
?INFO("Calling cloud_query: ~p ~p(~p)~n", [CloudName, Fun, Args]),
Reply = case catch cloud_query(P, CloudName, Fun, Args) of
{ok, {cloudResponse, _BinCloudName, _BinFun, [<<"unhandled monitor">>]}} -> {error, unhandled_monitor};
{ok, {cloudResponse, _BinCloudName, _BinFun, BinResponse}} ->
?INFO("Got back: ~p~n", [utils:turn_to_list(BinResponse)]),
{ok, utils:turn_to_list(BinResponse)};
% Errors
{error, {noproc, Reason}} ->
?ERROR("Cloud thrift server died. Restarting it: ~p~n", [Reason]),
start_thrift_cloud_server(StartArgs),
{error, Reason};
Else ->
?ERROR("There was an error: ~p~n", [Else]),
{error, Else}
end,
{reply, Reply, State};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
%%--------------------------------------------------------------------
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling cast messages
%%--------------------------------------------------------------------
handle_cast({cloud_run, CloudName, Fun, [Args]}, #state{thrift_pid = P} = State) ->
cloud_run(P, CloudName, Fun, Args),
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
%%--------------------------------------------------------------------
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State}
%% Description: Handling all non call/cast messages
%%--------------------------------------------------------------------
handle_info({'EXIT', _Pid, Reason}, #state{start_args = _Args} = State) ->
% Port = start_thrift_cloud_server(Args),
NewState = State#state{port = Port } ,
?INFO("Received Exit in ~p: ~p~n", [?MODULE, Reason]),
{noreply, State};
% The process could not be started, because of some foreign error
handle_info({_Port,{exit_status,10}}, State) -> {noreply, State};
handle_info({_Port,{exit_status,0}}, #state{start_args = Args} = State) -> {noreply, State};
handle_info({Port, {exit_status, Status}}, #state{port=Port}=State) ->
?ERROR("OS Process died with status: ~p", [Status]),
{stop, {exit_status, Status}, State};
handle_info({_Port, {data, {eol, Data}}}, State) ->
?INFO("~p~n", [Data]),
{noreply, State};
handle_info(Info, State) ->
?INFO("Received info in ~p: ~p~n", [?MODULE, Info]),
{noreply, State}.
%%--------------------------------------------------------------------
%% Function: terminate(Reason, State) -> void()
%% Description: This function is called by a gen_server when it is about to
%% terminate. It should be the opposite of Module:init/1 and do any necessary
%% cleaning up. When it returns, the gen_server terminates with Reason.
%% The return value is ignored.
%%--------------------------------------------------------------------
terminate(Reason, #state{start_args = _Args} = _State) ->
?ERROR("~p terminating: ~p~n", [?MODULE, Reason]),
ok.
%%--------------------------------------------------------------------
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
%% Description: Convert process state when code is changed
%%--------------------------------------------------------------------
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
%%--------------------------------------------------------------------
%% Function: get_hostname () -> HostName
%% Description: Quick accessor to local node's hostname
%% TODO: Make a commandline-passable-option
%%--------------------------------------------------------------------
get_hostname() ->
{ok, "localhost"}.
% inet:gethostname().
%%====================================================================
Start thrift server ( in erlang )
%%====================================================================
% thrift_server
start_thrift_server(Args) ->
ThriftPort = proplists:get_value(proto_port, Args),
Module = proplists:get_value(module, Args),
thrift_socket_server:start([
{port, ThriftPort},
{name, ambassador},
{service, ambassador_thrift},
{handler, Module},
{socket_opts, [{recv_timeout, infinity}]}]),
ok.
start_thrift_cloud_server(Args) ->
process_flag(trap_exit, true),
StartCmd = build_start_command("start", Args),
Port = open_port({spawn, StartCmd ++ " "}, ?PORT_OPTIONS),
Port.
% start_and_link_thrift_server(StartCmd).
% case whereis(cloud_thrift_server) of
% undefined -> start_and_link_thrift_server(StartCmd);
% Node -> Node
% end.
% start_and_link_thrift_server(StartCmd) ->
? INFO("Starting ~p : ~p ~ n " , [ ? MODULE , ] ) ,
% case (fun() -> os:cmd(StartCmd) end) of
% {error, Reason} ->
% ?INFO("Assuming the thrift_client is already started error: ~p~n", [Reason]),
% ok;
% Pid ->
% % case utils:is_process_alive(Pid) of
% % true ->
% erlang : ,
% erlang : monitor(process , Pid ) ,
% % _ -> ok
% % end,
Pid
% end.
stop_thrift_client(Args) ->
StopCmd = build_start_command("stop", Args),
?INFO("Stopping ~p: ~p~n", [?MODULE, StopCmd]),
spawn_link(fun() -> os:cmd(StopCmd) end).
%%--------------------------------------------------------------------
Function : build_start_command ( Action , ) - > cloud thrift string
%% Description: build a start command
%%--------------------------------------------------------------------
build_start_command(Action, Args) ->
ThriftPort = proplists:get_value(proto_port, Args),
CloudConfig = proplists:get_value(clouds_config, Args),
CloudName = proplists : get_value(cloud_name , ) ,
ExtraArgs = lists:append([
[" --port ", erlang:integer_to_list(ThriftPort)],
[" -c ", CloudConfig]
[ " -n " , ]
]),
StartCommand = lists:flatten(lists:append([["cloud thrift ", Action, " "], [ExtraArgs]])),
StartCommand.
%%====================================================================
%% Query on the thrift server
%%====================================================================
cloud_query(P, Name, Meth, Args) ->
Query = #cloudQuery{name=Name},
case catch thrift_client:call(P, run_command, [Query, Meth, Args]) of % infinite timeout
{'EXIT', R} ->
case R of
{timeout, _} -> {error, timeout};
E -> {error, E}
end;
E -> E
end.
cloud_run(P, Name, Meth, Args) ->
Query = #cloudQuery{name=Name},
?INFO("Casting the command ~p through ~p~n", [Meth, ?MODULE]),
case catch thrift_client:cast(P, run_command, [Query, Meth, Args]) of % infinite timeout
{'EXIT', R} ->
?ERROR("Got back an EXIT error: ~p~n", [R]),
case R of
{timeout, _} -> {error, timeout};
E -> {error, E}
end;
E ->
?INFO("Received ~p from cloud_run~n", [E]),
E
end.
| null | https://raw.githubusercontent.com/auser/hermes/32741eb75398ebbcbf640e2c73dfd2a54f0d1241/src/ambassador/ambassadors/thrift_ambassador.erl | erlang | -------------------------------------------------------------------
File :
Description :
-------------------------------------------------------------------
API
gen_server callbacks
args to start with
thrift client pid
port
times to retry
====================================================================
API
====================================================================
--------------------------------------------------------------------
Description: Starts the server
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: stop () -> ok
Description: Stop ourselves and the socket_server
--------------------------------------------------------------------
====================================================================
gen_server callbacks
====================================================================
--------------------------------------------------------------------
Function: init(Args) -> {ok, State} |
ignore |
{stop, Reason}
Description: Initiates the server
--------------------------------------------------------------------
O = thrift_client:start_link(HostName, ThriftPort, commandInterface_thrift),
--------------------------------------------------------------------
% handle_call(Request , From , State ) - > { reply , Reply , State } |
{stop, Reason, Reply, State} |
{stop, Reason, State}
Description: Handling call messages
--------------------------------------------------------------------
Errors
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling cast messages
--------------------------------------------------------------------
--------------------------------------------------------------------
{stop, Reason, State}
Description: Handling all non call/cast messages
--------------------------------------------------------------------
Port = start_thrift_cloud_server(Args),
The process could not be started, because of some foreign error
--------------------------------------------------------------------
Function: terminate(Reason, State) -> void()
Description: This function is called by a gen_server when it is about to
terminate. It should be the opposite of Module:init/1 and do any necessary
cleaning up. When it returns, the gen_server terminates with Reason.
The return value is ignored.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Convert process state when code is changed
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
Function: get_hostname () -> HostName
Description: Quick accessor to local node's hostname
TODO: Make a commandline-passable-option
--------------------------------------------------------------------
inet:gethostname().
====================================================================
====================================================================
thrift_server
start_and_link_thrift_server(StartCmd).
case whereis(cloud_thrift_server) of
undefined -> start_and_link_thrift_server(StartCmd);
Node -> Node
end.
start_and_link_thrift_server(StartCmd) ->
case (fun() -> os:cmd(StartCmd) end) of
{error, Reason} ->
?INFO("Assuming the thrift_client is already started error: ~p~n", [Reason]),
ok;
Pid ->
% case utils:is_process_alive(Pid) of
% true ->
erlang : ,
erlang : monitor(process , Pid ) ,
% _ -> ok
% end,
end.
--------------------------------------------------------------------
Description: build a start command
--------------------------------------------------------------------
====================================================================
Query on the thrift server
====================================================================
infinite timeout
infinite timeout | Author :
Created : We d Aug 12 14:19:36 PDT 2009
-module (thrift_ambassador).
-include ("hermes.hrl").
-include ("poolparty_types.hrl").
-include ("commandInterface_thrift.hrl").
-include ("poolparty_constants.hrl").
-behaviour(gen_server).
-export([start_link/1]).
-export ([
ask/3,
run/3,
stop/0
]).
-export ([start_thrift_server/1]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2,
terminate/2, code_change/3]).
-record(state, {
}).
-define(SERVER, ?MODULE).
-define(PORT_OPTIONS, [stream, {line, 1024}, binary, exit_status, hide]).
Function : start_link ( ) - > { ok , Pid } | ignore | { error , Error }
start_link(Args) ->
gen_server:start_link({local, ?SERVER}, ?MODULE, [Args], []).
ask(CloudName, Func, Msg) -> gen_server:call(?MODULE, {cloud_query, CloudName, Func, Msg}).
run(CloudName, Func, Msg) -> gen_server:cast(?MODULE, {cloud_run, CloudName, Func, Msg}).
stop() ->
?INFO("Stopping ~p~n", [?MODULE]),
stop_thrift_client(config:read()),
thrift_socket_server : stop(get_hostname ( ) ) ,
ok.
{ ok , State , Timeout } |
init([Args]) ->
ThriftPort = proplists:get_value(proto_port, Args),
CloudConfig = proplists:get_value(clouds_config, Args),
CloudName = proplists:get_value(cloud_name, Args),
stop_thrift_client(Args),
timer:sleep(500),
Port = start_thrift_cloud_server(Args),
{ok, HostName} = get_hostname(),
BannerArr = [
{"thrift_port", erlang:integer_to_list(ThriftPort)},
{"thrift client hostname", HostName},
{"cloud name", CloudName},
{"cloud config", CloudConfig}
],
loudmouth:banner("Started thrift", BannerArr),
timer:sleep(1000),
?INFO("Connecting with thrift_client on ~p:~p~n", [HostName, ThriftPort]),
P = case thrift_client:start_link(HostName, ThriftPort, commandInterface_thrift) of
{error, R} ->
?ERROR("Thrift client could not connect to: ~p, ~p, ~p = ~p~n", [HostName, ThriftPort, commandInterface_thrift, R]),
timer:sleep(1000),
self();
{ok, C} -> C
end,
?INFO("Connected! Ready to go!~n~n", []),
{ok, #state{
start_args = Args,
thrift_pid = P,
port = Port,
retry_times = 0
}}.
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call({cloud_query, CloudName, Fun, [Args]}, _From, #state{thrift_pid = P, start_args = StartArgs} = State) ->
?INFO("Calling cloud_query: ~p ~p(~p)~n", [CloudName, Fun, Args]),
Reply = case catch cloud_query(P, CloudName, Fun, Args) of
{ok, {cloudResponse, _BinCloudName, _BinFun, [<<"unhandled monitor">>]}} -> {error, unhandled_monitor};
{ok, {cloudResponse, _BinCloudName, _BinFun, BinResponse}} ->
?INFO("Got back: ~p~n", [utils:turn_to_list(BinResponse)]),
{ok, utils:turn_to_list(BinResponse)};
{error, {noproc, Reason}} ->
?ERROR("Cloud thrift server died. Restarting it: ~p~n", [Reason]),
start_thrift_cloud_server(StartArgs),
{error, Reason};
Else ->
?ERROR("There was an error: ~p~n", [Else]),
{error, Else}
end,
{reply, Reply, State};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
Function : handle_cast(Msg , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_cast({cloud_run, CloudName, Fun, [Args]}, #state{thrift_pid = P} = State) ->
cloud_run(P, CloudName, Fun, Args),
{noreply, State};
handle_cast(_Msg, State) ->
{noreply, State}.
Function : handle_info(Info , State ) - > { noreply , State } |
{ noreply , State , Timeout } |
handle_info({'EXIT', _Pid, Reason}, #state{start_args = _Args} = State) ->
NewState = State#state{port = Port } ,
?INFO("Received Exit in ~p: ~p~n", [?MODULE, Reason]),
{noreply, State};
handle_info({_Port,{exit_status,10}}, State) -> {noreply, State};
handle_info({_Port,{exit_status,0}}, #state{start_args = Args} = State) -> {noreply, State};
handle_info({Port, {exit_status, Status}}, #state{port=Port}=State) ->
?ERROR("OS Process died with status: ~p", [Status]),
{stop, {exit_status, Status}, State};
handle_info({_Port, {data, {eol, Data}}}, State) ->
?INFO("~p~n", [Data]),
{noreply, State};
handle_info(Info, State) ->
?INFO("Received info in ~p: ~p~n", [?MODULE, Info]),
{noreply, State}.
terminate(Reason, #state{start_args = _Args} = _State) ->
?ERROR("~p terminating: ~p~n", [?MODULE, Reason]),
ok.
Func : code_change(OldVsn , State , Extra ) - > { ok , NewState }
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
get_hostname() ->
{ok, "localhost"}.
Start thrift server ( in erlang )
start_thrift_server(Args) ->
ThriftPort = proplists:get_value(proto_port, Args),
Module = proplists:get_value(module, Args),
thrift_socket_server:start([
{port, ThriftPort},
{name, ambassador},
{service, ambassador_thrift},
{handler, Module},
{socket_opts, [{recv_timeout, infinity}]}]),
ok.
start_thrift_cloud_server(Args) ->
process_flag(trap_exit, true),
StartCmd = build_start_command("start", Args),
Port = open_port({spawn, StartCmd ++ " "}, ?PORT_OPTIONS),
Port.
? INFO("Starting ~p : ~p ~ n " , [ ? MODULE , ] ) ,
Pid
stop_thrift_client(Args) ->
StopCmd = build_start_command("stop", Args),
?INFO("Stopping ~p: ~p~n", [?MODULE, StopCmd]),
spawn_link(fun() -> os:cmd(StopCmd) end).
Function : build_start_command ( Action , ) - > cloud thrift string
build_start_command(Action, Args) ->
ThriftPort = proplists:get_value(proto_port, Args),
CloudConfig = proplists:get_value(clouds_config, Args),
CloudName = proplists : get_value(cloud_name , ) ,
ExtraArgs = lists:append([
[" --port ", erlang:integer_to_list(ThriftPort)],
[" -c ", CloudConfig]
[ " -n " , ]
]),
StartCommand = lists:flatten(lists:append([["cloud thrift ", Action, " "], [ExtraArgs]])),
StartCommand.
cloud_query(P, Name, Meth, Args) ->
Query = #cloudQuery{name=Name},
{'EXIT', R} ->
case R of
{timeout, _} -> {error, timeout};
E -> {error, E}
end;
E -> E
end.
cloud_run(P, Name, Meth, Args) ->
Query = #cloudQuery{name=Name},
?INFO("Casting the command ~p through ~p~n", [Meth, ?MODULE]),
{'EXIT', R} ->
?ERROR("Got back an EXIT error: ~p~n", [R]),
case R of
{timeout, _} -> {error, timeout};
E -> {error, E}
end;
E ->
?INFO("Received ~p from cloud_run~n", [E]),
E
end.
|
8d04d67457229ac65e83bec6fafb4509410314156b270c78d3b85a3746d1991e | engineyard/vertebra-erl | error_builder.erl | Copyright 2008 , Engine Yard , Inc.
%
This file is part of Vertebra .
%
Vertebra 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.
%
Vertebra 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 Vertebra . If not , see < / > .
-module(error_builder).
-author("").
-export([iq_error/3, vert_error/4]).
-include("xml.hrl").
-define(DEFAULT_ATTRS, [{"xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas"}]).
-define(ERROR_TYPES, [{400, [#xmlelement{name="bad-request",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"modify"]},
{403, [#xmlelement{name="forbidden",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"auth"]},
{404, [#xmlelement{name="recipient-unavailable",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"wait"]},
{500, [#xmlelement{name="undefined-condition",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"cancel"]},
{503, [#xmlelement{name="service-unavailable",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"cancel"]}].
vert_error(Message, {From, Id, StanzaType}, Token, To) ->
VertError = vertebra_protocol:error(Message, Token),
IQ = vertebra_protocol:finalize(VertError, StanzaType, Id),
NewIQ = case From of
undefined ->
IQ;
_ ->
IQ#xmlelement{attrs=[{"from", From}|IQ#xmlelement.attrs]}
end,
NewIQ#xmlelement{attrs=[{"to", To}|IQ#xmlelement.attrs]}.
iq_error(Code, From, To) ->
case proplists:get_value(Code, ?ERROR_TYPES) of
undefined ->
no_err_template;
[ErrorElement, ErrorType] ->
Attrs = case From =:= undefined of
true ->
[{"to", To},
{"type", "error"}];
false ->
[{"from", From},
{"to", To},
{"type", "error"}]
end,
#xmlelement{name="iq",
attrs=Attrs,
sub_el=[#xmlelement{name="error",
attrs=[{"type", ErrorType},
{"code", integer_to_list(Code)}],
sub_el=[ErrorElement]}]}
end.
| null | https://raw.githubusercontent.com/engineyard/vertebra-erl/cf6e7c84f6dfbf2e31f19c47e9db112ae292ec27/lib/vertebra/src/error_builder.erl | erlang |
terms of the GNU Lesser General Public License as published by the Free
later version.
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
| Copyright 2008 , Engine Yard , Inc.
This file is part of Vertebra .
Vertebra is free software : you can redistribute it and/or modify it under the
Software Foundation , either version 3 of the License , or ( at your option ) any
Vertebra is distributed in the hope that it will be useful , but WITHOUT ANY
You should have received a copy of the GNU Lesser General Public License
along with Vertebra . If not , see < / > .
-module(error_builder).
-author("").
-export([iq_error/3, vert_error/4]).
-include("xml.hrl").
-define(DEFAULT_ATTRS, [{"xmlns", "urn:ietf:params:xml:ns:xmpp-stanzas"}]).
-define(ERROR_TYPES, [{400, [#xmlelement{name="bad-request",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"modify"]},
{403, [#xmlelement{name="forbidden",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"auth"]},
{404, [#xmlelement{name="recipient-unavailable",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"wait"]},
{500, [#xmlelement{name="undefined-condition",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"cancel"]},
{503, [#xmlelement{name="service-unavailable",
attrs=?DEFAULT_ATTRS,
sub_el=[]},
"cancel"]}].
vert_error(Message, {From, Id, StanzaType}, Token, To) ->
VertError = vertebra_protocol:error(Message, Token),
IQ = vertebra_protocol:finalize(VertError, StanzaType, Id),
NewIQ = case From of
undefined ->
IQ;
_ ->
IQ#xmlelement{attrs=[{"from", From}|IQ#xmlelement.attrs]}
end,
NewIQ#xmlelement{attrs=[{"to", To}|IQ#xmlelement.attrs]}.
iq_error(Code, From, To) ->
case proplists:get_value(Code, ?ERROR_TYPES) of
undefined ->
no_err_template;
[ErrorElement, ErrorType] ->
Attrs = case From =:= undefined of
true ->
[{"to", To},
{"type", "error"}];
false ->
[{"from", From},
{"to", To},
{"type", "error"}]
end,
#xmlelement{name="iq",
attrs=Attrs,
sub_el=[#xmlelement{name="error",
attrs=[{"type", ErrorType},
{"code", integer_to_list(Code)}],
sub_el=[ErrorElement]}]}
end.
|
300f4ec5454313db507ef94dabff5a079fb043ad5077c93105c4adbb022d3a84 | denisidoro/graffiti | keyword.clj | (ns graffiti.keyword
(:require [camel-snake-kebab.core :as snake]
[clojure.spec.alpha :as s]
[com.wsscode.pathom.connect :as pc]
[quark.collection.map :as map]
[clojure.string :as str]))
(defn from-ident
[ident]
(let [get-spec (s/get-spec ident)]
(if (keyword? get-spec)
get-spec
(->> ident s/describe flatten reverse (map/find-first keyword?)))))
(defn from-resolver
[resolver]
(keyword (::pc/sym resolver)))
(defn from-type+input
[type input]
(keyword (name type) (-> (str (or (seq input) :none))
(str/replace #"[#\{\}:\(\)]" "")
(str/replace #"/" "_"))))
(defn snake-fn
[f k]
(if-not (keyword? k)
(f k)
(let [k-ns (namespace k)
k-name (name k)]
(if k-ns
(keyword (-> k-ns f name) (-> k-name f name))
(f k)))))
(def camel-case
(partial snake-fn snake/->camelCase))
(def kebab-case
(partial snake-fn snake/->kebab-case))
(defn sanitize
[k]
(let [k-ns (namespace k)
k-name (name k)]
(keyword (snake/->kebab-case k-ns) k-name)))
(defn graphql
[k]
(if (qualified-keyword? k)
(keyword (-> k namespace keyword graphql name)
(-> k name keyword graphql name))
(->> (str/split (name k) #"\.")
(map camel-case)
(str/join "_")
keyword)))
(defn eql
[k]
(if (qualified-keyword? k)
(keyword (-> k namespace keyword eql name)
(-> k name keyword eql name))
(->> (str/split (name k) #"\_")
(map kebab-case)
(str/join ".")
keyword)))
(defn fix-todo
[{:graffiti/keys [eql-conformer]
:lacinia/keys [objects]}
k]
(let [k-ns (keyword (namespace k))
k-name (name k)
k-ns+ (-> objects
(get k-ns)
namespace)
k-edn (keyword k-ns+ k-name)]
(eql-conformer k-edn)))
| null | https://raw.githubusercontent.com/denisidoro/graffiti/f4ea2103e060fafe2c84a14aff5f68cf8039e1aa/src/graffiti/keyword.clj | clojure | (ns graffiti.keyword
(:require [camel-snake-kebab.core :as snake]
[clojure.spec.alpha :as s]
[com.wsscode.pathom.connect :as pc]
[quark.collection.map :as map]
[clojure.string :as str]))
(defn from-ident
[ident]
(let [get-spec (s/get-spec ident)]
(if (keyword? get-spec)
get-spec
(->> ident s/describe flatten reverse (map/find-first keyword?)))))
(defn from-resolver
[resolver]
(keyword (::pc/sym resolver)))
(defn from-type+input
[type input]
(keyword (name type) (-> (str (or (seq input) :none))
(str/replace #"[#\{\}:\(\)]" "")
(str/replace #"/" "_"))))
(defn snake-fn
[f k]
(if-not (keyword? k)
(f k)
(let [k-ns (namespace k)
k-name (name k)]
(if k-ns
(keyword (-> k-ns f name) (-> k-name f name))
(f k)))))
(def camel-case
(partial snake-fn snake/->camelCase))
(def kebab-case
(partial snake-fn snake/->kebab-case))
(defn sanitize
[k]
(let [k-ns (namespace k)
k-name (name k)]
(keyword (snake/->kebab-case k-ns) k-name)))
(defn graphql
[k]
(if (qualified-keyword? k)
(keyword (-> k namespace keyword graphql name)
(-> k name keyword graphql name))
(->> (str/split (name k) #"\.")
(map camel-case)
(str/join "_")
keyword)))
(defn eql
[k]
(if (qualified-keyword? k)
(keyword (-> k namespace keyword eql name)
(-> k name keyword eql name))
(->> (str/split (name k) #"\_")
(map kebab-case)
(str/join ".")
keyword)))
(defn fix-todo
[{:graffiti/keys [eql-conformer]
:lacinia/keys [objects]}
k]
(let [k-ns (keyword (namespace k))
k-name (name k)
k-ns+ (-> objects
(get k-ns)
namespace)
k-edn (keyword k-ns+ k-name)]
(eql-conformer k-edn)))
| |
b559dff9f09711db6589821c9381448bc34320a98100fe9416999b6e0d539ad1 | aelve/guide | Core.hs | {-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
-- | Core types for content.
--
-- The whole site is a list of categories ('Category'). Categories have
-- items ('Item') in them. Items have some sections (fields inside of
-- 'Item'), as well as traits ('Trait').
module Guide.Types.Core
(
Trait(..),
TraitLenses(..),
TraitType (..),
ItemKind(..),
hackageName,
ItemSection(..),
Item(..),
ItemLenses(..),
CategoryStatus(..),
Category(..),
CategoryLenses(..),
categorySlug,
)
where
import Imports
-- acid-state
import Data.SafeCopy hiding (kind)
import Data.SafeCopy.Migrate
import Guide.Markdown
import Guide.Types.Hue
import Guide.Utils
import Guide.Uid
import Guide.Database.Utils (ToPostgres (..), FromPostgres (..))
import qualified Data.Aeson as Aeson
import qualified Data.Text as T
import qualified Hasql.Decoders as HD
import qualified Hasql.Encoders as HE
----------------------------------------------------------------------------
-- General notes on code
----------------------------------------------------------------------------
If you want to add a field to one of the types , see Note [ extending types ] .
For an explanation of deriveSafeCopySorted , see Note [ acid - state ] .
If you want to add a field to one of the types, see Note [extending types].
For an explanation of deriveSafeCopySorted, see Note [acid-state].
-}
----------------------------------------------------------------------------
-- Trait
----------------------------------------------------------------------------
-- | A trait (pro or con). Traits are stored in items.
data Trait = Trait {
traitUid :: Uid Trait,
traitContent :: MarkdownInline }
deriving (Show, Generic, Data, Eq)
deriveSafeCopySorted 4 'extension ''Trait
makeClassWithLenses ''Trait
changelog ''Trait (Current 4, Past 3) []
deriveSafeCopySorted 3 'base ''Trait_v3
instance Aeson.ToJSON Trait where
toJSON = Aeson.genericToJSON Aeson.defaultOptions {
Aeson.fieldLabelModifier = over _head toLower . drop (T.length "trait") }
| ADT for trait type . Traits can be pros ( positive traits ) and cons
-- (negative traits).
data TraitType = TraitTypePro | TraitTypeCon
deriving (Eq, Show)
instance ToPostgres TraitType where
toPostgres = HE.enum $ \case
TraitTypePro -> "pro"
TraitTypeCon -> "con"
instance FromPostgres TraitType where
fromPostgres = HD.enum $ \case
"pro" -> Just TraitTypePro
"con" -> Just TraitTypeCon
_ -> Nothing
----------------------------------------------------------------------------
-- Item
----------------------------------------------------------------------------
-- | Kind of an item (items can be libraries, tools, etc).
data ItemKind
= Library (Maybe Text) -- Hackage name
| Tool (Maybe Text) -- Hackage name
| Other
deriving (Eq, Show, Generic, Data)
deriveSafeCopySimple 3 'extension ''ItemKind
hackageName :: Traversal' ItemKind (Maybe Text)
hackageName f (Library x) = Library <$> f x
hackageName f (Tool x) = Tool <$> f x
hackageName _ Other = pure Other
instance Aeson.ToJSON ItemKind where
toJSON (Library x) = Aeson.object [
"tag" Aeson..= ("Library" :: Text),
"contents" Aeson..= x ]
toJSON (Tool x) = Aeson.object [
"tag" Aeson..= ("Tool" :: Text),
"contents" Aeson..= x ]
toJSON Other = Aeson.object [
"tag" Aeson..= ("Other" :: Text) ]
instance Aeson.FromJSON ItemKind where
parseJSON = Aeson.withObject "ItemKind" $ \o ->
o Aeson..: "tag" >>= \case
("Library" :: Text) -> Library <$> o Aeson..: "contents"
"Tool" -> Tool <$> o Aeson..: "contents"
"Other" -> pure Other
tag -> fail ("unknown tag " ++ show tag)
data ItemKind_v2
= Library_v2 (Maybe Text)
| Tool_v2 (Maybe Text)
| Other_v2
-- TODO: at the next migration change this to deriveSafeCopySimple!
deriveSafeCopy 2 'base ''ItemKind_v2
instance Migrate ItemKind where
type MigrateFrom ItemKind = ItemKind_v2
migrate (Library_v2 x) = Library x
migrate (Tool_v2 x) = Tool x
migrate Other_v2 = Other
-- | Different kinds of sections inside items. This type is only used for
-- 'categoryEnabledSections'.
data ItemSection
= ItemProsConsSection
| ItemEcosystemSection
| ItemNotesSection
deriving (Eq, Ord, Show, Generic, Data)
deriveSafeCopySimple 0 'base ''ItemSection
instance Aeson.ToJSON ItemSection where
toJSON = Aeson.genericToJSON Aeson.defaultOptions
instance Aeson.FromJSON ItemSection where
parseJSON = Aeson.genericParseJSON Aeson.defaultOptions
instance ToPostgres ItemSection where
toPostgres = HE.enum $ \case
ItemProsConsSection -> "pros_cons"
ItemEcosystemSection -> "ecosystem"
ItemNotesSection -> "notes"
instance FromPostgres ItemSection where
fromPostgres = HD.enum $ \case
"pros_cons" -> Just ItemProsConsSection
"ecosystem" -> Just ItemEcosystemSection
"notes" -> Just ItemNotesSection
_ -> Nothing
TODO : add a field like “ people to ask on IRC about this library if you
-- need help”
-- | An item (usually a library). Items are stored in categories.
data Item = Item {
itemUid :: Uid Item, -- ^ Item ID
itemName :: Text, -- ^ Item title
itemCreated :: UTCTime, -- ^ When the item was created
itemHackage :: Maybe Text, -- ^ Package name on Hackage
itemSummary :: MarkdownBlock, -- ^ Item summary
itemPros :: [Trait], -- ^ Pros (positive traits)
itemProsDeleted :: [Trait], -- ^ Deleted pros go here (so that
-- it'd be easy to restore them)
itemCons :: [Trait], -- ^ Cons (negative traits)
itemConsDeleted :: [Trait], -- ^ Deleted cons go here
itemEcosystem :: MarkdownBlock, -- ^ The ecosystem section
itemNotes :: MarkdownTree, -- ^ The notes section
itemLink :: Maybe Url -- ^ Link to homepage or something
}
deriving (Generic, Data, Eq, Show)
deriveSafeCopySorted 13 'extension ''Item
makeClassWithLenses ''Item
changelog ''Item (Current 13, Past 12)
[Removed "itemGroup_" [t|Maybe Text|] ]
deriveSafeCopySorted 12 'extension ''Item_v12
changelog ''Item (Past 12, Past 11)
[Removed "itemKind" [t|ItemKind|],
Added "itemHackage" [hs|
case itemKind of
Library m -> m
Tool m -> m
Other -> Nothing |],
Removed "itemDescription" [t|MarkdownBlock|],
Added "itemSummary" [hs|
itemDescription |] ]
deriveSafeCopySorted 11 'extension ''Item_v11
changelog ''Item (Past 11, Past 10) []
deriveSafeCopySorted 10 'base ''Item_v10
instance Aeson.ToJSON Item where
toJSON = Aeson.genericToJSON Aeson.defaultOptions {
Aeson.fieldLabelModifier = over _head toLower . drop (T.length "item") }
----------------------------------------------------------------------------
-- Category
----------------------------------------------------------------------------
-- | Category status
data CategoryStatus
^ “ ” = just created
^ “ WIP ” = work in progress
| CategoryFinished -- ^ “Finished” = complete or nearly complete
deriving (Eq, Show, Generic, Data)
deriveSafeCopySimple 2 'extension ''CategoryStatus
instance Aeson.ToJSON CategoryStatus where
toJSON = Aeson.genericToJSON Aeson.defaultOptions
instance Aeson.FromJSON CategoryStatus where
parseJSON = Aeson.genericParseJSON Aeson.defaultOptions
instance ToPostgres CategoryStatus where
toPostgres = HE.enum $ \case
CategoryStub -> "stub"
CategoryWIP -> "wip"
CategoryFinished -> "finished"
instance FromPostgres CategoryStatus where
fromPostgres = HD.enum $ \case
"stub" -> Just CategoryStub
"wip" -> Just CategoryWIP
"finished" -> Just CategoryFinished
_ -> Nothing
data CategoryStatus_v1
= CategoryStub_v1
| CategoryWIP_v1
| CategoryMostlyDone_v1
| CategoryFinished_v1
deriveSafeCopySimple 1 'base ''CategoryStatus_v1
instance Migrate CategoryStatus where
type MigrateFrom CategoryStatus = CategoryStatus_v1
migrate CategoryStub_v1 = CategoryStub
migrate CategoryWIP_v1 = CategoryWIP
migrate CategoryMostlyDone_v1 = CategoryFinished
migrate CategoryFinished_v1 = CategoryFinished
-- | A category
data Category = Category {
categoryUid :: Uid Category,
categoryTitle :: Text,
-- | When the category was created
categoryCreated :: UTCTime,
-- | The “grandcategory” of the category (“meta”, “basics”, etc)
categoryGroup :: Text,
categoryStatus :: CategoryStatus,
categoryNotes :: MarkdownBlock,
-- | Items stored in the category
categoryItems :: [Item],
-- | Items that were deleted from the category. We keep them here to make
-- it easier to restore them
categoryItemsDeleted :: [Item],
| Enabled sections in this category . E.g , if this set contains
-- 'ItemNotesSection', then notes will be shown for each item
categoryEnabledSections :: Set ItemSection
}
deriving (Generic, Data, Eq, Show)
deriveSafeCopySorted 13 'extension ''Category
makeClassWithLenses ''Category
changelog ''Category (Current 13, Past 12)
[Removed "categoryGroup_" [t|Text|]
,Added "categoryGroup" [hs|
categoryGroup_ |] ]
deriveSafeCopySorted 12 'extension ''Category_v12
changelog ''Category (Past 12, Past 11)
[Removed "categoryGroups" [t|Map Text Hue|] ]
deriveSafeCopySorted 11 'extension ''Category_v11
changelog ''Category (Past 11, Past 10)
[Removed "categoryProsConsEnabled" [t|Bool|],
Removed "categoryEcosystemEnabled" [t|Bool|],
Removed "categoryNotesEnabled" [t|Bool|],
Added "categoryEnabledSections" [hs|
toSet $ concat
[ [ItemProsConsSection | categoryProsConsEnabled]
, [ItemEcosystemSection | categoryEcosystemEnabled]
, [ItemNotesSection | categoryNotesEnabled] ] |] ]
deriveSafeCopySorted 10 'extension ''Category_v10
changelog ''Category (Past 10, Past 9)
[Added "categoryNotesEnabled" [hs|True|]]
deriveSafeCopySorted 9 'extension ''Category_v9
changelog ''Category (Past 9, Past 8) []
deriveSafeCopySorted 8 'base ''Category_v8
instance Aeson.ToJSON Category where
toJSON = Aeson.genericToJSON Aeson.defaultOptions {
Aeson.fieldLabelModifier = over _head toLower . drop (T.length "category") }
-- | Category identifier (used in URLs). E.g. for a category with title
-- “Performance optimization” and UID “t3c9hwzo” the slug would be
@performance - optimization - t3c9hwzo@.
categorySlug :: Category -> Text
categorySlug category =
format "{}-{}" (makeSlug (categoryTitle category)) (categoryUid category)
| null | https://raw.githubusercontent.com/aelve/guide/96a338d61976344d2405a16b11567e5464820a9e/back/src/Guide/Types/Core.hs | haskell | # LANGUAGE FlexibleContexts #
| Core types for content.
The whole site is a list of categories ('Category'). Categories have
items ('Item') in them. Items have some sections (fields inside of
'Item'), as well as traits ('Trait').
acid-state
--------------------------------------------------------------------------
General notes on code
--------------------------------------------------------------------------
--------------------------------------------------------------------------
Trait
--------------------------------------------------------------------------
| A trait (pro or con). Traits are stored in items.
(negative traits).
--------------------------------------------------------------------------
Item
--------------------------------------------------------------------------
| Kind of an item (items can be libraries, tools, etc).
Hackage name
Hackage name
TODO: at the next migration change this to deriveSafeCopySimple!
| Different kinds of sections inside items. This type is only used for
'categoryEnabledSections'.
need help”
| An item (usually a library). Items are stored in categories.
^ Item ID
^ Item title
^ When the item was created
^ Package name on Hackage
^ Item summary
^ Pros (positive traits)
^ Deleted pros go here (so that
it'd be easy to restore them)
^ Cons (negative traits)
^ Deleted cons go here
^ The ecosystem section
^ The notes section
^ Link to homepage or something
--------------------------------------------------------------------------
Category
--------------------------------------------------------------------------
| Category status
^ “Finished” = complete or nearly complete
| A category
| When the category was created
| The “grandcategory” of the category (“meta”, “basics”, etc)
| Items stored in the category
| Items that were deleted from the category. We keep them here to make
it easier to restore them
'ItemNotesSection', then notes will be shown for each item
| Category identifier (used in URLs). E.g. for a category with title
“Performance optimization” and UID “t3c9hwzo” the slug would be | # LANGUAGE FlexibleInstances #
module Guide.Types.Core
(
Trait(..),
TraitLenses(..),
TraitType (..),
ItemKind(..),
hackageName,
ItemSection(..),
Item(..),
ItemLenses(..),
CategoryStatus(..),
Category(..),
CategoryLenses(..),
categorySlug,
)
where
import Imports
import Data.SafeCopy hiding (kind)
import Data.SafeCopy.Migrate
import Guide.Markdown
import Guide.Types.Hue
import Guide.Utils
import Guide.Uid
import Guide.Database.Utils (ToPostgres (..), FromPostgres (..))
import qualified Data.Aeson as Aeson
import qualified Data.Text as T
import qualified Hasql.Decoders as HD
import qualified Hasql.Encoders as HE
If you want to add a field to one of the types , see Note [ extending types ] .
For an explanation of deriveSafeCopySorted , see Note [ acid - state ] .
If you want to add a field to one of the types, see Note [extending types].
For an explanation of deriveSafeCopySorted, see Note [acid-state].
-}
data Trait = Trait {
traitUid :: Uid Trait,
traitContent :: MarkdownInline }
deriving (Show, Generic, Data, Eq)
deriveSafeCopySorted 4 'extension ''Trait
makeClassWithLenses ''Trait
changelog ''Trait (Current 4, Past 3) []
deriveSafeCopySorted 3 'base ''Trait_v3
instance Aeson.ToJSON Trait where
toJSON = Aeson.genericToJSON Aeson.defaultOptions {
Aeson.fieldLabelModifier = over _head toLower . drop (T.length "trait") }
| ADT for trait type . Traits can be pros ( positive traits ) and cons
data TraitType = TraitTypePro | TraitTypeCon
deriving (Eq, Show)
instance ToPostgres TraitType where
toPostgres = HE.enum $ \case
TraitTypePro -> "pro"
TraitTypeCon -> "con"
instance FromPostgres TraitType where
fromPostgres = HD.enum $ \case
"pro" -> Just TraitTypePro
"con" -> Just TraitTypeCon
_ -> Nothing
data ItemKind
| Other
deriving (Eq, Show, Generic, Data)
deriveSafeCopySimple 3 'extension ''ItemKind
hackageName :: Traversal' ItemKind (Maybe Text)
hackageName f (Library x) = Library <$> f x
hackageName f (Tool x) = Tool <$> f x
hackageName _ Other = pure Other
instance Aeson.ToJSON ItemKind where
toJSON (Library x) = Aeson.object [
"tag" Aeson..= ("Library" :: Text),
"contents" Aeson..= x ]
toJSON (Tool x) = Aeson.object [
"tag" Aeson..= ("Tool" :: Text),
"contents" Aeson..= x ]
toJSON Other = Aeson.object [
"tag" Aeson..= ("Other" :: Text) ]
instance Aeson.FromJSON ItemKind where
parseJSON = Aeson.withObject "ItemKind" $ \o ->
o Aeson..: "tag" >>= \case
("Library" :: Text) -> Library <$> o Aeson..: "contents"
"Tool" -> Tool <$> o Aeson..: "contents"
"Other" -> pure Other
tag -> fail ("unknown tag " ++ show tag)
data ItemKind_v2
= Library_v2 (Maybe Text)
| Tool_v2 (Maybe Text)
| Other_v2
deriveSafeCopy 2 'base ''ItemKind_v2
instance Migrate ItemKind where
type MigrateFrom ItemKind = ItemKind_v2
migrate (Library_v2 x) = Library x
migrate (Tool_v2 x) = Tool x
migrate Other_v2 = Other
data ItemSection
= ItemProsConsSection
| ItemEcosystemSection
| ItemNotesSection
deriving (Eq, Ord, Show, Generic, Data)
deriveSafeCopySimple 0 'base ''ItemSection
instance Aeson.ToJSON ItemSection where
toJSON = Aeson.genericToJSON Aeson.defaultOptions
instance Aeson.FromJSON ItemSection where
parseJSON = Aeson.genericParseJSON Aeson.defaultOptions
instance ToPostgres ItemSection where
toPostgres = HE.enum $ \case
ItemProsConsSection -> "pros_cons"
ItemEcosystemSection -> "ecosystem"
ItemNotesSection -> "notes"
instance FromPostgres ItemSection where
fromPostgres = HD.enum $ \case
"pros_cons" -> Just ItemProsConsSection
"ecosystem" -> Just ItemEcosystemSection
"notes" -> Just ItemNotesSection
_ -> Nothing
TODO : add a field like “ people to ask on IRC about this library if you
data Item = Item {
}
deriving (Generic, Data, Eq, Show)
deriveSafeCopySorted 13 'extension ''Item
makeClassWithLenses ''Item
changelog ''Item (Current 13, Past 12)
[Removed "itemGroup_" [t|Maybe Text|] ]
deriveSafeCopySorted 12 'extension ''Item_v12
changelog ''Item (Past 12, Past 11)
[Removed "itemKind" [t|ItemKind|],
Added "itemHackage" [hs|
case itemKind of
Library m -> m
Tool m -> m
Other -> Nothing |],
Removed "itemDescription" [t|MarkdownBlock|],
Added "itemSummary" [hs|
itemDescription |] ]
deriveSafeCopySorted 11 'extension ''Item_v11
changelog ''Item (Past 11, Past 10) []
deriveSafeCopySorted 10 'base ''Item_v10
instance Aeson.ToJSON Item where
toJSON = Aeson.genericToJSON Aeson.defaultOptions {
Aeson.fieldLabelModifier = over _head toLower . drop (T.length "item") }
data CategoryStatus
^ “ ” = just created
^ “ WIP ” = work in progress
deriving (Eq, Show, Generic, Data)
deriveSafeCopySimple 2 'extension ''CategoryStatus
instance Aeson.ToJSON CategoryStatus where
toJSON = Aeson.genericToJSON Aeson.defaultOptions
instance Aeson.FromJSON CategoryStatus where
parseJSON = Aeson.genericParseJSON Aeson.defaultOptions
instance ToPostgres CategoryStatus where
toPostgres = HE.enum $ \case
CategoryStub -> "stub"
CategoryWIP -> "wip"
CategoryFinished -> "finished"
instance FromPostgres CategoryStatus where
fromPostgres = HD.enum $ \case
"stub" -> Just CategoryStub
"wip" -> Just CategoryWIP
"finished" -> Just CategoryFinished
_ -> Nothing
data CategoryStatus_v1
= CategoryStub_v1
| CategoryWIP_v1
| CategoryMostlyDone_v1
| CategoryFinished_v1
deriveSafeCopySimple 1 'base ''CategoryStatus_v1
instance Migrate CategoryStatus where
type MigrateFrom CategoryStatus = CategoryStatus_v1
migrate CategoryStub_v1 = CategoryStub
migrate CategoryWIP_v1 = CategoryWIP
migrate CategoryMostlyDone_v1 = CategoryFinished
migrate CategoryFinished_v1 = CategoryFinished
data Category = Category {
categoryUid :: Uid Category,
categoryTitle :: Text,
categoryCreated :: UTCTime,
categoryGroup :: Text,
categoryStatus :: CategoryStatus,
categoryNotes :: MarkdownBlock,
categoryItems :: [Item],
categoryItemsDeleted :: [Item],
| Enabled sections in this category . E.g , if this set contains
categoryEnabledSections :: Set ItemSection
}
deriving (Generic, Data, Eq, Show)
deriveSafeCopySorted 13 'extension ''Category
makeClassWithLenses ''Category
changelog ''Category (Current 13, Past 12)
[Removed "categoryGroup_" [t|Text|]
,Added "categoryGroup" [hs|
categoryGroup_ |] ]
deriveSafeCopySorted 12 'extension ''Category_v12
changelog ''Category (Past 12, Past 11)
[Removed "categoryGroups" [t|Map Text Hue|] ]
deriveSafeCopySorted 11 'extension ''Category_v11
changelog ''Category (Past 11, Past 10)
[Removed "categoryProsConsEnabled" [t|Bool|],
Removed "categoryEcosystemEnabled" [t|Bool|],
Removed "categoryNotesEnabled" [t|Bool|],
Added "categoryEnabledSections" [hs|
toSet $ concat
[ [ItemProsConsSection | categoryProsConsEnabled]
, [ItemEcosystemSection | categoryEcosystemEnabled]
, [ItemNotesSection | categoryNotesEnabled] ] |] ]
deriveSafeCopySorted 10 'extension ''Category_v10
changelog ''Category (Past 10, Past 9)
[Added "categoryNotesEnabled" [hs|True|]]
deriveSafeCopySorted 9 'extension ''Category_v9
changelog ''Category (Past 9, Past 8) []
deriveSafeCopySorted 8 'base ''Category_v8
instance Aeson.ToJSON Category where
toJSON = Aeson.genericToJSON Aeson.defaultOptions {
Aeson.fieldLabelModifier = over _head toLower . drop (T.length "category") }
@performance - optimization - t3c9hwzo@.
categorySlug :: Category -> Text
categorySlug category =
format "{}-{}" (makeSlug (categoryTitle category)) (categoryUid category)
|
a9bb197f0a4e54ca752b020379cc27abd1c4512eceb408b843bf221466df47f2 | meain/evil-textobj-tree-sitter | textobjects.scm | (block (body)? @block.inner ) @block.outer
(block (body (_) @statement.outer))
(comment) @comment.outer
| null | https://raw.githubusercontent.com/meain/evil-textobj-tree-sitter/f3b3e9554e5ecae55200454804e183e268b4a6fc/queries/hcl/textobjects.scm | scheme | (block (body)? @block.inner ) @block.outer
(block (body (_) @statement.outer))
(comment) @comment.outer
| |
65d04fd2f3096815e1473c7aba3c3b34369de64031ed45d9c9c9f8c85ac0eb22 | Clozure/ccl-tests | numbers-aux.lsp | ;-*- Mode: Lisp -*-
Author :
Created : Mon Apr 7 07:24:43 2003
;;;; Contains: Auxiliary functions for number tests
(in-package :cl-test)
(eval-when (:compile-toplevel :load-toplevel :execute)
(compile-and-load "random-aux.lsp"))
;;; Binary search on reals
(defun float-binary-search (fn lo hi)
"FN is a function that, if true for X, is true for all Y > X.
Find the smallest float in [lo,hi] for which the function
return true."
(assert (functionp fn))
(assert (floatp lo))
(assert (floatp hi))
(assert (<= lo hi))
(assert (funcall fn hi))
(loop while (<= lo hi)
do (let ((mid (/ (+ lo hi) 2)))
(if (funcall fn mid)
(if (= mid hi)
(return hi)
(setq hi mid))
(if (= mid lo)
(return hi)
(setq lo mid))))))
(defun integer-binary-search (fn lo hi)
"FN is a function that, if true for X, is true for all Y < X.
Find the largest integer in [lo,hi) for which the function
return true."
(assert (functionp fn))
(assert (integerp lo))
(assert (integerp hi))
(assert (<= lo hi))
(assert (funcall fn lo))
(loop while (< lo hi)
do (let ((mid (ceiling (+ lo hi) 2)))
(if (funcall fn mid)
(setq lo mid)
(if (= mid hi)
(return lo)
(setq hi mid))))
finally (return lo)))
(defun find-largest-exactly-floatable-integer (upper-bound)
(integer-binary-search
#'(lambda (i)
(let* ((f (float i))
(i- (1- i))
(f- (float i-)))
(and (= f i) (= f- i-))))
0 upper-bound))
(defun eqlzt (x y)
"Return T if (eql x y) or if both are zero of the same type."
(cond
((complexp x)
(and (complexp y)
(eqlzt (realpart x) (realpart y))
(eqlzt (imagpart x) (imagpart y))))
((zerop x)
(eqlt (abs x) (abs y)))
(t (eqlt x y))))
(defconstant +rational-most-negative-short-float+
(rational-safely most-negative-short-float))
(defconstant +rational-most-negative-single-float+
(rational-safely most-negative-single-float))
(defconstant +rational-most-negative-double-float+
(rational-safely most-negative-double-float))
(defconstant +rational-most-negative-long-float+
(rational-safely most-negative-long-float))
(defconstant +rational-most-positive-short-float+
(rational-safely most-positive-short-float))
(defconstant +rational-most-positive-single-float+
(rational-safely most-positive-single-float))
(defconstant +rational-most-positive-double-float+
(rational-safely most-positive-double-float))
(defconstant +rational-most-positive-long-float+
(rational-safely most-positive-long-float))
(defun float-exponent (x)
(if (floatp x)
(nth-value 1 (decode-float x))
0))
(defun numbers-are-compatible (x y)
(cond
((complexp x)
(and (numbers-are-compatible (realpart x) y)
(numbers-are-compatible (imagpart x) y)))
((complexp y)
(and (numbers-are-compatible x (realpart y))
(numbers-are-compatible x (imagpart y))))
(t
(when (floatp x) (rotatef x y))
(or (floatp x)
(not (floatp y))
(etypecase y
(short-float
(<= +rational-most-negative-short-float+
x
+rational-most-positive-short-float+))
(single-float
(<= +rational-most-negative-single-float+
x
+rational-most-positive-single-float+))
(double-float
(<= +rational-most-negative-double-float+
x
+rational-most-positive-double-float+))
(long-float
(<= +rational-most-negative-long-float+
x
+rational-most-positive-long-float+)))))))
NOTE ! According to section 12.1.4.1 , when a rational is compared
;;; to a float, the effect is as if the float is convert to a rational
;;; (by RATIONAL), not as if the rational is converted to a float.
;;; This means the calls to numbers-are-compatible are not necessary.
(defun =.4-fn ()
(loop for x in *numbers*
append
(loop for y in *numbers*
unless (or ;; (not (numbers-are-compatible x y))
(if (= x y) (= y x) (not (= y x))))
collect (list x y))))
(defun /=.4-fn ()
(loop for x in *numbers*
append
(loop for y in *numbers*
unless (or ;; (not (numbers-are-compatible x y))
(if (/= x y) (/= y x) (not (/= y x))))
collect (list x y))))
(defun /=.4a-fn ()
(loop for x in *numbers*
append
(loop for y in *numbers*
when (and ;; (numbers-are-compatible x y)
(if (= x y)
(/= x y)
(not (/= x y))))
collect (list x y))))
(defun <.8-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(and ;; (numbers-are-compatible x y)
(and (< x y) (> x y)))
(arithmetic-error () nil))
collect (list x y))))
(defun <.9-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(and ;; (numbers-are-compatible x y)
(if (< x y) (not (> y x))
(> y x)))
(arithmetic-error () nil))
collect (list x y))))
(defun <.10-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(and ;; (numbers-are-compatible x y)
(if (< x y) (>= x y)
(not (>= x y))))
(arithmetic-error () nil))
collect (list x y))))
(defun <=.8-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(and ;; (numbers-are-compatible x y)
(if (<= x y) (not (>= y x))
(>= y x)))
(arithmetic-error () nil))
collect (list x y))))
(defun <=.9-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(and ;; (numbers-are-compatible x y)
(if (<= x y) (not (or (= x y) (< x y)))
(or (= x y) (< x y))))
(arithmetic-error () nil))
collect (list x y))))
(defun >.8-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(and ;; (numbers-are-compatible x y)
(if (> x y) (<= x y)
(not (<= x y))))
(arithmetic-error () nil))
collect (list x y))))
(defun >=.8-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(and ;; (numbers-are-compatible x y)
(if (>= x y) (not (or (= x y) (> x y)))
(or (= x y) (> x y))))
(arithmetic-error () nil))
collect (list x y))))
;;; Comparison of rationsls
(defun compare-random-rationals (n m rep)
(loop for a = (- (random n) m)
for b = (- (random n) m)
for c = (- (random n) m)
for d = (- (random n) m)
repeat rep
when
(and (/= b 0)
(/= d 0)
(let ((q1 (/ a b))
(q2 (/ c d))
(ad (* a d))
(bc (* b c)))
(when (< (* b d) 0)
(setq ad (- ad))
(setq bc (- bc)))
(or (if (< q1 q2) (not (< ad bc)) (< ad bc))
(if (<= q1 q2) (not (<= ad bc)) (<= ad bc))
(if (> q1 q2) (not (> ad bc)) (> ad bc))
(if (>= q1 q2) (not (>= ad bc)) (>= ad bc))
(if (= q1 q2) (not (= ad bc)) (= ad bc))
(if (/= q1 q2) (not (/= ad bc)) (/= ad bc)))))
collect (list a b c d)))
(defun max.2-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when (numbers-are-compatible x y)
unless
(handler-case
(let ((m (max x y)))
(and (>= m x) (>= m y)
(or (= m x) (= m y))))
(floating-point-underflow () t)
(floating-point-overflow () t))
collect (list x y (max x y)))))
(defun min.2-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when (numbers-are-compatible x y)
unless
(handler-case
(let ((m (min x y)))
(and (<= m x) (<= m y)
(or (= m x) (= m y))))
(floating-point-underflow () t)
(floating-point-overflow () t))
collect (list x y (min x y)))))
Compute the number of digits that can be added to 1.0 in the appropriate
float type , a rational representation of the smallest radix^(-k )
1.0 + radix^(-k ) /= 1.0 , and the float representation of that value .
;;; Note that this will in general be > <float-type>-epsilon.
(defun find-epsilon (x)
(assert (floatp x))
(let* ((one (float 1 x))
(radix (float-radix one))
(eps (/ 1 radix)))
(loop
for next-eps = (/ eps radix)
for i from 1
until (eql one (+ one next-eps))
do (setq eps next-eps)
finally (return (values i eps (float eps one))))))
(defun test-log-op-with-decls (op xlo xhi ylo yhi niters
&optional
(decls '((optimize (speed 3) (safety 1)
(debug 1)))))
"Test that a compiled form of the LOG* function OP computes
the expected result on two random integers drawn from the
types `(integer ,xlo ,xhi) and `(integer ,ylo ,yhi). Try
niters choices. Return a list of pairs on which the test fails."
(assert (symbolp op))
(assert (integerp xlo))
(assert (integerp xhi))
(assert (integerp ylo))
(assert (integerp yhi))
(assert (integerp niters))
(assert (<= xlo xhi))
(assert (<= ylo yhi))
(let* ((source
`(lambda (x y)
(declare (type (integer ,xlo ,xhi) x)
(type (integer ,ylo ,yhi) y)
,@ decls)
(,op x y)))
(fn (compile nil source)))
(loop for i below niters
for x = (random-from-interval (1+ xhi) xlo)
for y = (random-from-interval (1+ yhi) ylo)
unless (eql (funcall (the symbol op) x y)
(funcall fn x y))
collect (list x y))))
(defun test-log-op (op n1 n2)
(flet ((%r () (let ((r (random 33)))
(- (random (ash 1 (1+ r))) (ash 1 r)))))
(loop for x1 = (%r)
for x2 = (%r)
for y1 = (%r)
for y2 = (%r)
repeat n1
nconc
(test-log-op-with-decls op
(min x1 x2) (max x1 x2)
(min y1 y2) (max y1 y2)
n2))))
(defun safe-tan (x &optional (default 0.0))
(handler-case
(let ((result (multiple-value-list (tan x))))
(assert (null (cdr result)))
(car result))
(arithmetic-error () default)))
| null | https://raw.githubusercontent.com/Clozure/ccl-tests/0478abddb34dbc16487a1975560d8d073a988060/ansi-tests/numbers-aux.lsp | lisp | -*- Mode: Lisp -*-
Contains: Auxiliary functions for number tests
Binary search on reals
to a float, the effect is as if the float is convert to a rational
(by RATIONAL), not as if the rational is converted to a float.
This means the calls to numbers-are-compatible are not necessary.
(not (numbers-are-compatible x y))
(not (numbers-are-compatible x y))
(numbers-are-compatible x y)
(numbers-are-compatible x y)
(numbers-are-compatible x y)
(numbers-are-compatible x y)
(numbers-are-compatible x y)
(numbers-are-compatible x y)
(numbers-are-compatible x y)
(numbers-are-compatible x y)
Comparison of rationsls
Note that this will in general be > <float-type>-epsilon. | Author :
Created : Mon Apr 7 07:24:43 2003
(in-package :cl-test)
(eval-when (:compile-toplevel :load-toplevel :execute)
(compile-and-load "random-aux.lsp"))
(defun float-binary-search (fn lo hi)
"FN is a function that, if true for X, is true for all Y > X.
Find the smallest float in [lo,hi] for which the function
return true."
(assert (functionp fn))
(assert (floatp lo))
(assert (floatp hi))
(assert (<= lo hi))
(assert (funcall fn hi))
(loop while (<= lo hi)
do (let ((mid (/ (+ lo hi) 2)))
(if (funcall fn mid)
(if (= mid hi)
(return hi)
(setq hi mid))
(if (= mid lo)
(return hi)
(setq lo mid))))))
(defun integer-binary-search (fn lo hi)
"FN is a function that, if true for X, is true for all Y < X.
Find the largest integer in [lo,hi) for which the function
return true."
(assert (functionp fn))
(assert (integerp lo))
(assert (integerp hi))
(assert (<= lo hi))
(assert (funcall fn lo))
(loop while (< lo hi)
do (let ((mid (ceiling (+ lo hi) 2)))
(if (funcall fn mid)
(setq lo mid)
(if (= mid hi)
(return lo)
(setq hi mid))))
finally (return lo)))
(defun find-largest-exactly-floatable-integer (upper-bound)
(integer-binary-search
#'(lambda (i)
(let* ((f (float i))
(i- (1- i))
(f- (float i-)))
(and (= f i) (= f- i-))))
0 upper-bound))
(defun eqlzt (x y)
"Return T if (eql x y) or if both are zero of the same type."
(cond
((complexp x)
(and (complexp y)
(eqlzt (realpart x) (realpart y))
(eqlzt (imagpart x) (imagpart y))))
((zerop x)
(eqlt (abs x) (abs y)))
(t (eqlt x y))))
(defconstant +rational-most-negative-short-float+
(rational-safely most-negative-short-float))
(defconstant +rational-most-negative-single-float+
(rational-safely most-negative-single-float))
(defconstant +rational-most-negative-double-float+
(rational-safely most-negative-double-float))
(defconstant +rational-most-negative-long-float+
(rational-safely most-negative-long-float))
(defconstant +rational-most-positive-short-float+
(rational-safely most-positive-short-float))
(defconstant +rational-most-positive-single-float+
(rational-safely most-positive-single-float))
(defconstant +rational-most-positive-double-float+
(rational-safely most-positive-double-float))
(defconstant +rational-most-positive-long-float+
(rational-safely most-positive-long-float))
(defun float-exponent (x)
(if (floatp x)
(nth-value 1 (decode-float x))
0))
(defun numbers-are-compatible (x y)
(cond
((complexp x)
(and (numbers-are-compatible (realpart x) y)
(numbers-are-compatible (imagpart x) y)))
((complexp y)
(and (numbers-are-compatible x (realpart y))
(numbers-are-compatible x (imagpart y))))
(t
(when (floatp x) (rotatef x y))
(or (floatp x)
(not (floatp y))
(etypecase y
(short-float
(<= +rational-most-negative-short-float+
x
+rational-most-positive-short-float+))
(single-float
(<= +rational-most-negative-single-float+
x
+rational-most-positive-single-float+))
(double-float
(<= +rational-most-negative-double-float+
x
+rational-most-positive-double-float+))
(long-float
(<= +rational-most-negative-long-float+
x
+rational-most-positive-long-float+)))))))
NOTE ! According to section 12.1.4.1 , when a rational is compared
(defun =.4-fn ()
(loop for x in *numbers*
append
(loop for y in *numbers*
(if (= x y) (= y x) (not (= y x))))
collect (list x y))))
(defun /=.4-fn ()
(loop for x in *numbers*
append
(loop for y in *numbers*
(if (/= x y) (/= y x) (not (/= y x))))
collect (list x y))))
(defun /=.4a-fn ()
(loop for x in *numbers*
append
(loop for y in *numbers*
(if (= x y)
(/= x y)
(not (/= x y))))
collect (list x y))))
(defun <.8-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(and (< x y) (> x y)))
(arithmetic-error () nil))
collect (list x y))))
(defun <.9-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(if (< x y) (not (> y x))
(> y x)))
(arithmetic-error () nil))
collect (list x y))))
(defun <.10-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(if (< x y) (>= x y)
(not (>= x y))))
(arithmetic-error () nil))
collect (list x y))))
(defun <=.8-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(if (<= x y) (not (>= y x))
(>= y x)))
(arithmetic-error () nil))
collect (list x y))))
(defun <=.9-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(if (<= x y) (not (or (= x y) (< x y)))
(or (= x y) (< x y))))
(arithmetic-error () nil))
collect (list x y))))
(defun >.8-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(if (> x y) (<= x y)
(not (<= x y))))
(arithmetic-error () nil))
collect (list x y))))
(defun >=.8-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when
(handler-case
(if (>= x y) (not (or (= x y) (> x y)))
(or (= x y) (> x y))))
(arithmetic-error () nil))
collect (list x y))))
(defun compare-random-rationals (n m rep)
(loop for a = (- (random n) m)
for b = (- (random n) m)
for c = (- (random n) m)
for d = (- (random n) m)
repeat rep
when
(and (/= b 0)
(/= d 0)
(let ((q1 (/ a b))
(q2 (/ c d))
(ad (* a d))
(bc (* b c)))
(when (< (* b d) 0)
(setq ad (- ad))
(setq bc (- bc)))
(or (if (< q1 q2) (not (< ad bc)) (< ad bc))
(if (<= q1 q2) (not (<= ad bc)) (<= ad bc))
(if (> q1 q2) (not (> ad bc)) (> ad bc))
(if (>= q1 q2) (not (>= ad bc)) (>= ad bc))
(if (= q1 q2) (not (= ad bc)) (= ad bc))
(if (/= q1 q2) (not (/= ad bc)) (/= ad bc)))))
collect (list a b c d)))
(defun max.2-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when (numbers-are-compatible x y)
unless
(handler-case
(let ((m (max x y)))
(and (>= m x) (>= m y)
(or (= m x) (= m y))))
(floating-point-underflow () t)
(floating-point-overflow () t))
collect (list x y (max x y)))))
(defun min.2-fn ()
(loop for x in *reals*
nconc
(loop for y in *reals*
when (numbers-are-compatible x y)
unless
(handler-case
(let ((m (min x y)))
(and (<= m x) (<= m y)
(or (= m x) (= m y))))
(floating-point-underflow () t)
(floating-point-overflow () t))
collect (list x y (min x y)))))
Compute the number of digits that can be added to 1.0 in the appropriate
float type , a rational representation of the smallest radix^(-k )
1.0 + radix^(-k ) /= 1.0 , and the float representation of that value .
(defun find-epsilon (x)
(assert (floatp x))
(let* ((one (float 1 x))
(radix (float-radix one))
(eps (/ 1 radix)))
(loop
for next-eps = (/ eps radix)
for i from 1
until (eql one (+ one next-eps))
do (setq eps next-eps)
finally (return (values i eps (float eps one))))))
(defun test-log-op-with-decls (op xlo xhi ylo yhi niters
&optional
(decls '((optimize (speed 3) (safety 1)
(debug 1)))))
"Test that a compiled form of the LOG* function OP computes
the expected result on two random integers drawn from the
types `(integer ,xlo ,xhi) and `(integer ,ylo ,yhi). Try
niters choices. Return a list of pairs on which the test fails."
(assert (symbolp op))
(assert (integerp xlo))
(assert (integerp xhi))
(assert (integerp ylo))
(assert (integerp yhi))
(assert (integerp niters))
(assert (<= xlo xhi))
(assert (<= ylo yhi))
(let* ((source
`(lambda (x y)
(declare (type (integer ,xlo ,xhi) x)
(type (integer ,ylo ,yhi) y)
,@ decls)
(,op x y)))
(fn (compile nil source)))
(loop for i below niters
for x = (random-from-interval (1+ xhi) xlo)
for y = (random-from-interval (1+ yhi) ylo)
unless (eql (funcall (the symbol op) x y)
(funcall fn x y))
collect (list x y))))
(defun test-log-op (op n1 n2)
(flet ((%r () (let ((r (random 33)))
(- (random (ash 1 (1+ r))) (ash 1 r)))))
(loop for x1 = (%r)
for x2 = (%r)
for y1 = (%r)
for y2 = (%r)
repeat n1
nconc
(test-log-op-with-decls op
(min x1 x2) (max x1 x2)
(min y1 y2) (max y1 y2)
n2))))
(defun safe-tan (x &optional (default 0.0))
(handler-case
(let ((result (multiple-value-list (tan x))))
(assert (null (cdr result)))
(car result))
(arithmetic-error () default)))
|
0448e504c3dae537efb35a96e8ed947b0b9e335e7bf3370d75de35fc957a965c | Bogdanp/racket-forms | form-tests.rkt | #lang racket/base
(require forms
(submod forms/private/form internal)
racket/match
racket/string
rackunit
(only-in web-server/http make-binding:form)
"util.rkt")
(provide form-tests)
(define empty-form
(form* () #f))
(struct signup-data (username password)
#:transparent)
(define signup-form
(form* ([username (ensure binding/email (required))]
[password (form* ([p1 (ensure binding/text (required) (longer-than 8))]
[p2 (ensure binding/text (required) (longer-than 8))])
(cond
[(string=? p1 p2) (ok p1)]
[else (err "The passwords must match.")]))])
(signup-data username password)))
(struct login-data (username password)
#:transparent)
(define login-form
(form* ([username (ensure binding/email (required))]
[password (ensure binding/text (required) (longer-than 8))])
(login-data username password)))
(define (render-login-form render-widget)
`(form ((action "")
(method "POST"))
(label "Username" ,(render-widget "username" (widget-text)))
,@(render-widget "username" (widget-errors))
(label "Password" ,(render-widget "password" (widget-password)))
,@(render-widget "password" (widget-errors))))
(define valid-login-data
(hash "username" (make-binding "bogdan@example")
"password" (make-binding "hunter1234")))
(struct author (name email) #:transparent)
(struct package (name version) #:transparent)
(struct release (author package) #:transparent)
(define author-form
(form* ([name (ensure binding/text (required))]
[email (ensure binding/email (required))])
(author name email)))
(define (render-author-form render-widget)
`(div (label "Name" ,(render-widget "name" (widget-text)))
,@(render-widget "name" (widget-errors))
(label "Email" ,(render-widget "email" (widget-email)))
,@(render-widget "email" (widget-errors))))
(define (parse-version v)
(define version (map string->number (string-split v ".")))
(if (member #f version)
(err "Invalid version.")
(ok version)))
(define package-form
(form* ([name (ensure binding/text (required))]
[version (ensure binding/text (required) parse-version)])
(package name version)))
(define (render-package-form render-widget)
`(div (label "Name" ,(render-widget "name" (widget-text)))
,@(render-widget "name" (widget-errors))
(label "Version" ,(render-widget "version" (widget-text)))
,@(render-widget "version" (widget-errors))))
(define release-form
(form* ([author author-form]
[package package-form])
(release author package)))
(define (render-release-form render-widget)
`(form ((action "")
(method "POST"))
(fieldset
(legend "Author")
,(render-author-form (widget-namespace "author" render-widget)))
(fieldset
(legend "Package")
,(render-package-form (widget-namespace "package" render-widget)))
(button ((type "submit")) "Save")))
(define valid-release-data
(hash "author.name" (make-binding "Bogdan Popa")
"author.email" (make-binding "")
"package.name" (make-binding "forms")
"package.version" (make-binding "1.5.3")))
(define form-tests
(test-suite
"form"
(test-suite
"form-lookup"
(test-case "can lookup formlets at any depth"
(check-false (form-lookup login-form "blah"))
(check-not-false (form-lookup login-form "username"))
(check-not-false (form-lookup signup-form "password.p1"))))
(test-suite
"form-validate"
(test-case "can validate missing inputs"
(check-equal?
(form-validate login-form (hash))
(err '((username . "This field is required.")
(password . "This field is required."))))
(check-equal?
(form-validate release-form (hash))
(err '((author . ((name . "This field is required.")
(email . "This field is required.")))
(package . ((name . "This field is required.")
(version . "This field is required.")))))))
(test-case "can validate bad inputs"
(check-equal?
(form-validate login-form (hash "username" (make-binding "bogdan")
"password" (make-binding "hunter2")))
(err '((username . "This field must contain an e-mail address.")
(password . "This field must contain 9 or more characters."))))
(check-equal?
(form-validate release-form (hash-set valid-release-data "package.version" (make-binding "a")))
(err '((package . ((version . "Invalid version.")))))))
(test-case "can validate good inputs"
(check-equal?
(form-validate login-form valid-login-data)
(ok (login-data "bogdan@example" "hunter1234")))
(check-equal?
(form-validate release-form valid-release-data)
(ok (release (author "Bogdan Popa" "")
(package "forms" '(1 5 3))))))
(test-case "can validate nested inputs"
(check-equal?
(form-validate signup-form (hash "username" (make-binding "")))
(err '((password (p1 . "This field is required.")
(p2 . "This field is required.")))))
(check-equal?
(form-validate signup-form (hash "username" (make-binding "")
"password.p1" (make-binding "password-123-a")
"password.p2" (make-binding "password-123-b")))
(err '((password . "The passwords must match."))))
(check-equal?
(form-validate signup-form (hash "username" (make-binding "")
"password.p1" (make-binding "password-123-a")
"password.p2" (make-binding "password-123-a")))
(ok (signup-data "" "password-123-a")))))
(test-suite
"form-process"
(test-case "can process pending inputs"
(check-match
(form-process login-form (hash) #:submitted? #f)
(list 'pending _ procedure?)))
(test-case "can process good inputs"
(check-match
(form-process login-form valid-login-data)
(list 'passed (login-data "bogdan@example" "hunter1234") procedure?)))
(test-case "can render pending forms"
(match (form-process login-form (hash) #:submitted? #f)
[(list 'pending _ render-widget)
(check-equal?
(render-login-form render-widget)
'(form ((action "")
(method "POST"))
(label "Username" (input ((type "text") (name "username"))))
(label "Password" (input ((type "password") (name "password"))))))]))
(test-case "can render failed forms"
(match (form-process login-form (hash "password" (make-binding "hunter1234")))
[(list 'failed _ render-widget)
(check-equal?
(render-login-form render-widget)
'(form ((action "")
(method "POST"))
(label "Username" (input ((type "text") (name "username"))))
(ul ((class "errors")) (li "This field is required."))
(label "Password" (input ((type "password") (name "password"))))))]))
(test-case "can render passed forms"
(match (form-process login-form valid-login-data)
[(list 'passed data render-widget)
(check-equal? data (login-data "bogdan@example" "hunter1234"))
(check-equal?
(render-login-form render-widget)
'(form ((action "")
(method "POST"))
(label "Username" (input ((type "text") (name "username") (value "bogdan@example"))))
(label "Password" (input ((type "password") (name "password"))))))])))
(test-suite
"form-process+widget-renderer"
(test-case "can render pending forms"
(match (form-process release-form (hash) #:submitted? #f)
[(list 'pending _ render-widget)
(check-equal?
(render-release-form render-widget)
'(form ((action "")
(method "POST"))
(fieldset
(legend "Author")
(div
(label "Name" (input ((type "text") (name "author.name"))))
(label "Email" (input ((type "email") (name "author.email"))))))
(fieldset
(legend "Package")
(div
(label "Name" (input ((type "text") (name "package.name"))))
(label "Version" (input ((type "text") (name "package.version"))))))
(button ((type "submit")) "Save")))])))
(test-suite
"form-run"
(test-case "treats GET requests as not submitted"
(match (form-run release-form (make-request))
[(list res _ _)
(check-equal? res 'pending)]))
(test-case "treats POST requests as submitted"
(match (form-run login-form (make-request #:method #"POST"
#:bindings (list (make-binding:form #"username" #"")
(make-binding:form #"password" #"hunter1234"))))
[(list res _ _)
(check-equal? res 'passed)])))))
(module+ test
(require rackunit/text-ui)
(run-tests form-tests))
| null | https://raw.githubusercontent.com/Bogdanp/racket-forms/80e6dee1184ab4c435678bb3c45fa11bfabf56ee/forms-test/tests/forms/form-tests.rkt | racket | #lang racket/base
(require forms
(submod forms/private/form internal)
racket/match
racket/string
rackunit
(only-in web-server/http make-binding:form)
"util.rkt")
(provide form-tests)
(define empty-form
(form* () #f))
(struct signup-data (username password)
#:transparent)
(define signup-form
(form* ([username (ensure binding/email (required))]
[password (form* ([p1 (ensure binding/text (required) (longer-than 8))]
[p2 (ensure binding/text (required) (longer-than 8))])
(cond
[(string=? p1 p2) (ok p1)]
[else (err "The passwords must match.")]))])
(signup-data username password)))
(struct login-data (username password)
#:transparent)
(define login-form
(form* ([username (ensure binding/email (required))]
[password (ensure binding/text (required) (longer-than 8))])
(login-data username password)))
(define (render-login-form render-widget)
`(form ((action "")
(method "POST"))
(label "Username" ,(render-widget "username" (widget-text)))
,@(render-widget "username" (widget-errors))
(label "Password" ,(render-widget "password" (widget-password)))
,@(render-widget "password" (widget-errors))))
(define valid-login-data
(hash "username" (make-binding "bogdan@example")
"password" (make-binding "hunter1234")))
(struct author (name email) #:transparent)
(struct package (name version) #:transparent)
(struct release (author package) #:transparent)
(define author-form
(form* ([name (ensure binding/text (required))]
[email (ensure binding/email (required))])
(author name email)))
(define (render-author-form render-widget)
`(div (label "Name" ,(render-widget "name" (widget-text)))
,@(render-widget "name" (widget-errors))
(label "Email" ,(render-widget "email" (widget-email)))
,@(render-widget "email" (widget-errors))))
(define (parse-version v)
(define version (map string->number (string-split v ".")))
(if (member #f version)
(err "Invalid version.")
(ok version)))
(define package-form
(form* ([name (ensure binding/text (required))]
[version (ensure binding/text (required) parse-version)])
(package name version)))
(define (render-package-form render-widget)
`(div (label "Name" ,(render-widget "name" (widget-text)))
,@(render-widget "name" (widget-errors))
(label "Version" ,(render-widget "version" (widget-text)))
,@(render-widget "version" (widget-errors))))
(define release-form
(form* ([author author-form]
[package package-form])
(release author package)))
(define (render-release-form render-widget)
`(form ((action "")
(method "POST"))
(fieldset
(legend "Author")
,(render-author-form (widget-namespace "author" render-widget)))
(fieldset
(legend "Package")
,(render-package-form (widget-namespace "package" render-widget)))
(button ((type "submit")) "Save")))
(define valid-release-data
(hash "author.name" (make-binding "Bogdan Popa")
"author.email" (make-binding "")
"package.name" (make-binding "forms")
"package.version" (make-binding "1.5.3")))
(define form-tests
(test-suite
"form"
(test-suite
"form-lookup"
(test-case "can lookup formlets at any depth"
(check-false (form-lookup login-form "blah"))
(check-not-false (form-lookup login-form "username"))
(check-not-false (form-lookup signup-form "password.p1"))))
(test-suite
"form-validate"
(test-case "can validate missing inputs"
(check-equal?
(form-validate login-form (hash))
(err '((username . "This field is required.")
(password . "This field is required."))))
(check-equal?
(form-validate release-form (hash))
(err '((author . ((name . "This field is required.")
(email . "This field is required.")))
(package . ((name . "This field is required.")
(version . "This field is required.")))))))
(test-case "can validate bad inputs"
(check-equal?
(form-validate login-form (hash "username" (make-binding "bogdan")
"password" (make-binding "hunter2")))
(err '((username . "This field must contain an e-mail address.")
(password . "This field must contain 9 or more characters."))))
(check-equal?
(form-validate release-form (hash-set valid-release-data "package.version" (make-binding "a")))
(err '((package . ((version . "Invalid version.")))))))
(test-case "can validate good inputs"
(check-equal?
(form-validate login-form valid-login-data)
(ok (login-data "bogdan@example" "hunter1234")))
(check-equal?
(form-validate release-form valid-release-data)
(ok (release (author "Bogdan Popa" "")
(package "forms" '(1 5 3))))))
(test-case "can validate nested inputs"
(check-equal?
(form-validate signup-form (hash "username" (make-binding "")))
(err '((password (p1 . "This field is required.")
(p2 . "This field is required.")))))
(check-equal?
(form-validate signup-form (hash "username" (make-binding "")
"password.p1" (make-binding "password-123-a")
"password.p2" (make-binding "password-123-b")))
(err '((password . "The passwords must match."))))
(check-equal?
(form-validate signup-form (hash "username" (make-binding "")
"password.p1" (make-binding "password-123-a")
"password.p2" (make-binding "password-123-a")))
(ok (signup-data "" "password-123-a")))))
(test-suite
"form-process"
(test-case "can process pending inputs"
(check-match
(form-process login-form (hash) #:submitted? #f)
(list 'pending _ procedure?)))
(test-case "can process good inputs"
(check-match
(form-process login-form valid-login-data)
(list 'passed (login-data "bogdan@example" "hunter1234") procedure?)))
(test-case "can render pending forms"
(match (form-process login-form (hash) #:submitted? #f)
[(list 'pending _ render-widget)
(check-equal?
(render-login-form render-widget)
'(form ((action "")
(method "POST"))
(label "Username" (input ((type "text") (name "username"))))
(label "Password" (input ((type "password") (name "password"))))))]))
(test-case "can render failed forms"
(match (form-process login-form (hash "password" (make-binding "hunter1234")))
[(list 'failed _ render-widget)
(check-equal?
(render-login-form render-widget)
'(form ((action "")
(method "POST"))
(label "Username" (input ((type "text") (name "username"))))
(ul ((class "errors")) (li "This field is required."))
(label "Password" (input ((type "password") (name "password"))))))]))
(test-case "can render passed forms"
(match (form-process login-form valid-login-data)
[(list 'passed data render-widget)
(check-equal? data (login-data "bogdan@example" "hunter1234"))
(check-equal?
(render-login-form render-widget)
'(form ((action "")
(method "POST"))
(label "Username" (input ((type "text") (name "username") (value "bogdan@example"))))
(label "Password" (input ((type "password") (name "password"))))))])))
(test-suite
"form-process+widget-renderer"
(test-case "can render pending forms"
(match (form-process release-form (hash) #:submitted? #f)
[(list 'pending _ render-widget)
(check-equal?
(render-release-form render-widget)
'(form ((action "")
(method "POST"))
(fieldset
(legend "Author")
(div
(label "Name" (input ((type "text") (name "author.name"))))
(label "Email" (input ((type "email") (name "author.email"))))))
(fieldset
(legend "Package")
(div
(label "Name" (input ((type "text") (name "package.name"))))
(label "Version" (input ((type "text") (name "package.version"))))))
(button ((type "submit")) "Save")))])))
(test-suite
"form-run"
(test-case "treats GET requests as not submitted"
(match (form-run release-form (make-request))
[(list res _ _)
(check-equal? res 'pending)]))
(test-case "treats POST requests as submitted"
(match (form-run login-form (make-request #:method #"POST"
#:bindings (list (make-binding:form #"username" #"")
(make-binding:form #"password" #"hunter1234"))))
[(list res _ _)
(check-equal? res 'passed)])))))
(module+ test
(require rackunit/text-ui)
(run-tests form-tests))
| |
f24148c117864a7e3d5148dc384e616d879e8a2e77c1daecb9a0cfdca21df8d3 | juxt/bolt | project.clj | Copyright © 2014 JUXT LTD .
(defproject bolt "0.6.0-SNAPSHOT"
:description "An integrated security system for applications built on component"
:url ""
:license {:name "The MIT License"
:url ""}
:dependencies
[[org.clojure/tools.logging "0.3.1"]
[juxt.modular/bidi "0.9.2" :exclusions [bidi]]
[juxt.modular/ring "0.5.2"]
[juxt.modular/email "0.0.1"]
[juxt.modular/co-dependency "0.2.0"]
[prismatic/schema "0.4.2"]
[prismatic/plumbing "0.4.2"]
Required for OAuth2 / OpenID - Connect support
[cheshire "5.4.0"]
[bidi "1.18.10" :exclusions [ring/ring-core
org.clojure/tools.reader]]
Does n't work with clojure 1.7.0 - beta2
#_[camel-snake-kebab "0.3.1"
:exclusions [com.keminglabs/cljx]]
;; We should probably replace clj-jwt with buddy
[clj-jwt "0.0.8"
;; Important we exclude bc here otherwise get an
;; this exception:
;;
;; class
;; "org.bouncycastle.crypto.digests.SHA3Digest"'s
;; signer information does not match signer
;; information of other classes in the same package
:exclusions [clj-time
org.bouncycastle/bcprov-jdk15]]
[buddy "0.5.1"]
[yada "0.4.2"]
[clj-time "0.9.0"]
;; Possibly needed old dependencies
#_[ring/ring-core "1.3.2"
:exclusions [org.clojure/tools.reader
clj-time]]
#_[org.clojure/tools.reader "0.8.13"]
#_[clj-time "0.9.0"]
#_[juxt.modular/http-kit "0.5.3"]
#_[hiccup "1.0.5"]
#_[liberator "0.12.0"]]
:repl-options {:init-ns user
:welcome (println "Type (dev) to start")}
:profiles
{:dev {:main bolt.dev.main
:dependencies
[[org.clojure/clojure "1.7.0-beta2"]
[org.clojure/tools.logging "0.2.6"]
[ch.qos.logback/logback-classic "1.0.7"
:exclusions [org.slf4j/slf4j-api]]
[org.slf4j/jul-to-slf4j "1.7.2"]
[org.slf4j/jcl-over-slf4j "1.7.2"]
[org.slf4j/log4j-over-slf4j "1.7.2"]
[com.stuartsierra/component "0.2.2"]
[org.clojure/tools.namespace "0.2.5"]
[markdown-clj "0.9.62"]
[juxt.modular/aleph "0.0.8" :exclusions [manifold]]
[juxt.modular/bidi "0.9.2" :exclusions [bidi]]
[juxt.modular/clostache "0.6.3"]
[juxt.modular/co-dependency "0.2.0"]
[juxt.modular/maker "0.5.0"]
[juxt.modular/test "0.1.0"]
[juxt.modular/template "0.6.3"]
[org.webjars/jquery "2.1.3"]
[org.webjars/bootstrap "3.3.2"]
]
:source-paths ["dev/src"]
:resource-paths ["dev/resources"]}})
| null | https://raw.githubusercontent.com/juxt/bolt/f77be416f82c1ca19d5dc20a15942375edc9b740/project.clj | clojure | We should probably replace clj-jwt with buddy
Important we exclude bc here otherwise get an
this exception:
class
"org.bouncycastle.crypto.digests.SHA3Digest"'s
signer information does not match signer
information of other classes in the same package
Possibly needed old dependencies | Copyright © 2014 JUXT LTD .
(defproject bolt "0.6.0-SNAPSHOT"
:description "An integrated security system for applications built on component"
:url ""
:license {:name "The MIT License"
:url ""}
:dependencies
[[org.clojure/tools.logging "0.3.1"]
[juxt.modular/bidi "0.9.2" :exclusions [bidi]]
[juxt.modular/ring "0.5.2"]
[juxt.modular/email "0.0.1"]
[juxt.modular/co-dependency "0.2.0"]
[prismatic/schema "0.4.2"]
[prismatic/plumbing "0.4.2"]
Required for OAuth2 / OpenID - Connect support
[cheshire "5.4.0"]
[bidi "1.18.10" :exclusions [ring/ring-core
org.clojure/tools.reader]]
Does n't work with clojure 1.7.0 - beta2
#_[camel-snake-kebab "0.3.1"
:exclusions [com.keminglabs/cljx]]
[clj-jwt "0.0.8"
:exclusions [clj-time
org.bouncycastle/bcprov-jdk15]]
[buddy "0.5.1"]
[yada "0.4.2"]
[clj-time "0.9.0"]
#_[ring/ring-core "1.3.2"
:exclusions [org.clojure/tools.reader
clj-time]]
#_[org.clojure/tools.reader "0.8.13"]
#_[clj-time "0.9.0"]
#_[juxt.modular/http-kit "0.5.3"]
#_[hiccup "1.0.5"]
#_[liberator "0.12.0"]]
:repl-options {:init-ns user
:welcome (println "Type (dev) to start")}
:profiles
{:dev {:main bolt.dev.main
:dependencies
[[org.clojure/clojure "1.7.0-beta2"]
[org.clojure/tools.logging "0.2.6"]
[ch.qos.logback/logback-classic "1.0.7"
:exclusions [org.slf4j/slf4j-api]]
[org.slf4j/jul-to-slf4j "1.7.2"]
[org.slf4j/jcl-over-slf4j "1.7.2"]
[org.slf4j/log4j-over-slf4j "1.7.2"]
[com.stuartsierra/component "0.2.2"]
[org.clojure/tools.namespace "0.2.5"]
[markdown-clj "0.9.62"]
[juxt.modular/aleph "0.0.8" :exclusions [manifold]]
[juxt.modular/bidi "0.9.2" :exclusions [bidi]]
[juxt.modular/clostache "0.6.3"]
[juxt.modular/co-dependency "0.2.0"]
[juxt.modular/maker "0.5.0"]
[juxt.modular/test "0.1.0"]
[juxt.modular/template "0.6.3"]
[org.webjars/jquery "2.1.3"]
[org.webjars/bootstrap "3.3.2"]
]
:source-paths ["dev/src"]
:resource-paths ["dev/resources"]}})
|
0af2637550095b0a7c8ebc42e23ca18e5d702d7aadcf039f335878b6f4bca075 | racket/typed-racket | bad-vector-ref.rkt | #lang racket/base
;; Test applications of `vector-ref` that should fail due to mis-matched
;; values and type constructors
(module t typed/racket/optional
(: f (-> (Vectorof Natural) Natural))
(define (f x)
(+ (vector-ref x 0)
(vector-ref x 1)))
(: g (-> (Vectorof (Vectorof Natural)) Natural))
(define (g x)
(define v (vector-ref x 0))
(+ (vector-ref (vector-ref x 0) 0) (vector-ref v 1)))
(: h (-> (Vector Natural Symbol) Natural))
(define (h x)
(vector-ref x 0))
(provide f g h))
(require 't racket/contract rackunit)
(check-exn #rx"\\+: contract violation"
(λ () (f (vector 4 'A 4 4))))
(check-exn #rx"vector-ref: contract violation"
(λ () (g (vector 3))))
(check-not-exn
(λ () (h (vector 1 'two 3))))
| null | https://raw.githubusercontent.com/racket/typed-racket/1dde78d165472d67ae682b68622d2b7ee3e15e1e/typed-racket-test/succeed/optional/bad-vector-ref.rkt | racket | Test applications of `vector-ref` that should fail due to mis-matched
values and type constructors | #lang racket/base
(module t typed/racket/optional
(: f (-> (Vectorof Natural) Natural))
(define (f x)
(+ (vector-ref x 0)
(vector-ref x 1)))
(: g (-> (Vectorof (Vectorof Natural)) Natural))
(define (g x)
(define v (vector-ref x 0))
(+ (vector-ref (vector-ref x 0) 0) (vector-ref v 1)))
(: h (-> (Vector Natural Symbol) Natural))
(define (h x)
(vector-ref x 0))
(provide f g h))
(require 't racket/contract rackunit)
(check-exn #rx"\\+: contract violation"
(λ () (f (vector 4 'A 4 4))))
(check-exn #rx"vector-ref: contract violation"
(λ () (g (vector 3))))
(check-not-exn
(λ () (h (vector 1 'two 3))))
|
ba736601e8b44a291e4c36a11c760d1c7808e5edbc0a66a70c835fceaf986184 | taruen/apertiumpp | info.rkt | #lang info
(define scribblings '(("scribblings/apertiumpp-kaz.scrbl" ())))
| null | https://raw.githubusercontent.com/taruen/apertiumpp/73eeacc19015170e54c77824e015224f6456cf3e/apertiumpp-kaz/info.rkt | racket | #lang info
(define scribblings '(("scribblings/apertiumpp-kaz.scrbl" ())))
| |
7bb44a07fd110272ae48b4461fbef4b6cd65a3d2ef1c3f1052853ef72da22321 | fpco/ide-backend | IPI641.hs | -----------------------------------------------------------------------------
-- |
Module : Distribution . Simple .
Copyright : ( c ) The University of Glasgow 2004
-- License : BSD3
--
-- Maintainer :
-- Portability : portable
--
module Distribution.Simple.GHC.IPI641 (
InstalledPackageInfo(..),
toCurrent,
) where
import qualified Distribution.InstalledPackageInfo as Current
import qualified Distribution.Package as Current hiding (depends, installedPackageId)
import Distribution.Text (display)
import Distribution.Simple.GHC.IPI642
( PackageIdentifier, convertPackageId
, License, convertLicense, convertModuleName )
| This is the InstalledPackageInfo type used by ghc-6.4 and 6.4.1 .
--
-- It's here purely for the 'Read' instance so that we can read the package
database used by those ghc versions . It is a little hacky to read the
-- package db directly, but we do need the info and until ghc-6.9 there was
-- no better method.
--
In ghc-6.4.2 the format changed a bit . See " Distribution . Simple . GHC.IPI642 "
--
data InstalledPackageInfo = InstalledPackageInfo {
package :: PackageIdentifier,
license :: License,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
homepage :: String,
pkgUrl :: String,
description :: String,
category :: String,
exposed :: Bool,
exposedModules :: [String],
hiddenModules :: [String],
importDirs :: [FilePath],
libraryDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
includeDirs :: [FilePath],
includes :: [String],
depends :: [PackageIdentifier],
hugsOptions :: [String],
ccOptions :: [String],
ldOptions :: [String],
frameworkDirs :: [FilePath],
frameworks :: [String],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath]
}
deriving Read
mkInstalledPackageId :: Current.PackageIdentifier -> Current.InstalledPackageId
mkInstalledPackageId = Current.InstalledPackageId . display
toCurrent :: InstalledPackageInfo -> Current.InstalledPackageInfo
toCurrent ipi@InstalledPackageInfo{} =
let pid = convertPackageId (package ipi)
mkExposedModule m = Current.ExposedModule m Nothing Nothing
in Current.InstalledPackageInfo {
Current.installedPackageId = mkInstalledPackageId (convertPackageId (package ipi)),
Current.sourcePackageId = pid,
Current.packageKey = Current.OldPackageKey pid,
Current.license = convertLicense (license ipi),
Current.copyright = copyright ipi,
Current.maintainer = maintainer ipi,
Current.author = author ipi,
Current.stability = stability ipi,
Current.homepage = homepage ipi,
Current.pkgUrl = pkgUrl ipi,
Current.synopsis = "",
Current.description = description ipi,
Current.category = category ipi,
Current.exposed = exposed ipi,
Current.exposedModules = map (mkExposedModule . convertModuleName) (exposedModules ipi),
Current.instantiatedWith = [],
Current.hiddenModules = map convertModuleName (hiddenModules ipi),
Current.trusted = Current.trusted Current.emptyInstalledPackageInfo,
Current.importDirs = importDirs ipi,
Current.libraryDirs = libraryDirs ipi,
Current.dataDir = "",
Current.hsLibraries = hsLibraries ipi,
Current.extraLibraries = extraLibraries ipi,
Current.extraGHCiLibraries = [],
Current.includeDirs = includeDirs ipi,
Current.includes = includes ipi,
Current.depends = map (mkInstalledPackageId.convertPackageId) (depends ipi),
Current.ccOptions = ccOptions ipi,
Current.ldOptions = ldOptions ipi,
Current.frameworkDirs = frameworkDirs ipi,
Current.frameworks = frameworks ipi,
Current.haddockInterfaces = haddockInterfaces ipi,
Current.haddockHTMLs = haddockHTMLs ipi,
Current.pkgRoot = Nothing
}
| null | https://raw.githubusercontent.com/fpco/ide-backend/860636f2d0e872e9481569236bce690637e0016e/ide-backend/TestSuite/inputs/Cabal-1.22.0.0/Distribution/Simple/GHC/IPI641.hs | haskell | ---------------------------------------------------------------------------
|
License : BSD3
Maintainer :
Portability : portable
It's here purely for the 'Read' instance so that we can read the package
package db directly, but we do need the info and until ghc-6.9 there was
no better method.
| Module : Distribution . Simple .
Copyright : ( c ) The University of Glasgow 2004
module Distribution.Simple.GHC.IPI641 (
InstalledPackageInfo(..),
toCurrent,
) where
import qualified Distribution.InstalledPackageInfo as Current
import qualified Distribution.Package as Current hiding (depends, installedPackageId)
import Distribution.Text (display)
import Distribution.Simple.GHC.IPI642
( PackageIdentifier, convertPackageId
, License, convertLicense, convertModuleName )
| This is the InstalledPackageInfo type used by ghc-6.4 and 6.4.1 .
database used by those ghc versions . It is a little hacky to read the
In ghc-6.4.2 the format changed a bit . See " Distribution . Simple . GHC.IPI642 "
data InstalledPackageInfo = InstalledPackageInfo {
package :: PackageIdentifier,
license :: License,
copyright :: String,
maintainer :: String,
author :: String,
stability :: String,
homepage :: String,
pkgUrl :: String,
description :: String,
category :: String,
exposed :: Bool,
exposedModules :: [String],
hiddenModules :: [String],
importDirs :: [FilePath],
libraryDirs :: [FilePath],
hsLibraries :: [String],
extraLibraries :: [String],
includeDirs :: [FilePath],
includes :: [String],
depends :: [PackageIdentifier],
hugsOptions :: [String],
ccOptions :: [String],
ldOptions :: [String],
frameworkDirs :: [FilePath],
frameworks :: [String],
haddockInterfaces :: [FilePath],
haddockHTMLs :: [FilePath]
}
deriving Read
mkInstalledPackageId :: Current.PackageIdentifier -> Current.InstalledPackageId
mkInstalledPackageId = Current.InstalledPackageId . display
toCurrent :: InstalledPackageInfo -> Current.InstalledPackageInfo
toCurrent ipi@InstalledPackageInfo{} =
let pid = convertPackageId (package ipi)
mkExposedModule m = Current.ExposedModule m Nothing Nothing
in Current.InstalledPackageInfo {
Current.installedPackageId = mkInstalledPackageId (convertPackageId (package ipi)),
Current.sourcePackageId = pid,
Current.packageKey = Current.OldPackageKey pid,
Current.license = convertLicense (license ipi),
Current.copyright = copyright ipi,
Current.maintainer = maintainer ipi,
Current.author = author ipi,
Current.stability = stability ipi,
Current.homepage = homepage ipi,
Current.pkgUrl = pkgUrl ipi,
Current.synopsis = "",
Current.description = description ipi,
Current.category = category ipi,
Current.exposed = exposed ipi,
Current.exposedModules = map (mkExposedModule . convertModuleName) (exposedModules ipi),
Current.instantiatedWith = [],
Current.hiddenModules = map convertModuleName (hiddenModules ipi),
Current.trusted = Current.trusted Current.emptyInstalledPackageInfo,
Current.importDirs = importDirs ipi,
Current.libraryDirs = libraryDirs ipi,
Current.dataDir = "",
Current.hsLibraries = hsLibraries ipi,
Current.extraLibraries = extraLibraries ipi,
Current.extraGHCiLibraries = [],
Current.includeDirs = includeDirs ipi,
Current.includes = includes ipi,
Current.depends = map (mkInstalledPackageId.convertPackageId) (depends ipi),
Current.ccOptions = ccOptions ipi,
Current.ldOptions = ldOptions ipi,
Current.frameworkDirs = frameworkDirs ipi,
Current.frameworks = frameworks ipi,
Current.haddockInterfaces = haddockInterfaces ipi,
Current.haddockHTMLs = haddockHTMLs ipi,
Current.pkgRoot = Nothing
}
|
fd2fd9dc4ece9a5b9a1111227ce251bb2f54a98e8588e5b68bfd9c576fd1f29c | dalaing/reflex-host-examples | Host1.hs |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
{-# LANGUAGE RankNTypes #-}
module Host1 (
go1
) where
import Control.Monad (forever)
import Control.Monad.Fix (MonadFix)
import Control.Monad.Identity (Identity(..))
import Control.Monad.IO.Class (liftIO)
import Data.IORef (readIORef)
import System.IO
import Data.Dependent.Sum
import Reflex
import Reflex.Host.Class
-- First we define a type for our applications.
--
-- In this case, our applications will take an
-- 'Event t String' as input return a
-- 'Behavior t Int' as output.
--
-- While we're at it, we capture various
-- typeclass constraints that we know we're
-- going to need in this type synonym.
type SampleApp1 t m =
( Reflex t
, MonadHold t m
, MonadFix m
) => Event t String
-> m (Behavior t Int)
-- This is our sample FRP application.
--
-- It doesn't care what kind of event it gets
-- as an input, because we're just using it to
-- count the events that are occurring.
guest :: SampleApp1 t m
guest e = do
-- increment every time the input event fires
d <- foldDyn (+) 0 (1 <$ e)
-- return the running count as a behavior
return $ current d
-- This is the code that runs our FRP applications.
host :: (forall t m. SampleApp1 t m)
-> IO ()
host myGuest =
We use the implementation of Reflex .
runSpiderHost $ do
-- We create a new event and a trigger for the event.
(e, eTriggerRef) <- newEventWithTriggerRef
-- e :: Event t a
eTriggerRef : : Ref m ( Maybe ( EventTrigger t a ) )
--
-- This gives us an event - which we need so that
-- we can provide an input to 'myGuest' - and an event
-- trigger.
--
-- 'Ref' is an abstraction over things like 'IORef' etc..
--
-- If the event isn't being used - or if it stops
-- being used due to changes in the network - the 'Ref' will
-- hold 'Nothing'.
--
-- If something is interested in the event, then the 'Ref'
-- will hold 'Just t' where 't' is a trigger for the event.
-- Now we set up our basic event network for use with 'myGuest e'.
b <- runHostFrame $ myGuest e
-- This will give us a 'Behavior Int' which we'll use a little later.
-- At this point the event network is set up, but there are no
-- events firing and so nothing much is happening.
--
-- We address that by putting together an event loop to handle
-- the firing of the event we are intersted in.
--
In this case we 're just going to read lines from stdin
-- and fire our event with the resulting 'String' values.
First we make sure stdin is buffering things by line .
liftIO $ hSetBuffering stdin LineBuffering
-- then we start our loop:
forever $ do
We get a line from stdin
input <- liftIO getLine
-- and we print some debugging output, just to show that we
-- do things like that with no ill effect
liftIO $ putStrLn $ "Input Event: " ++ show input
-- Now we read the reference holding our trigger
mETrigger <- liftIO $ readIORef eTriggerRef
case mETrigger of
-- If the value is 'Nothing', then the guest FRP network
-- doesn't care about this event at the moment, so we do nothing.
Nothing -> do
return ()
-- In other host settings, where we have events that might be
-- expensive to handle from the host side, we might read the
reference first and then skip the expensive operation when
-- no one is listening.
-- If there is someone listening, we get hold of the trigger and
-- use that to fire the events.
Just eTrigger -> do
fireEvents : : [ DSum ( EventTrigger t ) Identity ] - > m ( )
fireEvents [eTrigger :=> Identity input]
' DSum ' comes from ' dependent - sum ' , and allows us to deal with
-- collections of events with different types in a homogenous way,
-- but without giving up type-safety. It's really nifty, and worth
-- playing around with if you have a moment.
--
At the moment we 're only firing one event , so it 's not that
-- exciting.
-- There is a helper function that reads the trigger reference and fires
-- the trigger if it is not 'Nothing', so we could replace the above
-- block with:
-- fireEventRef eTriggerRef input
-- After each time that we fire the events, we read the output
-- 'Behavior'. We do that using 'sample' - to get the current
-- value of the 'Behavior' inside of the event network - and
-- 'runHostFrame' - to cause the event network to process another
-- moment in time so that we can get hold of that value on the
-- outside of the event network.
output <- runHostFrame $ sample b
-- We'll print our output here
liftIO $ putStrLn $ "Output Behavior: " ++ show output
-- Now we can run our sample application ('guest') using
-- our code for hosting this kind of applications ('host').
go1 :: IO ()
go1 =
host guest
| null | https://raw.githubusercontent.com/dalaing/reflex-host-examples/ef3aa5f428e87b289fd7999c97ee679c231b5e05/src/Host1.hs | haskell | # LANGUAGE RankNTypes #
First we define a type for our applications.
In this case, our applications will take an
'Event t String' as input return a
'Behavior t Int' as output.
While we're at it, we capture various
typeclass constraints that we know we're
going to need in this type synonym.
This is our sample FRP application.
It doesn't care what kind of event it gets
as an input, because we're just using it to
count the events that are occurring.
increment every time the input event fires
return the running count as a behavior
This is the code that runs our FRP applications.
We create a new event and a trigger for the event.
e :: Event t a
This gives us an event - which we need so that
we can provide an input to 'myGuest' - and an event
trigger.
'Ref' is an abstraction over things like 'IORef' etc..
If the event isn't being used - or if it stops
being used due to changes in the network - the 'Ref' will
hold 'Nothing'.
If something is interested in the event, then the 'Ref'
will hold 'Just t' where 't' is a trigger for the event.
Now we set up our basic event network for use with 'myGuest e'.
This will give us a 'Behavior Int' which we'll use a little later.
At this point the event network is set up, but there are no
events firing and so nothing much is happening.
We address that by putting together an event loop to handle
the firing of the event we are intersted in.
and fire our event with the resulting 'String' values.
then we start our loop:
and we print some debugging output, just to show that we
do things like that with no ill effect
Now we read the reference holding our trigger
If the value is 'Nothing', then the guest FRP network
doesn't care about this event at the moment, so we do nothing.
In other host settings, where we have events that might be
expensive to handle from the host side, we might read the
no one is listening.
If there is someone listening, we get hold of the trigger and
use that to fire the events.
collections of events with different types in a homogenous way,
but without giving up type-safety. It's really nifty, and worth
playing around with if you have a moment.
exciting.
There is a helper function that reads the trigger reference and fires
the trigger if it is not 'Nothing', so we could replace the above
block with:
fireEventRef eTriggerRef input
After each time that we fire the events, we read the output
'Behavior'. We do that using 'sample' - to get the current
value of the 'Behavior' inside of the event network - and
'runHostFrame' - to cause the event network to process another
moment in time so that we can get hold of that value on the
outside of the event network.
We'll print our output here
Now we can run our sample application ('guest') using
our code for hosting this kind of applications ('host'). |
Copyright : ( c ) , 2016
License : :
Stability : experimental
Portability : non - portable
Copyright : (c) Dave Laing, 2016
License : BSD3
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Host1 (
go1
) where
import Control.Monad (forever)
import Control.Monad.Fix (MonadFix)
import Control.Monad.Identity (Identity(..))
import Control.Monad.IO.Class (liftIO)
import Data.IORef (readIORef)
import System.IO
import Data.Dependent.Sum
import Reflex
import Reflex.Host.Class
type SampleApp1 t m =
( Reflex t
, MonadHold t m
, MonadFix m
) => Event t String
-> m (Behavior t Int)
guest :: SampleApp1 t m
guest e = do
d <- foldDyn (+) 0 (1 <$ e)
return $ current d
host :: (forall t m. SampleApp1 t m)
-> IO ()
host myGuest =
We use the implementation of Reflex .
runSpiderHost $ do
(e, eTriggerRef) <- newEventWithTriggerRef
eTriggerRef : : Ref m ( Maybe ( EventTrigger t a ) )
b <- runHostFrame $ myGuest e
In this case we 're just going to read lines from stdin
First we make sure stdin is buffering things by line .
liftIO $ hSetBuffering stdin LineBuffering
forever $ do
We get a line from stdin
input <- liftIO getLine
liftIO $ putStrLn $ "Input Event: " ++ show input
mETrigger <- liftIO $ readIORef eTriggerRef
case mETrigger of
Nothing -> do
return ()
reference first and then skip the expensive operation when
Just eTrigger -> do
fireEvents : : [ DSum ( EventTrigger t ) Identity ] - > m ( )
fireEvents [eTrigger :=> Identity input]
' DSum ' comes from ' dependent - sum ' , and allows us to deal with
At the moment we 're only firing one event , so it 's not that
output <- runHostFrame $ sample b
liftIO $ putStrLn $ "Output Behavior: " ++ show output
go1 :: IO ()
go1 =
host guest
|
df09afe5cac04b0a20f0326fde59fe134c78d41eb791b32b0f02d98910db37dc | hiroshi-unno/coar | parser.mli | open Core
val from_cctl_file: string -> (MuCLP.Problem.t, Error.t) result
val from_cltl_file: string -> (MuCLP.Problem.t, Error.t) result
val parse_cctl: string -> (MuCLP.Problem.t, Error.t) result
val parse_cltl: string -> (MuCLP.Problem.t, Error.t) result
| null | https://raw.githubusercontent.com/hiroshi-unno/coar/90a23a09332c68f380efd4115b3f6fdc825f413d/lib/c/parser.mli | ocaml | open Core
val from_cctl_file: string -> (MuCLP.Problem.t, Error.t) result
val from_cltl_file: string -> (MuCLP.Problem.t, Error.t) result
val parse_cctl: string -> (MuCLP.Problem.t, Error.t) result
val parse_cltl: string -> (MuCLP.Problem.t, Error.t) result
| |
343c744ef12c8d33262cef745833876453e1ca352a6fa615c787437c51f4cf92 | ocaml/odoc | rendering.ml | open Odoc_document
open Or_error
let document_of_odocl ~syntax input =
Odoc_file.load input >>= fun unit ->
match unit.content with
| Odoc_file.Page_content odoctree ->
Ok (Renderer.document_of_page ~syntax odoctree)
| Unit_content odoctree ->
Ok (Renderer.document_of_compilation_unit ~syntax odoctree)
let document_of_input ~resolver ~warnings_options ~syntax input =
let output = Fs.File.(set_ext ".odocl" input) in
Odoc_link.from_odoc ~resolver ~warnings_options input output >>= function
| `Page page -> Ok (Renderer.document_of_page ~syntax page)
| `Module m -> Ok (Renderer.document_of_compilation_unit ~syntax m)
let render_document renderer ~output:root_dir ~extra_suffix ~extra odoctree =
let pages = renderer.Renderer.render extra odoctree in
Renderer.traverse pages ~f:(fun filename content ->
let filename =
match extra_suffix with
| Some s -> Fpath.add_ext s filename
| None -> filename
in
let filename = Fpath.normalize @@ Fs.File.append root_dir filename in
let directory = Fs.File.dirname filename in
Fs.Directory.mkdir_p directory;
let oc = open_out (Fs.File.to_string filename) in
let fmt = Format.formatter_of_out_channel oc in
Format.fprintf fmt "%t@?" content;
close_out oc);
Ok ()
let render_odoc ~resolver ~warnings_options ~syntax ~renderer ~output extra file
=
document_of_input ~resolver ~warnings_options ~syntax file
>>= render_document renderer ~output ~extra_suffix:None ~extra
let generate_odoc ~syntax ~renderer ~output ~extra_suffix extra file =
document_of_odocl ~syntax file
>>= render_document renderer ~output ~extra_suffix ~extra
let targets_odoc ~resolver ~warnings_options ~syntax ~renderer ~output:root_dir
~extra odoctree =
let doc =
if Fpath.get_ext odoctree = ".odoc" then
document_of_input ~resolver ~warnings_options ~syntax odoctree
else document_of_odocl ~syntax odoctree
in
doc >>= fun odoctree ->
let pages = renderer.Renderer.render extra odoctree in
Renderer.traverse pages ~f:(fun filename _content ->
let filename = Fpath.normalize @@ Fs.File.append root_dir filename in
Format.printf "%a\n" Fpath.pp filename);
Ok ()
| null | https://raw.githubusercontent.com/ocaml/odoc/40aa7587a5140a88d77c2ce400f426acf5da79a8/src/odoc/rendering.ml | ocaml | open Odoc_document
open Or_error
let document_of_odocl ~syntax input =
Odoc_file.load input >>= fun unit ->
match unit.content with
| Odoc_file.Page_content odoctree ->
Ok (Renderer.document_of_page ~syntax odoctree)
| Unit_content odoctree ->
Ok (Renderer.document_of_compilation_unit ~syntax odoctree)
let document_of_input ~resolver ~warnings_options ~syntax input =
let output = Fs.File.(set_ext ".odocl" input) in
Odoc_link.from_odoc ~resolver ~warnings_options input output >>= function
| `Page page -> Ok (Renderer.document_of_page ~syntax page)
| `Module m -> Ok (Renderer.document_of_compilation_unit ~syntax m)
let render_document renderer ~output:root_dir ~extra_suffix ~extra odoctree =
let pages = renderer.Renderer.render extra odoctree in
Renderer.traverse pages ~f:(fun filename content ->
let filename =
match extra_suffix with
| Some s -> Fpath.add_ext s filename
| None -> filename
in
let filename = Fpath.normalize @@ Fs.File.append root_dir filename in
let directory = Fs.File.dirname filename in
Fs.Directory.mkdir_p directory;
let oc = open_out (Fs.File.to_string filename) in
let fmt = Format.formatter_of_out_channel oc in
Format.fprintf fmt "%t@?" content;
close_out oc);
Ok ()
let render_odoc ~resolver ~warnings_options ~syntax ~renderer ~output extra file
=
document_of_input ~resolver ~warnings_options ~syntax file
>>= render_document renderer ~output ~extra_suffix:None ~extra
let generate_odoc ~syntax ~renderer ~output ~extra_suffix extra file =
document_of_odocl ~syntax file
>>= render_document renderer ~output ~extra_suffix ~extra
let targets_odoc ~resolver ~warnings_options ~syntax ~renderer ~output:root_dir
~extra odoctree =
let doc =
if Fpath.get_ext odoctree = ".odoc" then
document_of_input ~resolver ~warnings_options ~syntax odoctree
else document_of_odocl ~syntax odoctree
in
doc >>= fun odoctree ->
let pages = renderer.Renderer.render extra odoctree in
Renderer.traverse pages ~f:(fun filename _content ->
let filename = Fpath.normalize @@ Fs.File.append root_dir filename in
Format.printf "%a\n" Fpath.pp filename);
Ok ()
| |
ec6803b1072ebf2b334cba1b121498b33a0dc9d89f19a59833462b181b52926f | chaoxu/fancy-walks | 133.hs |
R(10^n ) = ( 10^(10^n ) - 1 ) / 9
R(10^n ) % p = = 0 < = = > 10^(10^n ) % ( 9 * n ) = = 1
< = = > 10^(10^n ) % 9 = = 1(surely ) & & 10^(10^n ) % p = = 1
< = = > 10^(10^n % ( p - 1 ) ) % p = = 1
< = = > 10^n % ( p - 1 ) should be mutiple of order(10 , p )
< = = > order ( 10 , p ) contains only 2^x*5^y
< = = > order ( 10 , p ) divides phi(p ) = p - 1
< = = > enumerate all 2^x * 5 ^ y factors of p - 1
import Math.Sieve.ONeill
import Data.Int
import Data.List
powMod a 0 m = 1
powMod a p m | odd p = powMod a (p - 1) m * a `mod` m
| otherwise = let b = powMod a (p `div` 2) m in b * b `mod` m
check 3 = False
check p = not (null lst)
where
go n x | n `mod` x == 0 = x : go (n `div` x) x
| otherwise = []
factor2 = scanl (*) 1 $ go (p - 1) 2
factor5 = scanl (*) 1 $ go (p - 1) 5
lst = [ f2 * f5
| f2 <- factor2
, f5 <- factor5
, powMod 10 (f2 * f5) p == 1
]
problem_133 = sum [p | p <- takeWhile (<100000) primes, not (check p)]
main = print problem_133
| null | https://raw.githubusercontent.com/chaoxu/fancy-walks/952fcc345883181144131f839aa61e36f488998d/projecteuler.net/133.hs | haskell |
R(10^n ) = ( 10^(10^n ) - 1 ) / 9
R(10^n ) % p = = 0 < = = > 10^(10^n ) % ( 9 * n ) = = 1
< = = > 10^(10^n ) % 9 = = 1(surely ) & & 10^(10^n ) % p = = 1
< = = > 10^(10^n % ( p - 1 ) ) % p = = 1
< = = > 10^n % ( p - 1 ) should be mutiple of order(10 , p )
< = = > order ( 10 , p ) contains only 2^x*5^y
< = = > order ( 10 , p ) divides phi(p ) = p - 1
< = = > enumerate all 2^x * 5 ^ y factors of p - 1
import Math.Sieve.ONeill
import Data.Int
import Data.List
powMod a 0 m = 1
powMod a p m | odd p = powMod a (p - 1) m * a `mod` m
| otherwise = let b = powMod a (p `div` 2) m in b * b `mod` m
check 3 = False
check p = not (null lst)
where
go n x | n `mod` x == 0 = x : go (n `div` x) x
| otherwise = []
factor2 = scanl (*) 1 $ go (p - 1) 2
factor5 = scanl (*) 1 $ go (p - 1) 5
lst = [ f2 * f5
| f2 <- factor2
, f5 <- factor5
, powMod 10 (f2 * f5) p == 1
]
problem_133 = sum [p | p <- takeWhile (<100000) primes, not (check p)]
main = print problem_133
| |
b3dd54ab43dc4c55fd79cee3ce00c572866bf9971b9aa36d1178252a0746e2fc | gedge-platform/gedge-platform | rabbit_mgmt_sup_sup.erl | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%%
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
%%
-module(rabbit_mgmt_sup_sup).
-behaviour(supervisor).
-export([init/1]).
-export([start_link/0, start_child/0]).
-include_lib("rabbit_common/include/rabbit.hrl").
-include("rabbit_mgmt.hrl").
start_child() ->
supervisor:start_child(?MODULE, sup()).
sup() ->
#{
id => rabbit_mgmt_sup,
start => {rabbit_mgmt_sup, start_link, []},
restart => temporary,
shutdown => ?SUPERVISOR_WAIT,
type => supervisor,
modules => [rabbit_mgmt_sup]
}.
init([]) ->
%% This scope is used in the child process, so start it
%% early. We don't attach it to the supervision tree because
%%
%% * rabbitmq_management and rabbitmq_management_agent share a scope
%% * start an already running scope results in an "already started" error returned
%% * such errors wreck supervision tree startup
%%
%% So we expect management agent to start the scope as part of its
%% supervision tree and only start it here for environments
%% such as tests that may be testing parts of this plugin in isolation.
_ = pg:start_link(?MANAGEMENT_PG_SCOPE),
Flags = #{
strategy => one_for_one,
intensity => 0,
period => 1
},
Specs = [sup()],
{ok, {Flags, Specs}}.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
| null | https://raw.githubusercontent.com/gedge-platform/gedge-platform/97c1e87faf28ba2942a77196b6be0a952bff1c3e/gs-broker/broker-server/deps/rabbitmq_management/src/rabbit_mgmt_sup_sup.erl | erlang |
This scope is used in the child process, so start it
early. We don't attach it to the supervision tree because
* rabbitmq_management and rabbitmq_management_agent share a scope
* start an already running scope results in an "already started" error returned
* such errors wreck supervision tree startup
So we expect management agent to start the scope as part of its
supervision tree and only start it here for environments
such as tests that may be testing parts of this plugin in isolation. | This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
Copyright ( c ) 2007 - 2021 VMware , Inc. or its affiliates . All rights reserved .
-module(rabbit_mgmt_sup_sup).
-behaviour(supervisor).
-export([init/1]).
-export([start_link/0, start_child/0]).
-include_lib("rabbit_common/include/rabbit.hrl").
-include("rabbit_mgmt.hrl").
start_child() ->
supervisor:start_child(?MODULE, sup()).
sup() ->
#{
id => rabbit_mgmt_sup,
start => {rabbit_mgmt_sup, start_link, []},
restart => temporary,
shutdown => ?SUPERVISOR_WAIT,
type => supervisor,
modules => [rabbit_mgmt_sup]
}.
init([]) ->
_ = pg:start_link(?MANAGEMENT_PG_SCOPE),
Flags = #{
strategy => one_for_one,
intensity => 0,
period => 1
},
Specs = [sup()],
{ok, {Flags, Specs}}.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
|
1eafe25b6388d9f1698ff76d6a8d825e0bcc9861a9fdde1df52bab5ab9371906 | BumblebeeBat/FlyingFox | channel_close_tx.erl | %If you did not get slashed, and you waited delay since channel_timeout, then this is how you close the channel and get the money out.
-module(channel_close_tx).
-export([doit/7, slow_close/2, id/1]).
-record(channel_close, {acc = 0, nonce = 0, id = 0, fee = 0}).
id(X) -> X#channel_close.id.
doit(Tx, ParentKey, Channels, Accounts, TotalCoins, S, NewHeight) ->
Id = Tx#channel_close.id,
Channel = block_tree:channel(Id, ParentKey, Channels),
SignedOriginTimeout = channel_block_tx:origin_tx(channels:timeout_height(Channel), ParentKey, Id),
OriginTimeout = sign:data(SignedOriginTimeout),
SignedOriginTx = channel_timeout_tx:channel_block(OriginTimeout),
OriginTx = sign:data(SignedOriginTx),
T = block_tree:read(top),
Top = block_tree:height(T),
true = channels:timeout_height(Channel) < (Top - channel_block_tx:delay(OriginTx) + 1),
Acc = block_tree:account(Tx#channel_close.acc, ParentKey, Accounts),
NAcc = accounts:update(Acc, NewHeight, -Tx#channel_close.fee, 0, 1, TotalCoins),
NewAccounts = dict:store(Tx#channel_close.acc, NAcc, Accounts),
Nonce = accounts:nonce(NAcc),
Nonce = Tx#channel_close.nonce,
channel_block_tx:channel(SignedOriginTx, ParentKey, Channels, NewAccounts, TotalCoins, S, NewHeight).
slow_close(Id, MyId) ->
Acc = block_tree:account(MyId),
#channel_close{acc = MyId, nonce = accounts:nonce(Acc) + 1, id = Id}.
| null | https://raw.githubusercontent.com/BumblebeeBat/FlyingFox/0fa039cd2394b08b1a85559f9392086c6be47fa6/src/consensus/txs/channel_close_tx.erl | erlang | If you did not get slashed, and you waited delay since channel_timeout, then this is how you close the channel and get the money out. |
-module(channel_close_tx).
-export([doit/7, slow_close/2, id/1]).
-record(channel_close, {acc = 0, nonce = 0, id = 0, fee = 0}).
id(X) -> X#channel_close.id.
doit(Tx, ParentKey, Channels, Accounts, TotalCoins, S, NewHeight) ->
Id = Tx#channel_close.id,
Channel = block_tree:channel(Id, ParentKey, Channels),
SignedOriginTimeout = channel_block_tx:origin_tx(channels:timeout_height(Channel), ParentKey, Id),
OriginTimeout = sign:data(SignedOriginTimeout),
SignedOriginTx = channel_timeout_tx:channel_block(OriginTimeout),
OriginTx = sign:data(SignedOriginTx),
T = block_tree:read(top),
Top = block_tree:height(T),
true = channels:timeout_height(Channel) < (Top - channel_block_tx:delay(OriginTx) + 1),
Acc = block_tree:account(Tx#channel_close.acc, ParentKey, Accounts),
NAcc = accounts:update(Acc, NewHeight, -Tx#channel_close.fee, 0, 1, TotalCoins),
NewAccounts = dict:store(Tx#channel_close.acc, NAcc, Accounts),
Nonce = accounts:nonce(NAcc),
Nonce = Tx#channel_close.nonce,
channel_block_tx:channel(SignedOriginTx, ParentKey, Channels, NewAccounts, TotalCoins, S, NewHeight).
slow_close(Id, MyId) ->
Acc = block_tree:account(MyId),
#channel_close{acc = MyId, nonce = accounts:nonce(Acc) + 1, id = Id}.
|
8c0fd751dde966ac637c82a5c3fbdd680716d7952ca874c15c9c184a47902cdb | lem-project/lem | ex-command.lisp | (defpackage :lem-vi-mode.ex-command
(:use :cl :lem-vi-mode.ex-core)
(:import-from #:lem-vi-mode.jump-motions
#:with-jump-motion))
(in-package :lem-vi-mode.ex-command)
(defun ex-write (range filename touch)
(case (length range)
(0 (if (string= filename "")
(lem:save-current-buffer touch)
(lem:write-file filename)))
(2 (lem:write-region-file (first range) (second range)
(if (string= filename "")
(lem:buffer-filename (lem:current-buffer))
filename)))
(otherwise (syntax-error))))
(defun ex-write-quit (range filename force touch)
(ex-write range filename touch)
(lem-vi-mode.commands:vi-quit force))
(define-ex-command "^e$" (range filename)
(declare (ignore range))
(lem:find-file (merge-pathnames filename
(lem:buffer-directory))))
(define-ex-command "^(w|write)$" (range filename)
(ex-write range filename t))
(define-ex-command "^update$" (range filename)
(when (lem:buffer-modified-p (lem:current-buffer))
(ex-write range filename t)))
(define-ex-command "^wq$" (range filename)
(ex-write-quit range filename nil t))
(define-ex-command "^wq!$" (range filename)
(ex-write-quit range filename t t))
(define-ex-command "^q$" (range argument)
(declare (ignore range argument))
(lem-vi-mode.commands:vi-quit t))
(define-ex-command "^qa$" (range argument)
(declare (ignore range argument))
(lem:exit-lem t))
(define-ex-command "^q!$" (range argument)
(declare (ignore range argument))
(lem-vi-mode.commands:vi-quit nil))
(define-ex-command "^qa!$" (range argument)
(declare (ignore range argument))
(lem:exit-lem nil))
(define-ex-command "^wqa$" (range filename)
(ex-write range filename nil)
(lem:exit-lem t))
(define-ex-command "^wqa!$" (range filename)
(ex-write range filename nil)
(lem:exit-lem nil))
(define-ex-command "^(x|xit)$" (range filename)
(ex-write-quit range filename nil nil))
(define-ex-command "^(x|xit)!$" (range filename)
(ex-write-quit range filename t nil))
(define-ex-command "^(sp|split)$" (range filename)
(declare (ignore range))
(lem:split-active-window-vertically)
(unless (string= filename "")
(lem:find-file (merge-pathnames filename
(lem:buffer-directory)))))
(define-ex-command "^(vs|vsplit)$" (range filename)
(declare (ignore range))
(lem:split-active-window-horizontally)
(unless (string= filename "")
(lem:find-file (merge-pathnames filename
(lem:buffer-directory)))))
(define-ex-command "^(s|substitute)$" (range argument)
(with-jump-motion
(let (start end)
(case (length range)
((0)
(setf start (lem:line-start (lem:copy-point *point* :temporary))
end (lem:line-end (lem:copy-point *point* :temporary))))
((2)
(setf start (first range)
end (second range))))
(destructuring-bind (before after flag)
(lem-vi-mode.ex-parser:parse-subst-argument argument)
(if (not (lem:with-point ((s start)
(e end))
(lem:search-forward-regexp s before e)))
(lem:message "Pattern not found")
(lem:with-point ((last-match (lem:with-point ((s start)
(e end))
(lem:search-backward-regexp e before s))))
(flet ((rep (start end count)
(lem:with-point ((s start)
(e end))
(lem.isearch::query-replace-internal before
after
#'lem:search-forward-regexp
#'lem:search-backward-regexp
:query nil
:start s
:end e
:count count))))
(if (equal flag "g")
(rep start end nil)
(progn
(lem:move-point (lem:current-point) start)
(loop until (lem:point< end (lem:current-point))
do (lem:with-point ((replace-start (lem:current-point))
(replace-end (lem:current-point)))
(lem:line-start replace-start)
(lem:line-end replace-end)
(rep replace-start replace-end 1))
(lem:next-logical-line 1)
(lem:line-start (lem:current-point))))))
(let ((p (lem:current-point)))
(lem:move-point p last-match)
(lem:line-start p))))))))
(define-ex-command "^!" (range command)
(declare (ignore range))
(lem:pipe-command
(format nil "~A ~A"
(subseq lem-vi-mode.ex-core:*command* 1)
command)))
(define-ex-command "^(buffers|ls|files)$" (range argument)
(declare (ignore range argument))
(lem.list-buffers:list-buffers))
| null | https://raw.githubusercontent.com/lem-project/lem/4f620f94a1fd3bdfb8b2364185e7db16efab57a1/modes/vi-mode/ex-command.lisp | lisp | (defpackage :lem-vi-mode.ex-command
(:use :cl :lem-vi-mode.ex-core)
(:import-from #:lem-vi-mode.jump-motions
#:with-jump-motion))
(in-package :lem-vi-mode.ex-command)
(defun ex-write (range filename touch)
(case (length range)
(0 (if (string= filename "")
(lem:save-current-buffer touch)
(lem:write-file filename)))
(2 (lem:write-region-file (first range) (second range)
(if (string= filename "")
(lem:buffer-filename (lem:current-buffer))
filename)))
(otherwise (syntax-error))))
(defun ex-write-quit (range filename force touch)
(ex-write range filename touch)
(lem-vi-mode.commands:vi-quit force))
(define-ex-command "^e$" (range filename)
(declare (ignore range))
(lem:find-file (merge-pathnames filename
(lem:buffer-directory))))
(define-ex-command "^(w|write)$" (range filename)
(ex-write range filename t))
(define-ex-command "^update$" (range filename)
(when (lem:buffer-modified-p (lem:current-buffer))
(ex-write range filename t)))
(define-ex-command "^wq$" (range filename)
(ex-write-quit range filename nil t))
(define-ex-command "^wq!$" (range filename)
(ex-write-quit range filename t t))
(define-ex-command "^q$" (range argument)
(declare (ignore range argument))
(lem-vi-mode.commands:vi-quit t))
(define-ex-command "^qa$" (range argument)
(declare (ignore range argument))
(lem:exit-lem t))
(define-ex-command "^q!$" (range argument)
(declare (ignore range argument))
(lem-vi-mode.commands:vi-quit nil))
(define-ex-command "^qa!$" (range argument)
(declare (ignore range argument))
(lem:exit-lem nil))
(define-ex-command "^wqa$" (range filename)
(ex-write range filename nil)
(lem:exit-lem t))
(define-ex-command "^wqa!$" (range filename)
(ex-write range filename nil)
(lem:exit-lem nil))
(define-ex-command "^(x|xit)$" (range filename)
(ex-write-quit range filename nil nil))
(define-ex-command "^(x|xit)!$" (range filename)
(ex-write-quit range filename t nil))
(define-ex-command "^(sp|split)$" (range filename)
(declare (ignore range))
(lem:split-active-window-vertically)
(unless (string= filename "")
(lem:find-file (merge-pathnames filename
(lem:buffer-directory)))))
(define-ex-command "^(vs|vsplit)$" (range filename)
(declare (ignore range))
(lem:split-active-window-horizontally)
(unless (string= filename "")
(lem:find-file (merge-pathnames filename
(lem:buffer-directory)))))
(define-ex-command "^(s|substitute)$" (range argument)
(with-jump-motion
(let (start end)
(case (length range)
((0)
(setf start (lem:line-start (lem:copy-point *point* :temporary))
end (lem:line-end (lem:copy-point *point* :temporary))))
((2)
(setf start (first range)
end (second range))))
(destructuring-bind (before after flag)
(lem-vi-mode.ex-parser:parse-subst-argument argument)
(if (not (lem:with-point ((s start)
(e end))
(lem:search-forward-regexp s before e)))
(lem:message "Pattern not found")
(lem:with-point ((last-match (lem:with-point ((s start)
(e end))
(lem:search-backward-regexp e before s))))
(flet ((rep (start end count)
(lem:with-point ((s start)
(e end))
(lem.isearch::query-replace-internal before
after
#'lem:search-forward-regexp
#'lem:search-backward-regexp
:query nil
:start s
:end e
:count count))))
(if (equal flag "g")
(rep start end nil)
(progn
(lem:move-point (lem:current-point) start)
(loop until (lem:point< end (lem:current-point))
do (lem:with-point ((replace-start (lem:current-point))
(replace-end (lem:current-point)))
(lem:line-start replace-start)
(lem:line-end replace-end)
(rep replace-start replace-end 1))
(lem:next-logical-line 1)
(lem:line-start (lem:current-point))))))
(let ((p (lem:current-point)))
(lem:move-point p last-match)
(lem:line-start p))))))))
(define-ex-command "^!" (range command)
(declare (ignore range))
(lem:pipe-command
(format nil "~A ~A"
(subseq lem-vi-mode.ex-core:*command* 1)
command)))
(define-ex-command "^(buffers|ls|files)$" (range argument)
(declare (ignore range argument))
(lem.list-buffers:list-buffers))
| |
412c527e2bcba457313e977796245fcd55da19bfa9b9f73ff0f50ca6d0d8e40e | jeroanan/rkt-coreutils | gidutil.rkt | #lang typed/racket/base
Copyright 2020
; See COPYING for details
(provide gid->group-name
get-user-groups)
(require typed/racket/class)
(require/typed "../libc/grp.rkt"
[get-getgrgid (-> Number (Instance Getgrgid%))]
[get-group-list (-> String Number (Listof Integer))])
(require/typed "../libc/pwd.rkt"
[get-pwnam (-> String (Instance Getpwnam%))])
(require "../typedef/getgrgid.rkt"
"../typedef/getpwnam.rkt")
;; Take a group id and return its name
(: gid->group-name (-> Integer String))
(define (gid->group-name gid)
(let ([grgid (get-getgrgid gid)])
(send grgid get-name)))
;; Get all groups that the given user-name is a member of
(: get-user-groups (-> String (Listof Integer)))
(define (get-user-groups user-name)
(let* ([pwnam (get-pwnam user-name)]
[primary-gid (send pwnam get-gid)]
[the-groups (get-group-list user-name primary-gid)])
the-groups))
| null | https://raw.githubusercontent.com/jeroanan/rkt-coreutils/571629d1e2562c557ba258b31ce454add2e93dd9/src/repl/util/gidutil.rkt | racket | See COPYING for details
Take a group id and return its name
Get all groups that the given user-name is a member of | #lang typed/racket/base
Copyright 2020
(provide gid->group-name
get-user-groups)
(require typed/racket/class)
(require/typed "../libc/grp.rkt"
[get-getgrgid (-> Number (Instance Getgrgid%))]
[get-group-list (-> String Number (Listof Integer))])
(require/typed "../libc/pwd.rkt"
[get-pwnam (-> String (Instance Getpwnam%))])
(require "../typedef/getgrgid.rkt"
"../typedef/getpwnam.rkt")
(: gid->group-name (-> Integer String))
(define (gid->group-name gid)
(let ([grgid (get-getgrgid gid)])
(send grgid get-name)))
(: get-user-groups (-> String (Listof Integer)))
(define (get-user-groups user-name)
(let* ([pwnam (get-pwnam user-name)]
[primary-gid (send pwnam get-gid)]
[the-groups (get-group-list user-name primary-gid)])
the-groups))
|
86b38bb5b4ba96dacb87ecd8291f9c2ba788eabb1211aab142ad625335a3414b | jrh13/hol-light | Propositional_logic.ml | TAUT
`(~input_a ==> (internal <=> T)) /\
(~input_b ==> (output <=> internal)) /\
(input_a ==> (output <=> F)) /\
(input_b ==> (output <=> F))
==> (output <=> ~(input_a \/ input_b))`;;
TAUT
`(i1 /\ i2 <=> a) /\
(i1 /\ i3 <=> b) /\
(i2 /\ i3 <=> c) /\
(i1 /\ c <=> d) /\
(m /\ r <=> e) /\
(m /\ w <=> f) /\
(n /\ w <=> g) /\
(p /\ w <=> h) /\
(q /\ w <=> i) /\
(s /\ x <=> j) /\
(t /\ x <=> k) /\
(v /\ x <=> l) /\
(i1 \/ i2 <=> m) /\
(i1 \/ i3 <=> n) /\
(i1 \/ q <=> p) /\
(i2 \/ i3 <=> q) /\
(i3 \/ a <=> r) /\
(a \/ w <=> s) /\
(b \/ w <=> t) /\
(d \/ h <=> u) /\
(c \/ w <=> v) /\
(~e <=> w) /\
(~u <=> x) /\
(i \/ l <=> o1) /\
(g \/ k <=> o2) /\
(f \/ j <=> o3)
==> (o1 <=> ~i1) /\ (o2 <=> ~i2) /\ (o3 <=> ~i3)`;;
| null | https://raw.githubusercontent.com/jrh13/hol-light/d125b0ae73e546a63ed458a7891f4e14ae0409e2/Tutorial/Propositional_logic.ml | ocaml | TAUT
`(~input_a ==> (internal <=> T)) /\
(~input_b ==> (output <=> internal)) /\
(input_a ==> (output <=> F)) /\
(input_b ==> (output <=> F))
==> (output <=> ~(input_a \/ input_b))`;;
TAUT
`(i1 /\ i2 <=> a) /\
(i1 /\ i3 <=> b) /\
(i2 /\ i3 <=> c) /\
(i1 /\ c <=> d) /\
(m /\ r <=> e) /\
(m /\ w <=> f) /\
(n /\ w <=> g) /\
(p /\ w <=> h) /\
(q /\ w <=> i) /\
(s /\ x <=> j) /\
(t /\ x <=> k) /\
(v /\ x <=> l) /\
(i1 \/ i2 <=> m) /\
(i1 \/ i3 <=> n) /\
(i1 \/ q <=> p) /\
(i2 \/ i3 <=> q) /\
(i3 \/ a <=> r) /\
(a \/ w <=> s) /\
(b \/ w <=> t) /\
(d \/ h <=> u) /\
(c \/ w <=> v) /\
(~e <=> w) /\
(~u <=> x) /\
(i \/ l <=> o1) /\
(g \/ k <=> o2) /\
(f \/ j <=> o3)
==> (o1 <=> ~i1) /\ (o2 <=> ~i2) /\ (o3 <=> ~i3)`;;
| |
cf03e0073c799253ee2ca5de3d9cb59836211f07e8948e054d69a839645ea80d | robdockins/edison | BraunSeq.hs | -- |
-- Module : Data.Edison.Seq.BraunSeq
Copyright : Copyright ( c ) 1998 - 1999 , 2008
License : MIT ; see COPYRIGHT file for terms and conditions
--
Maintainer : robdockins AT fastmail DOT fm
-- Stability : stable
Portability : GHC , Hugs ( MPTC and FD )
--
One - sided sequences . All running times are as listed in
-- "Data.Edison.Seq" except the following:
--
* lview , lcons , * @O ( log n ) @
--
* rcons , rview , rhead * , rtail * , size @O ( log^2 n ) @
--
* copy , inBounds , lookup * , update , adjust @O ( log i ) @
--
* append @O ( n1 log n2 ) @
--
-- * concat @O( n + m log m )@
--
-- * drop, splitAt @O( i log n )@
--
-- * subseq @O( i log n + len )@
--
* reverseOnto @O ( n1 log n2 ) @
--
* concatMap , ( > > ( n * t + m log m ) @ , where @n@ is the length of the input sequence
-- @m@ is the length of the output sequence and @t@
is the running time of @f@
--
By keeping track of the size , we could get , rview , rhead * , and rtail *
down to @O(log n)@ as well ; furthermore , size would be @O ( 1 ) @.
--
/References:/
--
* . \"A symmetric set of efficient list operations\ " .
/Journal of Functional Programming/ , 2(4):505 - -513 , 1992 .
--
* . \"A Logarithmic Implementation of Flexible Arrays\ " .
/Mathematics of Program Construction/ ( MPC'92 ) , pages 191 - 207 .
--
* . \"Three algorithms on " .
/Journal of Function Programming/ 7(6):661 - 666 . Novemebr 1997 .
module Data.Edison.Seq.BraunSeq (
-- * Sequence Type
instance of Sequence , Functor , Monad , MonadPlus
-- * Sequence Operations
empty,singleton,lcons,rcons,append,lview,lhead,ltail,rview,rhead,rtail,
lheadM,ltailM,rheadM,rtailM,
null,size,concat,reverse,reverseOnto,fromList,toList,map,concatMap,
fold,fold',fold1,fold1',foldr,foldr',foldl,foldl',foldr1,foldr1',foldl1,foldl1',
reducer,reducer',reducel,reducel',reduce1,reduce1',
copy,inBounds,lookup,lookupM,lookupWithDefault,update,adjust,
mapWithIndex,foldrWithIndex,foldrWithIndex',foldlWithIndex,foldlWithIndex',
take,drop,splitAt,subseq,filter,partition,takeWhile,dropWhile,splitWhile,
zip,zip3,zipWith,zipWith3,unzip,unzip3,unzipWith,unzipWith3,
strict, strictWith,
-- * Unit testing
structuralInvariant,
-- * Documentation
moduleName
) where
import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1,
filter,takeWhile,dropWhile,lookup,take,drop,splitAt,
zip,zip3,zipWith,zipWith3,unzip,unzip3,null)
import qualified Control.Applicative as App
import qualified Control.Monad.Fail as Fail
import Control.Monad
import Data.Maybe
import Data.Monoid
import Data.Semigroup as SG
import Test.QuickCheck
import Data.Edison.Prelude ( runFail_ )
import qualified Data.Edison.Seq as S ( Sequence(..) )
import Data.Edison.Seq.Defaults
import qualified Data.Edison.Seq.ListSeq as L
-- signatures for exported functions
moduleName :: String
empty :: Seq a
singleton :: a -> Seq a
lcons :: a -> Seq a -> Seq a
rcons :: a -> Seq a -> Seq a
append :: Seq a -> Seq a -> Seq a
lview :: (Fail.MonadFail m) => Seq a -> m (a, Seq a)
lhead :: Seq a -> a
lheadM :: (Fail.MonadFail m) => Seq a -> m a
ltail :: Seq a -> Seq a
ltailM :: (Fail.MonadFail m) => Seq a -> m (Seq a)
rview :: (Fail.MonadFail m) => Seq a -> m (a, Seq a)
rhead :: Seq a -> a
rheadM :: (Fail.MonadFail m) => Seq a -> m a
rtail :: Seq a -> Seq a
rtailM :: (Fail.MonadFail m) => Seq a -> m (Seq a)
null :: Seq a -> Bool
size :: Seq a -> Int
concat :: Seq (Seq a) -> Seq a
reverse :: Seq a -> Seq a
reverseOnto :: Seq a -> Seq a -> Seq a
fromList :: [a] -> Seq a
toList :: Seq a -> [a]
map :: (a -> b) -> Seq a -> Seq b
concatMap :: (a -> Seq b) -> Seq a -> Seq b
fold :: (a -> b -> b) -> b -> Seq a -> b
fold' :: (a -> b -> b) -> b -> Seq a -> b
fold1 :: (a -> a -> a) -> Seq a -> a
fold1' :: (a -> a -> a) -> Seq a -> a
foldr :: (a -> b -> b) -> b -> Seq a -> b
foldl :: (b -> a -> b) -> b -> Seq a -> b
foldr1 :: (a -> a -> a) -> Seq a -> a
foldl1 :: (a -> a -> a) -> Seq a -> a
reducer :: (a -> a -> a) -> a -> Seq a -> a
reducel :: (a -> a -> a) -> a -> Seq a -> a
reduce1 :: (a -> a -> a) -> Seq a -> a
foldr' :: (a -> b -> b) -> b -> Seq a -> b
foldl' :: (b -> a -> b) -> b -> Seq a -> b
foldr1' :: (a -> a -> a) -> Seq a -> a
foldl1' :: (a -> a -> a) -> Seq a -> a
reducer' :: (a -> a -> a) -> a -> Seq a -> a
reducel' :: (a -> a -> a) -> a -> Seq a -> a
reduce1' :: (a -> a -> a) -> Seq a -> a
copy :: Int -> a -> Seq a
inBounds :: Int -> Seq a -> Bool
lookup :: Int -> Seq a -> a
lookupM :: (Fail.MonadFail m) => Int -> Seq a -> m a
lookupWithDefault :: a -> Int -> Seq a -> a
update :: Int -> a -> Seq a -> Seq a
adjust :: (a -> a) -> Int -> Seq a -> Seq a
mapWithIndex :: (Int -> a -> b) -> Seq a -> Seq b
foldrWithIndex :: (Int -> a -> b -> b) -> b -> Seq a -> b
foldlWithIndex :: (b -> Int -> a -> b) -> b -> Seq a -> b
foldrWithIndex' :: (Int -> a -> b -> b) -> b -> Seq a -> b
foldlWithIndex' :: (b -> Int -> a -> b) -> b -> Seq a -> b
take :: Int -> Seq a -> Seq a
drop :: Int -> Seq a -> Seq a
splitAt :: Int -> Seq a -> (Seq a, Seq a)
subseq :: Int -> Int -> Seq a -> Seq a
filter :: (a -> Bool) -> Seq a -> Seq a
partition :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
takeWhile :: (a -> Bool) -> Seq a -> Seq a
dropWhile :: (a -> Bool) -> Seq a -> Seq a
splitWhile :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
zip :: Seq a -> Seq b -> Seq (a,b)
zip3 :: Seq a -> Seq b -> Seq c -> Seq (a,b,c)
zipWith :: (a -> b -> c) -> Seq a -> Seq b -> Seq c
zipWith3 :: (a -> b -> c -> d) -> Seq a -> Seq b -> Seq c -> Seq d
unzip :: Seq (a,b) -> (Seq a, Seq b)
unzip3 :: Seq (a,b,c) -> (Seq a, Seq b, Seq c)
unzipWith :: (a -> b) -> (a -> c) -> Seq a -> (Seq b, Seq c)
unzipWith3 :: (a -> b) -> (a -> c) -> (a -> d) -> Seq a -> (Seq b, Seq c, Seq d)
strict :: Seq a -> Seq a
strictWith :: (a -> b) -> Seq a -> Seq a
structuralInvariant :: Seq a -> Bool
moduleName = "Data.Edison.Seq.BraunSeq"
data Seq a = E | B a (Seq a) (Seq a) deriving (Eq)
half :: Int -> Int
half n = n `quot` 2 -- use a shift?
empty = E
singleton x = B x E E
lcons x E = singleton x
lcons x (B y a b) = B x (lcons y b) a
rcons y ys = insAt (size ys) ys
where insAt 0 _ = singleton y
insAt i (B x a b)
| odd i = B x (insAt (half i) a) b
| otherwise = B x a (insAt (half i - 1) b)
insAt _ _ = error "BraunSeq.rcons: bug. Impossible case!"
append xs E = xs
append xs ys = app (size xs) xs ys
where app 0 _ ys = ys
app _ xs E = xs
app n (B x a b) (B y c d)
| odd n = B x (app m a (lcons y d)) (app m b c)
| otherwise = B x (app m a c) (app (m-1) b (lcons y d))
where m = half n
app _ _ _ = error "BraunSeq.append: bug!"
-- how does it compare to converting to/from lists?
lview E = fail "BraunSeq.lview: empty sequence"
lview (B x a b) = return (x, combine a b)
-- not exported
combine :: Seq a -> Seq a -> Seq a
combine E _ = E
combine (B x a b) c = B x c (combine a b)
lhead E = error "BraunSeq.lhead: empty sequence"
lhead (B x _ _) = x
lheadM E = fail "BraunSeq.lheadM: empty sequence"
lheadM (B x _ _) = return x
ltail E = error "BraunSeq.ltail: empty sequence"
ltail (B _ a b) = combine a b
ltailM E = fail "BraunSeq.ltailM: empty sequence"
ltailM (B _ a b) = return (combine a b)
-- not exported
precondition : i > = 0
delAt :: Int -> Seq a -> Seq a
delAt 0 _ = E
delAt i (B x a b)
| odd i = B x (delAt (half i) a) b
| otherwise = B x a (delAt (half i - 1) b)
delAt _ _ = error "BraunSeq.delAt: bug. Impossible case!"
rview E = fail "BraunSeq.rview: empty sequence"
rview xs = return (lookup m xs, delAt m xs)
where m = size xs - 1
rhead E = error "BraunSeq.rhead: empty sequence"
rhead xs = lookup (size xs - 1) xs
rheadM E = fail "BraunSeq.rheadM: empty sequence"
rheadM xs = return (lookup (size xs - 1) xs)
rtail E = error "BraunSeq.rtail: empty sequence"
rtail xs = delAt (size xs - 1) xs
rtailM E = fail "BraunSeq.rtailM: empty sequence"
rtailM xs = return (delAt (size xs - 1) xs)
null E = True
null _ = False
size E = 0
size (B _ a b) = 1 + n + n + diff n a
where n = size b
diff 0 E = 0
diff 0 (B _ _ _) = 1
diff i (B _ a b)
| odd i = diff (half i) a
| otherwise = diff (half i - 1) b
diff _ _ = error "BraunSeq.size: bug. Impossible case in diff!"
reverse xs = rev00 (size xs) xs
where
rev00 n xs
| n <= 1 = xs
rev00 n (B x a b)
| odd n = let a' = rev00 m a
(x',b') = rev11 m x b in B x' a' b'
| otherwise = let (x',a') = rev01 m a
b' = rev10 (m-1) x b in B x' b' a'
where m = half n
rev00 _ _ = error "BraunSeq.reverse: bug!"
rev11 _ x E = (x,E)
rev11 n x (B y a b)
| odd n = let (x',a') = rev11 m x a
(y',b') = rev11 m y b in (y', B x' b' a')
| otherwise = let (x',a') = rev11 m x a
(y',b') = rev11 (m-1) y b in (x', B y' a' b')
where m = half n
rev01 _ E = error "BraunSeq.reverse: bug!"
rev01 n (B x a b)
| n == 1 = (x, E)
| odd n = let (y',a') = rev01 m a
(x',b') = rev11 m x b in (x', B y' b' a')
| otherwise = let (y',a') = rev01 m a
(x',b') = rev11 (m-1) x b in (y', B x' a' b')
where m = half n
rev10 _ x E = B x E E
rev10 n x (B y a b)
| odd n = let a' = rev10 m x a
(y',b') = rev11 m y b in B y' a' b'
| otherwise = let (x',a') = rev11 m x a
b' = rev10 (m-1) y b in B x' b' a'
where m = half n
fromList = L.lhead . L.foldr build [E] . rows 1
where rows _ [] = []
rows k xs = (k, ys) : rows (k+k) zs
where (ys,zs) = L.splitAt k xs
build (k,xs) ts = zipWithB xs ts1 ts2
where (ts1, ts2) = L.splitAt k ts
zipWithB [] _ _ = []
zipWithB (x:xs) [] _ = singleton x : L.map singleton xs
zipWithB (x:xs) (t:ts) [] = B x t E : zipWithB xs ts []
zipWithB (x:xs) (t1:ts1) (t2:ts2) = B x t1 t2 : zipWithB xs ts1 ts2
toList E = []
toList t = tol [t]
where tol [] = []
tol ts = xs ++ tol (ts1 ++ ts2)
where xs = L.map root ts
(ts1,ts2) = children ts
children [] = ([],[])
children (B _ E _ : _) = ([],[])
children (B _ a E : ts) = (a : leftChildren ts, [])
children (B _ a b : ts) = (a : ts1, b : ts2)
where (ts1, ts2) = children ts
children _ = error "BraunSeq.toList: bug!"
leftChildren [] = []
leftChildren (B _ E _ : _) = []
leftChildren (B _ a _ : ts) = a : leftChildren ts
leftChildren _ = error "BraunSeq.toList: bug!"
root (B x _ _) = x
root _ = error "BraunSeq.toList: bug!"
(B _ a _) = a
-- (left _) = error "BraunSeq.toList: bug!"
map _ E = E
map f (B x a b) = B (f x) (map f a) (map f b)
copy n x = if n <= 0 then empty else fst (copy2 n)
where copy2 n
| odd n = (B x a a, B x b a)
| n == 0 = (E, singleton x)
| otherwise = (B x b a, B x b b)
where (a, b) = copy2 (half (n-1))
inBounds i xs = (i >= 0) && inb xs i
where inb E _ = False
inb (B _ a b) i
| odd i = inb a (half i)
| i == 0 = True
| otherwise = inb b (half i - 1)
lookup i xs = runFail_ (lookupM i xs)
lookupM i xs
| i < 0 = fail "BraunSeq.lookupM: bad subscript"
| otherwise = look xs i
where look E _ = nothing
look (B x a b) i
| odd i = look a (half i)
| i == 0 = return x
| otherwise = look b (half i - 1)
nothing = fail "BraunSeq.lookupM: not found"
lookupWithDefault d i xs = if i < 0 then d
else look xs i
where look E _ = d
look (B x a b) i
| odd i = look a (half i)
| i == 0 = x
| otherwise = look b (half i - 1)
update i y xs = if i < 0 then xs else upd i xs
where upd _ E = E
upd i (B x a b)
| odd i = B x (upd (half i) a) b
| i == 0 = B y a b
| otherwise = B x a (upd (half i - 1) b)
adjust f i xs = if i < 0 then xs else adj i xs
where adj _ E = E
adj i (B x a b)
| odd i = B x (adj (half i) a) b
| i == 0 = B (f x) a b
| otherwise = B x a (adj (half i - 1) b)
mapWithIndex f xs = mwi 0 1 xs
where mwi _ _ E = E
mwi i d (B x a b) = B (f i x) (mwi (i+d) dd a) (mwi (i+dd) dd b)
where dd = d+d
take n xs = if n <= 0 then E else ta n xs
where ta _ E = E
ta n (B x a b)
| odd n = B x (ta m a) (ta m b)
| n == 0 = E
| otherwise = B x (ta m a) (ta (m-1) b)
where m = half n
drop n xs = if n <= 0 then xs else dr n xs
where dr _ E = E
dr n t@(B _ a b)
| odd n = combine (dr m a) (dr m b)
| n == 0 = t
| otherwise = combine (dr (m-1) b) (dr m a)
where m = half n
zip (B x a b) (B y c d) = B (x,y) (zip a c) (zip b d)
zip _ _ = E
zip3 (B x a b) (B y c d) (B z e f) = B (x,y,z) (zip3 a c e) (zip3 b d f)
zip3 _ _ _ = E
zipWith f (B x a b) (B y c d) = B (f x y) (zipWith f a c) (zipWith f b d)
zipWith _ _ _ = E
zipWith3 fn (B x a b) (B y c d) (B z e f) =
B (fn x y z) (zipWith3 fn a c e) (zipWith3 fn b d f)
zipWith3 _ _ _ _ = E
unzip E = (E, E)
unzip (B (x,y) a b) = (B x a1 b1, B y a2 b2)
where (a1,a2) = unzip a
(b1,b2) = unzip b
unzip3 E = (E, E, E)
unzip3 (B (x,y,z) a b) = (B x a1 b1, B y a2 b2, B z a3 b3)
where (a1,a2,a3) = unzip3 a
(b1,b2,b3) = unzip3 b
unzipWith _ _ E = (E, E)
unzipWith f g (B x a b) = (B (f x) a1 b1, B (g x) a2 b2)
where (a1,a2) = unzipWith f g a
(b1,b2) = unzipWith f g b
unzipWith3 _ _ _ E = (E, E, E)
unzipWith3 f g h (B x a b) = (B (f x) a1 b1, B (g x) a2 b2, B (h x) a3 b3)
where (a1,a2,a3) = unzipWith3 f g h a
(b1,b2,b3) = unzipWith3 f g h b
strict s@E = s
strict s@(B _ l r) = strict l `seq` strict r `seq` s
strictWith _ s@E = s
strictWith f s@(B x l r) = f x `seq` strictWith f l `seq` strictWith f r `seq` s
-- invariants:
-- * Left subtree is exactily the same size as the right
subtree , or one element larger
-- structuralInvariant :: Seq a -> Bool
structuralInvariant E = True
structuralInvariant (B _ l r) = isJust (check l r)
where check :: Seq a -> Seq a -> Maybe Int
check E E = Just 1
check (B _ E E) E = Just 2
check (B _ l1 l2) (B _ r1 r2) = do
x <- check l1 l2
y <- check r1 r2
if (x == y) || (x == y + 1)
then return (x+y+1)
else fail "unbalanced tree"
check _ _ = fail "unbalanced tree"
-- the remaining functions all use defaults
concat = concatUsingFoldr
reverseOnto = reverseOntoUsingReverse
concatMap = concatMapUsingFoldr
fold = foldrUsingLists
fold' f = foldl'UsingLists (flip f)
fold1 = fold1UsingFold
fold1' = fold1'UsingFold'
foldr = foldrUsingLists
foldr' = foldr'UsingLists
foldl = foldlUsingLists
foldl' = foldl'UsingLists
foldr1 = foldr1UsingLists
foldr1' = foldr1'UsingLists
foldl1 = foldl1UsingLists
foldl1' = foldl1UsingLists
reducer = reducerUsingReduce1
reducer' = reducer'UsingReduce1'
reducel = reducelUsingReduce1
reducel' = reducel'UsingReduce1'
reduce1 = reduce1UsingLists
reduce1' = reduce1'UsingLists
foldrWithIndex = foldrWithIndexUsingLists
foldrWithIndex' = foldrWithIndex'UsingLists
foldlWithIndex = foldlWithIndexUsingLists
foldlWithIndex' = foldlWithIndex'UsingLists
splitAt = splitAtDefault
subseq = subseqDefault
filter = filterUsingLists
partition = partitionUsingLists
takeWhile = takeWhileUsingLview
dropWhile = dropWhileUsingLview
splitWhile = splitWhileUsingLview
-- instances
instance S.Sequence Seq where
{lcons = lcons; rcons = rcons;
lview = lview; lhead = lhead; ltail = ltail;
lheadM = lheadM; ltailM = ltailM; rheadM = rheadM; rtailM = rtailM;
rview = rview; rhead = rhead; rtail = rtail; null = null;
size = size; concat = concat; reverse = reverse;
reverseOnto = reverseOnto; fromList = fromList; toList = toList;
fold = fold; fold' = fold'; fold1 = fold1; fold1' = fold1';
foldr = foldr; foldr' = foldr'; foldl = foldl; foldl' = foldl';
foldr1 = foldr1; foldr1' = foldr1'; foldl1 = foldl1; foldl1' = foldl1';
reducer = reducer; reducer' = reducer'; reducel = reducel;
reducel' = reducel'; reduce1 = reduce1; reduce1' = reduce1';
copy = copy; inBounds = inBounds; lookup = lookup;
lookupM = lookupM; lookupWithDefault = lookupWithDefault;
update = update; adjust = adjust; mapWithIndex = mapWithIndex;
foldrWithIndex = foldrWithIndex; foldrWithIndex' = foldrWithIndex';
foldlWithIndex = foldlWithIndex; foldlWithIndex' = foldlWithIndex';
take = take; drop = drop; splitAt = splitAt; subseq = subseq;
filter = filter; partition = partition; takeWhile = takeWhile;
dropWhile = dropWhile; splitWhile = splitWhile; zip = zip;
zip3 = zip3; zipWith = zipWith; zipWith3 = zipWith3; unzip = unzip;
unzip3 = unzip3; unzipWith = unzipWith; unzipWith3 = unzipWith3;
strict = strict; strictWith = strictWith;
structuralInvariant = structuralInvariant; instanceName _ = moduleName}
instance Functor Seq where
fmap = map
instance App.Alternative Seq where
empty = empty
(<|>) = append
instance App.Applicative Seq where
pure = return
x <*> y = do
x' <- x
y' <- y
return (x' y')
instance Monad Seq where
return = singleton
xs >>= k = concatMap k xs
instance MonadPlus Seq where
mplus = append
mzero = empty
instance ( Seq a ) is derived
instance Ord a => Ord (Seq a) where
compare = defaultCompare
instance Show a => Show (Seq a) where
showsPrec = showsPrecUsingToList
instance Read a => Read (Seq a) where
readsPrec = readsPrecUsingFromList
instance Arbitrary a => Arbitrary (Seq a) where
arbitrary = arbitrary >>= (return . fromList)
instance CoArbitrary a => CoArbitrary (Seq a) where
coarbitrary xs = coarbitrary (toList xs)
instance Semigroup (Seq a) where
(<>) = append
instance Monoid (Seq a) where
mempty = empty
mappend = (SG.<>)
| null | https://raw.githubusercontent.com/robdockins/edison/e9024cc5b9c4cf6b59d33baf7564e509366c79da/edison-core/src/Data/Edison/Seq/BraunSeq.hs | haskell | |
Module : Data.Edison.Seq.BraunSeq
Stability : stable
"Data.Edison.Seq" except the following:
* concat @O( n + m log m )@
* drop, splitAt @O( i log n )@
* subseq @O( i log n + len )@
@m@ is the length of the output sequence and @t@
* Sequence Type
* Sequence Operations
* Unit testing
* Documentation
signatures for exported functions
use a shift?
how does it compare to converting to/from lists?
not exported
not exported
(left _) = error "BraunSeq.toList: bug!"
invariants:
* Left subtree is exactily the same size as the right
structuralInvariant :: Seq a -> Bool
the remaining functions all use defaults
instances | Copyright : Copyright ( c ) 1998 - 1999 , 2008
License : MIT ; see COPYRIGHT file for terms and conditions
Maintainer : robdockins AT fastmail DOT fm
Portability : GHC , Hugs ( MPTC and FD )
One - sided sequences . All running times are as listed in
* lview , lcons , * @O ( log n ) @
* rcons , rview , rhead * , rtail * , size @O ( log^2 n ) @
* copy , inBounds , lookup * , update , adjust @O ( log i ) @
* append @O ( n1 log n2 ) @
* reverseOnto @O ( n1 log n2 ) @
* concatMap , ( > > ( n * t + m log m ) @ , where @n@ is the length of the input sequence
is the running time of @f@
By keeping track of the size , we could get , rview , rhead * , and rtail *
down to @O(log n)@ as well ; furthermore , size would be @O ( 1 ) @.
/References:/
* . \"A symmetric set of efficient list operations\ " .
/Journal of Functional Programming/ , 2(4):505 - -513 , 1992 .
* . \"A Logarithmic Implementation of Flexible Arrays\ " .
/Mathematics of Program Construction/ ( MPC'92 ) , pages 191 - 207 .
* . \"Three algorithms on " .
/Journal of Function Programming/ 7(6):661 - 666 . Novemebr 1997 .
module Data.Edison.Seq.BraunSeq (
instance of Sequence , Functor , Monad , MonadPlus
empty,singleton,lcons,rcons,append,lview,lhead,ltail,rview,rhead,rtail,
lheadM,ltailM,rheadM,rtailM,
null,size,concat,reverse,reverseOnto,fromList,toList,map,concatMap,
fold,fold',fold1,fold1',foldr,foldr',foldl,foldl',foldr1,foldr1',foldl1,foldl1',
reducer,reducer',reducel,reducel',reduce1,reduce1',
copy,inBounds,lookup,lookupM,lookupWithDefault,update,adjust,
mapWithIndex,foldrWithIndex,foldrWithIndex',foldlWithIndex,foldlWithIndex',
take,drop,splitAt,subseq,filter,partition,takeWhile,dropWhile,splitWhile,
zip,zip3,zipWith,zipWith3,unzip,unzip3,unzipWith,unzipWith3,
strict, strictWith,
structuralInvariant,
moduleName
) where
import Prelude hiding (concat,reverse,map,concatMap,foldr,foldl,foldr1,foldl1,
filter,takeWhile,dropWhile,lookup,take,drop,splitAt,
zip,zip3,zipWith,zipWith3,unzip,unzip3,null)
import qualified Control.Applicative as App
import qualified Control.Monad.Fail as Fail
import Control.Monad
import Data.Maybe
import Data.Monoid
import Data.Semigroup as SG
import Test.QuickCheck
import Data.Edison.Prelude ( runFail_ )
import qualified Data.Edison.Seq as S ( Sequence(..) )
import Data.Edison.Seq.Defaults
import qualified Data.Edison.Seq.ListSeq as L
moduleName :: String
empty :: Seq a
singleton :: a -> Seq a
lcons :: a -> Seq a -> Seq a
rcons :: a -> Seq a -> Seq a
append :: Seq a -> Seq a -> Seq a
lview :: (Fail.MonadFail m) => Seq a -> m (a, Seq a)
lhead :: Seq a -> a
lheadM :: (Fail.MonadFail m) => Seq a -> m a
ltail :: Seq a -> Seq a
ltailM :: (Fail.MonadFail m) => Seq a -> m (Seq a)
rview :: (Fail.MonadFail m) => Seq a -> m (a, Seq a)
rhead :: Seq a -> a
rheadM :: (Fail.MonadFail m) => Seq a -> m a
rtail :: Seq a -> Seq a
rtailM :: (Fail.MonadFail m) => Seq a -> m (Seq a)
null :: Seq a -> Bool
size :: Seq a -> Int
concat :: Seq (Seq a) -> Seq a
reverse :: Seq a -> Seq a
reverseOnto :: Seq a -> Seq a -> Seq a
fromList :: [a] -> Seq a
toList :: Seq a -> [a]
map :: (a -> b) -> Seq a -> Seq b
concatMap :: (a -> Seq b) -> Seq a -> Seq b
fold :: (a -> b -> b) -> b -> Seq a -> b
fold' :: (a -> b -> b) -> b -> Seq a -> b
fold1 :: (a -> a -> a) -> Seq a -> a
fold1' :: (a -> a -> a) -> Seq a -> a
foldr :: (a -> b -> b) -> b -> Seq a -> b
foldl :: (b -> a -> b) -> b -> Seq a -> b
foldr1 :: (a -> a -> a) -> Seq a -> a
foldl1 :: (a -> a -> a) -> Seq a -> a
reducer :: (a -> a -> a) -> a -> Seq a -> a
reducel :: (a -> a -> a) -> a -> Seq a -> a
reduce1 :: (a -> a -> a) -> Seq a -> a
foldr' :: (a -> b -> b) -> b -> Seq a -> b
foldl' :: (b -> a -> b) -> b -> Seq a -> b
foldr1' :: (a -> a -> a) -> Seq a -> a
foldl1' :: (a -> a -> a) -> Seq a -> a
reducer' :: (a -> a -> a) -> a -> Seq a -> a
reducel' :: (a -> a -> a) -> a -> Seq a -> a
reduce1' :: (a -> a -> a) -> Seq a -> a
copy :: Int -> a -> Seq a
inBounds :: Int -> Seq a -> Bool
lookup :: Int -> Seq a -> a
lookupM :: (Fail.MonadFail m) => Int -> Seq a -> m a
lookupWithDefault :: a -> Int -> Seq a -> a
update :: Int -> a -> Seq a -> Seq a
adjust :: (a -> a) -> Int -> Seq a -> Seq a
mapWithIndex :: (Int -> a -> b) -> Seq a -> Seq b
foldrWithIndex :: (Int -> a -> b -> b) -> b -> Seq a -> b
foldlWithIndex :: (b -> Int -> a -> b) -> b -> Seq a -> b
foldrWithIndex' :: (Int -> a -> b -> b) -> b -> Seq a -> b
foldlWithIndex' :: (b -> Int -> a -> b) -> b -> Seq a -> b
take :: Int -> Seq a -> Seq a
drop :: Int -> Seq a -> Seq a
splitAt :: Int -> Seq a -> (Seq a, Seq a)
subseq :: Int -> Int -> Seq a -> Seq a
filter :: (a -> Bool) -> Seq a -> Seq a
partition :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
takeWhile :: (a -> Bool) -> Seq a -> Seq a
dropWhile :: (a -> Bool) -> Seq a -> Seq a
splitWhile :: (a -> Bool) -> Seq a -> (Seq a, Seq a)
zip :: Seq a -> Seq b -> Seq (a,b)
zip3 :: Seq a -> Seq b -> Seq c -> Seq (a,b,c)
zipWith :: (a -> b -> c) -> Seq a -> Seq b -> Seq c
zipWith3 :: (a -> b -> c -> d) -> Seq a -> Seq b -> Seq c -> Seq d
unzip :: Seq (a,b) -> (Seq a, Seq b)
unzip3 :: Seq (a,b,c) -> (Seq a, Seq b, Seq c)
unzipWith :: (a -> b) -> (a -> c) -> Seq a -> (Seq b, Seq c)
unzipWith3 :: (a -> b) -> (a -> c) -> (a -> d) -> Seq a -> (Seq b, Seq c, Seq d)
strict :: Seq a -> Seq a
strictWith :: (a -> b) -> Seq a -> Seq a
structuralInvariant :: Seq a -> Bool
moduleName = "Data.Edison.Seq.BraunSeq"
data Seq a = E | B a (Seq a) (Seq a) deriving (Eq)
half :: Int -> Int
empty = E
singleton x = B x E E
lcons x E = singleton x
lcons x (B y a b) = B x (lcons y b) a
rcons y ys = insAt (size ys) ys
where insAt 0 _ = singleton y
insAt i (B x a b)
| odd i = B x (insAt (half i) a) b
| otherwise = B x a (insAt (half i - 1) b)
insAt _ _ = error "BraunSeq.rcons: bug. Impossible case!"
append xs E = xs
append xs ys = app (size xs) xs ys
where app 0 _ ys = ys
app _ xs E = xs
app n (B x a b) (B y c d)
| odd n = B x (app m a (lcons y d)) (app m b c)
| otherwise = B x (app m a c) (app (m-1) b (lcons y d))
where m = half n
app _ _ _ = error "BraunSeq.append: bug!"
lview E = fail "BraunSeq.lview: empty sequence"
lview (B x a b) = return (x, combine a b)
combine :: Seq a -> Seq a -> Seq a
combine E _ = E
combine (B x a b) c = B x c (combine a b)
lhead E = error "BraunSeq.lhead: empty sequence"
lhead (B x _ _) = x
lheadM E = fail "BraunSeq.lheadM: empty sequence"
lheadM (B x _ _) = return x
ltail E = error "BraunSeq.ltail: empty sequence"
ltail (B _ a b) = combine a b
ltailM E = fail "BraunSeq.ltailM: empty sequence"
ltailM (B _ a b) = return (combine a b)
precondition : i > = 0
delAt :: Int -> Seq a -> Seq a
delAt 0 _ = E
delAt i (B x a b)
| odd i = B x (delAt (half i) a) b
| otherwise = B x a (delAt (half i - 1) b)
delAt _ _ = error "BraunSeq.delAt: bug. Impossible case!"
rview E = fail "BraunSeq.rview: empty sequence"
rview xs = return (lookup m xs, delAt m xs)
where m = size xs - 1
rhead E = error "BraunSeq.rhead: empty sequence"
rhead xs = lookup (size xs - 1) xs
rheadM E = fail "BraunSeq.rheadM: empty sequence"
rheadM xs = return (lookup (size xs - 1) xs)
rtail E = error "BraunSeq.rtail: empty sequence"
rtail xs = delAt (size xs - 1) xs
rtailM E = fail "BraunSeq.rtailM: empty sequence"
rtailM xs = return (delAt (size xs - 1) xs)
null E = True
null _ = False
size E = 0
size (B _ a b) = 1 + n + n + diff n a
where n = size b
diff 0 E = 0
diff 0 (B _ _ _) = 1
diff i (B _ a b)
| odd i = diff (half i) a
| otherwise = diff (half i - 1) b
diff _ _ = error "BraunSeq.size: bug. Impossible case in diff!"
reverse xs = rev00 (size xs) xs
where
rev00 n xs
| n <= 1 = xs
rev00 n (B x a b)
| odd n = let a' = rev00 m a
(x',b') = rev11 m x b in B x' a' b'
| otherwise = let (x',a') = rev01 m a
b' = rev10 (m-1) x b in B x' b' a'
where m = half n
rev00 _ _ = error "BraunSeq.reverse: bug!"
rev11 _ x E = (x,E)
rev11 n x (B y a b)
| odd n = let (x',a') = rev11 m x a
(y',b') = rev11 m y b in (y', B x' b' a')
| otherwise = let (x',a') = rev11 m x a
(y',b') = rev11 (m-1) y b in (x', B y' a' b')
where m = half n
rev01 _ E = error "BraunSeq.reverse: bug!"
rev01 n (B x a b)
| n == 1 = (x, E)
| odd n = let (y',a') = rev01 m a
(x',b') = rev11 m x b in (x', B y' b' a')
| otherwise = let (y',a') = rev01 m a
(x',b') = rev11 (m-1) x b in (y', B x' a' b')
where m = half n
rev10 _ x E = B x E E
rev10 n x (B y a b)
| odd n = let a' = rev10 m x a
(y',b') = rev11 m y b in B y' a' b'
| otherwise = let (x',a') = rev11 m x a
b' = rev10 (m-1) y b in B x' b' a'
where m = half n
fromList = L.lhead . L.foldr build [E] . rows 1
where rows _ [] = []
rows k xs = (k, ys) : rows (k+k) zs
where (ys,zs) = L.splitAt k xs
build (k,xs) ts = zipWithB xs ts1 ts2
where (ts1, ts2) = L.splitAt k ts
zipWithB [] _ _ = []
zipWithB (x:xs) [] _ = singleton x : L.map singleton xs
zipWithB (x:xs) (t:ts) [] = B x t E : zipWithB xs ts []
zipWithB (x:xs) (t1:ts1) (t2:ts2) = B x t1 t2 : zipWithB xs ts1 ts2
toList E = []
toList t = tol [t]
where tol [] = []
tol ts = xs ++ tol (ts1 ++ ts2)
where xs = L.map root ts
(ts1,ts2) = children ts
children [] = ([],[])
children (B _ E _ : _) = ([],[])
children (B _ a E : ts) = (a : leftChildren ts, [])
children (B _ a b : ts) = (a : ts1, b : ts2)
where (ts1, ts2) = children ts
children _ = error "BraunSeq.toList: bug!"
leftChildren [] = []
leftChildren (B _ E _ : _) = []
leftChildren (B _ a _ : ts) = a : leftChildren ts
leftChildren _ = error "BraunSeq.toList: bug!"
root (B x _ _) = x
root _ = error "BraunSeq.toList: bug!"
(B _ a _) = a
map _ E = E
map f (B x a b) = B (f x) (map f a) (map f b)
copy n x = if n <= 0 then empty else fst (copy2 n)
where copy2 n
| odd n = (B x a a, B x b a)
| n == 0 = (E, singleton x)
| otherwise = (B x b a, B x b b)
where (a, b) = copy2 (half (n-1))
inBounds i xs = (i >= 0) && inb xs i
where inb E _ = False
inb (B _ a b) i
| odd i = inb a (half i)
| i == 0 = True
| otherwise = inb b (half i - 1)
lookup i xs = runFail_ (lookupM i xs)
lookupM i xs
| i < 0 = fail "BraunSeq.lookupM: bad subscript"
| otherwise = look xs i
where look E _ = nothing
look (B x a b) i
| odd i = look a (half i)
| i == 0 = return x
| otherwise = look b (half i - 1)
nothing = fail "BraunSeq.lookupM: not found"
lookupWithDefault d i xs = if i < 0 then d
else look xs i
where look E _ = d
look (B x a b) i
| odd i = look a (half i)
| i == 0 = x
| otherwise = look b (half i - 1)
update i y xs = if i < 0 then xs else upd i xs
where upd _ E = E
upd i (B x a b)
| odd i = B x (upd (half i) a) b
| i == 0 = B y a b
| otherwise = B x a (upd (half i - 1) b)
adjust f i xs = if i < 0 then xs else adj i xs
where adj _ E = E
adj i (B x a b)
| odd i = B x (adj (half i) a) b
| i == 0 = B (f x) a b
| otherwise = B x a (adj (half i - 1) b)
mapWithIndex f xs = mwi 0 1 xs
where mwi _ _ E = E
mwi i d (B x a b) = B (f i x) (mwi (i+d) dd a) (mwi (i+dd) dd b)
where dd = d+d
take n xs = if n <= 0 then E else ta n xs
where ta _ E = E
ta n (B x a b)
| odd n = B x (ta m a) (ta m b)
| n == 0 = E
| otherwise = B x (ta m a) (ta (m-1) b)
where m = half n
drop n xs = if n <= 0 then xs else dr n xs
where dr _ E = E
dr n t@(B _ a b)
| odd n = combine (dr m a) (dr m b)
| n == 0 = t
| otherwise = combine (dr (m-1) b) (dr m a)
where m = half n
zip (B x a b) (B y c d) = B (x,y) (zip a c) (zip b d)
zip _ _ = E
zip3 (B x a b) (B y c d) (B z e f) = B (x,y,z) (zip3 a c e) (zip3 b d f)
zip3 _ _ _ = E
zipWith f (B x a b) (B y c d) = B (f x y) (zipWith f a c) (zipWith f b d)
zipWith _ _ _ = E
zipWith3 fn (B x a b) (B y c d) (B z e f) =
B (fn x y z) (zipWith3 fn a c e) (zipWith3 fn b d f)
zipWith3 _ _ _ _ = E
unzip E = (E, E)
unzip (B (x,y) a b) = (B x a1 b1, B y a2 b2)
where (a1,a2) = unzip a
(b1,b2) = unzip b
unzip3 E = (E, E, E)
unzip3 (B (x,y,z) a b) = (B x a1 b1, B y a2 b2, B z a3 b3)
where (a1,a2,a3) = unzip3 a
(b1,b2,b3) = unzip3 b
unzipWith _ _ E = (E, E)
unzipWith f g (B x a b) = (B (f x) a1 b1, B (g x) a2 b2)
where (a1,a2) = unzipWith f g a
(b1,b2) = unzipWith f g b
unzipWith3 _ _ _ E = (E, E, E)
unzipWith3 f g h (B x a b) = (B (f x) a1 b1, B (g x) a2 b2, B (h x) a3 b3)
where (a1,a2,a3) = unzipWith3 f g h a
(b1,b2,b3) = unzipWith3 f g h b
strict s@E = s
strict s@(B _ l r) = strict l `seq` strict r `seq` s
strictWith _ s@E = s
strictWith f s@(B x l r) = f x `seq` strictWith f l `seq` strictWith f r `seq` s
subtree , or one element larger
structuralInvariant E = True
structuralInvariant (B _ l r) = isJust (check l r)
where check :: Seq a -> Seq a -> Maybe Int
check E E = Just 1
check (B _ E E) E = Just 2
check (B _ l1 l2) (B _ r1 r2) = do
x <- check l1 l2
y <- check r1 r2
if (x == y) || (x == y + 1)
then return (x+y+1)
else fail "unbalanced tree"
check _ _ = fail "unbalanced tree"
concat = concatUsingFoldr
reverseOnto = reverseOntoUsingReverse
concatMap = concatMapUsingFoldr
fold = foldrUsingLists
fold' f = foldl'UsingLists (flip f)
fold1 = fold1UsingFold
fold1' = fold1'UsingFold'
foldr = foldrUsingLists
foldr' = foldr'UsingLists
foldl = foldlUsingLists
foldl' = foldl'UsingLists
foldr1 = foldr1UsingLists
foldr1' = foldr1'UsingLists
foldl1 = foldl1UsingLists
foldl1' = foldl1UsingLists
reducer = reducerUsingReduce1
reducer' = reducer'UsingReduce1'
reducel = reducelUsingReduce1
reducel' = reducel'UsingReduce1'
reduce1 = reduce1UsingLists
reduce1' = reduce1'UsingLists
foldrWithIndex = foldrWithIndexUsingLists
foldrWithIndex' = foldrWithIndex'UsingLists
foldlWithIndex = foldlWithIndexUsingLists
foldlWithIndex' = foldlWithIndex'UsingLists
splitAt = splitAtDefault
subseq = subseqDefault
filter = filterUsingLists
partition = partitionUsingLists
takeWhile = takeWhileUsingLview
dropWhile = dropWhileUsingLview
splitWhile = splitWhileUsingLview
instance S.Sequence Seq where
{lcons = lcons; rcons = rcons;
lview = lview; lhead = lhead; ltail = ltail;
lheadM = lheadM; ltailM = ltailM; rheadM = rheadM; rtailM = rtailM;
rview = rview; rhead = rhead; rtail = rtail; null = null;
size = size; concat = concat; reverse = reverse;
reverseOnto = reverseOnto; fromList = fromList; toList = toList;
fold = fold; fold' = fold'; fold1 = fold1; fold1' = fold1';
foldr = foldr; foldr' = foldr'; foldl = foldl; foldl' = foldl';
foldr1 = foldr1; foldr1' = foldr1'; foldl1 = foldl1; foldl1' = foldl1';
reducer = reducer; reducer' = reducer'; reducel = reducel;
reducel' = reducel'; reduce1 = reduce1; reduce1' = reduce1';
copy = copy; inBounds = inBounds; lookup = lookup;
lookupM = lookupM; lookupWithDefault = lookupWithDefault;
update = update; adjust = adjust; mapWithIndex = mapWithIndex;
foldrWithIndex = foldrWithIndex; foldrWithIndex' = foldrWithIndex';
foldlWithIndex = foldlWithIndex; foldlWithIndex' = foldlWithIndex';
take = take; drop = drop; splitAt = splitAt; subseq = subseq;
filter = filter; partition = partition; takeWhile = takeWhile;
dropWhile = dropWhile; splitWhile = splitWhile; zip = zip;
zip3 = zip3; zipWith = zipWith; zipWith3 = zipWith3; unzip = unzip;
unzip3 = unzip3; unzipWith = unzipWith; unzipWith3 = unzipWith3;
strict = strict; strictWith = strictWith;
structuralInvariant = structuralInvariant; instanceName _ = moduleName}
instance Functor Seq where
fmap = map
instance App.Alternative Seq where
empty = empty
(<|>) = append
instance App.Applicative Seq where
pure = return
x <*> y = do
x' <- x
y' <- y
return (x' y')
instance Monad Seq where
return = singleton
xs >>= k = concatMap k xs
instance MonadPlus Seq where
mplus = append
mzero = empty
instance ( Seq a ) is derived
instance Ord a => Ord (Seq a) where
compare = defaultCompare
instance Show a => Show (Seq a) where
showsPrec = showsPrecUsingToList
instance Read a => Read (Seq a) where
readsPrec = readsPrecUsingFromList
instance Arbitrary a => Arbitrary (Seq a) where
arbitrary = arbitrary >>= (return . fromList)
instance CoArbitrary a => CoArbitrary (Seq a) where
coarbitrary xs = coarbitrary (toList xs)
instance Semigroup (Seq a) where
(<>) = append
instance Monoid (Seq a) where
mempty = empty
mappend = (SG.<>)
|
2639c6f16cb8fbfc48c5a7e0773fc824256027604ceb762fe4f5048b30ddefec | akhudek/zip-visit | visit_test.cljc | (ns zip.visit-test
(:require
[clojure.zip :as z]
#?@(:clj
[[clojure.test :refer :all]
[zip.visit :as zv]])
#?@(:cljs
[[cljs.test :refer-macros [deftest testing is]]
[zip.visit :as zv :include-macros true]])))
(defn -xor [a b] (and (or a b) (not (and a b))))
(deftest false-is-not-nil
(testing "false node propagation"
(is (= {:node [false true true false true true], :state nil}
(zv/visit
(z/vector-zip [0 1 1 2 3 5])
nil
[(zv/visitor :pre [n s] (if (number? n) {:node (odd? n)}))]))))
(testing "false state propagation"
(is (= {:node [0 1 1 2 3 5],
:state (reduce -xor false [0 1 1 2 3 5])}
(zv/visit
(z/vector-zip [0 1 1 2 3 5])
false
[(zv/visitor :pre [n s] (if (number? n) {:state (-xor s (odd? n))}))])))))
| null | https://raw.githubusercontent.com/akhudek/zip-visit/e7bd7b6a013f3bf294bfc38b3575947d170fe2f8/test/zip/visit_test.cljc | clojure | (ns zip.visit-test
(:require
[clojure.zip :as z]
#?@(:clj
[[clojure.test :refer :all]
[zip.visit :as zv]])
#?@(:cljs
[[cljs.test :refer-macros [deftest testing is]]
[zip.visit :as zv :include-macros true]])))
(defn -xor [a b] (and (or a b) (not (and a b))))
(deftest false-is-not-nil
(testing "false node propagation"
(is (= {:node [false true true false true true], :state nil}
(zv/visit
(z/vector-zip [0 1 1 2 3 5])
nil
[(zv/visitor :pre [n s] (if (number? n) {:node (odd? n)}))]))))
(testing "false state propagation"
(is (= {:node [0 1 1 2 3 5],
:state (reduce -xor false [0 1 1 2 3 5])}
(zv/visit
(z/vector-zip [0 1 1 2 3 5])
false
[(zv/visitor :pre [n s] (if (number? n) {:state (-xor s (odd? n))}))])))))
| |
288a9e92d05d426d399b80fa7940749999ce314585e494e2f9cdef2c8d6a647a | CryptoKami/cryptokami-core | Connection.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE TypeFamilies #
-- | Module for websockets implementation of Daedalus API.
-- This implements unidirectional sockets from server to client.
-- Every message received from client will be ignored.
module Pos.Wallet.Web.Sockets.Connection
( MonadWalletWebSockets
, getWalletWebSockets
, initWSConnections
, closeWSConnections
, upgradeApplicationWS
, notifyAll
) where
import Universum
import Control.Concurrent.STM.TVar (swapTVar)
import Data.Aeson (encode)
import Data.Default (Default (def))
import Formatting (build, sformat, (%))
import Network.Wai (Application)
import Network.Wai.Handler.WebSockets (websocketsOr)
import qualified Network.WebSockets as WS
import System.Wlog (logError, logNotice, usingLoggerName)
import Pos.Util.Util (HasLens (..), HasLens')
import Pos.Wallet.Aeson ()
import qualified Pos.Wallet.Web.Sockets.ConnSet as CS
import Pos.Wallet.Web.Sockets.Types (NotifyEvent (ConnectionClosed, ConnectionOpened),
WSConnection)
initWSConnections :: MonadIO m => m CS.ConnectionsVar
initWSConnections = newTVarIO def
closeWSConnection :: MonadIO m => CS.ConnectionTag -> CS.ConnectionsVar -> m ()
closeWSConnection tag var = liftIO $ usingLoggerName "closeWSConnection" $ do
maybeConn <- atomically $ CS.deregisterConnection tag var
case maybeConn of
Nothing ->
logError $ sformat ("Attempted to close an unknown connection with tag "%build) tag
Just conn -> do
liftIO $ WS.sendClose conn ConnectionClosed
logNotice $ sformat ("Closed WS connection with tag "%build) tag
closeWSConnections :: MonadIO m => CS.ConnectionsVar -> m ()
closeWSConnections var = liftIO $ do
conns <- atomically $ swapTVar var def
for_ (CS.listConnections conns) $ flip WS.sendClose ConnectionClosed
appendWSConnection :: CS.ConnectionsVar -> WS.ServerApp
appendWSConnection var pending = do
conn <- WS.acceptRequest pending
bracket (atomically $ CS.registerConnection conn var) releaseResources $ \_ -> do
sendWS conn ConnectionOpened
WS.forkPingThread conn 30
forever (ignoreData conn)
where
ignoreData :: WSConnection -> IO Text
ignoreData = WS.receiveData
releaseResources :: MonadIO m => CS.ConnectionTag -> m ()
releaseResources tag = closeWSConnection tag var
-- FIXME: we have no authentication and accept all incoming connections.
-- Possible solution: reject pending connection if WS handshake doesn't have valid auth session token.
upgradeApplicationWS :: CS.ConnectionsVar -> Application -> Application
upgradeApplicationWS var = websocketsOr WS.defaultConnectionOptions (appendWSConnection var)
-- sendClose :: MonadIO m => ConnectionsVar -> NotifyEvent -> m ()
sendClose = send WS.sendClose
-- Sends notification msg to connected client. If there is no connection, notification msg will be ignored.
sendWS :: MonadIO m => WSConnection -> NotifyEvent -> m ()
sendWS = send WS.sendTextData
send :: MonadIO m => (WSConnection -> NotifyEvent -> IO ()) -> WSConnection -> NotifyEvent -> m ()
send f conn msg = liftIO $ f conn msg
instance WS.WebSocketsData NotifyEvent where
fromLazyByteString _ = error "Attempt to deserialize NotifyEvent is illegal"
toLazyByteString = encode
--------
-- API
--------
-- | MonadWalletWebSockets stands for monad which is able to get web wallet sockets
type MonadWalletWebSockets ctx m =
( MonadIO m
, MonadReader ctx m
, HasLens' ctx CS.ConnectionsVar
)
getWalletWebSockets :: MonadWalletWebSockets ctx m => m CS.ConnectionsVar
getWalletWebSockets = view (lensOf @CS.ConnectionsVar)
notifyAll :: MonadWalletWebSockets ctx m => NotifyEvent -> m ()
notifyAll msg = do
var <- getWalletWebSockets
conns <- readTVarIO var
for_ (CS.listConnections conns) $ flip sendWS msg
| null | https://raw.githubusercontent.com/CryptoKami/cryptokami-core/12ca60a9ad167b6327397b3b2f928c19436ae114/wallet/src/Pos/Wallet/Web/Sockets/Connection.hs | haskell | | Module for websockets implementation of Daedalus API.
This implements unidirectional sockets from server to client.
Every message received from client will be ignored.
FIXME: we have no authentication and accept all incoming connections.
Possible solution: reject pending connection if WS handshake doesn't have valid auth session token.
sendClose :: MonadIO m => ConnectionsVar -> NotifyEvent -> m ()
Sends notification msg to connected client. If there is no connection, notification msg will be ignored.
------
API
------
| MonadWalletWebSockets stands for monad which is able to get web wallet sockets | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE TypeFamilies #
module Pos.Wallet.Web.Sockets.Connection
( MonadWalletWebSockets
, getWalletWebSockets
, initWSConnections
, closeWSConnections
, upgradeApplicationWS
, notifyAll
) where
import Universum
import Control.Concurrent.STM.TVar (swapTVar)
import Data.Aeson (encode)
import Data.Default (Default (def))
import Formatting (build, sformat, (%))
import Network.Wai (Application)
import Network.Wai.Handler.WebSockets (websocketsOr)
import qualified Network.WebSockets as WS
import System.Wlog (logError, logNotice, usingLoggerName)
import Pos.Util.Util (HasLens (..), HasLens')
import Pos.Wallet.Aeson ()
import qualified Pos.Wallet.Web.Sockets.ConnSet as CS
import Pos.Wallet.Web.Sockets.Types (NotifyEvent (ConnectionClosed, ConnectionOpened),
WSConnection)
initWSConnections :: MonadIO m => m CS.ConnectionsVar
initWSConnections = newTVarIO def
closeWSConnection :: MonadIO m => CS.ConnectionTag -> CS.ConnectionsVar -> m ()
closeWSConnection tag var = liftIO $ usingLoggerName "closeWSConnection" $ do
maybeConn <- atomically $ CS.deregisterConnection tag var
case maybeConn of
Nothing ->
logError $ sformat ("Attempted to close an unknown connection with tag "%build) tag
Just conn -> do
liftIO $ WS.sendClose conn ConnectionClosed
logNotice $ sformat ("Closed WS connection with tag "%build) tag
closeWSConnections :: MonadIO m => CS.ConnectionsVar -> m ()
closeWSConnections var = liftIO $ do
conns <- atomically $ swapTVar var def
for_ (CS.listConnections conns) $ flip WS.sendClose ConnectionClosed
appendWSConnection :: CS.ConnectionsVar -> WS.ServerApp
appendWSConnection var pending = do
conn <- WS.acceptRequest pending
bracket (atomically $ CS.registerConnection conn var) releaseResources $ \_ -> do
sendWS conn ConnectionOpened
WS.forkPingThread conn 30
forever (ignoreData conn)
where
ignoreData :: WSConnection -> IO Text
ignoreData = WS.receiveData
releaseResources :: MonadIO m => CS.ConnectionTag -> m ()
releaseResources tag = closeWSConnection tag var
upgradeApplicationWS :: CS.ConnectionsVar -> Application -> Application
upgradeApplicationWS var = websocketsOr WS.defaultConnectionOptions (appendWSConnection var)
sendClose = send WS.sendClose
sendWS :: MonadIO m => WSConnection -> NotifyEvent -> m ()
sendWS = send WS.sendTextData
send :: MonadIO m => (WSConnection -> NotifyEvent -> IO ()) -> WSConnection -> NotifyEvent -> m ()
send f conn msg = liftIO $ f conn msg
instance WS.WebSocketsData NotifyEvent where
fromLazyByteString _ = error "Attempt to deserialize NotifyEvent is illegal"
toLazyByteString = encode
type MonadWalletWebSockets ctx m =
( MonadIO m
, MonadReader ctx m
, HasLens' ctx CS.ConnectionsVar
)
getWalletWebSockets :: MonadWalletWebSockets ctx m => m CS.ConnectionsVar
getWalletWebSockets = view (lensOf @CS.ConnectionsVar)
notifyAll :: MonadWalletWebSockets ctx m => NotifyEvent -> m ()
notifyAll msg = do
var <- getWalletWebSockets
conns <- readTVarIO var
for_ (CS.listConnections conns) $ flip sendWS msg
|
9f10c942644314561b0f805d7b7afd39fa4ba06d72ed4a1015cc8aa5a1840f1b | prl-julia/juliette-wa | redex.rkt | #lang racket
(require redex)
; import surface language
(require "../../../src/redex/core/wa-surface.rkt")
; import full language
(require "../../../src/redex/core/wa-full.rkt")
; import optimizations
(require "../../../src/redex/optimizations/wa-optimized.rkt")
(displayln "Test for litmus-wa/test05:")
(define p
(term
(evalg
(seq
(mdef "r3" () (mcall r2))
(seq
(mdef "m" () (seq (evalg (mdef "r2" () 2)) (evalg (mcall r3))))
(mcall m)))))
)
(test-equal (term (run-to-r ,p)) (term 2))
(test-results) | null | https://raw.githubusercontent.com/prl-julia/juliette-wa/1d1a2154e7b4e232ea2166fba485a3bf574ebd88/tests/litmus-wa/test05/redex.rkt | racket | import surface language
import full language
import optimizations | #lang racket
(require redex)
(require "../../../src/redex/core/wa-surface.rkt")
(require "../../../src/redex/core/wa-full.rkt")
(require "../../../src/redex/optimizations/wa-optimized.rkt")
(displayln "Test for litmus-wa/test05:")
(define p
(term
(evalg
(seq
(mdef "r3" () (mcall r2))
(seq
(mdef "m" () (seq (evalg (mdef "r2" () 2)) (evalg (mcall r3))))
(mcall m)))))
)
(test-equal (term (run-to-r ,p)) (term 2))
(test-results) |
c5375983216d6c896bdc3d18c723233df29a97d5534e5538aa0bc76c5a0c6345 | OlafChitil/hat | List.hs | module List (
elemIndex, elemIndices,
find, findIndex, findIndices,
nub, nubBy, delete, deleteBy, (\\), deleteFirstsBy,
union, unionBy, intersect, intersectBy,
intersperse, transpose, partition, group, groupBy,
inits, tails, isPrefixOf, isSuffixOf,
mapAccumL, mapAccumR,
sort, sortBy, insert, insertBy, maximumBy, minimumBy,
genericLength, genericTake, genericDrop,
genericSplitAt, genericIndex, genericReplicate,
zip4, zip5, zip6, zip7,
zipWith4, zipWith5, zipWith6, zipWith7,
unzip4, unzip5, unzip6, unzip7, unfoldr,
-- ...and what the Prelude exports
-- []((:), []), -- This is built-in syntax
map, (++), concat, filter,
head, last, tail, init, null, length, (!!),
foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1,
iterate, repeat, replicate, cycle,
take, drop, splitAt, takeWhile, dropWhile, span, break,
lines, words, unlines, unwords, reverse, and, or,
any, all, elem, notElem, lookup,
sum, product, maximum, minimum, concatMap,
zip, zip3, zipWith, zipWith3, unzip, unzip3
) where
import Maybe( listToMaybe )
infix 5 \\
elemIndex :: Eq a => a -> [a] -> Maybe Int
elemIndex x = findIndex (x ==)
elemIndices :: Eq a => a -> [a] -> [Int]
elemIndices x = findIndices (x ==)
find :: (a -> Bool) -> [a] -> Maybe a
find p = listToMaybe . filter p
findIndex :: (a -> Bool) -> [a] -> Maybe Int
findIndex p = listToMaybe . findIndices p
findIndices :: (a -> Bool) -> [a] -> [Int]
findIndices p xs = [ i | (x,i) <- zip xs [0..], p x ]
nub :: Eq a => [a] -> [a]
nub = nubBy (==)
nubBy :: (a -> a -> Bool) -> [a] -> [a]
nubBy eq [] = []
nubBy eq (x:xs) = x : nubBy eq (filter (\y -> not (eq x y)) xs)
delete :: Eq a => a -> [a] -> [a]
delete = deleteBy (==)
deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
deleteBy eq x [] = []
deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys
(\\) :: Eq a => [a] -> [a] -> [a]
(\\) = foldl (flip delete)
deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
deleteFirstsBy eq = foldl (flip (deleteBy eq))
union :: Eq a => [a] -> [a] -> [a]
union = unionBy (==)
unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
unionBy eq xs ys = xs ++ deleteFirstsBy eq (nubBy eq ys) xs
intersect :: Eq a => [a] -> [a] -> [a]
intersect = intersectBy (==)
intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
intersectBy eq xs ys = [x | x <- xs, any (eq x) ys]
intersperse :: a -> [a] -> [a]
intersperse sep [] = []
intersperse sep [x] = [x]
intersperse sep (x:xs) = x : sep : intersperse sep xs
-- transpose is lazy in both rows and columns,
-- and works for non-rectangular 'matrices'
-- For example, transpose [[1,2],[3,4,5],[]] = [[1,3],[2,4],[5]]
-- Note that [h | (h:t) <- xss] is not the same as (map head xss)
because the former discards empty sublists inside xss
transpose :: [[a]] -> [[a]]
transpose [] = []
transpose ([] : xss) = transpose xss
transpose ((x:xs) : xss) = (x : [h | (h:t) <- xss]) :
transpose (xs : [t | (h:t) <- xss])
partition :: (a -> Bool) -> [a] -> ([a],[a])
partition p xs = (filter p xs, filter (not . p) xs)
-- group splits its list argument into a list of lists of equal, adjacent
-- elements. e.g.,
group " Mississippi " = = [ " M","i","ss","i","ss","i","pp","i " ]
group :: Eq a => [a] -> [[a]]
group = groupBy (==)
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy eq [] = []
groupBy eq (x:xs) = (x:ys) : groupBy eq zs
where (ys,zs) = span (eq x) xs
inits xs returns the list of initial segments of xs , shortest first .
e.g. , inits " abc " = = [ " " , " a","ab","abc " ]
inits :: [a] -> [[a]]
inits [] = [[]]
inits (x:xs) = [[]] ++ map (x:) (inits xs)
tails xs returns the list of all final segments of xs , longest first .
e.g. , tails " abc " = = [ " abc " , " bc " , " c " , " " ]
tails :: [a] -> [[a]]
tails [] = [[]]
tails xxs@(_:xs) = xxs : tails xs
isPrefixOf :: Eq a => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xs) (y:ys) = x == y && isPrefixOf xs ys
isSuffixOf :: Eq a => [a] -> [a] -> Bool
isSuffixOf x y = reverse x `isPrefixOf` reverse y
mapAccumL :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
mapAccumL f s [] = (s, [])
mapAccumL f s (x:xs) = (s'',y:ys)
where (s', y ) = f s x
(s'',ys) = mapAccumL f s' xs
mapAccumR :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
mapAccumR f s [] = (s, [])
mapAccumR f s (x:xs) = (s'', y:ys)
where (s'',y ) = f s' x
(s', ys) = mapAccumR f s xs
unfoldr :: (b -> Maybe (a,b)) -> b -> [a]
unfoldr f b = case f b of
Nothing -> []
Just (a,b) -> a : unfoldr f b
sort :: (Ord a) => [a] -> [a]
sort = sortBy compare
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
sortBy cmp = mergeAll . sequences
where
sequences (a:b:xs)
| a `cmp` b == GT = descending b [a] xs
| otherwise = ascending b (a:) xs
sequences xs = [xs]
descending a as (b:bs)
| a `cmp` b == GT = descending b (a:as) bs
descending a as bs = (a:as): sequences bs
ascending a as (b:bs)
| a `cmp` b /= GT = ascending b (\ys -> as (a:ys)) bs
ascending a as bs = as [a]: sequences bs
mergeAll [x] = x
mergeAll xs = mergeAll (mergePairs xs)
mergePairs (a:b:xs) = merge a b: mergePairs xs
mergePairs xs = xs
merge as@(a:as') bs@(b:bs')
| a `cmp` b == GT = b:merge as bs'
| otherwise = a:merge as' bs
merge [] bs = bs
merge as [] = as
insert :: (Ord a) => a -> [a] -> [a]
insert = insertBy compare
insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
insertBy cmp x [] = [x]
insertBy cmp x ys@(y:ys')
= case cmp x y of
GT -> y : insertBy cmp x ys'
_ -> x : ys
maximumBy :: (a -> a -> Ordering) -> [a] -> a
maximumBy cmp [] = error "List.maximumBy: empty list"
maximumBy cmp xs = foldl1 max xs
where
max x y = case cmp x y of
GT -> x
_ -> y
minimumBy :: (a -> a -> Ordering) -> [a] -> a
minimumBy cmp [] = error "List.minimumBy: empty list"
minimumBy cmp xs = foldl1 min xs
where
min x y = case cmp x y of
GT -> y
_ -> x
genericLength :: (Integral a) => [b] -> a
genericLength [] = 0
genericLength (x:xs) = 1 + genericLength xs
genericTake :: (Integral a) => a -> [b] -> [b]
genericTake _ [] = []
genericTake 0 _ = []
genericTake n (x:xs)
| n > 0 = x : genericTake (n-1) xs
| otherwise = error "List.genericTake: negative argument"
genericDrop :: (Integral a) => a -> [b] -> [b]
genericDrop 0 xs = xs
genericDrop _ [] = []
genericDrop n (_:xs)
| n > 0 = genericDrop (n-1) xs
| otherwise = error "List.genericDrop: negative argument"
genericSplitAt :: (Integral a) => a -> [b] -> ([b],[b])
genericSplitAt 0 xs = ([],xs)
genericSplitAt _ [] = ([],[])
genericSplitAt n (x:xs)
| n > 0 = (x:xs',xs'')
| otherwise = error "List.genericSplitAt: negative argument"
where (xs',xs'') = genericSplitAt (n-1) xs
genericIndex :: (Integral a) => [b] -> a -> b
genericIndex (x:_) 0 = x
genericIndex (_:xs) n
| n > 0 = genericIndex xs (n-1)
| otherwise = error "List.genericIndex: negative argument"
genericIndex _ _ = error "List.genericIndex: index too large"
genericReplicate :: (Integral a) => a -> b -> [b]
genericReplicate n x = genericTake n (repeat x)
zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
zip4 = zipWith4 (,,,)
zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
zip5 = zipWith5 (,,,,)
zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
[(a,b,c,d,e,f)]
zip6 = zipWith6 (,,,,,)
zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
[g] -> [(a,b,c,d,e,f,g)]
zip7 = zipWith7 (,,,,,,)
zipWith4 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
= z a b c d : zipWith4 z as bs cs ds
zipWith4 _ _ _ _ _ = []
zipWith5 :: (a->b->c->d->e->f) ->
[a]->[b]->[c]->[d]->[e]->[f]
zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
= z a b c d e : zipWith5 z as bs cs ds es
zipWith5 _ _ _ _ _ _ = []
zipWith6 :: (a->b->c->d->e->f->g) ->
[a]->[b]->[c]->[d]->[e]->[f]->[g]
zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
= z a b c d e f : zipWith6 z as bs cs ds es fs
zipWith6 _ _ _ _ _ _ _ = []
zipWith7 :: (a->b->c->d->e->f->g->h) ->
[a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
= z a b c d e f g : zipWith7 z as bs cs ds es fs gs
zipWith7 _ _ _ _ _ _ _ _ = []
unzip4 :: [(a,b,c,d)] -> ([a],[b],[c],[d])
unzip4 = foldr (\(a,b,c,d) ~(as,bs,cs,ds) ->
(a:as,b:bs,c:cs,d:ds))
([],[],[],[])
unzip5 :: [(a,b,c,d,e)] -> ([a],[b],[c],[d],[e])
unzip5 = foldr (\(a,b,c,d,e) ~(as,bs,cs,ds,es) ->
(a:as,b:bs,c:cs,d:ds,e:es))
([],[],[],[],[])
unzip6 :: [(a,b,c,d,e,f)] -> ([a],[b],[c],[d],[e],[f])
unzip6 = foldr (\(a,b,c,d,e,f) ~(as,bs,cs,ds,es,fs) ->
(a:as,b:bs,c:cs,d:ds,e:es,f:fs))
([],[],[],[],[],[])
unzip7 :: [(a,b,c,d,e,f,g)] -> ([a],[b],[c],[d],[e],[f],[g])
unzip7 = foldr (\(a,b,c,d,e,f,g) ~(as,bs,cs,ds,es,fs,gs) ->
(a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs))
([],[],[],[],[],[],[])
| null | https://raw.githubusercontent.com/OlafChitil/hat/8840a480c076f9f01e58ce24b346850169498be2/libraries/List.hs | haskell | ...and what the Prelude exports
[]((:), []), -- This is built-in syntax
transpose is lazy in both rows and columns,
and works for non-rectangular 'matrices'
For example, transpose [[1,2],[3,4,5],[]] = [[1,3],[2,4],[5]]
Note that [h | (h:t) <- xss] is not the same as (map head xss)
group splits its list argument into a list of lists of equal, adjacent
elements. e.g., | module List (
elemIndex, elemIndices,
find, findIndex, findIndices,
nub, nubBy, delete, deleteBy, (\\), deleteFirstsBy,
union, unionBy, intersect, intersectBy,
intersperse, transpose, partition, group, groupBy,
inits, tails, isPrefixOf, isSuffixOf,
mapAccumL, mapAccumR,
sort, sortBy, insert, insertBy, maximumBy, minimumBy,
genericLength, genericTake, genericDrop,
genericSplitAt, genericIndex, genericReplicate,
zip4, zip5, zip6, zip7,
zipWith4, zipWith5, zipWith6, zipWith7,
unzip4, unzip5, unzip6, unzip7, unfoldr,
map, (++), concat, filter,
head, last, tail, init, null, length, (!!),
foldl, foldl1, scanl, scanl1, foldr, foldr1, scanr, scanr1,
iterate, repeat, replicate, cycle,
take, drop, splitAt, takeWhile, dropWhile, span, break,
lines, words, unlines, unwords, reverse, and, or,
any, all, elem, notElem, lookup,
sum, product, maximum, minimum, concatMap,
zip, zip3, zipWith, zipWith3, unzip, unzip3
) where
import Maybe( listToMaybe )
infix 5 \\
elemIndex :: Eq a => a -> [a] -> Maybe Int
elemIndex x = findIndex (x ==)
elemIndices :: Eq a => a -> [a] -> [Int]
elemIndices x = findIndices (x ==)
find :: (a -> Bool) -> [a] -> Maybe a
find p = listToMaybe . filter p
findIndex :: (a -> Bool) -> [a] -> Maybe Int
findIndex p = listToMaybe . findIndices p
findIndices :: (a -> Bool) -> [a] -> [Int]
findIndices p xs = [ i | (x,i) <- zip xs [0..], p x ]
nub :: Eq a => [a] -> [a]
nub = nubBy (==)
nubBy :: (a -> a -> Bool) -> [a] -> [a]
nubBy eq [] = []
nubBy eq (x:xs) = x : nubBy eq (filter (\y -> not (eq x y)) xs)
delete :: Eq a => a -> [a] -> [a]
delete = deleteBy (==)
deleteBy :: (a -> a -> Bool) -> a -> [a] -> [a]
deleteBy eq x [] = []
deleteBy eq x (y:ys) = if x `eq` y then ys else y : deleteBy eq x ys
(\\) :: Eq a => [a] -> [a] -> [a]
(\\) = foldl (flip delete)
deleteFirstsBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
deleteFirstsBy eq = foldl (flip (deleteBy eq))
union :: Eq a => [a] -> [a] -> [a]
union = unionBy (==)
unionBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
unionBy eq xs ys = xs ++ deleteFirstsBy eq (nubBy eq ys) xs
intersect :: Eq a => [a] -> [a] -> [a]
intersect = intersectBy (==)
intersectBy :: (a -> a -> Bool) -> [a] -> [a] -> [a]
intersectBy eq xs ys = [x | x <- xs, any (eq x) ys]
intersperse :: a -> [a] -> [a]
intersperse sep [] = []
intersperse sep [x] = [x]
intersperse sep (x:xs) = x : sep : intersperse sep xs
because the former discards empty sublists inside xss
transpose :: [[a]] -> [[a]]
transpose [] = []
transpose ([] : xss) = transpose xss
transpose ((x:xs) : xss) = (x : [h | (h:t) <- xss]) :
transpose (xs : [t | (h:t) <- xss])
partition :: (a -> Bool) -> [a] -> ([a],[a])
partition p xs = (filter p xs, filter (not . p) xs)
group " Mississippi " = = [ " M","i","ss","i","ss","i","pp","i " ]
group :: Eq a => [a] -> [[a]]
group = groupBy (==)
groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
groupBy eq [] = []
groupBy eq (x:xs) = (x:ys) : groupBy eq zs
where (ys,zs) = span (eq x) xs
inits xs returns the list of initial segments of xs , shortest first .
e.g. , inits " abc " = = [ " " , " a","ab","abc " ]
inits :: [a] -> [[a]]
inits [] = [[]]
inits (x:xs) = [[]] ++ map (x:) (inits xs)
tails xs returns the list of all final segments of xs , longest first .
e.g. , tails " abc " = = [ " abc " , " bc " , " c " , " " ]
tails :: [a] -> [[a]]
tails [] = [[]]
tails xxs@(_:xs) = xxs : tails xs
isPrefixOf :: Eq a => [a] -> [a] -> Bool
isPrefixOf [] _ = True
isPrefixOf _ [] = False
isPrefixOf (x:xs) (y:ys) = x == y && isPrefixOf xs ys
isSuffixOf :: Eq a => [a] -> [a] -> Bool
isSuffixOf x y = reverse x `isPrefixOf` reverse y
mapAccumL :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
mapAccumL f s [] = (s, [])
mapAccumL f s (x:xs) = (s'',y:ys)
where (s', y ) = f s x
(s'',ys) = mapAccumL f s' xs
mapAccumR :: (a -> b -> (a, c)) -> a -> [b] -> (a, [c])
mapAccumR f s [] = (s, [])
mapAccumR f s (x:xs) = (s'', y:ys)
where (s'',y ) = f s' x
(s', ys) = mapAccumR f s xs
unfoldr :: (b -> Maybe (a,b)) -> b -> [a]
unfoldr f b = case f b of
Nothing -> []
Just (a,b) -> a : unfoldr f b
sort :: (Ord a) => [a] -> [a]
sort = sortBy compare
sortBy :: (a -> a -> Ordering) -> [a] -> [a]
sortBy cmp = mergeAll . sequences
where
sequences (a:b:xs)
| a `cmp` b == GT = descending b [a] xs
| otherwise = ascending b (a:) xs
sequences xs = [xs]
descending a as (b:bs)
| a `cmp` b == GT = descending b (a:as) bs
descending a as bs = (a:as): sequences bs
ascending a as (b:bs)
| a `cmp` b /= GT = ascending b (\ys -> as (a:ys)) bs
ascending a as bs = as [a]: sequences bs
mergeAll [x] = x
mergeAll xs = mergeAll (mergePairs xs)
mergePairs (a:b:xs) = merge a b: mergePairs xs
mergePairs xs = xs
merge as@(a:as') bs@(b:bs')
| a `cmp` b == GT = b:merge as bs'
| otherwise = a:merge as' bs
merge [] bs = bs
merge as [] = as
insert :: (Ord a) => a -> [a] -> [a]
insert = insertBy compare
insertBy :: (a -> a -> Ordering) -> a -> [a] -> [a]
insertBy cmp x [] = [x]
insertBy cmp x ys@(y:ys')
= case cmp x y of
GT -> y : insertBy cmp x ys'
_ -> x : ys
maximumBy :: (a -> a -> Ordering) -> [a] -> a
maximumBy cmp [] = error "List.maximumBy: empty list"
maximumBy cmp xs = foldl1 max xs
where
max x y = case cmp x y of
GT -> x
_ -> y
minimumBy :: (a -> a -> Ordering) -> [a] -> a
minimumBy cmp [] = error "List.minimumBy: empty list"
minimumBy cmp xs = foldl1 min xs
where
min x y = case cmp x y of
GT -> y
_ -> x
genericLength :: (Integral a) => [b] -> a
genericLength [] = 0
genericLength (x:xs) = 1 + genericLength xs
genericTake :: (Integral a) => a -> [b] -> [b]
genericTake _ [] = []
genericTake 0 _ = []
genericTake n (x:xs)
| n > 0 = x : genericTake (n-1) xs
| otherwise = error "List.genericTake: negative argument"
genericDrop :: (Integral a) => a -> [b] -> [b]
genericDrop 0 xs = xs
genericDrop _ [] = []
genericDrop n (_:xs)
| n > 0 = genericDrop (n-1) xs
| otherwise = error "List.genericDrop: negative argument"
genericSplitAt :: (Integral a) => a -> [b] -> ([b],[b])
genericSplitAt 0 xs = ([],xs)
genericSplitAt _ [] = ([],[])
genericSplitAt n (x:xs)
| n > 0 = (x:xs',xs'')
| otherwise = error "List.genericSplitAt: negative argument"
where (xs',xs'') = genericSplitAt (n-1) xs
genericIndex :: (Integral a) => [b] -> a -> b
genericIndex (x:_) 0 = x
genericIndex (_:xs) n
| n > 0 = genericIndex xs (n-1)
| otherwise = error "List.genericIndex: negative argument"
genericIndex _ _ = error "List.genericIndex: index too large"
genericReplicate :: (Integral a) => a -> b -> [b]
genericReplicate n x = genericTake n (repeat x)
zip4 :: [a] -> [b] -> [c] -> [d] -> [(a,b,c,d)]
zip4 = zipWith4 (,,,)
zip5 :: [a] -> [b] -> [c] -> [d] -> [e] -> [(a,b,c,d,e)]
zip5 = zipWith5 (,,,,)
zip6 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
[(a,b,c,d,e,f)]
zip6 = zipWith6 (,,,,,)
zip7 :: [a] -> [b] -> [c] -> [d] -> [e] -> [f] ->
[g] -> [(a,b,c,d,e,f,g)]
zip7 = zipWith7 (,,,,,,)
zipWith4 :: (a->b->c->d->e) -> [a]->[b]->[c]->[d]->[e]
zipWith4 z (a:as) (b:bs) (c:cs) (d:ds)
= z a b c d : zipWith4 z as bs cs ds
zipWith4 _ _ _ _ _ = []
zipWith5 :: (a->b->c->d->e->f) ->
[a]->[b]->[c]->[d]->[e]->[f]
zipWith5 z (a:as) (b:bs) (c:cs) (d:ds) (e:es)
= z a b c d e : zipWith5 z as bs cs ds es
zipWith5 _ _ _ _ _ _ = []
zipWith6 :: (a->b->c->d->e->f->g) ->
[a]->[b]->[c]->[d]->[e]->[f]->[g]
zipWith6 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs)
= z a b c d e f : zipWith6 z as bs cs ds es fs
zipWith6 _ _ _ _ _ _ _ = []
zipWith7 :: (a->b->c->d->e->f->g->h) ->
[a]->[b]->[c]->[d]->[e]->[f]->[g]->[h]
zipWith7 z (a:as) (b:bs) (c:cs) (d:ds) (e:es) (f:fs) (g:gs)
= z a b c d e f g : zipWith7 z as bs cs ds es fs gs
zipWith7 _ _ _ _ _ _ _ _ = []
unzip4 :: [(a,b,c,d)] -> ([a],[b],[c],[d])
unzip4 = foldr (\(a,b,c,d) ~(as,bs,cs,ds) ->
(a:as,b:bs,c:cs,d:ds))
([],[],[],[])
unzip5 :: [(a,b,c,d,e)] -> ([a],[b],[c],[d],[e])
unzip5 = foldr (\(a,b,c,d,e) ~(as,bs,cs,ds,es) ->
(a:as,b:bs,c:cs,d:ds,e:es))
([],[],[],[],[])
unzip6 :: [(a,b,c,d,e,f)] -> ([a],[b],[c],[d],[e],[f])
unzip6 = foldr (\(a,b,c,d,e,f) ~(as,bs,cs,ds,es,fs) ->
(a:as,b:bs,c:cs,d:ds,e:es,f:fs))
([],[],[],[],[],[])
unzip7 :: [(a,b,c,d,e,f,g)] -> ([a],[b],[c],[d],[e],[f],[g])
unzip7 = foldr (\(a,b,c,d,e,f,g) ~(as,bs,cs,ds,es,fs,gs) ->
(a:as,b:bs,c:cs,d:ds,e:es,f:fs,g:gs))
([],[],[],[],[],[],[])
|
86b8c555faad0da94cd874039325ae119337a08f6eb44411be54d78b92535720 | RaphaelJ/friday | Threshold.hs | # LANGUAGE BangPatterns
, FlexibleContexts
, GADTs #
, FlexibleContexts
, GADTs #-}
module Vision.Image.Threshold (
-- * Simple threshold
ThresholdType (..), thresholdType
, threshold
-- * Adaptive threshold
, AdaptiveThresholdKernel (..), AdaptiveThreshold
, adaptiveThreshold, adaptiveThresholdFilter
-- * Other methods
, otsu, scw
) where
import Data.Int
import Foreign.Storable (Storable)
import qualified Data.Vector.Storable as V
import qualified Data.Vector as VU
import Vision.Image.Class (
Image, ImagePixel, FromFunction (..), FunctorImage, (!), shape
)
import Vision.Image.Filter.Internal (
Filter (..), BoxFilter, Kernel (..), SeparableFilter, SeparatelyFiltrable
, KernelAnchor (KernelAnchorCenter), FilterFold (..)
, BorderInterpolate (BorderReplicate)
, apply, blur, gaussianBlur, Mean, mean
)
import Vision.Image.Type (Manifest, delayed, manifest)
import Vision.Histogram (
HistogramShape, PixelValueSpace, ToHistogram, histogram
)
import Vision.Primitive (Z (..), (:.) (..), Size, shapeLength)
import qualified Vision.Histogram as H
import qualified Vision.Image.Class as I
-- | Specifies what to do with pixels matching the threshold predicate.
--
@'BinaryThreshold ' a b@ will replace matching pixels by @a@ and non - matchings
pixels by @b@.
--
@'Truncate ' a@ will replace matching pixels by
--
@'TruncateInv ' a@ will replace non - matching pixels by
data ThresholdType src res where
BinaryThreshold :: res -> res -> ThresholdType src res
Truncate :: src -> ThresholdType src src
TruncateInv :: src -> ThresholdType src src
-- | Given the thresholding method, a boolean indicating if the pixel match the
-- thresholding condition and the pixel, returns the new pixel value.
thresholdType :: ThresholdType src res -> Bool -> src -> res
thresholdType (BinaryThreshold ifTrue ifFalse) match _ | match = ifTrue
| otherwise = ifFalse
thresholdType (Truncate ifTrue) match pix | match = ifTrue
| otherwise = pix
thresholdType (TruncateInv ifFalse) match pix | match = pix
| otherwise = ifFalse
# INLINE thresholdType #
-- -----------------------------------------------------------------------------
-- | Applies the given predicate and threshold policy on the image.
threshold :: FunctorImage src res
=> (ImagePixel src -> Bool)
-> ThresholdType (ImagePixel src) (ImagePixel res) -> src -> res
threshold !cond !thresType =
I.map (\pix -> thresholdType thresType (cond pix) pix)
# INLINE threshold #
-- -----------------------------------------------------------------------------
-- | Defines how pixels of the kernel of the adaptive threshold will be
-- weighted.
--
With ' MeanKernel ' , pixels of the kernel have the same weight .
--
-- With @'GaussianKernel' sigma@, pixels are weighted according to their distance
from the thresholded pixel using a Gaussian function parametred by @sigma@.
-- See 'gaussianBlur' for details.
data AdaptiveThresholdKernel acc where
MeanKernel :: Integral acc => AdaptiveThresholdKernel acc
GaussianKernel :: (Floating acc, RealFrac acc)
=> Maybe acc -> AdaptiveThresholdKernel acc
-- | Compares every pixel to its surrounding ones in the kernel of the given
-- radius.
adaptiveThreshold :: ( Image src, Integral (ImagePixel src)
, Ord (ImagePixel src)
, FromFunction res, Integral (FromFunctionPixel res)
, Storable acc
, SeparatelyFiltrable src res acc)
=> AdaptiveThresholdKernel acc
-> Int
-- ^ Kernel radius.
-> ImagePixel src
-- ^ Minimum difference between the pixel and the kernel
average . The pixel is thresholded if
-- @pixel_value - kernel_mean > difference@ where difference
-- is this number. Can be negative.
-> ThresholdType (ImagePixel src) (FromFunctionPixel res)
-> src
-> res
adaptiveThreshold kernelType radius thres thresType img =
adaptiveThresholdFilter kernelType radius thres thresType `apply` img
# INLINABLE adaptiveThreshold #
type AdaptiveThreshold src acc res = SeparableFilter src () acc res
-- | Creates an adaptive thresholding filter to be used with 'apply'.
--
Use ' ' if you only want to apply the filter on the image .
--
-- Compares every pixel to its surrounding ones in the kernel of the given
-- radius.
adaptiveThresholdFilter :: (Integral src, Ord src, Storable acc)
=> AdaptiveThresholdKernel acc
-> Int
-- ^ Kernel radius.
-> src
-- ^ Minimum difference between the pixel and the kernel
average . The pixel is thresholded if
-- @pixel_value - kernel_mean > difference@ where
-- difference is this number. Can be negative.
-> ThresholdType src res
-> AdaptiveThreshold src acc res
adaptiveThresholdFilter !kernelType !radius !thres !thresType =
kernelFilter { fPost = post }
where
!kernelFilter =
case kernelType of MeanKernel -> blur radius
GaussianKernel sig -> gaussianBlur radius sig
post ix pix ini acc =
let !acc' = (fPost kernelFilter) ix pix ini acc
!cond = (pix - acc') > thres
in thresholdType thresType cond pix
# INLINE adaptiveThresholdFilter #
-- -----------------------------------------------------------------------------
| Applies a clustering - based image thresholding using the Otsu 's method .
--
-- See <'s_method>.
otsu :: ( HistogramShape (PixelValueSpace (ImagePixel src))
, ToHistogram (ImagePixel src), FunctorImage src res
, Ord (ImagePixel src), Num (ImagePixel src), Enum (ImagePixel src))
=> ThresholdType (ImagePixel src) (ImagePixel res) -> src -> res
otsu !thresType !img =
threshold (<= thresh) thresType img
where
!thresh =
let hist = histogram Nothing img
histV = H.vector hist
tot = shapeLength (I.shape img)
runningMul = V.zipWith (\v i -> v * i) histV (V.fromList [0..255])
sm = double (V.sum $ V.drop 1 runningMul)
wB = V.scanl1 (+) histV
wF = V.map (\x -> tot - x) wB
sumB = V.scanl1 (+) runningMul
mB = V.zipWith (\n d -> if d == 0 then 1
else double n / double d)
sumB wB
mF = V.zipWith (\b f -> if f == 0 then 1
else (sm - double b)
/ double f)
sumB wF
between = V.zipWith4 (\x y b f -> double x * double y
* (b - f)^two)
wB wF mB mF
in snd $ VU.maximum (VU.zip (VU.fromList $ V.toList between)
(VU.fromList [0..255]))
!two = 2 :: Int
# INLINABLE otsu #
-- -----------------------------------------------------------------------------
| This is a sliding concentric window filter ( SCW ) that uses the ratio of the
standard deviations of two sliding windows centered on a same point to detect
-- regions of interest (ROI).
--
> scw sizeWindowB beta thresType img
--
Let @σA@ be the standard deviation of a fist window around a pixel and @σB@
-- be the standard deviation of another window around the same pixel.
Then the pixel will match the threshold if @σB / σA > = beta@ , and will be
thresholded according to the given ' ThresholdType ' .
--
-- See <>.
scw :: ( Image src, Integral (ImagePixel src), FromFunction dst
, Floating stdev, Fractional stdev, Ord stdev, Storable stdev)
=> Size -> Size -> stdev
-> ThresholdType (ImagePixel src) (FromFunctionPixel dst) -> src -> dst
scw !sizeA !sizeB !beta !thresType !img =
betaThreshold (stdDev sizeA) (stdDev sizeB)
where
betaThreshold a b =
fromFunction (shape img) $ \pt ->
let !cond = (b ! pt) / (a ! pt) < beta
in thresholdType thresType cond (img ! pt)
stdDev size =
let filt :: (Integral src, Fractional res) => Mean src Int16 res
filt = mean size
!meanImg = manifest $ apply filt img
!varImg = manifest $ apply (variance size meanImg) img
in delayed $ I.map sqrt varImg
# INLINABLE scw #
-- | Given a mean image and an original image, computes the variance of the
-- kernel of the given size.
--
-- @average [ (origPix - mean)^2 | origPix <- kernel pixels on original ]@.
variance :: (Integral src, Fractional res, Storable res)
=> Size -> Manifest res -> BoxFilter src res res res
variance !size@(Z :. h :. w) !meanImg =
Filter size KernelAnchorCenter (Kernel kernel) (\pt _ -> meanImg ! pt)
(FilterFold (const 0)) post BorderReplicate
where
kernel !kernelMean _ !val !acc =
acc + square (fromIntegral val - kernelMean)
!nPixsFactor = 1 / (fromIntegral $! h * w)
post _ _ _ !acc = acc * nPixsFactor
# INLINABLE variance #
-- -----------------------------------------------------------------------------
square :: Num a => a -> a
square a = a * a
double :: Integral a => a -> Double
double = fromIntegral
| null | https://raw.githubusercontent.com/RaphaelJ/friday/13c6bb16bb04856e0cb226726017e7a7ad502cb5/src/Vision/Image/Threshold.hs | haskell | * Simple threshold
* Adaptive threshold
* Other methods
| Specifies what to do with pixels matching the threshold predicate.
| Given the thresholding method, a boolean indicating if the pixel match the
thresholding condition and the pixel, returns the new pixel value.
-----------------------------------------------------------------------------
| Applies the given predicate and threshold policy on the image.
-----------------------------------------------------------------------------
| Defines how pixels of the kernel of the adaptive threshold will be
weighted.
With @'GaussianKernel' sigma@, pixels are weighted according to their distance
See 'gaussianBlur' for details.
| Compares every pixel to its surrounding ones in the kernel of the given
radius.
^ Kernel radius.
^ Minimum difference between the pixel and the kernel
@pixel_value - kernel_mean > difference@ where difference
is this number. Can be negative.
| Creates an adaptive thresholding filter to be used with 'apply'.
Compares every pixel to its surrounding ones in the kernel of the given
radius.
^ Kernel radius.
^ Minimum difference between the pixel and the kernel
@pixel_value - kernel_mean > difference@ where
difference is this number. Can be negative.
-----------------------------------------------------------------------------
See <'s_method>.
-----------------------------------------------------------------------------
regions of interest (ROI).
be the standard deviation of another window around the same pixel.
See <>.
| Given a mean image and an original image, computes the variance of the
kernel of the given size.
@average [ (origPix - mean)^2 | origPix <- kernel pixels on original ]@.
----------------------------------------------------------------------------- | # LANGUAGE BangPatterns
, FlexibleContexts
, GADTs #
, FlexibleContexts
, GADTs #-}
module Vision.Image.Threshold (
ThresholdType (..), thresholdType
, threshold
, AdaptiveThresholdKernel (..), AdaptiveThreshold
, adaptiveThreshold, adaptiveThresholdFilter
, otsu, scw
) where
import Data.Int
import Foreign.Storable (Storable)
import qualified Data.Vector.Storable as V
import qualified Data.Vector as VU
import Vision.Image.Class (
Image, ImagePixel, FromFunction (..), FunctorImage, (!), shape
)
import Vision.Image.Filter.Internal (
Filter (..), BoxFilter, Kernel (..), SeparableFilter, SeparatelyFiltrable
, KernelAnchor (KernelAnchorCenter), FilterFold (..)
, BorderInterpolate (BorderReplicate)
, apply, blur, gaussianBlur, Mean, mean
)
import Vision.Image.Type (Manifest, delayed, manifest)
import Vision.Histogram (
HistogramShape, PixelValueSpace, ToHistogram, histogram
)
import Vision.Primitive (Z (..), (:.) (..), Size, shapeLength)
import qualified Vision.Histogram as H
import qualified Vision.Image.Class as I
@'BinaryThreshold ' a b@ will replace matching pixels by @a@ and non - matchings
pixels by @b@.
@'Truncate ' a@ will replace matching pixels by
@'TruncateInv ' a@ will replace non - matching pixels by
data ThresholdType src res where
BinaryThreshold :: res -> res -> ThresholdType src res
Truncate :: src -> ThresholdType src src
TruncateInv :: src -> ThresholdType src src
thresholdType :: ThresholdType src res -> Bool -> src -> res
thresholdType (BinaryThreshold ifTrue ifFalse) match _ | match = ifTrue
| otherwise = ifFalse
thresholdType (Truncate ifTrue) match pix | match = ifTrue
| otherwise = pix
thresholdType (TruncateInv ifFalse) match pix | match = pix
| otherwise = ifFalse
# INLINE thresholdType #
threshold :: FunctorImage src res
=> (ImagePixel src -> Bool)
-> ThresholdType (ImagePixel src) (ImagePixel res) -> src -> res
threshold !cond !thresType =
I.map (\pix -> thresholdType thresType (cond pix) pix)
# INLINE threshold #
With ' MeanKernel ' , pixels of the kernel have the same weight .
from the thresholded pixel using a Gaussian function parametred by @sigma@.
data AdaptiveThresholdKernel acc where
MeanKernel :: Integral acc => AdaptiveThresholdKernel acc
GaussianKernel :: (Floating acc, RealFrac acc)
=> Maybe acc -> AdaptiveThresholdKernel acc
adaptiveThreshold :: ( Image src, Integral (ImagePixel src)
, Ord (ImagePixel src)
, FromFunction res, Integral (FromFunctionPixel res)
, Storable acc
, SeparatelyFiltrable src res acc)
=> AdaptiveThresholdKernel acc
-> Int
-> ImagePixel src
average . The pixel is thresholded if
-> ThresholdType (ImagePixel src) (FromFunctionPixel res)
-> src
-> res
adaptiveThreshold kernelType radius thres thresType img =
adaptiveThresholdFilter kernelType radius thres thresType `apply` img
# INLINABLE adaptiveThreshold #
type AdaptiveThreshold src acc res = SeparableFilter src () acc res
Use ' ' if you only want to apply the filter on the image .
adaptiveThresholdFilter :: (Integral src, Ord src, Storable acc)
=> AdaptiveThresholdKernel acc
-> Int
-> src
average . The pixel is thresholded if
-> ThresholdType src res
-> AdaptiveThreshold src acc res
adaptiveThresholdFilter !kernelType !radius !thres !thresType =
kernelFilter { fPost = post }
where
!kernelFilter =
case kernelType of MeanKernel -> blur radius
GaussianKernel sig -> gaussianBlur radius sig
post ix pix ini acc =
let !acc' = (fPost kernelFilter) ix pix ini acc
!cond = (pix - acc') > thres
in thresholdType thresType cond pix
# INLINE adaptiveThresholdFilter #
| Applies a clustering - based image thresholding using the Otsu 's method .
otsu :: ( HistogramShape (PixelValueSpace (ImagePixel src))
, ToHistogram (ImagePixel src), FunctorImage src res
, Ord (ImagePixel src), Num (ImagePixel src), Enum (ImagePixel src))
=> ThresholdType (ImagePixel src) (ImagePixel res) -> src -> res
otsu !thresType !img =
threshold (<= thresh) thresType img
where
!thresh =
let hist = histogram Nothing img
histV = H.vector hist
tot = shapeLength (I.shape img)
runningMul = V.zipWith (\v i -> v * i) histV (V.fromList [0..255])
sm = double (V.sum $ V.drop 1 runningMul)
wB = V.scanl1 (+) histV
wF = V.map (\x -> tot - x) wB
sumB = V.scanl1 (+) runningMul
mB = V.zipWith (\n d -> if d == 0 then 1
else double n / double d)
sumB wB
mF = V.zipWith (\b f -> if f == 0 then 1
else (sm - double b)
/ double f)
sumB wF
between = V.zipWith4 (\x y b f -> double x * double y
* (b - f)^two)
wB wF mB mF
in snd $ VU.maximum (VU.zip (VU.fromList $ V.toList between)
(VU.fromList [0..255]))
!two = 2 :: Int
# INLINABLE otsu #
| This is a sliding concentric window filter ( SCW ) that uses the ratio of the
standard deviations of two sliding windows centered on a same point to detect
> scw sizeWindowB beta thresType img
Let @σA@ be the standard deviation of a fist window around a pixel and @σB@
Then the pixel will match the threshold if @σB / σA > = beta@ , and will be
thresholded according to the given ' ThresholdType ' .
scw :: ( Image src, Integral (ImagePixel src), FromFunction dst
, Floating stdev, Fractional stdev, Ord stdev, Storable stdev)
=> Size -> Size -> stdev
-> ThresholdType (ImagePixel src) (FromFunctionPixel dst) -> src -> dst
scw !sizeA !sizeB !beta !thresType !img =
betaThreshold (stdDev sizeA) (stdDev sizeB)
where
betaThreshold a b =
fromFunction (shape img) $ \pt ->
let !cond = (b ! pt) / (a ! pt) < beta
in thresholdType thresType cond (img ! pt)
stdDev size =
let filt :: (Integral src, Fractional res) => Mean src Int16 res
filt = mean size
!meanImg = manifest $ apply filt img
!varImg = manifest $ apply (variance size meanImg) img
in delayed $ I.map sqrt varImg
# INLINABLE scw #
variance :: (Integral src, Fractional res, Storable res)
=> Size -> Manifest res -> BoxFilter src res res res
variance !size@(Z :. h :. w) !meanImg =
Filter size KernelAnchorCenter (Kernel kernel) (\pt _ -> meanImg ! pt)
(FilterFold (const 0)) post BorderReplicate
where
kernel !kernelMean _ !val !acc =
acc + square (fromIntegral val - kernelMean)
!nPixsFactor = 1 / (fromIntegral $! h * w)
post _ _ _ !acc = acc * nPixsFactor
# INLINABLE variance #
square :: Num a => a -> a
square a = a * a
double :: Integral a => a -> Double
double = fromIntegral
|
08a97f61016c3be9fd79d95f59cea990276b23a82721931b75e8e94bbbea02ab | vikram/lisplibraries | store-api.lisp |
(in-package :weblocks)
(export '(open-store close-store clean-store *default-store*
begin-transaction commit-transaction rollback-transaction
persist-object delete-persistent-object
delete-persistent-object-by-id find-persistent-objects
find-persistent-object-by-id count-persistent-objects))
;;; Store initialization and finalization
(defgeneric open-store (store-type &rest args)
(:documentation "Opens a connection to a store specified by
'store-type'. This function must return the instance of the
connection to the store. Methods can accept any number of custom
keyword parameters. Additionally, the function must set
*default-store* to the value of newly created store."))
(defgeneric close-store (store)
(:documentation "Closes a connection to the store. If the value of
*default-store* is equal to 'store', *default-store* must be set to
NIL."))
(defgeneric clean-store (store)
(:documentation "Cleans all the data in the store. This function
should erase data, but not necessarily any schema information (like
tables, etc.)"))
(defparameter *default-store* nil
"The default store to which objects are persisted.")
;;; Transactions
(defgeneric begin-transaction (store)
(:documentation "Begins a transaction on 'store'. Note, if the given
store does not have transaction support, this function should return
NIL without signalling errors."))
(defgeneric commit-transaction (store)
(:documentation "Commits a transaction started on 'store'. Note, if
the given store does not have transaction support, or the store
isn't in a transaction, this function should return NIL without
signalling errors."))
(defgeneric rollback-transaction (store)
(:documentation "Rolls back a transaction started on 'store'. Note,
if the given store does not have transaction support, or the store
isn't in a transaction, this function should return NIL without
signalling errors."))
;;; Creating and deleting persistent objects
(defgeneric persist-object (store object)
(:documentation "Persists 'object' into 'store'. If the object does
not have a unique ID (see 'object-id'), persist 'object' into store
and set its unique ID via (see '(setf object-id)'). If the object
has a unique ID, find relevant entry in the store and update it with
'object'."))
(defgeneric delete-persistent-object (store object)
(:documentation "Deletes the persistent object from 'store'. After
deleting the persistent object, set unique ID of 'object' to
NIL (see '(setf object-id)')."))
(defgeneric delete-persistent-object-by-id (store class-name object-id)
(:documentation "Similar to 'delete-persistent-object', but instead
deletes object with the specified 'object-id'."))
;;; Querying persistent objects
(defgeneric find-persistent-object-by-id (store class-name object-id)
(:documentation "Finds and returns a persistent object of a given
class name in a given store by its unique id. If the object isn't
found, returns NIL."))
(defgeneric find-persistent-objects (store class-name
&key order-by range
&allow-other-keys)
(:documentation "Looks up and returns objects of appropriate
'class-name' in the 'store' bound by the given keyword
parameters.
If 'order-by' is specified, orders the returned objects by the given
slot in the given order. If 'order-by' is not NIL, it is expected to
be a cons cell with slot name as 'car' and :asc or :desc as
'cdr'.
If 'range' is specified, returns only the specified range of
objects. The CAR of 'range' is the index of the initial
object (inclusive) and CDR is the index past the last object. Note,
the range should be applied after the objects have been filtered and
ordered if necessary.
Other implementation dependent keys may be defined by a given
store."))
(defgeneric count-persistent-objects (store class-name &key &allow-other-keys)
(:documentation "Returns the number of persistent objects stored in
'store' of 'class-name', bound by the given keyword parameters. For
documentation of keyword parameters, see
'find-persistent-objects'.
Other implementation dependent keys may be defined by a given
store."))
| null | https://raw.githubusercontent.com/vikram/lisplibraries/105e3ef2d165275eb78f36f5090c9e2cdd0754dd/site/weblocks-stable/src/store/store-api.lisp | lisp | Store initialization and finalization
Transactions
Creating and deleting persistent objects
Querying persistent objects |
(in-package :weblocks)
(export '(open-store close-store clean-store *default-store*
begin-transaction commit-transaction rollback-transaction
persist-object delete-persistent-object
delete-persistent-object-by-id find-persistent-objects
find-persistent-object-by-id count-persistent-objects))
(defgeneric open-store (store-type &rest args)
(:documentation "Opens a connection to a store specified by
'store-type'. This function must return the instance of the
connection to the store. Methods can accept any number of custom
keyword parameters. Additionally, the function must set
*default-store* to the value of newly created store."))
(defgeneric close-store (store)
(:documentation "Closes a connection to the store. If the value of
*default-store* is equal to 'store', *default-store* must be set to
NIL."))
(defgeneric clean-store (store)
(:documentation "Cleans all the data in the store. This function
should erase data, but not necessarily any schema information (like
tables, etc.)"))
(defparameter *default-store* nil
"The default store to which objects are persisted.")
(defgeneric begin-transaction (store)
(:documentation "Begins a transaction on 'store'. Note, if the given
store does not have transaction support, this function should return
NIL without signalling errors."))
(defgeneric commit-transaction (store)
(:documentation "Commits a transaction started on 'store'. Note, if
the given store does not have transaction support, or the store
isn't in a transaction, this function should return NIL without
signalling errors."))
(defgeneric rollback-transaction (store)
(:documentation "Rolls back a transaction started on 'store'. Note,
if the given store does not have transaction support, or the store
isn't in a transaction, this function should return NIL without
signalling errors."))
(defgeneric persist-object (store object)
(:documentation "Persists 'object' into 'store'. If the object does
not have a unique ID (see 'object-id'), persist 'object' into store
and set its unique ID via (see '(setf object-id)'). If the object
has a unique ID, find relevant entry in the store and update it with
'object'."))
(defgeneric delete-persistent-object (store object)
(:documentation "Deletes the persistent object from 'store'. After
deleting the persistent object, set unique ID of 'object' to
NIL (see '(setf object-id)')."))
(defgeneric delete-persistent-object-by-id (store class-name object-id)
(:documentation "Similar to 'delete-persistent-object', but instead
deletes object with the specified 'object-id'."))
(defgeneric find-persistent-object-by-id (store class-name object-id)
(:documentation "Finds and returns a persistent object of a given
class name in a given store by its unique id. If the object isn't
found, returns NIL."))
(defgeneric find-persistent-objects (store class-name
&key order-by range
&allow-other-keys)
(:documentation "Looks up and returns objects of appropriate
'class-name' in the 'store' bound by the given keyword
parameters.
If 'order-by' is specified, orders the returned objects by the given
slot in the given order. If 'order-by' is not NIL, it is expected to
be a cons cell with slot name as 'car' and :asc or :desc as
'cdr'.
If 'range' is specified, returns only the specified range of
objects. The CAR of 'range' is the index of the initial
object (inclusive) and CDR is the index past the last object. Note,
the range should be applied after the objects have been filtered and
ordered if necessary.
Other implementation dependent keys may be defined by a given
store."))
(defgeneric count-persistent-objects (store class-name &key &allow-other-keys)
(:documentation "Returns the number of persistent objects stored in
'store' of 'class-name', bound by the given keyword parameters. For
documentation of keyword parameters, see
'find-persistent-objects'.
Other implementation dependent keys may be defined by a given
store."))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.