_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
a1018c670c152f94cab7ba362f13abadf13cd0363526817dcc81e823ded57317
cuplv/dai
state.mli
include Domain.Abstract.Dom
null
https://raw.githubusercontent.com/cuplv/dai/e74b80154264c9a629e25a7e8830210387e6fb84/src/analysis/domain/shape/state.mli
ocaml
include Domain.Abstract.Dom
c8f1d2d97184d4d164185ea4bbbac273d57b1f6c4a464f89a86c0cc4a56fce84
8c6794b6/haskell-sc-scratch
SynthDefs.hs
# LANGUAGE NoMonomorphismRestriction # | Module : $ Header$ CopyRight : ( c ) 8c6794b6 License : : Stability : unstable Portability : non - portable Module to play with sending node repeatedly with response to sendReply . This module contains UGen to be parsed with writeSynthdef . Module : $Header$ CopyRight : (c) 8c6794b6 License : BSD3 Maintainer : Stability : unstable Portability : non-portable Module to play with sending node repeatedly with response to sendReply. This module contains UGen to be parsed with writeSynthdef. -} module Cd22e9d.SynthDefs where import System.Random import Control.Applicative import Control.Monad.State import Control.Monad import Sound.OpenSoundControl import Sound.SC3 import Sound.SC3.ID import Sound.SC3.Lepton -- -- master controls -- met9d :: UGen met9d = out ("out"@@0) (impulse kr bpm 0) where bpm = ("bpm"@@120) / 60 tr9d :: UGen tr9d = mrg [out ("out"@@0) pc, sendReply t 0 "/cd22e9d" [pc]] where t = "t_trig"@@0 pc = pulseCount t 0 -- -- trigger controls -- -- For recording piece cd2thuh1 :: UGen cd2thuh1 = mkDemand $ sseq 1 [sseq 4 [0,1,0,0, 1,0,0,1, 0,0,1,0, 1,0,1,0] ,sseq sinf [sseq 12 [0,1,0,0, 1,0,0,1, 0,0,1,0, 1,0,1,0] ,sseq 4 [0,1,0,1, 1,1,0,0, 0,0,0,1, 1,0,0,1]]] cd2thuh2 :: UGen cd2thuh2 = mkDemand $ sseq 1 [sseq 64 [0] ,sseq sinf [sseq 12 [1,0,1,0, 1,0,0,0, 1,0,1,0, 1,0,0,0] ,sseq 56 [0], sseq 4 [0,1]]] cd2thuh3 :: UGen cd2thuh3 = mkDemand $ sseq 1 [sseq 64 [0] ,sseq sinf [sseq 12 [0,1,0,1, 0,0,0,1, 0,1,0,1, 0,0,0,1] ,sseq 56 [0], sseq 4 [1,0]]] cd2that :: UGen cd2that = mkDemand $ sseq 1 [sseq 62 [0], sseq 1 [0.6,0.8] ,sseq sinf [sseq 3 [sseq 32 [srand 1 [0,0,0,0,0,0,0.2] ,srand 1 [0.5,0.8,1.0]]] ,sseq 32 [0] ,sseq 1 [sseq 28 [0], srand 4 [0,0.3,0.6,0.8,1]]]] cd2tsnr :: UGen cd2tsnr = mkDemand $ sseq 1 [sseq 56 [0], sseq 1 [0.8,0.6,0,0.2, 0.2,0.8,0.4,1.0] ,sseq sinf [sseq 3 [sseq 3 [sseq 3 [0,0,srand 1 [0.6,1.0],0] ,sseq 1 [0,0,srand 1 [0.6,0.7,0.8],srand 1 [0.6,0.8]]] ,sseq 1 [sseq 2 [0,0,1,0], srand 8 [0,0,0.5,0.75,1]]] ,sseq 3 [0,0,0,0, srand 1 [0.9,1.0],0,0,0 ,0,0,0,0, srand 4 [1,0.8,0]] ,sseq 1 [0,0,0,0, srand 1 [0.9,1.0],0,0,0 ,srand 8 [0,0,0,0.5,0.6,0.7,0.8,0.9,1]]]] cd2tkik :: UGen cd2tkik = mkDemand $ sseq sinf [sseq 4 [1,0,0,0, 1,0,0,0, 0.8,0,0,0, 1,0,0,1] ,sseq sinf [sseq 3 [sseq 4 [1,0,0,0, 0.8,0,0,srand 1 [0,0.7,0.8,1] ,0.89,0,0,0, 1,0,0,srand 1 [0,0.7,0.8,1]]] ,sseq 4 [1,0,0,0.7, 1,0,0,1, 0,0.9,0,0.8, 0.9,0,0,1]]] cd2tdrn1 :: UGen cd2tdrn1 = mkTdrn pat where pat = sseq 1 [sseq 32 [0] ,sseq sinf [sseq 3 [72, 0, 0, 0, 0, 0, 0, 0, 0,67, 0, 0, 65, 0, 0, 0 ,67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 0, 0, 0 ,60, 0, 0, 0, 0, 0, 0, 0, 0,55, 0, 0, 65, 0, 0, 0 ,67, sseq 15 [0]] ,sseq 1 [72, sseq 31 [0] ,60, sseq 31 [0]]]] cd2tdrn2 :: UGen cd2tdrn2 = mkTdrn pat where pat = sseq 1 [sseq 32 [0] ,sseq sinf [sseq 3 [ 0, 0, 55,0, 0, 0,60, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0 , 0, 0, 0, 0, 0, 0,67, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ,sseq 1 [ 0, 0, 55,0, sseq 28 [0] , 0, 0, 0,0, 0, 0, 67, 0, sseq 24 [0]]]] cd2tpu :: UGen cd2tpu = out ("out"@@0) $ midiCPS $ demand ("t_trig"@@0) 0 $ evalSupply pat $ mkStdGen 0xffafacc8809 where pat = sseq 1 [sseq 32 [0] ,sseq sinf [srand 7 [sseq 1 [36,55,62,36, 55,62,36,55] ,sseq 1 [36,60,72,36, 60,72,36,60] ,sseq 1 [36,53,58,36, 53,58,36,53]] ,36, srand 2 [60,67] ,36, srand 2 [67,72] ,srand 2 [48,53,55,60,65,67]]] lfsin :: UGen lfsin = out ("out"@@100) $ sinOsc kr ("freq"@@1) 0 * ("mul"@@1) + ("add"@@0) cd2tshw :: UGen cd2tshw = mrg [mkOut "outa" ta, mkOut "outt" tt] where mkOut n pt = out (n@@0) $ demand t 0 pt * t t = "t_trig"@@0 (ta,tt) = (evalSupply ampPat g0, evalSupply trigPat g0) g0 = mkStdGen 0 ampPat = sseq sinf [sseq 40 [0], sseq 5 [1,1,0],1 ,sseq sinf [sseq 5 [1,1,0],1,sseq 48 [0] ,sseq 64 [0]]] trigPat = sseq sinf [sseq 39 [0], 1, sseq 16 [0] ,sseq sinf [sseq 48 [0], sseq 64 [0] ,sseq 15 [0], 1]] cd2tbell :: UGen cd2tbell = out ("out"@@0) $ midiCPS $ (t * f) where t = "t_trig"@@0 f = demand t 0 $ evalSupply pat $ mkStdGen 0x898fa pat = sseq sinf [sseq 64 [0] ,sseq 24 [0] ,sseq sinf [srand 16 (replicate 64 0 ++ [79,84,89,91,96]) ,sseq 48 [0]]] -- -- sound sources -- cd2huh :: UGen cd2huh = cd2huh' (whiteNoise 'a' ar) ("t_trig"@@0) cd2huh' srcn tick = out ("out"@@0) (mix $ resonz srcn freq bndw * ampe) where freq = mce [tRand 'a' 600 800 tick ,tRand 'b' 1000 1400 tick ,tRand 'c' 2400 2800 tick] `lag` 0.1 bndw = mce [130/700, 70/1220, 160/2600] ampe = envGen kr (coinGate 'g' 0.99 tick) 1 0 1 DoNothing $ envSine ed ev ed = tRand 'd' 0.1 0.4 tick ev = tRand 'e' 0.1 0.6 tick cd2nzf :: UGen cd2nzf = cd2nzf' ("t_amp"@@0) ("freq"@@0) cd2nzf' amp freq = out ("out"@@0) sig where sig = sum [rlpf nz freq 2 * ae1 ,rlpf nz (freq*2.002321) 1.5 * ae2 ,rlpf nz (freq*2.9989989) 1 * ae3] nz = pulse ar freq (lfdNoise3 'f' kr 9.32 * 0.5 + 0.5) ae1 = mkAE [0,1,0.2,0.8,0] [28e-3,200e-3,100e-3,285e-3] ae2 = mkAE [0,0.5,0.8,0] [120e-3,30e-3, 130e-3] ae3 = mkAE [0,1,0.2,0] [25e-3, 180e-3, 310e-3] mkAE vs ts = envGen kr amp amp 0 0.25 DoNothing $ env vs ts [EnvNum 3] (-1) (-1) cd2cgt :: UGen cd2cgt = out ("out"@@0) (coinGate 'g' ("prob"@@0.5) ("t_trig"@@0) * ("amp"@@1)) cd2kik :: UGen cd2kik = cd2kik' ("t_trig"@@0) cd2kik' tick = out ("out"@@0) ((lfCub ar freq 0.05 + impl) * ampe) where freq = (mix $ mce [200.32, 230.32, 360.79, 110.13]) * fenv fenv = envGen kr tick 1 0 1 DoNothing $ env [0.2, 0.2, 0.1, 0.1] [10e-3, 10e-3, 10e-3] [EnvSqr] 0 (-1) impl = impulse ar 28 0.3 * decay2 tick 1e-4 2e-3 ampe = envGen kr tick lvls 0 1 DoNothing $ env [0,1,1,0] [1e-3,25e-3,228e-3] [EnvNum (-13)] (-1) (-1) lvls = latch tick tick cd2snr :: UGen cd2snr = cd2snr' ("t_trig"@@0) cd2snr' tick = out ("out"@@0) (sig * ampe * 0.3) where sig = mix $ ringz (whiteNoise 'a' ar) fs qs * 0.1 fs = mce [943.232, 350.32, 680.192] qs = mce [0.1,0.05,0.025] ampe = envGen kr tick amp' 0 1 DoNothing $ env [0,1,1,0] [1e-3,15e-3,189e-3] [EnvNum (-8)] (-1) (-1) amp' = latch tick tick cd2hat :: UGen cd2hat = cd2hat' ("t_trig"@@0) cd2hat' tick = out ("out"@@0) (sig * amp) where sig = mix $ rhpf (whiteNoise 'z' ar) (mce [5908.32,8803,6723]) (mce [0.1,0.1,0.1]) amp = envGen kr tick tamp 0 1 DoNothing $ env [0,1,0] [3e-4, 80e-3] [EnvNum (-3)] (-1) (-1) tamp = latch tick tick cd2drn :: UGen cd2drn = cd2drn' ("amp"@@0.3) ("gate"@@1) ("freq"@@440) cd2drn' amp gt freq = out ("out"@@0) sig where sig = foldr (\a b -> allpassN b 0.05 a 4) sig' $ map (\i -> mce2 (rand i 0 0.05) (rand (succ i) 0 0.05)) "qrst" sig' = resonz sig'' q 0.5 q = lfdNoise3 '\813' kr 1.23 * 2300 + 3000 sig'' = lfPulse ar freq 0 bw * aenv bw = lfdNoise3 '\992' kr 0.7778 * 0.4 + 0.5 aenv = envGen kr gt amp 0 1 DoNothing $ env [0, 1, 0.8, 0.8, 0] [5e-3, 20e-3, 20e-3, 30e-3] [EnvCub] 2 1 cd2pu :: UGen cd2pu = cd2pu' ("t_trig"@@0) cd2pu' tick = out ("out"@@0) $ foldr f v (zipWith mce2 rs1 rs2) where v = rlpf (pulse ar (mce2 freq (freq*1.01)) bw * 0.2 * ampe * amp) (lfdNoise3 'n' kr 2.323 * 2000 + 2200) (lfdNoise3 'q' kr 1.110 * 0.498 + 0.5) f a b = allpassN b 0.05 a 4 rs1 = map mkR "abcd" rs2 = map mkR "efgh" mkR x = rand x 0.001 0.05 freq = "freq"@@0 ampe = decay2 tick 5e-4 950e-3 amp = "amp"@@0.3 bw = lfdNoise3 'b' kr 0.1123 * 0.48 + 0.5 cd2chr :: UGen cd2chr = cd2chr' ("amp"@@0.3) ("gate"@@1) ("freq"@@440) cd2chr' a g f = 0 cd2bell :: UGen cd2bell = cd2bell ' ( dust 'd ' kr 1 ) 440 ( " amp"@@0.3 ) cd2bell = cd2bell' ("t_trig"@@0) ("freq"@@0) ("amp"@@0.3) cd2bell' tick freq amp = out ("out"@@0) (sig * amp) where sig = foldr f sig' (zipWith mce2 rs1 rs2) sig' = sinOsc ar (mce [freq',freq'*1.01]) 0 * aenv freq' = freq'' freq ' = ( freq''/2 ) + ( sinOsc kr ( freq''*8 ) 0 * freq '' * 4 ) freq'' = latch freq tick f a b = allpassL b 250e-3 a 2 rs1 = map mkR [(1::Int)..8] rs2 = map mkR [(1001::Int)..1008] mkR x = expRand x 1e-4 150e-3 nz = pinkNoise 'p' ar aenv = decay2 tick 50e-3 1 cd2shw :: UGen cd2shw = cd2shw' ("t_trig"@@0) cd2shw' tick = out ("out"@@0) (resonz sig freq bw) where sig = brownNoise 'b' ar * tamp tamp = decay2 tick 1e-3 1 freq = el * ("freq"@@8000) + 50 bw = el * 0.8 + 0.1 el = envGen kr ("t_envr"@@0) 1 0 1 DoNothing $ env [ 1e-3,1,1e-3 ] [ 25e-3,7.3 ] [ EnvCub ] ( -1 ) ( -1 ) env [2.5e-2,1,2.5e-2] [25e-3,8.4] [EnvCub] (-1) (-1) -- -- effects -- cd2rev :: UGen cd2rev = cd2rev' ("a_in"@@0) cd2rev' input = replaceOut ("out"@@0) sig where sig = mix $ foldr f input (zipWith mce2 r1 r2) r1 = map mkR [(1::Int) .. 3] r2 = map mkR [(101::Int) .. 103] mkR i = rand i 0.001 0.05 f a b = b + combC b 0.5 ("dlyt"@@0.123) a * ("dmul"@@0.25) cd2dly :: UGen cd2dly = cd2dly' ("a_in"@@0) cd2dly' input = replaceOut ("out"@@0) sig where sig = foldr f input rs f a b = delayL b ("maxdt"@@0.5) a rs = map mkR "asdqwerpoiu;lkj/.m" mkR x = expRand x 5e-3 ("maxdt"@@0.5) -- -- mixer -- cd2mix :: UGen cd2mix = cd2mix' ("a_in"@@0) cd2mix' input = out ("out"@@0) ((pan2 input ("pan"@@0) 1) * ("amp"@@0) * ("mamp"@@1)) cd2mixm :: UGen cd2mixm = cd2mixm' ("a_in"@@0) cd2mixm' input = out ("out"@@0) (input * ("amp"@@1)) cd2mst :: UGen cd2mst = cd2mst' ("amp"@@0) cd2mst' amp = replaceOut ("out"@@0) (hpf (mce [l,r] * amp) 15) where ( hpf ( limiter ( mce [ l , r ] * amp ) 1 0.25 ) 15 ) where l = in' 1 ar 0 r = in' 1 ar 1 -- -- utility -- mkDemand :: Supply -> UGen mkDemand p = out ("out"@@0) (demand tick 0 p' * tick) where tick = "t_trig"@@1 p' = evalSupply p (mkStdGen 0x92af8afff) mkTdrn :: Supply -> UGen mkTdrn pat = mrg [fval, gval] where fval = out ("outf"@@0) (midiCPS (gate val (val >* 0)) `lag` ("lag"@@0.6)) gval = out ("outg"@@0) $ 0 <=* val val = demand ("t_trig"@@0) ("t_reset"@@0) $ evalSupply pat (mkStdGen 0xafcd08921fb) -- | Multiply trigger value with buffer index value. bufTrig :: UGen -- ^ Buffer index -> UGen -- ^ Trigger -> UGen bufTrig i t = index i (stepper t 0 0 (bufFrames kr i -1) 1 0) * t -- | Percussive filtered noise sound, for next piece. cd2tkl :: UGen cd2tkl = cd2tkl' ("t_trig"@@1) cd2tkl' tick = out ("out"@@0) $ decay2 tick 1e-3 1.2 * sig * 0.2 where sig = foldr f sig' (map (\i -> rand i 0.001 0.05) "abwewpoew") f a b = allpassN b 0.05 a 4 sig' = ringz nz freq rt freq = tExpRand 'f' 1020 12800 tick nz = pinkNoise 'a' ar rt = mouseX kr 0.04 4 Linear 0.1 -- -- Too glassy for now -- cd2tnzfa : : UGen -- cd2tnzfa = mrg [amp, freq] where amp = out ( " outa"@@0 ) ( " ) -- freq = out ("outf"@@0) (midiCPS . (+60) $ demand ("t_trig"@@1) 0 pat) pat = dseq ' a ' dinf $ mce $ [ 2,0,7,0 , 7,5,7,0 , 0,0,2,7 , 0,7,5,7 ] cd2tnzfa2 : : UGen -- cd2tnzfa2 = mrg [amp, freq] where amp = out ( " outa"@@0 ) ( " ) -- freq = out ("outf"@@0) (midiCPS . (+60) $ demand ("t_trig"@@1) 0 pat) pat = dseq ' a ' dinf $ mce $ [ 0,0,0,0 , 0,5,7,0 , 0,0,2,7 , 0,0,0,0 ] cd2tnzfb : : UGen -- cd2tnzfb = mrg [amp, freq] where amp = out ( " outa"@@0 ) ( " ) freq = out ( " outf"@@0 ) ( midiCPS . ( +48 ) $ demand ( " t_trig"@@1 ) 0 pat ) pat = dseq ' b ' dinf $ mce $ [ 0 , 0 , ( -5 ) , 0 , 0 , 0 , ( -5 ) , 0 , 7 , 0 , 0 , 0 , 0 , 0 , ( -5 ) , 0 ] cd2tnzfb2 : : UGen cd2tnzfb2 = mrg [ amp , freq ] where amp = out ( " outa"@@0 ) ( " ) freq = out ( " outf"@@0 ) ( midiCPS . ( +48 ) $ demand ( " t_trig"@@1 ) 0 pat ) pat = dseq ' b ' dinf $ mce $ [ 0 , 0 , ( -5 ) , 0 , 0 , 0 , ( -5 ) , 0 , 7 , 0 , 0 , 0 , 0 , 0 , ( -5 ) , 0 ] -- For playing with switching between patterns cd2thuh1a :: UGen cd2thuh1a = mkDemand $ sseq sinf [0,1,0,0, 1,0,0,1, 0,0,1,0, 1,0,1,0] cd2thuh2a :: UGen cd2thuh2a = mkDemand $ sseq sinf [1,0,1,0, 1,0,0,0, 1,0,1,0, 1,0,0,0] cd2thuh3a :: UGen cd2thuh3a = mkDemand $ sseq sinf [0,1,0,1, 0,0,0,1, 0,1,0,1, 0,0,0,1] cd2thata :: UGen cd2thata = mkDemand $ sseq sinf [0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1] cd2tsnra :: UGen cd2tsnra = mkDemand $ sseq sinf [sseq 3 [sseq 3 [0,0,1,0], sseq 1 [0,0,1,1]] ,sseq 1 [sseq 2 [0,0,1,0], srand 8 [0,1,1]]] cd2tkika :: UGen cd2tkika = mkDemand $ sseq sinf [1,0,0,0, 1,0,0,0, 1,0,0,0, 1,0,0,1] cd2thuh1b :: UGen cd2thuh1b = mkDemand $ sseq sinf [0,1,0,1, 1,1,0,0, 0,0,0,1, 1,0,0,1] cd2thatb :: UGen cd2thatb = mkDemand $ srand sinf [1,0] cd2tsnrb :: UGen cd2tsnrb = mkDemand $ sseq sinf [sseq 1 [0,0,0,0, 1,0,0,0, 0,0,0,0], srand 4 [0,1]] cd2tkikb :: UGen cd2tkikb = mkDemand $ sseq sinf [1,0,0,1, 1,0,0,1, 0,1,0,1, 1,0,0,1] cd2tpua :: UGen cd2tpua = out ("out"@@0) $ midiCPS $ demand ("t_trig"@@0) 0 $ evalSupply s1 $ mkStdGen 0xffafacc8809 s1 :: Supply s1 = sseq sinf [srand 7 [sseq 1 [36,55,62,36, 55,62,36,55] ,sseq 1 [36,60,72,36, 60,72,36,60] ,sseq 1 [36,53,58,36, 53,58,36,53]] ,36, srand 2 [60,67] ,36, srand 2 [67,72] ,srand 2 [48,53,55,60,65,67]] cd2tdrn2a :: UGen cd2tdrn2a = cd2tdrn1a cd2tdrn1b :: UGen cd2tdrn1b = cd2tdrn' ("t_trig"@@1) cd2tdrn' tick = mrg [fval, rval] where fval = out ("outf"@@0) (midiCPS (gate val (val >* 0)) `lag` 0.6) rval = out ("outg"@@0) $ 0 <=* val val = demand tick 0 $ evalSupply pat (mkStdGen 0xFAFAFAFACCDD) pat = sseq sinf [72, 0, 0, 0, 0, 0, 0, 0, 0,67, 0, 0, 65, 0, 0, 0 ,67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 0, 0, 0 ,60, 0, 0, 0, 0, 0, 0, 0, 0,55, 0, 0, 65, 0, 0, 0 ,67, sseq 15 [0]] cd2tdrn1a :: UGen cd2tdrn1a = mkTdrn pat where pat = sseq sinf [72, 0, 0, 0, 0, 0, 0, 0, 0,67, 0, 0, 65, 0, 0, 0 ,67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 0, 0, 0 ,60, 0, 0, 0, 0, 0, 0, 0, 0,55, 0, 0, 65, 0, 0, 0 ,67, sseq 15 [0]] cd2tdrn2b :: UGen cd2tdrn2b = mkTdrn pat where pat = sseq sinf [ 0, 0,55, 0, 0, 0,60, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0 , 0, 0, 0, 0, 0, 0,67, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
null
https://raw.githubusercontent.com/8c6794b6/haskell-sc-scratch/22de2199359fa56f256b544609cd6513b5e40f43/Scratch/Misc/Cd22e9d/SynthDefs.hs
haskell
master controls trigger controls For recording piece sound sources effects mixer utility | Multiply trigger value with buffer index value. ^ Buffer index ^ Trigger | Percussive filtered noise sound, for next piece. Too glassy for now cd2tnzfa = mrg [amp, freq] where freq = out ("outf"@@0) (midiCPS . (+60) $ demand ("t_trig"@@1) 0 pat) cd2tnzfa2 = mrg [amp, freq] where freq = out ("outf"@@0) (midiCPS . (+60) $ demand ("t_trig"@@1) 0 pat) cd2tnzfb = mrg [amp, freq] where For playing with switching between patterns
# LANGUAGE NoMonomorphismRestriction # | Module : $ Header$ CopyRight : ( c ) 8c6794b6 License : : Stability : unstable Portability : non - portable Module to play with sending node repeatedly with response to sendReply . This module contains UGen to be parsed with writeSynthdef . Module : $Header$ CopyRight : (c) 8c6794b6 License : BSD3 Maintainer : Stability : unstable Portability : non-portable Module to play with sending node repeatedly with response to sendReply. This module contains UGen to be parsed with writeSynthdef. -} module Cd22e9d.SynthDefs where import System.Random import Control.Applicative import Control.Monad.State import Control.Monad import Sound.OpenSoundControl import Sound.SC3 import Sound.SC3.ID import Sound.SC3.Lepton met9d :: UGen met9d = out ("out"@@0) (impulse kr bpm 0) where bpm = ("bpm"@@120) / 60 tr9d :: UGen tr9d = mrg [out ("out"@@0) pc, sendReply t 0 "/cd22e9d" [pc]] where t = "t_trig"@@0 pc = pulseCount t 0 cd2thuh1 :: UGen cd2thuh1 = mkDemand $ sseq 1 [sseq 4 [0,1,0,0, 1,0,0,1, 0,0,1,0, 1,0,1,0] ,sseq sinf [sseq 12 [0,1,0,0, 1,0,0,1, 0,0,1,0, 1,0,1,0] ,sseq 4 [0,1,0,1, 1,1,0,0, 0,0,0,1, 1,0,0,1]]] cd2thuh2 :: UGen cd2thuh2 = mkDemand $ sseq 1 [sseq 64 [0] ,sseq sinf [sseq 12 [1,0,1,0, 1,0,0,0, 1,0,1,0, 1,0,0,0] ,sseq 56 [0], sseq 4 [0,1]]] cd2thuh3 :: UGen cd2thuh3 = mkDemand $ sseq 1 [sseq 64 [0] ,sseq sinf [sseq 12 [0,1,0,1, 0,0,0,1, 0,1,0,1, 0,0,0,1] ,sseq 56 [0], sseq 4 [1,0]]] cd2that :: UGen cd2that = mkDemand $ sseq 1 [sseq 62 [0], sseq 1 [0.6,0.8] ,sseq sinf [sseq 3 [sseq 32 [srand 1 [0,0,0,0,0,0,0.2] ,srand 1 [0.5,0.8,1.0]]] ,sseq 32 [0] ,sseq 1 [sseq 28 [0], srand 4 [0,0.3,0.6,0.8,1]]]] cd2tsnr :: UGen cd2tsnr = mkDemand $ sseq 1 [sseq 56 [0], sseq 1 [0.8,0.6,0,0.2, 0.2,0.8,0.4,1.0] ,sseq sinf [sseq 3 [sseq 3 [sseq 3 [0,0,srand 1 [0.6,1.0],0] ,sseq 1 [0,0,srand 1 [0.6,0.7,0.8],srand 1 [0.6,0.8]]] ,sseq 1 [sseq 2 [0,0,1,0], srand 8 [0,0,0.5,0.75,1]]] ,sseq 3 [0,0,0,0, srand 1 [0.9,1.0],0,0,0 ,0,0,0,0, srand 4 [1,0.8,0]] ,sseq 1 [0,0,0,0, srand 1 [0.9,1.0],0,0,0 ,srand 8 [0,0,0,0.5,0.6,0.7,0.8,0.9,1]]]] cd2tkik :: UGen cd2tkik = mkDemand $ sseq sinf [sseq 4 [1,0,0,0, 1,0,0,0, 0.8,0,0,0, 1,0,0,1] ,sseq sinf [sseq 3 [sseq 4 [1,0,0,0, 0.8,0,0,srand 1 [0,0.7,0.8,1] ,0.89,0,0,0, 1,0,0,srand 1 [0,0.7,0.8,1]]] ,sseq 4 [1,0,0,0.7, 1,0,0,1, 0,0.9,0,0.8, 0.9,0,0,1]]] cd2tdrn1 :: UGen cd2tdrn1 = mkTdrn pat where pat = sseq 1 [sseq 32 [0] ,sseq sinf [sseq 3 [72, 0, 0, 0, 0, 0, 0, 0, 0,67, 0, 0, 65, 0, 0, 0 ,67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 0, 0, 0 ,60, 0, 0, 0, 0, 0, 0, 0, 0,55, 0, 0, 65, 0, 0, 0 ,67, sseq 15 [0]] ,sseq 1 [72, sseq 31 [0] ,60, sseq 31 [0]]]] cd2tdrn2 :: UGen cd2tdrn2 = mkTdrn pat where pat = sseq 1 [sseq 32 [0] ,sseq sinf [sseq 3 [ 0, 0, 55,0, 0, 0,60, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0 , 0, 0, 0, 0, 0, 0,67, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] ,sseq 1 [ 0, 0, 55,0, sseq 28 [0] , 0, 0, 0,0, 0, 0, 67, 0, sseq 24 [0]]]] cd2tpu :: UGen cd2tpu = out ("out"@@0) $ midiCPS $ demand ("t_trig"@@0) 0 $ evalSupply pat $ mkStdGen 0xffafacc8809 where pat = sseq 1 [sseq 32 [0] ,sseq sinf [srand 7 [sseq 1 [36,55,62,36, 55,62,36,55] ,sseq 1 [36,60,72,36, 60,72,36,60] ,sseq 1 [36,53,58,36, 53,58,36,53]] ,36, srand 2 [60,67] ,36, srand 2 [67,72] ,srand 2 [48,53,55,60,65,67]]] lfsin :: UGen lfsin = out ("out"@@100) $ sinOsc kr ("freq"@@1) 0 * ("mul"@@1) + ("add"@@0) cd2tshw :: UGen cd2tshw = mrg [mkOut "outa" ta, mkOut "outt" tt] where mkOut n pt = out (n@@0) $ demand t 0 pt * t t = "t_trig"@@0 (ta,tt) = (evalSupply ampPat g0, evalSupply trigPat g0) g0 = mkStdGen 0 ampPat = sseq sinf [sseq 40 [0], sseq 5 [1,1,0],1 ,sseq sinf [sseq 5 [1,1,0],1,sseq 48 [0] ,sseq 64 [0]]] trigPat = sseq sinf [sseq 39 [0], 1, sseq 16 [0] ,sseq sinf [sseq 48 [0], sseq 64 [0] ,sseq 15 [0], 1]] cd2tbell :: UGen cd2tbell = out ("out"@@0) $ midiCPS $ (t * f) where t = "t_trig"@@0 f = demand t 0 $ evalSupply pat $ mkStdGen 0x898fa pat = sseq sinf [sseq 64 [0] ,sseq 24 [0] ,sseq sinf [srand 16 (replicate 64 0 ++ [79,84,89,91,96]) ,sseq 48 [0]]] cd2huh :: UGen cd2huh = cd2huh' (whiteNoise 'a' ar) ("t_trig"@@0) cd2huh' srcn tick = out ("out"@@0) (mix $ resonz srcn freq bndw * ampe) where freq = mce [tRand 'a' 600 800 tick ,tRand 'b' 1000 1400 tick ,tRand 'c' 2400 2800 tick] `lag` 0.1 bndw = mce [130/700, 70/1220, 160/2600] ampe = envGen kr (coinGate 'g' 0.99 tick) 1 0 1 DoNothing $ envSine ed ev ed = tRand 'd' 0.1 0.4 tick ev = tRand 'e' 0.1 0.6 tick cd2nzf :: UGen cd2nzf = cd2nzf' ("t_amp"@@0) ("freq"@@0) cd2nzf' amp freq = out ("out"@@0) sig where sig = sum [rlpf nz freq 2 * ae1 ,rlpf nz (freq*2.002321) 1.5 * ae2 ,rlpf nz (freq*2.9989989) 1 * ae3] nz = pulse ar freq (lfdNoise3 'f' kr 9.32 * 0.5 + 0.5) ae1 = mkAE [0,1,0.2,0.8,0] [28e-3,200e-3,100e-3,285e-3] ae2 = mkAE [0,0.5,0.8,0] [120e-3,30e-3, 130e-3] ae3 = mkAE [0,1,0.2,0] [25e-3, 180e-3, 310e-3] mkAE vs ts = envGen kr amp amp 0 0.25 DoNothing $ env vs ts [EnvNum 3] (-1) (-1) cd2cgt :: UGen cd2cgt = out ("out"@@0) (coinGate 'g' ("prob"@@0.5) ("t_trig"@@0) * ("amp"@@1)) cd2kik :: UGen cd2kik = cd2kik' ("t_trig"@@0) cd2kik' tick = out ("out"@@0) ((lfCub ar freq 0.05 + impl) * ampe) where freq = (mix $ mce [200.32, 230.32, 360.79, 110.13]) * fenv fenv = envGen kr tick 1 0 1 DoNothing $ env [0.2, 0.2, 0.1, 0.1] [10e-3, 10e-3, 10e-3] [EnvSqr] 0 (-1) impl = impulse ar 28 0.3 * decay2 tick 1e-4 2e-3 ampe = envGen kr tick lvls 0 1 DoNothing $ env [0,1,1,0] [1e-3,25e-3,228e-3] [EnvNum (-13)] (-1) (-1) lvls = latch tick tick cd2snr :: UGen cd2snr = cd2snr' ("t_trig"@@0) cd2snr' tick = out ("out"@@0) (sig * ampe * 0.3) where sig = mix $ ringz (whiteNoise 'a' ar) fs qs * 0.1 fs = mce [943.232, 350.32, 680.192] qs = mce [0.1,0.05,0.025] ampe = envGen kr tick amp' 0 1 DoNothing $ env [0,1,1,0] [1e-3,15e-3,189e-3] [EnvNum (-8)] (-1) (-1) amp' = latch tick tick cd2hat :: UGen cd2hat = cd2hat' ("t_trig"@@0) cd2hat' tick = out ("out"@@0) (sig * amp) where sig = mix $ rhpf (whiteNoise 'z' ar) (mce [5908.32,8803,6723]) (mce [0.1,0.1,0.1]) amp = envGen kr tick tamp 0 1 DoNothing $ env [0,1,0] [3e-4, 80e-3] [EnvNum (-3)] (-1) (-1) tamp = latch tick tick cd2drn :: UGen cd2drn = cd2drn' ("amp"@@0.3) ("gate"@@1) ("freq"@@440) cd2drn' amp gt freq = out ("out"@@0) sig where sig = foldr (\a b -> allpassN b 0.05 a 4) sig' $ map (\i -> mce2 (rand i 0 0.05) (rand (succ i) 0 0.05)) "qrst" sig' = resonz sig'' q 0.5 q = lfdNoise3 '\813' kr 1.23 * 2300 + 3000 sig'' = lfPulse ar freq 0 bw * aenv bw = lfdNoise3 '\992' kr 0.7778 * 0.4 + 0.5 aenv = envGen kr gt amp 0 1 DoNothing $ env [0, 1, 0.8, 0.8, 0] [5e-3, 20e-3, 20e-3, 30e-3] [EnvCub] 2 1 cd2pu :: UGen cd2pu = cd2pu' ("t_trig"@@0) cd2pu' tick = out ("out"@@0) $ foldr f v (zipWith mce2 rs1 rs2) where v = rlpf (pulse ar (mce2 freq (freq*1.01)) bw * 0.2 * ampe * amp) (lfdNoise3 'n' kr 2.323 * 2000 + 2200) (lfdNoise3 'q' kr 1.110 * 0.498 + 0.5) f a b = allpassN b 0.05 a 4 rs1 = map mkR "abcd" rs2 = map mkR "efgh" mkR x = rand x 0.001 0.05 freq = "freq"@@0 ampe = decay2 tick 5e-4 950e-3 amp = "amp"@@0.3 bw = lfdNoise3 'b' kr 0.1123 * 0.48 + 0.5 cd2chr :: UGen cd2chr = cd2chr' ("amp"@@0.3) ("gate"@@1) ("freq"@@440) cd2chr' a g f = 0 cd2bell :: UGen cd2bell = cd2bell ' ( dust 'd ' kr 1 ) 440 ( " amp"@@0.3 ) cd2bell = cd2bell' ("t_trig"@@0) ("freq"@@0) ("amp"@@0.3) cd2bell' tick freq amp = out ("out"@@0) (sig * amp) where sig = foldr f sig' (zipWith mce2 rs1 rs2) sig' = sinOsc ar (mce [freq',freq'*1.01]) 0 * aenv freq' = freq'' freq ' = ( freq''/2 ) + ( sinOsc kr ( freq''*8 ) 0 * freq '' * 4 ) freq'' = latch freq tick f a b = allpassL b 250e-3 a 2 rs1 = map mkR [(1::Int)..8] rs2 = map mkR [(1001::Int)..1008] mkR x = expRand x 1e-4 150e-3 nz = pinkNoise 'p' ar aenv = decay2 tick 50e-3 1 cd2shw :: UGen cd2shw = cd2shw' ("t_trig"@@0) cd2shw' tick = out ("out"@@0) (resonz sig freq bw) where sig = brownNoise 'b' ar * tamp tamp = decay2 tick 1e-3 1 freq = el * ("freq"@@8000) + 50 bw = el * 0.8 + 0.1 el = envGen kr ("t_envr"@@0) 1 0 1 DoNothing $ env [ 1e-3,1,1e-3 ] [ 25e-3,7.3 ] [ EnvCub ] ( -1 ) ( -1 ) env [2.5e-2,1,2.5e-2] [25e-3,8.4] [EnvCub] (-1) (-1) cd2rev :: UGen cd2rev = cd2rev' ("a_in"@@0) cd2rev' input = replaceOut ("out"@@0) sig where sig = mix $ foldr f input (zipWith mce2 r1 r2) r1 = map mkR [(1::Int) .. 3] r2 = map mkR [(101::Int) .. 103] mkR i = rand i 0.001 0.05 f a b = b + combC b 0.5 ("dlyt"@@0.123) a * ("dmul"@@0.25) cd2dly :: UGen cd2dly = cd2dly' ("a_in"@@0) cd2dly' input = replaceOut ("out"@@0) sig where sig = foldr f input rs f a b = delayL b ("maxdt"@@0.5) a rs = map mkR "asdqwerpoiu;lkj/.m" mkR x = expRand x 5e-3 ("maxdt"@@0.5) cd2mix :: UGen cd2mix = cd2mix' ("a_in"@@0) cd2mix' input = out ("out"@@0) ((pan2 input ("pan"@@0) 1) * ("amp"@@0) * ("mamp"@@1)) cd2mixm :: UGen cd2mixm = cd2mixm' ("a_in"@@0) cd2mixm' input = out ("out"@@0) (input * ("amp"@@1)) cd2mst :: UGen cd2mst = cd2mst' ("amp"@@0) cd2mst' amp = replaceOut ("out"@@0) (hpf (mce [l,r] * amp) 15) where ( hpf ( limiter ( mce [ l , r ] * amp ) 1 0.25 ) 15 ) where l = in' 1 ar 0 r = in' 1 ar 1 mkDemand :: Supply -> UGen mkDemand p = out ("out"@@0) (demand tick 0 p' * tick) where tick = "t_trig"@@1 p' = evalSupply p (mkStdGen 0x92af8afff) mkTdrn :: Supply -> UGen mkTdrn pat = mrg [fval, gval] where fval = out ("outf"@@0) (midiCPS (gate val (val >* 0)) `lag` ("lag"@@0.6)) gval = out ("outg"@@0) $ 0 <=* val val = demand ("t_trig"@@0) ("t_reset"@@0) $ evalSupply pat (mkStdGen 0xafcd08921fb) -> UGen bufTrig i t = index i (stepper t 0 0 (bufFrames kr i -1) 1 0) * t cd2tkl :: UGen cd2tkl = cd2tkl' ("t_trig"@@1) cd2tkl' tick = out ("out"@@0) $ decay2 tick 1e-3 1.2 * sig * 0.2 where sig = foldr f sig' (map (\i -> rand i 0.001 0.05) "abwewpoew") f a b = allpassN b 0.05 a 4 sig' = ringz nz freq rt freq = tExpRand 'f' 1020 12800 tick nz = pinkNoise 'a' ar rt = mouseX kr 0.04 4 Linear 0.1 cd2tnzfa : : UGen amp = out ( " outa"@@0 ) ( " ) pat = dseq ' a ' dinf $ mce $ [ 2,0,7,0 , 7,5,7,0 , 0,0,2,7 , 0,7,5,7 ] cd2tnzfa2 : : UGen amp = out ( " outa"@@0 ) ( " ) pat = dseq ' a ' dinf $ mce $ [ 0,0,0,0 , 0,5,7,0 , 0,0,2,7 , 0,0,0,0 ] cd2tnzfb : : UGen amp = out ( " outa"@@0 ) ( " ) freq = out ( " outf"@@0 ) ( midiCPS . ( +48 ) $ demand ( " t_trig"@@1 ) 0 pat ) pat = dseq ' b ' dinf $ mce $ [ 0 , 0 , ( -5 ) , 0 , 0 , 0 , ( -5 ) , 0 , 7 , 0 , 0 , 0 , 0 , 0 , ( -5 ) , 0 ] cd2tnzfb2 : : UGen cd2tnzfb2 = mrg [ amp , freq ] where amp = out ( " outa"@@0 ) ( " ) freq = out ( " outf"@@0 ) ( midiCPS . ( +48 ) $ demand ( " t_trig"@@1 ) 0 pat ) pat = dseq ' b ' dinf $ mce $ [ 0 , 0 , ( -5 ) , 0 , 0 , 0 , ( -5 ) , 0 , 7 , 0 , 0 , 0 , 0 , 0 , ( -5 ) , 0 ] cd2thuh1a :: UGen cd2thuh1a = mkDemand $ sseq sinf [0,1,0,0, 1,0,0,1, 0,0,1,0, 1,0,1,0] cd2thuh2a :: UGen cd2thuh2a = mkDemand $ sseq sinf [1,0,1,0, 1,0,0,0, 1,0,1,0, 1,0,0,0] cd2thuh3a :: UGen cd2thuh3a = mkDemand $ sseq sinf [0,1,0,1, 0,0,0,1, 0,1,0,1, 0,0,0,1] cd2thata :: UGen cd2thata = mkDemand $ sseq sinf [0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1] cd2tsnra :: UGen cd2tsnra = mkDemand $ sseq sinf [sseq 3 [sseq 3 [0,0,1,0], sseq 1 [0,0,1,1]] ,sseq 1 [sseq 2 [0,0,1,0], srand 8 [0,1,1]]] cd2tkika :: UGen cd2tkika = mkDemand $ sseq sinf [1,0,0,0, 1,0,0,0, 1,0,0,0, 1,0,0,1] cd2thuh1b :: UGen cd2thuh1b = mkDemand $ sseq sinf [0,1,0,1, 1,1,0,0, 0,0,0,1, 1,0,0,1] cd2thatb :: UGen cd2thatb = mkDemand $ srand sinf [1,0] cd2tsnrb :: UGen cd2tsnrb = mkDemand $ sseq sinf [sseq 1 [0,0,0,0, 1,0,0,0, 0,0,0,0], srand 4 [0,1]] cd2tkikb :: UGen cd2tkikb = mkDemand $ sseq sinf [1,0,0,1, 1,0,0,1, 0,1,0,1, 1,0,0,1] cd2tpua :: UGen cd2tpua = out ("out"@@0) $ midiCPS $ demand ("t_trig"@@0) 0 $ evalSupply s1 $ mkStdGen 0xffafacc8809 s1 :: Supply s1 = sseq sinf [srand 7 [sseq 1 [36,55,62,36, 55,62,36,55] ,sseq 1 [36,60,72,36, 60,72,36,60] ,sseq 1 [36,53,58,36, 53,58,36,53]] ,36, srand 2 [60,67] ,36, srand 2 [67,72] ,srand 2 [48,53,55,60,65,67]] cd2tdrn2a :: UGen cd2tdrn2a = cd2tdrn1a cd2tdrn1b :: UGen cd2tdrn1b = cd2tdrn' ("t_trig"@@1) cd2tdrn' tick = mrg [fval, rval] where fval = out ("outf"@@0) (midiCPS (gate val (val >* 0)) `lag` 0.6) rval = out ("outg"@@0) $ 0 <=* val val = demand tick 0 $ evalSupply pat (mkStdGen 0xFAFAFAFACCDD) pat = sseq sinf [72, 0, 0, 0, 0, 0, 0, 0, 0,67, 0, 0, 65, 0, 0, 0 ,67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 0, 0, 0 ,60, 0, 0, 0, 0, 0, 0, 0, 0,55, 0, 0, 65, 0, 0, 0 ,67, sseq 15 [0]] cd2tdrn1a :: UGen cd2tdrn1a = mkTdrn pat where pat = sseq sinf [72, 0, 0, 0, 0, 0, 0, 0, 0,67, 0, 0, 65, 0, 0, 0 ,67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 65, 0, 0, 0 ,60, 0, 0, 0, 0, 0, 0, 0, 0,55, 0, 0, 65, 0, 0, 0 ,67, sseq 15 [0]] cd2tdrn2b :: UGen cd2tdrn2b = mkTdrn pat where pat = sseq sinf [ 0, 0,55, 0, 0, 0,60, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 67, 0, 0, 0, 0, 0, 0, 0, 60, 0, 0, 0 , 0, 0, 0, 0, 0, 0,67, 0, 0, 0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 60, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
28d7d8f4f2d5d5bde7fb5026526485e6eb09ddc431b9de60bfadecd5a87bd308
ktakashi/json-tools
json-select.scm
;; json-tools library formula (formula (description "JSON tools for R6RS Scheme") (version "HEAD") (homepage :url "-tools") (author :name "Takashi Kato" :email "") (source :type zip :url "-tools/archive/master.zip") (install (directories ("src"))))
null
https://raw.githubusercontent.com/ktakashi/json-tools/502f63bd1b5acf4792451aa814107377cd04be79/formula/json-select.scm
scheme
json-tools library formula
(formula (description "JSON tools for R6RS Scheme") (version "HEAD") (homepage :url "-tools") (author :name "Takashi Kato" :email "") (source :type zip :url "-tools/archive/master.zip") (install (directories ("src"))))
9d773e971d868f4503546adc1365d792fc55ff35c65431d083e7f59d356d793b
nurpax/sqlite-simple
Main.hs
import Common import Control.Exception (bracket) import Control.Monad (when) import System.Exit (exitFailure) import System.IO import Debug import DirectSqlite import Errors import Fold import ParamConv import QQ import Simple import Function import Statement import TestImports() import TestImports import UserInstances import Utf8Strings tests :: [TestEnv -> Test] tests = [ TestLabel "Simple" . testSimpleSelect , TestLabel "Simple" . testSimpleOnePlusOne , TestLabel "Simple" . testSimpleParams , TestLabel "Simple" . testSimpleTime , TestLabel "Simple" . testSimpleTimeFract , TestLabel "Simple" . testSimpleInsertId , TestLabel "Simple" . testSimpleMultiInsert , TestLabel "Simple" . testSimpleUTCTime , TestLabel "Simple" . testSimpleUTCTimeTZ , TestLabel "Simple" . testSimpleUTCTimeParams , TestLabel "Simple" . testSimpleQueryCov , TestLabel "Simple" . testSimpleStrings , TestLabel "Simple" . testSimpleChanges , TestLabel "ParamConv" . testParamConvNull , TestLabel "ParamConv" . testParamConvInt , TestLabel "ParamConv" . testParamConvIntWidths , TestLabel "ParamConv" . testParamConvIntWidthsFromField , TestLabel "ParamConv" . testParamConvFloat , TestLabel "ParamConv" . testParamConvDateTime , TestLabel "ParamConv" . testParamConvBools , TestLabel "ParamConv" . testParamConvToRow , TestLabel "ParamConv" . testParamConvFromRow , TestLabel "ParamConv" . testParamConvComposite , TestLabel "ParamConv" . testParamNamed , TestLabel "Errors" . testErrorsColumns , TestLabel "Errors" . testErrorsInvalidParams , TestLabel "Errors" . testErrorsInvalidNamedParams , TestLabel "Errors" . testErrorsWithStatement , TestLabel "Errors" . testErrorsColumnName , TestLabel "Errors" . testErrorsTransaction , TestLabel "Errors" . testErrorsImmediateTransaction , TestLabel "Errors" . testErrorsExclusiveTransaction , TestLabel "Errors" . testErrorsSavepoint , TestLabel "Utf8" . testUtf8Simplest , TestLabel "Utf8" . testBlobs , TestLabel "Instances" . testUserFromField , TestLabel "Instances" . testSQLDataFromField , TestLabel "Fold" . testFolds , TestLabel "Statement" . testBind , TestLabel "Statement" . testDoubleBind , TestLabel "Statement" . testPreparedStatements , TestLabel "Statement" . testPreparedStatementsColumnCount , TestLabel "Debug" . testDebugTracing , TestLabel "Functions" . testExternalAddition , TestLabel "Direct" . testDirectSqlite , TestLabel "Imports" . testImports , TestLabel "QQ" . testSimpleQQ , TestLabel "QQ" . testMultiLinedQQ ] -- | Action for connecting to the database that will be used for testing. -- Note that some tests , such as Notify , use multiple connections , and assume that ' testConnect ' connects to the same database every time it is called . testConnect :: IO Connection testConnect = open ":memory:" withTestEnv :: (TestEnv -> IO a) -> IO a withTestEnv cb = withConn $ \conn -> cb TestEnv { conn = conn } where withConn = bracket testConnect close main :: IO () main = do mapM_ (`hSetBuffering` LineBuffering) [stdout, stderr] Counts{cases, tried, errors, failures} <- withTestEnv $ \env -> runTestTT $ TestList $ map ($ env) tests when (cases /= tried || errors /= 0 || failures /= 0) $ exitFailure
null
https://raw.githubusercontent.com/nurpax/sqlite-simple/91900808c0986f8a9f142c2897847a9d1e67d349/test/Main.hs
haskell
| Action for connecting to the database that will be used for testing.
import Common import Control.Exception (bracket) import Control.Monad (when) import System.Exit (exitFailure) import System.IO import Debug import DirectSqlite import Errors import Fold import ParamConv import QQ import Simple import Function import Statement import TestImports() import TestImports import UserInstances import Utf8Strings tests :: [TestEnv -> Test] tests = [ TestLabel "Simple" . testSimpleSelect , TestLabel "Simple" . testSimpleOnePlusOne , TestLabel "Simple" . testSimpleParams , TestLabel "Simple" . testSimpleTime , TestLabel "Simple" . testSimpleTimeFract , TestLabel "Simple" . testSimpleInsertId , TestLabel "Simple" . testSimpleMultiInsert , TestLabel "Simple" . testSimpleUTCTime , TestLabel "Simple" . testSimpleUTCTimeTZ , TestLabel "Simple" . testSimpleUTCTimeParams , TestLabel "Simple" . testSimpleQueryCov , TestLabel "Simple" . testSimpleStrings , TestLabel "Simple" . testSimpleChanges , TestLabel "ParamConv" . testParamConvNull , TestLabel "ParamConv" . testParamConvInt , TestLabel "ParamConv" . testParamConvIntWidths , TestLabel "ParamConv" . testParamConvIntWidthsFromField , TestLabel "ParamConv" . testParamConvFloat , TestLabel "ParamConv" . testParamConvDateTime , TestLabel "ParamConv" . testParamConvBools , TestLabel "ParamConv" . testParamConvToRow , TestLabel "ParamConv" . testParamConvFromRow , TestLabel "ParamConv" . testParamConvComposite , TestLabel "ParamConv" . testParamNamed , TestLabel "Errors" . testErrorsColumns , TestLabel "Errors" . testErrorsInvalidParams , TestLabel "Errors" . testErrorsInvalidNamedParams , TestLabel "Errors" . testErrorsWithStatement , TestLabel "Errors" . testErrorsColumnName , TestLabel "Errors" . testErrorsTransaction , TestLabel "Errors" . testErrorsImmediateTransaction , TestLabel "Errors" . testErrorsExclusiveTransaction , TestLabel "Errors" . testErrorsSavepoint , TestLabel "Utf8" . testUtf8Simplest , TestLabel "Utf8" . testBlobs , TestLabel "Instances" . testUserFromField , TestLabel "Instances" . testSQLDataFromField , TestLabel "Fold" . testFolds , TestLabel "Statement" . testBind , TestLabel "Statement" . testDoubleBind , TestLabel "Statement" . testPreparedStatements , TestLabel "Statement" . testPreparedStatementsColumnCount , TestLabel "Debug" . testDebugTracing , TestLabel "Functions" . testExternalAddition , TestLabel "Direct" . testDirectSqlite , TestLabel "Imports" . testImports , TestLabel "QQ" . testSimpleQQ , TestLabel "QQ" . testMultiLinedQQ ] Note that some tests , such as Notify , use multiple connections , and assume that ' testConnect ' connects to the same database every time it is called . testConnect :: IO Connection testConnect = open ":memory:" withTestEnv :: (TestEnv -> IO a) -> IO a withTestEnv cb = withConn $ \conn -> cb TestEnv { conn = conn } where withConn = bracket testConnect close main :: IO () main = do mapM_ (`hSetBuffering` LineBuffering) [stdout, stderr] Counts{cases, tried, errors, failures} <- withTestEnv $ \env -> runTestTT $ TestList $ map ($ env) tests when (cases /= tried || errors /= 0 || failures /= 0) $ exitFailure
0f5460d5ac1b9d2031454cfd0808a24a023a7fd2fc7532fefd443b0987c50145
SNePS/SNePS2
and.lisp
-*- Mode : Lisp ; Syntax : Common - Lisp ; Package : SNIP ; Base : 10 -*- Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : and.lisp , v 1.2 2013/08/28 19:07:27 shapiro Exp $ ;; This file is part of SNePS. $ BEGIN LICENSE$ The contents of this file are subject to the University at Buffalo Public License Version 1.0 ( the " License " ) ; you may ;;; not use this file except in compliance with the License. You ;;; may obtain a copy of the License at ;;; . edu/sneps/Downloads/ubpl.pdf. ;;; Software distributed under the License is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express ;;; or implied. See the License for the specific language gov ;;; erning rights and limitations under the License. ;;; The Original Code is SNePS 2.8 . ;;; The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . ;;; Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :snip) ; and functions ; (defun rule-handler.and (ant-report cqch) ;; if the antecedents have the same set of variables, use S - indexing , otherwise use linear ruiset handling (do.set (rui (if (or (null (ants.cqch cqch)) (is-all-pat-same-vars (ants.cqch cqch))) (get-rule-use-info-sindexing ant-report cqch) (get-rule-use-info ant-report cqch)) t) (case (sign.rep ant-report) (NEG (if (equal (signature.rep ant-report) (destination.ch (channel.cqch cqch))) (let ((restr (make.restr (subst.rui rui))) (ch (channel.cqch cqch))) (unless-remarkedp.rui rui (remark '"~%I know it is not the case that" (makeone.ns (destination.ch ch)) restr)) (send-reports (makeone.repset (make.rep (restrict.sbst (subst.rui rui) (freevars.n *NODE*)) (compute-new-support.and ch rui ant-report) 'NEG *NODE* nil (context.ch ch))) ch)))) (POS (if (or (equal (signature.rep ant-report) (destination.ch (channel.cqch cqch))) (equal (match::applysubst *NODE* (subst.rep ant-report)) (node.rep ant-report))) (let ((restr (make.restr (subst.rui rui))) (ch (channel.cqch cqch))) (unless-remarkedp.rui rui (remark '"~%It is the case that" (makeone.ns (destination.ch ch)) restr)) (send-reports (makeone.repset (make.rep (restrict.sbst (subst.rui rui) (freevars.n (destination.ch ch))) (compute-new-support.and ch rui ant-report) 'POS *NODE* nil (context.ch ch) )) ch))))))) ; ; ============================================================================== ; (defun usability-test.and (sign) (declare (ignore sign)) (or (isnew.ns (quantified-vars.n *NODE*)) (not (isnew.ns (nodeset.n *NODE* 'sneps::forall))))) ; ; ; ============================================================================= ; ; compute-new-support.and ; ----------------------- ; ; arguments : ch - <channel> ; rui - <rule-use-info> ; antrep - <report> ; ; returns : <support> ; ; description : Computes a new support based on: ; 1- the support of the rule node if it is asserted; ; 2- the support of the instances (of the rule) which ; are asserted in the 'ch' context and has the ; appropriate substitution. ; ; ; ; written : njm 12/5/88 ; modified: ; ; (defun compute-new-support.and (ch rui antrep) ( cond ( ( eq ( cardinality.ns ( nodeset.n * NODE * ' sneps : arg ) ) 1 ) ; (change-tag-support (support.rep antrep))) ; (t ...)) (let ((crntct (context.ch ch)) (newsupport (new.sup)) (freevars (freevars.n *NODE*))) (when (isassert.n *NODE*) (setq newsupport (compute-new-support1.and (support.rep antrep) (sneps:node-asupport *NODE*)))) (when *KNOWN-INSTANCES* (do.set (inst *KNOWN-INSTANCES*) (let* ((instnode (match::applysubst *NODE* (subst.inst inst))) (supinstnode (filter.sup (sneps:node-asupport instnode) crntct))) (when (and (not (isnew.sup supinstnode)) (match:issubset.sbst (restrict.sbst (subst.rui rui) freevars) (restrict.sbst (subst.inst inst) freevars))) (setq newsupport (merge.sup newsupport (compute-new-support1.nor (support.rep antrep) supinstnode))))))) newsupport)) ; ; ============================================================================= ; ; compute-new-support1.and ; ------------------------ ; arguments : < support > ; supr - <support> ; ; returns : <support> ; ; description : receives as arguments: ; 'sup' -- the support of the report ; 'supr' -- the support of the rule node ; Computes a new support based on 'sup' and on the support ; of the `supr'. ; ; ; ; written : njm 12/5/88 ; modified: ; ; (defun compute-new-support1.and (sup supr) (let ((newsupport (new.sup))) (do* ((s1 supr (others.sup s1)) (ot1 (ot.sup s1) (ot.sup s1)) (cts1 (ctset.sup s1) (ctset.sup s1))) ((isnew.sup s1) newsupport) (dolist (ct1 cts1) (do* ((s2 sup (others.sup s2)) (ot2 (ot.sup s2) (ot.sup s2)) (cts2 (ctset.sup s2) (ctset.sup s2))) ((isnew.sup s2) t) (dolist (ct2 cts2) (setq newsupport (insert.sup (combine-ots ot1 ot2) (fullbuildcontext (new.ns) (make.cts ct1 ct2)) newsupport)))))))) ;
null
https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/snip/fns/and.lisp
lisp
Syntax : Common - Lisp ; Package : SNIP ; Base : 10 -*- This file is part of SNePS. you may not use this file except in compliance with the License. You may obtain a copy of the License at . edu/sneps/Downloads/ubpl.pdf. or implied. See the License for the specific language gov erning rights and limitations under the License. and functions if the antecedents have the same set of variables, ============================================================================== ============================================================================= compute-new-support.and ----------------------- arguments : ch - <channel> rui - <rule-use-info> antrep - <report> returns : <support> description : Computes a new support based on: 1- the support of the rule node if it is asserted; 2- the support of the instances (of the rule) which are asserted in the 'ch' context and has the appropriate substitution. written : njm 12/5/88 modified: (change-tag-support (support.rep antrep))) (t ...)) ============================================================================= compute-new-support1.and ------------------------ supr - <support> returns : <support> description : receives as arguments: 'sup' -- the support of the report 'supr' -- the support of the rule node Computes a new support based on 'sup' and on the support of the `supr'. written : njm 12/5/88 modified:
Copyright ( C ) 1984 - -2013 Research Foundation of State University of New York Version : $ I d : and.lisp , v 1.2 2013/08/28 19:07:27 shapiro Exp $ $ BEGIN LICENSE$ The contents of this file are subject to the University at Software distributed under the License is distributed on an " AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express The Original Code is SNePS 2.8 . The Initial Developer of the Original Code is Research Foun dation of State University of New York , on behalf of Univer sity at Buffalo . Portions created by the Initial Developer are Copyright ( C ) 2011 Research Foundation of State University of New York , on behalf of University at Buffalo . All Rights Reserved . $ END LICENSE$ (in-package :snip) (defun rule-handler.and (ant-report cqch) use S - indexing , otherwise use linear ruiset handling (do.set (rui (if (or (null (ants.cqch cqch)) (is-all-pat-same-vars (ants.cqch cqch))) (get-rule-use-info-sindexing ant-report cqch) (get-rule-use-info ant-report cqch)) t) (case (sign.rep ant-report) (NEG (if (equal (signature.rep ant-report) (destination.ch (channel.cqch cqch))) (let ((restr (make.restr (subst.rui rui))) (ch (channel.cqch cqch))) (unless-remarkedp.rui rui (remark '"~%I know it is not the case that" (makeone.ns (destination.ch ch)) restr)) (send-reports (makeone.repset (make.rep (restrict.sbst (subst.rui rui) (freevars.n *NODE*)) (compute-new-support.and ch rui ant-report) 'NEG *NODE* nil (context.ch ch))) ch)))) (POS (if (or (equal (signature.rep ant-report) (destination.ch (channel.cqch cqch))) (equal (match::applysubst *NODE* (subst.rep ant-report)) (node.rep ant-report))) (let ((restr (make.restr (subst.rui rui))) (ch (channel.cqch cqch))) (unless-remarkedp.rui rui (remark '"~%It is the case that" (makeone.ns (destination.ch ch)) restr)) (send-reports (makeone.repset (make.rep (restrict.sbst (subst.rui rui) (freevars.n (destination.ch ch))) (compute-new-support.and ch rui ant-report) 'POS *NODE* nil (context.ch ch) )) ch))))))) (defun usability-test.and (sign) (declare (ignore sign)) (or (isnew.ns (quantified-vars.n *NODE*)) (not (isnew.ns (nodeset.n *NODE* 'sneps::forall))))) (defun compute-new-support.and (ch rui antrep) ( cond ( ( eq ( cardinality.ns ( nodeset.n * NODE * ' sneps : arg ) ) 1 ) (let ((crntct (context.ch ch)) (newsupport (new.sup)) (freevars (freevars.n *NODE*))) (when (isassert.n *NODE*) (setq newsupport (compute-new-support1.and (support.rep antrep) (sneps:node-asupport *NODE*)))) (when *KNOWN-INSTANCES* (do.set (inst *KNOWN-INSTANCES*) (let* ((instnode (match::applysubst *NODE* (subst.inst inst))) (supinstnode (filter.sup (sneps:node-asupport instnode) crntct))) (when (and (not (isnew.sup supinstnode)) (match:issubset.sbst (restrict.sbst (subst.rui rui) freevars) (restrict.sbst (subst.inst inst) freevars))) (setq newsupport (merge.sup newsupport (compute-new-support1.nor (support.rep antrep) supinstnode))))))) newsupport)) arguments : < support > (defun compute-new-support1.and (sup supr) (let ((newsupport (new.sup))) (do* ((s1 supr (others.sup s1)) (ot1 (ot.sup s1) (ot.sup s1)) (cts1 (ctset.sup s1) (ctset.sup s1))) ((isnew.sup s1) newsupport) (dolist (ct1 cts1) (do* ((s2 sup (others.sup s2)) (ot2 (ot.sup s2) (ot.sup s2)) (cts2 (ctset.sup s2) (ctset.sup s2))) ((isnew.sup s2) t) (dolist (ct2 cts2) (setq newsupport (insert.sup (combine-ots ot1 ot2) (fullbuildcontext (new.ns) (make.cts ct1 ct2)) newsupport))))))))
3952c277444a06f1981b090252627cb25b1ae91a710e23901f79897920f4a16b
idubrov/siperl
sip_ua_CANCEL_SUITE.erl
@author < > @doc CANCEL method tests . Note that implementation of ` CANCEL ' processing is in sip_simple_uas . %%% @end 2011 - 2012 . See LICENSE file . -module(sip_ua_CANCEL_SUITE). %% Exports -export([all/0, init_per_suite/1, end_per_suite/1, init_per_testcase/2, end_per_testcase/2]). -export([apply_fun/2]). -export([cancel_487/1, cancel_487_handler/2, cancel_481/1, cancel_200/1, cancel_200_handler/2]). %% Include files -include_lib("common_test/include/ct.hrl"). -include("sip.hrl"). -define(HOST, "sip.example.org"). %% Common tests all() -> [cancel_487, cancel_481, cancel_200]. init_per_suite(Config) -> ok = application:start(gproc), ok = application:start(sip), ok = application:set_env(sip, self, ?HOST), Config. end_per_suite(_Config) -> ok = application:stop(sip), ok = application:stop(gproc), ok. init_per_testcase(TestCase, Config) -> Fun = list_to_atom(atom_to_list(TestCase) ++ "_handler"), {ok, UAC} = sip_simple_uac:start_link(), {ok, UAS} = sip_simple_uas:start_link(fun(Request, ReplyFun) -> ?MODULE:Fun(Request, ReplyFun) end), [{uac, UAC}, {uas, UAS} | Config]. end_per_testcase(_TestCase, Config) -> ok = sip_test:shutdown(?config(uac, Config)), ok = sip_test:shutdown(?config(uas, Config)), ok. apply_fun(Fun, Args) -> erlang:apply(Fun, Args). @doc The 200 response should be overriden by 487 Request Terminated %% @end cancel_487_handler(Request, ReplyFun) -> Response = sip_ua:create_response(Request, 200), Response2 = sip_message:append_header('content-type', <<"application/sdp">>, Response), timer:apply_after(2000, erlang, apply, [ReplyFun, [Response2]]), ok. @doc Verify that CANCEL on active INVITE requests forces INVITE to return status 487 %% @end cancel_487(Config) -> UAC = ?config(uac, Config), cancel the request after 500 milliseconds {ok, _TRef} = timer:apply_after(500, sip_simple_uac, cancel, [UAC]), To = sip_headers:address(<<>>, <<"sip:127.0.0.1">>, []), {ok, Response} = sip_simple_uac:send_invite(UAC, To), validate INVITE response status #sip_response{status = 487, reason = <<"Request Terminated">>} = Response, timer:sleep(5000), ok. @doc Do not reply on INVITE request ( it will be cancelled ) %% @end cancel_200_handler(#sip_request{method = 'INVITE'} = Request, ReplyFun) -> Response = sip_ua:create_response(Request, 200), Response2 = sip_message:append_header('content-type', <<"application/sdp">>, Response), ReplyFun(Response2), ok. @doc Verify that CANCEL on responded INVITE has no effect %% @end cancel_200(Config) -> UAC = ?config(uac, Config), send INVITE and receive response To = sip_headers:address(<<>>, <<"sip:127.0.0.1">>, []), {ok, Response} = sip_simple_uac:send_invite(UAC, To), #sip_response{status = 200, reason = <<"Ok">>} = Response, % cancel the request ok = sip_simple_uac:cancel(UAC), wait until CANCEL is processed ok. @doc Verify that CANCEL on non - existent transaction returns status 481 %% @end cancel_481(Config) -> UAC = ?config(uac, Config), To = sip_headers:address(<<>>, <<"sip:127.0.0.1">>, []), Invite = sip_ua:create_request('INVITE', To), Cancel = sip_message:create_cancel(Invite), {ok, Response} = sip_simple_uac:send_request(UAC, Cancel), #sip_response{status = 481, reason = <<"Call/Transaction Does Not Exist">>} = Response, ok.
null
https://raw.githubusercontent.com/idubrov/siperl/251daf3a0d7c7442f56f42cfd6c92764a4f475a7/apps/sip/test/sip_ua_CANCEL_SUITE.erl
erlang
@end Exports Include files Common tests @end @end @end @end cancel the request @end
@author < > @doc CANCEL method tests . Note that implementation of ` CANCEL ' processing is in sip_simple_uas . 2011 - 2012 . See LICENSE file . -module(sip_ua_CANCEL_SUITE). -export([all/0, init_per_suite/1, end_per_suite/1, init_per_testcase/2, end_per_testcase/2]). -export([apply_fun/2]). -export([cancel_487/1, cancel_487_handler/2, cancel_481/1, cancel_200/1, cancel_200_handler/2]). -include_lib("common_test/include/ct.hrl"). -include("sip.hrl"). -define(HOST, "sip.example.org"). all() -> [cancel_487, cancel_481, cancel_200]. init_per_suite(Config) -> ok = application:start(gproc), ok = application:start(sip), ok = application:set_env(sip, self, ?HOST), Config. end_per_suite(_Config) -> ok = application:stop(sip), ok = application:stop(gproc), ok. init_per_testcase(TestCase, Config) -> Fun = list_to_atom(atom_to_list(TestCase) ++ "_handler"), {ok, UAC} = sip_simple_uac:start_link(), {ok, UAS} = sip_simple_uas:start_link(fun(Request, ReplyFun) -> ?MODULE:Fun(Request, ReplyFun) end), [{uac, UAC}, {uas, UAS} | Config]. end_per_testcase(_TestCase, Config) -> ok = sip_test:shutdown(?config(uac, Config)), ok = sip_test:shutdown(?config(uas, Config)), ok. apply_fun(Fun, Args) -> erlang:apply(Fun, Args). @doc The 200 response should be overriden by 487 Request Terminated cancel_487_handler(Request, ReplyFun) -> Response = sip_ua:create_response(Request, 200), Response2 = sip_message:append_header('content-type', <<"application/sdp">>, Response), timer:apply_after(2000, erlang, apply, [ReplyFun, [Response2]]), ok. @doc Verify that CANCEL on active INVITE requests forces INVITE to return status 487 cancel_487(Config) -> UAC = ?config(uac, Config), cancel the request after 500 milliseconds {ok, _TRef} = timer:apply_after(500, sip_simple_uac, cancel, [UAC]), To = sip_headers:address(<<>>, <<"sip:127.0.0.1">>, []), {ok, Response} = sip_simple_uac:send_invite(UAC, To), validate INVITE response status #sip_response{status = 487, reason = <<"Request Terminated">>} = Response, timer:sleep(5000), ok. @doc Do not reply on INVITE request ( it will be cancelled ) cancel_200_handler(#sip_request{method = 'INVITE'} = Request, ReplyFun) -> Response = sip_ua:create_response(Request, 200), Response2 = sip_message:append_header('content-type', <<"application/sdp">>, Response), ReplyFun(Response2), ok. @doc Verify that CANCEL on responded INVITE has no effect cancel_200(Config) -> UAC = ?config(uac, Config), send INVITE and receive response To = sip_headers:address(<<>>, <<"sip:127.0.0.1">>, []), {ok, Response} = sip_simple_uac:send_invite(UAC, To), #sip_response{status = 200, reason = <<"Ok">>} = Response, ok = sip_simple_uac:cancel(UAC), wait until CANCEL is processed ok. @doc Verify that CANCEL on non - existent transaction returns status 481 cancel_481(Config) -> UAC = ?config(uac, Config), To = sip_headers:address(<<>>, <<"sip:127.0.0.1">>, []), Invite = sip_ua:create_request('INVITE', To), Cancel = sip_message:create_cancel(Invite), {ok, Response} = sip_simple_uac:send_request(UAC, Cancel), #sip_response{status = 481, reason = <<"Call/Transaction Does Not Exist">>} = Response, ok.
186b2c86a37aff483b6a342ba93f85feef892d60dc8c8407bf0f1ddcaa2fc8ee
miraj-project/miraj
world.clj
(println "starting load of hello/world.clj") (miraj/co-ns hello.world "docstring here" (:main index) (:meta :description "Miraj Hello World demo" :title "Hello World!" ;; global attrs: #global-attributes ;; meta standard names: :application-name, :author, :description, :generator, :keywords ;; :charset; :itemprop? ;; extensions: ;; see ;; :viewport gets special treatment ;; e.g. :dc {:created ".." :creator "foo" ...} :application-name "hello-world" :apple {:mobile-capable :true :status-bar-style "black" :title "Hello" :touch-icon "images/touch/apple-touch-icon.png"} :msapplication {:navbutton-color "..." :tile-color "#3372DF" :tile-image "images/ms-touch-icon-144x144-precomposed.png"} :mobile-capable true :theme-color "#2E3AA1") (:base ..) #the-base-element : , : target (:aria ..) ;; link elts must have :rel and :href instead of rel="foo " href="bar " , we do { : foo " bar " } (:link {:author ""}) : first , : last , : prev , : next ( link rel vals ) (:icon {:sizes "192x192" :href="images/chrome-touch-icon-192x192.png"}) (:viewport ...) ;; :width, :height, initial-scale, minimum-scale, maximum-scale, user-scalable (:pragma ;; #pragma-directives ;; = http-equiv attrib on meta elt ;; standard: :content-language, :content-type, :default-style, :refresh, :set-cookie, :x - ua - compatible , : Content - Security - Policy extensions : ) (:polymer [polymer.paper :as paper :only [card]] [polymer.iron :as iron :only [flex-layout]] [polymer.font :as fnt :only [roboto]]) (:styles [hello.world :refer [core]]) ;; :refer or :use? or either? (:scripts [hello.world :refer [core]]) (:require [miraj :as miraj :refer :all] [miraj.html :as h] [miraj.http.response :refer [ok created]] [cheshire.core :as json :refer :all] [clojure.tools.logging :as log :only [trace debug error info]] [clojure.pprint :as pp] [clojure.string :as string])) (log/trace "loading") ;;(println (meta hello.world)) (miraj/co-fn index [] (h/div {:id "cards"} (paper/card (h/div {:class "card-content"} (h/div "Hello, world!" (h/br)(h/br) (h/span "Hoorah!")))))) ;; params ;; ^:? a = a is a required query/body param ;; ^:?? a = a is an optional query/body param ;; ^:meta uri = uri is a rqst meta-param, e.g. :uri (defn employee [lname fname mi ^:? status ^:?? foo] ; & remainder] (log/trace "employee " lname status fname) (ok (json/generate-string {:lname lname :fname fname :status status :foo foo}))) (defn f1 [lname fname mi ^:? status ^:?? foo] ; & remainder] (log/trace "f1 " lname status fname) (ok (json/generate-string {:fn :f1 :lname lname :fname fname :status status :foo foo}))) (defn f2 [lname fname mi ^:? status ^:?? foo] ; & remainder] (log/trace "f2 " lname status fname) (ok (json/generate-string {:fn :f2 :lname lname :fname fname :status status :foo foo}))) (defn f1! [^:? lname ^:? fname] (log/trace "f2 " lname fname) (created (json/generate-string {:fn :f1! :lname lname :fname fname}))) (defn f2! [foo ^:? lname ^:? fname] (log/trace "f2 " lname fname) (created (json/generate-string {:fn :f2! :foo foo :lname lname :fname fname}))) accepted 202 , non - authoritative - information 203 , no - content 204 (defn dump [] (ok (miraj/dump-dispatch-map)))
null
https://raw.githubusercontent.com/miraj-project/miraj/bf6f7d4d1c383ac9294dcdef2ad48b3863b6d84f/dev/gae/mod-main/src/main/clojure/hello/world.clj
clojure
global attrs: #global-attributes meta standard names: :application-name, :author, :description, :generator, :keywords :charset; :itemprop? extensions: see :viewport gets special treatment e.g. :dc {:created ".." :creator "foo" ...} link elts must have :rel and :href :width, :height, initial-scale, minimum-scale, maximum-scale, user-scalable #pragma-directives = http-equiv attrib on meta elt standard: :content-language, :content-type, :default-style, :refresh, :set-cookie, :refer or :use? or either? (println (meta hello.world)) params ^:? a = a is a required query/body param ^:?? a = a is an optional query/body param ^:meta uri = uri is a rqst meta-param, e.g. :uri & remainder] & remainder] & remainder]
(println "starting load of hello/world.clj") (miraj/co-ns hello.world "docstring here" (:main index) (:meta :description "Miraj Hello World demo" :title "Hello World!" :application-name "hello-world" :apple {:mobile-capable :true :status-bar-style "black" :title "Hello" :touch-icon "images/touch/apple-touch-icon.png"} :msapplication {:navbutton-color "..." :tile-color "#3372DF" :tile-image "images/ms-touch-icon-144x144-precomposed.png"} :mobile-capable true :theme-color "#2E3AA1") (:base ..) #the-base-element : , : target (:aria ..) instead of rel="foo " href="bar " , we do { : foo " bar " } (:link {:author ""}) : first , : last , : prev , : next ( link rel vals ) (:icon {:sizes "192x192" :href="images/chrome-touch-icon-192x192.png"}) :x - ua - compatible , : Content - Security - Policy extensions : ) (:polymer [polymer.paper :as paper :only [card]] [polymer.iron :as iron :only [flex-layout]] [polymer.font :as fnt :only [roboto]]) (:scripts [hello.world :refer [core]]) (:require [miraj :as miraj :refer :all] [miraj.html :as h] [miraj.http.response :refer [ok created]] [cheshire.core :as json :refer :all] [clojure.tools.logging :as log :only [trace debug error info]] [clojure.pprint :as pp] [clojure.string :as string])) (log/trace "loading") (miraj/co-fn index [] (h/div {:id "cards"} (paper/card (h/div {:class "card-content"} (h/div "Hello, world!" (h/br)(h/br) (h/span "Hoorah!")))))) (log/trace "employee " lname status fname) (ok (json/generate-string {:lname lname :fname fname :status status :foo foo}))) (log/trace "f1 " lname status fname) (ok (json/generate-string {:fn :f1 :lname lname :fname fname :status status :foo foo}))) (log/trace "f2 " lname status fname) (ok (json/generate-string {:fn :f2 :lname lname :fname fname :status status :foo foo}))) (defn f1! [^:? lname ^:? fname] (log/trace "f2 " lname fname) (created (json/generate-string {:fn :f1! :lname lname :fname fname}))) (defn f2! [foo ^:? lname ^:? fname] (log/trace "f2 " lname fname) (created (json/generate-string {:fn :f2! :foo foo :lname lname :fname fname}))) accepted 202 , non - authoritative - information 203 , no - content 204 (defn dump [] (ok (miraj/dump-dispatch-map)))
995788791257296cf092b9f1269dd5a15e2b4b8da01d56fd12b216ef0aa81dc4
soupi/yh
Types.hs
# LANGUAGE PatternSynonyms # module Play.Engine.Types where import qualified SDL.Vect as Vect import Control.Lens ----------- -- Types -- ----------- type Point a = Vect.V2 a type IPoint = Vect.V2 Int type FPoint = Vect.V2 Float type Size = Vect.V2 Int x :: Lens' (Vect.V2 a) a x = lens (\(Vect.V2 a _) -> a) (\(Vect.V2 _ b) a -> (Vect.V2 a b)) y :: Lens' (Vect.V2 a) a y = lens (\(Vect.V2 _ b) -> b) (\(Vect.V2 a _) b -> (Vect.V2 a b)) pattern Point :: a -> a -> Vect.V2 a pattern Point x' y' = Vect.V2 x' y' pointToTuple :: Point a -> (a, a) pointToTuple (Point !x' !y') = (x', y') sizeToTuple :: Size -> (Int, Int) sizeToTuple (Vect.V2 !w !h) = (w, h)
null
https://raw.githubusercontent.com/soupi/yh/4cfbcc7da6f3ca5e330b7fd7d4adeacee7e2dff4/src/Play/Engine/Types.hs
haskell
--------- Types -- ---------
# LANGUAGE PatternSynonyms # module Play.Engine.Types where import qualified SDL.Vect as Vect import Control.Lens type Point a = Vect.V2 a type IPoint = Vect.V2 Int type FPoint = Vect.V2 Float type Size = Vect.V2 Int x :: Lens' (Vect.V2 a) a x = lens (\(Vect.V2 a _) -> a) (\(Vect.V2 _ b) a -> (Vect.V2 a b)) y :: Lens' (Vect.V2 a) a y = lens (\(Vect.V2 _ b) -> b) (\(Vect.V2 a _) b -> (Vect.V2 a b)) pattern Point :: a -> a -> Vect.V2 a pattern Point x' y' = Vect.V2 x' y' pointToTuple :: Point a -> (a, a) pointToTuple (Point !x' !y') = (x', y') sizeToTuple :: Size -> (Int, Int) sizeToTuple (Vect.V2 !w !h) = (w, h)
63eecb7c8b2f0de98a5c46c72a9a513ae7abd968e41a378083597181c2e46f10
0x0f0f0f/yasih
Evaluator.hs
# LANGUAGE FlexibleContexts # module Yasih.Evaluator where import Yasih.LispTypes import Yasih.LispParser import Yasih.Environment import Yasih.Evaluator.Operators import Yasih.Evaluator.Numerical import Yasih.Evaluator.Char import Yasih.Evaluator.Strings import Yasih.Evaluator.Lists import Yasih.Evaluator.Bool import Yasih.Evaluator.Symbols import Yasih.Evaluator.Equivalence import Yasih.Evaluator.IO import Yasih.Evaluator.Vector import Yasih.Evaluator.Extension import Data.IORef import Data.Maybe import Control.Monad.Except -- |Evaluate expressions. Returns a monadic IOThrowsError value -- In Lisp, data types for both code and data are the same -- This means that this Evaluator returns a value of type IOThrowsError LispVal The val@ notation matches against any LispVal that corresponds To the specified constructor then binds it back into a LispVal The result has type LispVal instead of the matched Constructor eval :: Env -> LispVal -> IOThrowsError LispVal eval env val@(Number _) = return val eval env val@(Float _) = return val eval env val@(Ratio x) | x == 0 = return $ Number 0 | otherwise = return val eval env val@(Complex _) = return val eval env val@(String _) = return val eval env val@(Character _) = return val eval env val@(Bool _) = return val eval env val@(Vector _) = return val eval env (List [Atom "quote", val]) = return val -- Get a variable eval env (Atom id) = getVar env id -- Access the current lexical environment eval env (List [Atom "env"]) = do vars <- getVars env return $ List $ map toPair vars where toPair (var, val) = List [Atom var, val] -- | load a file and evaluate its contents. A special form -- is used because apply does not accept an env binding but -- statements in the loaded file can affect the top level environment eval env (List [Atom "load", String filename]) = do loadedFile <- loadHelper filename if null loadedFile then return $ List [] else (liftM last . mapM (eval env)) loadedFile -- Set a variable eval env (List [Atom "set!", Atom var, form]) = checkReserved var >> eval env form >>= setVar env var -- Define a variable eval env (List [Atom "define", Atom var, form]) = checkReserved var >> eval env form >>= defineVar env var -- Define a macro eval env (List (Atom "define-syntax" : List (Atom var : params) : body)) = makeMacro env params body >>= defineVar env var -- Evaluate quasiquotation. AKA macro expander. -- Recursively evaluate unquote forms, or just return the items if not unquoted eval env (List [Atom "quasiquote", form]) = evalUnquotes form where evalUnquotes form = case form of List [Atom "unquote", form] -> eval env form List items -> do results <- traverse evalUnquotes items return $ List results _ -> return form -- Define a function -- (define (f x y) (+ x y)) => (lamda ("x" "y") ...) eval env (List (Atom "define" : List (Atom var : params) : body)) = checkReserved var >> makeNormalFunc env params body >>= defineVar env var -- Define a variable argument function -- (define (func a b) c . body) eval env (List (Atom "define" : DottedList (Atom var : params) varargs : body)) = checkReserved var >> makeVarargs varargs env params body >>= defineVar env var -- λλλ Lambda functions! λλλ -- (lambda (a b c) (+ a b c)) eval env (List (Atom "lambda" : List params : body)) = makeNormalFunc env params body -- (lambda (a b c . d) body) eval env (List (Atom "lambda" : DottedList params varargs: body)) = makeVarargs varargs env params body -- (lambda args body) eval env (List (Atom "lambda" : varargs@(Atom _) : body)) = makeVarargs varargs env [] body -- If-clause. #f is false and any other value is considered true eval env (List [Atom "if", pred, conseq, alt]) = do result <- eval env pred -- Evaluate pred, if it is false eval alt, if true eval conseq case result of Bool False -> eval env alt Bool True -> eval env conseq badArg -> throwError $ TypeMismatch "boolean" badArg -- If-clause without an else eval env (List [Atom "if", pred, conseq]) = do result <- eval env pred -- Evaluate pred, if it is false eval alt, if true eval conseq case result of Bool False -> return $ List [] Bool True -> eval env conseq badArg -> throwError $ TypeMismatch "boolean" badArg cond clause : test each one of the alts clauses and eval the first -- which test evaluates to true, otherwise eval the 'else' clause Example : ( cond ( ( > 3 2 ) ' greater ) ( ( < 3 2 ) ' less ) ( else ' equal ) ) -- Evaluates to the atom greater. see eval env form@(List (Atom "cond" : clauses)) = if null clauses then throwError $ BadSpecialForm "No true clause in cond expression" form else case head clauses of List (Atom "else" : exprs) -> if null exprs then return $ List [] else mapM (eval env) exprs >>= liftThrows . return . last -- Piggy back the evaluation of the clauses on the already -- Existing if clause. List [test, expr] -> eval env $ List [Atom "if", test, expr, -- If test is not true, recurse the evaluation of -- cond on the remaining clauses List (Atom "cond" : tail clauses)] _ -> throwError $ BadSpecialForm "Ill-formed clause in cond expression" form -- case expression -- Evaluate a key expression and iterate over ((<datum1>, ...) expr) clauses -- To check if the key value appears at least once in the datums list. -- If so, evaluate that clause. -- Example: ( case ( * 2 3 ) ( ( 2 3 5 7 ) ' prime ) -- ((1 4 6 8 9) 'composite)) ===> composite eval env form@(List (Atom "case" : (key : clauses))) = if null clauses then throwError $ BadSpecialForm "No true clause in case expression" form else case head clauses of List (Atom "else" : exprs) -> if null exprs then return $ List [] else mapM (eval env) exprs >>= liftThrows . return . last List (List datums : exprs) -> do keyValue <- eval env key -- Evaluate the key Iterate over datums to check for an equal one equality <- mapM (\x -> liftThrows (eqv [keyValue, x])) datums if Bool True `elem` equality then if null exprs then return $ List [] else mapM (eval env) exprs >>= liftThrows . return . last else eval env $ List (Atom "case" : key : tail clauses) _ -> throwError $ BadSpecialForm "Ill-formed clause in case expression" form -- Function application clause -- Run eval recursively over args then apply func over the resulting list eval env (List (function : args)) = do func <- eval env function case func of Func {isMacro = True} -> apply func args >>= eval env _ -> mapM (eval env) args >>= apply func -- Bad form clause eval env badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm -- |Apply a function defined in a primitives table -- apply func args -- Look for func into the primitives table then return -- the corresponding function if found, otherwise throw an error apply :: LispVal -> [LispVal] -> IOThrowsError LispVal apply (PrimitiveFunc func) args = liftThrows $ func args apply (IOFunc func) args = func args apply (Func isMacro params varargs body closure) args -- Throw error if argument number is wrong | num params /= num args && isNothing varargs = throwError $ NumArgs (num params) args -- Bind arguments to a new env and execute statements -- Zip together parameter names and already evaluated args -- together into a list of pairs, then create -- a new environment for the function closure | otherwise = liftIO (bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalBody where remainingArgs = drop (length params) args num = toInteger . length -- Map the monadic function eval env over every statement in the func body evalBody env = liftM last $ mapM (eval env) body -- Bind variable argument list to env if present bindVarArgs arg env = case arg of Just argName -> liftIO $ bindVars env [(argName, List remainingArgs)] Nothing -> return env apply badForm args = throwError $ NotFunction "Not a function: " $ show badForm -- |Take an initial null environment, make name/value pairs and bind -- primitives into the new environment primitiveBindings :: IO Env primitiveBindings = nullEnv >>= flip bindVars (map (makeFunc IOFunc) Yasih.Evaluator.ioPrimitives ++ map (makeFunc PrimitiveFunc) primitives) where makeFunc constructor (var, func) = (var, constructor func) -- |Primitive functions table primitives :: [(String, [LispVal] -> ThrowsError LispVal)] primitives = numericalPrimitives ++ charPrimitives ++ stringPrimitives ++ boolPrimitives ++ symbolPrimitives ++ listPrimitives ++ equivalencePrimitives ++ extensionPrimitives ++ vectorPrimitives ioPrimitives :: [(String, [LispVal] -> IOThrowsError LispVal)] ioPrimitives = ("apply", applyProc) : Yasih.Evaluator.IO.ioPrimitives -- | Wrapper around apply responsible for destructuring the argument list -- into the form apply expects applyProc :: [LispVal] -> IOThrowsError LispVal applyProc [func, List args] = apply func args applyProc [func, DottedList args rest] = applyProc [func, List (args ++ [rest]) ] applyProc (func : args) = apply func args reservedKeywords = ["define", "load", "if", "cond", "case", "apply", "lambda", "set!"] checkReserved :: String -> IOThrowsError () checkReserved var | var `elem` reservedKeywords = throwError $ ReservedKeyword var | otherwise = case lookup var primitives of Just a -> throwError $ ReservedKeyword var Nothing -> return ()
null
https://raw.githubusercontent.com/0x0f0f0f/yasih/d7cedc4e5b4ea5c6c59d2799bbd37524969f2467/src/Yasih/Evaluator.hs
haskell
|Evaluate expressions. Returns a monadic IOThrowsError value In Lisp, data types for both code and data are the same This means that this Evaluator returns a value of type IOThrowsError LispVal Get a variable Access the current lexical environment | load a file and evaluate its contents. A special form is used because apply does not accept an env binding but statements in the loaded file can affect the top level environment Set a variable Define a variable Define a macro Evaluate quasiquotation. AKA macro expander. Recursively evaluate unquote forms, or just return the items if not unquoted Define a function (define (f x y) (+ x y)) => (lamda ("x" "y") ...) Define a variable argument function (define (func a b) c . body) λλλ Lambda functions! λλλ (lambda (a b c) (+ a b c)) (lambda (a b c . d) body) (lambda args body) If-clause. #f is false and any other value is considered true Evaluate pred, if it is false eval alt, if true eval conseq If-clause without an else Evaluate pred, if it is false eval alt, if true eval conseq which test evaluates to true, otherwise eval the 'else' clause Evaluates to the atom greater. Piggy back the evaluation of the clauses on the already Existing if clause. If test is not true, recurse the evaluation of cond on the remaining clauses case expression Evaluate a key expression and iterate over ((<datum1>, ...) expr) clauses To check if the key value appears at least once in the datums list. If so, evaluate that clause. Example: ((1 4 6 8 9) 'composite)) ===> composite Evaluate the key Function application clause Run eval recursively over args then apply func over the resulting list Bad form clause |Apply a function defined in a primitives table apply func args Look for func into the primitives table then return the corresponding function if found, otherwise throw an error Throw error if argument number is wrong Bind arguments to a new env and execute statements Zip together parameter names and already evaluated args together into a list of pairs, then create a new environment for the function closure Map the monadic function eval env over every statement in the func body Bind variable argument list to env if present |Take an initial null environment, make name/value pairs and bind primitives into the new environment |Primitive functions table | Wrapper around apply responsible for destructuring the argument list into the form apply expects
# LANGUAGE FlexibleContexts # module Yasih.Evaluator where import Yasih.LispTypes import Yasih.LispParser import Yasih.Environment import Yasih.Evaluator.Operators import Yasih.Evaluator.Numerical import Yasih.Evaluator.Char import Yasih.Evaluator.Strings import Yasih.Evaluator.Lists import Yasih.Evaluator.Bool import Yasih.Evaluator.Symbols import Yasih.Evaluator.Equivalence import Yasih.Evaluator.IO import Yasih.Evaluator.Vector import Yasih.Evaluator.Extension import Data.IORef import Data.Maybe import Control.Monad.Except The val@ notation matches against any LispVal that corresponds To the specified constructor then binds it back into a LispVal The result has type LispVal instead of the matched Constructor eval :: Env -> LispVal -> IOThrowsError LispVal eval env val@(Number _) = return val eval env val@(Float _) = return val eval env val@(Ratio x) | x == 0 = return $ Number 0 | otherwise = return val eval env val@(Complex _) = return val eval env val@(String _) = return val eval env val@(Character _) = return val eval env val@(Bool _) = return val eval env val@(Vector _) = return val eval env (List [Atom "quote", val]) = return val eval env (Atom id) = getVar env id eval env (List [Atom "env"]) = do vars <- getVars env return $ List $ map toPair vars where toPair (var, val) = List [Atom var, val] eval env (List [Atom "load", String filename]) = do loadedFile <- loadHelper filename if null loadedFile then return $ List [] else (liftM last . mapM (eval env)) loadedFile eval env (List [Atom "set!", Atom var, form]) = checkReserved var >> eval env form >>= setVar env var eval env (List [Atom "define", Atom var, form]) = checkReserved var >> eval env form >>= defineVar env var eval env (List (Atom "define-syntax" : List (Atom var : params) : body)) = makeMacro env params body >>= defineVar env var eval env (List [Atom "quasiquote", form]) = evalUnquotes form where evalUnquotes form = case form of List [Atom "unquote", form] -> eval env form List items -> do results <- traverse evalUnquotes items return $ List results _ -> return form eval env (List (Atom "define" : List (Atom var : params) : body)) = checkReserved var >> makeNormalFunc env params body >>= defineVar env var eval env (List (Atom "define" : DottedList (Atom var : params) varargs : body)) = checkReserved var >> makeVarargs varargs env params body >>= defineVar env var eval env (List (Atom "lambda" : List params : body)) = makeNormalFunc env params body eval env (List (Atom "lambda" : DottedList params varargs: body)) = makeVarargs varargs env params body eval env (List (Atom "lambda" : varargs@(Atom _) : body)) = makeVarargs varargs env [] body eval env (List [Atom "if", pred, conseq, alt]) = do result <- eval env pred case result of Bool False -> eval env alt Bool True -> eval env conseq badArg -> throwError $ TypeMismatch "boolean" badArg eval env (List [Atom "if", pred, conseq]) = do result <- eval env pred case result of Bool False -> return $ List [] Bool True -> eval env conseq badArg -> throwError $ TypeMismatch "boolean" badArg cond clause : test each one of the alts clauses and eval the first Example : ( cond ( ( > 3 2 ) ' greater ) ( ( < 3 2 ) ' less ) ( else ' equal ) ) see eval env form@(List (Atom "cond" : clauses)) = if null clauses then throwError $ BadSpecialForm "No true clause in cond expression" form else case head clauses of List (Atom "else" : exprs) -> if null exprs then return $ List [] else mapM (eval env) exprs >>= liftThrows . return . last List [test, expr] -> eval env $ List [Atom "if", test, expr, List (Atom "cond" : tail clauses)] _ -> throwError $ BadSpecialForm "Ill-formed clause in cond expression" form ( case ( * 2 3 ) ( ( 2 3 5 7 ) ' prime ) eval env form@(List (Atom "case" : (key : clauses))) = if null clauses then throwError $ BadSpecialForm "No true clause in case expression" form else case head clauses of List (Atom "else" : exprs) -> if null exprs then return $ List [] else mapM (eval env) exprs >>= liftThrows . return . last List (List datums : exprs) -> do Iterate over datums to check for an equal one equality <- mapM (\x -> liftThrows (eqv [keyValue, x])) datums if Bool True `elem` equality then if null exprs then return $ List [] else mapM (eval env) exprs >>= liftThrows . return . last else eval env $ List (Atom "case" : key : tail clauses) _ -> throwError $ BadSpecialForm "Ill-formed clause in case expression" form eval env (List (function : args)) = do func <- eval env function case func of Func {isMacro = True} -> apply func args >>= eval env _ -> mapM (eval env) args >>= apply func eval env badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm apply :: LispVal -> [LispVal] -> IOThrowsError LispVal apply (PrimitiveFunc func) args = liftThrows $ func args apply (IOFunc func) args = func args apply (Func isMacro params varargs body closure) args | num params /= num args && isNothing varargs = throwError $ NumArgs (num params) args | otherwise = liftIO (bindVars closure $ zip params args) >>= bindVarArgs varargs >>= evalBody where remainingArgs = drop (length params) args num = toInteger . length evalBody env = liftM last $ mapM (eval env) body bindVarArgs arg env = case arg of Just argName -> liftIO $ bindVars env [(argName, List remainingArgs)] Nothing -> return env apply badForm args = throwError $ NotFunction "Not a function: " $ show badForm primitiveBindings :: IO Env primitiveBindings = nullEnv >>= flip bindVars (map (makeFunc IOFunc) Yasih.Evaluator.ioPrimitives ++ map (makeFunc PrimitiveFunc) primitives) where makeFunc constructor (var, func) = (var, constructor func) primitives :: [(String, [LispVal] -> ThrowsError LispVal)] primitives = numericalPrimitives ++ charPrimitives ++ stringPrimitives ++ boolPrimitives ++ symbolPrimitives ++ listPrimitives ++ equivalencePrimitives ++ extensionPrimitives ++ vectorPrimitives ioPrimitives :: [(String, [LispVal] -> IOThrowsError LispVal)] ioPrimitives = ("apply", applyProc) : Yasih.Evaluator.IO.ioPrimitives applyProc :: [LispVal] -> IOThrowsError LispVal applyProc [func, List args] = apply func args applyProc [func, DottedList args rest] = applyProc [func, List (args ++ [rest]) ] applyProc (func : args) = apply func args reservedKeywords = ["define", "load", "if", "cond", "case", "apply", "lambda", "set!"] checkReserved :: String -> IOThrowsError () checkReserved var | var `elem` reservedKeywords = throwError $ ReservedKeyword var | otherwise = case lookup var primitives of Just a -> throwError $ ReservedKeyword var Nothing -> return ()
019556ee7ba2cda59312f2cd59d9cd5707f74aa17a9bfb366499f4961921c53f
elaforge/karya
Config.hs
Copyright 2015 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt -- | Calls that configure other calls. module Derive.C.Prelude.Config (library) where import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Map as Map import qualified Data.Set as Set import qualified Util.Maps as Maps import qualified Util.Seq as Seq import qualified Derive.Args as Args import qualified Derive.Call.Make as Make import qualified Derive.Call.Module as Module import qualified Derive.Call.Post as Post import qualified Derive.Call.Tags as Tags import qualified Derive.Controls as Controls import qualified Derive.Derive as Derive import qualified Derive.DeriveT as DeriveT import qualified Derive.Env as Env import qualified Derive.EnvKey as EnvKey import qualified Derive.Flags as Flags import qualified Derive.Library as Library import qualified Derive.PSignal as PSignal import qualified Derive.Score as Score import qualified Derive.ScoreT as ScoreT import qualified Derive.Sig as Sig import qualified Derive.Stream as Stream import qualified Derive.Typecheck as Typecheck import qualified Perform.Pitch as Pitch import qualified Perform.Signal as Signal import qualified Synth.Shared.Note as Note import Global library :: Library.Library library = mconcat [ Library.poly_transformers [("h", c_hold)] , Library.transformers [ ("add-flag", c_add_flag) , ("infer-dur", c_infer_dur) , ("initialize", c_initialize) ] ] c_add_flag :: Derive.Transformer Derive.Note c_add_flag = Derive.transformer Module.prelude "add-flag" Tags.postproc "Add the given flags to transformed events.\ \ Mostly for debugging and testing." $ Sig.callt (Sig.many1 "flag" "Add these flags.") $ \flags _args -> fmap $ Post.emap1_ $ Score.add_flags $ mconcatMap Flags.flag $ NonEmpty.toList flags c_hold :: Derive.Taggable d => Derive.Transformer d c_hold = Make.environ Module.prelude EnvKey.hold "'Derive.EnvKey.hold'" (Sig.defaulted "time" (Typecheck.real 0.25) "Hold this long.") Typecheck._real c_infer_dur :: Derive.Transformer Derive.Note c_infer_dur = Derive.transformer Module.prelude "infer-dur" Tags.postproc "Add 'Derive.Flags.infer_duration' to the events." $ Sig.call0t $ \_args -> fmap $ Post.emap1_ $ Score.add_flags Flags.infer_duration -- * initialize c_initialize :: Derive.Transformer Derive.Note c_initialize = Derive.transformer Module.prelude "initialize" mempty "Emit initialization controls for im instruments." $ Sig.callt ((,) <$> Sig.required "inst" "Instrument to initialize." <*> Sig.many_pairs "control,val" "(control, val) pairs.\ \ If the val is a list, expect the instrument to have that many\ \ elements, and set the control for each element." ) $ \(inst, pairs) args deriver -> do elements <- Derive.inst_elements . snd <$> Derive.get_instrument inst start <- Args.real_start args -- [(_, [Either _ Pitch])] -> [(_, [Either _ Transposed])] pairs <- (traverse . traverse . traverse . traverse) (Derive.resolve_pitch start) pairs element_controls <- Derive.require_right id $ parse_pairs (Set.toAscList elements) pairs let notes = map (uncurry (dummy_note inst)) (Map.toList element_controls) (Stream.from_events notes <>) <$> deriver dummy_note :: ScoreT.Instrument -> Note.Element -> Map ScoreT.Control Double -> Score.Event dummy_note inst element controls = Score.empty_event { Score.event_controls = make_val <$> Map.insert Controls.dynamic 0 (Map.delete pitch controls) , Score.event_pitch = case Map.lookup pitch controls of Nothing -> mempty Just nn -> PSignal.constant $ PSignal.nn_pitch (Pitch.nn nn) , Score.event_text = "faust initialize" , Score.event_instrument = inst , Score.event_environ = Env.from_list [(EnvKey.element, Typecheck.to_val element)] } where pitch = "pitch" make_val = ScoreT.untyped . Signal.constant parse_pairs :: [Note.Element] -> [(ScoreT.Control, [Either Double PSignal.Transposed])] -> Either Text (Map Note.Element (Map ScoreT.Control Double)) parse_pairs elements = fmap (fmap Map.fromList . Maps.multimap) . concatMapM parse where parse (_, []) = return [] parse (control, [val]) = do val <- resolve val return [(fromMaybe "" (Seq.head elements), (control, val))] parse (control, vals) | length vals /= length elements = Left $ showt (length vals) <> " values for " <> showt (length elements) <> " elements: " <> pretty vals <> " vs. " <> pretty elements | otherwise = do vals <- mapM resolve vals return $ zip elements (map (control,) vals) resolve (Left nn) = Right nn resolve (Right p) = bimap pretty Pitch.nn_to_double $ DeriveT.pitch_nn p
null
https://raw.githubusercontent.com/elaforge/karya/471a2131f5a68b3b10b1a138e6f9ed1282980a18/Derive/C/Prelude/Config.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt | Calls that configure other calls. * initialize [(_, [Either _ Pitch])] -> [(_, [Either _ Transposed])]
Copyright 2015 module Derive.C.Prelude.Config (library) where import qualified Data.List.NonEmpty as NonEmpty import qualified Data.Map as Map import qualified Data.Set as Set import qualified Util.Maps as Maps import qualified Util.Seq as Seq import qualified Derive.Args as Args import qualified Derive.Call.Make as Make import qualified Derive.Call.Module as Module import qualified Derive.Call.Post as Post import qualified Derive.Call.Tags as Tags import qualified Derive.Controls as Controls import qualified Derive.Derive as Derive import qualified Derive.DeriveT as DeriveT import qualified Derive.Env as Env import qualified Derive.EnvKey as EnvKey import qualified Derive.Flags as Flags import qualified Derive.Library as Library import qualified Derive.PSignal as PSignal import qualified Derive.Score as Score import qualified Derive.ScoreT as ScoreT import qualified Derive.Sig as Sig import qualified Derive.Stream as Stream import qualified Derive.Typecheck as Typecheck import qualified Perform.Pitch as Pitch import qualified Perform.Signal as Signal import qualified Synth.Shared.Note as Note import Global library :: Library.Library library = mconcat [ Library.poly_transformers [("h", c_hold)] , Library.transformers [ ("add-flag", c_add_flag) , ("infer-dur", c_infer_dur) , ("initialize", c_initialize) ] ] c_add_flag :: Derive.Transformer Derive.Note c_add_flag = Derive.transformer Module.prelude "add-flag" Tags.postproc "Add the given flags to transformed events.\ \ Mostly for debugging and testing." $ Sig.callt (Sig.many1 "flag" "Add these flags.") $ \flags _args -> fmap $ Post.emap1_ $ Score.add_flags $ mconcatMap Flags.flag $ NonEmpty.toList flags c_hold :: Derive.Taggable d => Derive.Transformer d c_hold = Make.environ Module.prelude EnvKey.hold "'Derive.EnvKey.hold'" (Sig.defaulted "time" (Typecheck.real 0.25) "Hold this long.") Typecheck._real c_infer_dur :: Derive.Transformer Derive.Note c_infer_dur = Derive.transformer Module.prelude "infer-dur" Tags.postproc "Add 'Derive.Flags.infer_duration' to the events." $ Sig.call0t $ \_args -> fmap $ Post.emap1_ $ Score.add_flags Flags.infer_duration c_initialize :: Derive.Transformer Derive.Note c_initialize = Derive.transformer Module.prelude "initialize" mempty "Emit initialization controls for im instruments." $ Sig.callt ((,) <$> Sig.required "inst" "Instrument to initialize." <*> Sig.many_pairs "control,val" "(control, val) pairs.\ \ If the val is a list, expect the instrument to have that many\ \ elements, and set the control for each element." ) $ \(inst, pairs) args deriver -> do elements <- Derive.inst_elements . snd <$> Derive.get_instrument inst start <- Args.real_start args pairs <- (traverse . traverse . traverse . traverse) (Derive.resolve_pitch start) pairs element_controls <- Derive.require_right id $ parse_pairs (Set.toAscList elements) pairs let notes = map (uncurry (dummy_note inst)) (Map.toList element_controls) (Stream.from_events notes <>) <$> deriver dummy_note :: ScoreT.Instrument -> Note.Element -> Map ScoreT.Control Double -> Score.Event dummy_note inst element controls = Score.empty_event { Score.event_controls = make_val <$> Map.insert Controls.dynamic 0 (Map.delete pitch controls) , Score.event_pitch = case Map.lookup pitch controls of Nothing -> mempty Just nn -> PSignal.constant $ PSignal.nn_pitch (Pitch.nn nn) , Score.event_text = "faust initialize" , Score.event_instrument = inst , Score.event_environ = Env.from_list [(EnvKey.element, Typecheck.to_val element)] } where pitch = "pitch" make_val = ScoreT.untyped . Signal.constant parse_pairs :: [Note.Element] -> [(ScoreT.Control, [Either Double PSignal.Transposed])] -> Either Text (Map Note.Element (Map ScoreT.Control Double)) parse_pairs elements = fmap (fmap Map.fromList . Maps.multimap) . concatMapM parse where parse (_, []) = return [] parse (control, [val]) = do val <- resolve val return [(fromMaybe "" (Seq.head elements), (control, val))] parse (control, vals) | length vals /= length elements = Left $ showt (length vals) <> " values for " <> showt (length elements) <> " elements: " <> pretty vals <> " vs. " <> pretty elements | otherwise = do vals <- mapM resolve vals return $ zip elements (map (control,) vals) resolve (Left nn) = Right nn resolve (Right p) = bimap pretty Pitch.nn_to_double $ DeriveT.pitch_nn p
3876f3cc83321ae43c848afa7cb80b47413e2ed25ca4bbc7c8c89a98bd7e029d
SimulaVR/godot-haskell
AStar.hs
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.AStar (Godot.Core.AStar._compute_cost, Godot.Core.AStar._estimate_cost, Godot.Core.AStar.add_point, Godot.Core.AStar.are_points_connected, Godot.Core.AStar.clear, Godot.Core.AStar.connect_points, Godot.Core.AStar.disconnect_points, Godot.Core.AStar.get_available_point_id, Godot.Core.AStar.get_closest_point, Godot.Core.AStar.get_closest_position_in_segment, Godot.Core.AStar.get_id_path, Godot.Core.AStar.get_point_capacity, Godot.Core.AStar.get_point_connections, Godot.Core.AStar.get_point_count, Godot.Core.AStar.get_point_path, Godot.Core.AStar.get_point_position, Godot.Core.AStar.get_point_weight_scale, Godot.Core.AStar.get_points, Godot.Core.AStar.has_point, Godot.Core.AStar.is_point_disabled, Godot.Core.AStar.remove_point, Godot.Core.AStar.reserve_space, Godot.Core.AStar.set_point_disabled, Godot.Core.AStar.set_point_position, Godot.Core.AStar.set_point_weight_scale) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Reference() # NOINLINE bindAStar__compute_cost # | Called when computing the cost between two connected points . Note that this function is hidden in the default @AStar@ class . bindAStar__compute_cost :: MethodBind bindAStar__compute_cost = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "_compute_cost" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Called when computing the cost between two connected points . Note that this function is hidden in the default @AStar@ class . _compute_cost :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> IO Float _compute_cost cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar__compute_cost (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "_compute_cost" '[Int, Int] (IO Float) where nodeMethod = Godot.Core.AStar._compute_cost {-# NOINLINE bindAStar__estimate_cost #-} -- | Called when estimating the cost between a point and the path's ending point. Note that this function is hidden in the default @AStar@ class . bindAStar__estimate_cost :: MethodBind bindAStar__estimate_cost = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "_estimate_cost" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Called when estimating the cost between a point and the path's ending point. Note that this function is hidden in the default @AStar@ class . _estimate_cost :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> IO Float _estimate_cost cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar__estimate_cost (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "_estimate_cost" '[Int, Int] (IO Float) where nodeMethod = Godot.Core.AStar._estimate_cost # NOINLINE bindAStar_add_point # | Adds a new point at the given position with the given identifier . The algorithm prefers points with lower @weight_scale@ to form a path . The @id@ must be 0 or larger , and the @weight_scale@ must be 1 or larger . -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(1 , 0 , 0 ) , 4 ) # Adds the point ( 1 , 0 , 0 ) with weight_scale 4 and i d 1 -- -- @ -- -- If there already exists a point for the given @id@, its position and weight scale are updated to the given values. bindAStar_add_point :: MethodBind bindAStar_add_point = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "add_point" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a new point at the given position with the given identifier . The algorithm prefers points with lower @weight_scale@ to form a path . The @id@ must be 0 or larger , and the @weight_scale@ must be 1 or larger . -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(1 , 0 , 0 ) , 4 ) # Adds the point ( 1 , 0 , 0 ) with weight_scale 4 and i d 1 -- -- @ -- -- If there already exists a point for the given @id@, its position and weight scale are updated to the given values. add_point :: (AStar :< cls, Object :< cls) => cls -> Int -> Vector3 -> Maybe Float -> IO () add_point cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, maybe (VariantReal (1)) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_add_point (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "add_point" '[Int, Vector3, Maybe Float] (IO ()) where nodeMethod = Godot.Core.AStar.add_point # NOINLINE bindAStar_are_points_connected # | Returns whether the two given points are directly connected by a segment . If @bidirectional@ is @false@ , returns whether movement from @id@ to @to_id@ is possible through this segment . bindAStar_are_points_connected :: MethodBind bindAStar_are_points_connected = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "are_points_connected" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns whether the two given points are directly connected by a segment . If @bidirectional@ is @false@ , returns whether movement from @id@ to @to_id@ is possible through this segment . are_points_connected :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> Maybe Bool -> IO Bool are_points_connected cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, maybe (VariantBool True) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_are_points_connected (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "are_points_connected" '[Int, Int, Maybe Bool] (IO Bool) where nodeMethod = Godot.Core.AStar.are_points_connected # NOINLINE bindAStar_clear # -- | Clears all the points and segments. bindAStar_clear :: MethodBind bindAStar_clear = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "clear" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Clears all the points and segments. clear :: (AStar :< cls, Object :< cls) => cls -> IO () clear cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_clear (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "clear" '[] (IO ()) where nodeMethod = Godot.Core.AStar.clear {-# NOINLINE bindAStar_connect_points #-} -- | Creates a segment between the given points. If @bidirectional@ is @false@, only movement from @id@ to @to_id@ is allowed, not the reverse direction. -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(1 , 1 , 0 ) ) astar.add_point(2 , Vector3(0 , 5 , 0 ) ) astar.connect_points(1 , 2 , false ) -- -- @ bindAStar_connect_points :: MethodBind bindAStar_connect_points = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "connect_points" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Creates a segment between the given points. If @bidirectional@ is @false@, only movement from @id@ to @to_id@ is allowed, not the reverse direction. -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(1 , 1 , 0 ) ) astar.add_point(2 , Vector3(0 , 5 , 0 ) ) astar.connect_points(1 , 2 , false ) -- -- @ connect_points :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> Maybe Bool -> IO () connect_points cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, maybe (VariantBool True) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_connect_points (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "connect_points" '[Int, Int, Maybe Bool] (IO ()) where nodeMethod = Godot.Core.AStar.connect_points # NOINLINE bindAStar_disconnect_points # -- | Deletes the segment between the given points. If @bidirectional@ is @false@, only movement from @id@ to @to_id@ is prevented, and a unidirectional segment possibly remains. bindAStar_disconnect_points :: MethodBind bindAStar_disconnect_points = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "disconnect_points" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Deletes the segment between the given points. If @bidirectional@ is @false@, only movement from @id@ to @to_id@ is prevented, and a unidirectional segment possibly remains. disconnect_points :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> Maybe Bool -> IO () disconnect_points cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, maybe (VariantBool True) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_disconnect_points (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "disconnect_points" '[Int, Int, Maybe Bool] (IO ()) where nodeMethod = Godot.Core.AStar.disconnect_points # NOINLINE bindAStar_get_available_point_id # -- | Returns the next available point ID with no point associated to it. bindAStar_get_available_point_id :: MethodBind bindAStar_get_available_point_id = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_available_point_id" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns the next available point ID with no point associated to it. get_available_point_id :: (AStar :< cls, Object :< cls) => cls -> IO Int get_available_point_id cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_available_point_id (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_available_point_id" '[] (IO Int) where nodeMethod = Godot.Core.AStar.get_available_point_id # NOINLINE bindAStar_get_closest_point # -- | Returns the ID of the closest point to @to_position@, optionally taking disabled points into account. Returns @-1@ if there are no points in the points pool. -- __Note:__ If several points are the closest to @to_position@, the one with the smallest ID will be returned, ensuring a deterministic result. bindAStar_get_closest_point :: MethodBind bindAStar_get_closest_point = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_closest_point" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns the ID of the closest point to @to_position@, optionally taking disabled points into account. Returns @-1@ if there are no points in the points pool. -- __Note:__ If several points are the closest to @to_position@, the one with the smallest ID will be returned, ensuring a deterministic result. get_closest_point :: (AStar :< cls, Object :< cls) => cls -> Vector3 -> Maybe Bool -> IO Int get_closest_point cls arg1 arg2 = withVariantArray [toVariant arg1, maybe (VariantBool False) toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_closest_point (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_closest_point" '[Vector3, Maybe Bool] (IO Int) where nodeMethod = Godot.Core.AStar.get_closest_point # NOINLINE bindAStar_get_closest_position_in_segment # | Returns the closest position to @to_position@ that resides inside a segment between two connected points . -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 5 , 0 ) ) astar.connect_points(1 , 2 ) var res = astar.get_closest_position_in_segment(Vector3(3 , 3 , 0 ) ) # Returns ( 0 , 3 , 0 ) -- -- @ -- The result is in the segment that goes from @y = 0@ to @y = 5@. It 's the closest position in the segment to the given point . bindAStar_get_closest_position_in_segment :: MethodBind bindAStar_get_closest_position_in_segment = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_closest_position_in_segment" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the closest position to @to_position@ that resides inside a segment between two connected points . -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 5 , 0 ) ) astar.connect_points(1 , 2 ) var res = astar.get_closest_position_in_segment(Vector3(3 , 3 , 0 ) ) # Returns ( 0 , 3 , 0 ) -- -- @ -- The result is in the segment that goes from @y = 0@ to @y = 5@. It 's the closest position in the segment to the given point . get_closest_position_in_segment :: (AStar :< cls, Object :< cls) => cls -> Vector3 -> IO Vector3 get_closest_position_in_segment cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_closest_position_in_segment (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_closest_position_in_segment" '[Vector3] (IO Vector3) where nodeMethod = Godot.Core.AStar.get_closest_position_in_segment # NOINLINE bindAStar_get_id_path # -- | Returns an array with the IDs of the points that form the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path. -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 1 , 0 ) , 1 ) # Default weight is 1 astar.add_point(3 , Vector3(1 , 1 , 0 ) ) astar.add_point(4 , Vector3(2 , 0 , 0 ) ) -- astar.connect_points(1 , 2 , false ) astar.connect_points(2 , 3 , false ) astar.connect_points(4 , 3 , false ) astar.connect_points(1 , 4 , false ) -- var res = astar.get_id_path(1 , 3 ) # Returns @1 , 2 , 3@ -- -- @ -- If you change the 2nd point 's weight to 3 , then the result will be @@1 , 4 , 3@@ instead , because now even though the distance is longer , it 's " easier " to get through point 4 than through point 2 . bindAStar_get_id_path :: MethodBind bindAStar_get_id_path = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_id_path" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns an array with the IDs of the points that form the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path. -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 1 , 0 ) , 1 ) # Default weight is 1 astar.add_point(3 , Vector3(1 , 1 , 0 ) ) astar.add_point(4 , Vector3(2 , 0 , 0 ) ) -- astar.connect_points(1 , 2 , false ) astar.connect_points(2 , 3 , false ) astar.connect_points(4 , 3 , false ) astar.connect_points(1 , 4 , false ) -- var res = astar.get_id_path(1 , 3 ) # Returns @1 , 2 , 3@ -- -- @ -- If you change the 2nd point 's weight to 3 , then the result will be @@1 , 4 , 3@@ instead , because now even though the distance is longer , it 's " easier " to get through point 4 than through point 2 . get_id_path :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> IO PoolIntArray get_id_path cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_id_path (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_id_path" '[Int, Int] (IO PoolIntArray) where nodeMethod = Godot.Core.AStar.get_id_path # NOINLINE bindAStar_get_point_capacity # -- | Returns the capacity of the structure backing the points, useful in conjunction with @reserve_space@. bindAStar_get_point_capacity :: MethodBind bindAStar_get_point_capacity = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_capacity" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns the capacity of the structure backing the points, useful in conjunction with @reserve_space@. get_point_capacity :: (AStar :< cls, Object :< cls) => cls -> IO Int get_point_capacity cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_capacity (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_capacity" '[] (IO Int) where nodeMethod = Godot.Core.AStar.get_point_capacity # NOINLINE bindAStar_get_point_connections # -- | Returns an array with the IDs of the points that form the connection with the given point. -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 1 , 0 ) ) astar.add_point(3 , Vector3(1 , 1 , 0 ) ) astar.add_point(4 , Vector3(2 , 0 , 0 ) ) -- astar.connect_points(1 , 2 , true ) astar.connect_points(1 , 3 , true ) -- var neighbors = astar.get_point_connections(1 ) # Returns @2 , 3@ -- -- @ bindAStar_get_point_connections :: MethodBind bindAStar_get_point_connections = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_connections" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns an array with the IDs of the points that form the connection with the given point. -- -- @ -- var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 1 , 0 ) ) astar.add_point(3 , Vector3(1 , 1 , 0 ) ) astar.add_point(4 , Vector3(2 , 0 , 0 ) ) -- astar.connect_points(1 , 2 , true ) astar.connect_points(1 , 3 , true ) -- var neighbors = astar.get_point_connections(1 ) # Returns @2 , 3@ -- -- @ get_point_connections :: (AStar :< cls, Object :< cls) => cls -> Int -> IO PoolIntArray get_point_connections cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_connections (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_connections" '[Int] (IO PoolIntArray) where nodeMethod = Godot.Core.AStar.get_point_connections # NOINLINE bindAStar_get_point_count # -- | Returns the number of points currently in the points pool. bindAStar_get_point_count :: MethodBind bindAStar_get_point_count = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns the number of points currently in the points pool. get_point_count :: (AStar :< cls, Object :< cls) => cls -> IO Int get_point_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_count" '[] (IO Int) where nodeMethod = Godot.Core.AStar.get_point_count # NOINLINE bindAStar_get_point_path # -- | Returns an array with the points that are in the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path. bindAStar_get_point_path :: MethodBind bindAStar_get_point_path = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_path" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns an array with the points that are in the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path. get_point_path :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> IO PoolVector3Array get_point_path cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_path (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_path" '[Int, Int] (IO PoolVector3Array) where nodeMethod = Godot.Core.AStar.get_point_path # NOINLINE bindAStar_get_point_position # | Returns the position of the point associated with the given bindAStar_get_point_position :: MethodBind bindAStar_get_point_position = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_position" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the position of the point associated with the given get_point_position :: (AStar :< cls, Object :< cls) => cls -> Int -> IO Vector3 get_point_position cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_position (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_position" '[Int] (IO Vector3) where nodeMethod = Godot.Core.AStar.get_point_position # NOINLINE bindAStar_get_point_weight_scale # | Returns the weight scale of the point associated with the given bindAStar_get_point_weight_scale :: MethodBind bindAStar_get_point_weight_scale = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_weight_scale" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the weight scale of the point associated with the given get_point_weight_scale :: (AStar :< cls, Object :< cls) => cls -> Int -> IO Float get_point_weight_scale cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_weight_scale (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_weight_scale" '[Int] (IO Float) where nodeMethod = Godot.Core.AStar.get_point_weight_scale # NOINLINE bindAStar_get_points # -- | Returns an array of all points. bindAStar_get_points :: MethodBind bindAStar_get_points = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_points" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns an array of all points. get_points :: (AStar :< cls, Object :< cls) => cls -> IO Array get_points cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_points (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_points" '[] (IO Array) where nodeMethod = Godot.Core.AStar.get_points # NOINLINE bindAStar_has_point # -- | Returns whether a point associated with the given @id@ exists. bindAStar_has_point :: MethodBind bindAStar_has_point = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "has_point" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns whether a point associated with the given @id@ exists. has_point :: (AStar :< cls, Object :< cls) => cls -> Int -> IO Bool has_point cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_has_point (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "has_point" '[Int] (IO Bool) where nodeMethod = Godot.Core.AStar.has_point # NOINLINE bindAStar_is_point_disabled # -- | Returns whether a point is disabled or not for pathfinding. By default, all points are enabled. bindAStar_is_point_disabled :: MethodBind bindAStar_is_point_disabled = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "is_point_disabled" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Returns whether a point is disabled or not for pathfinding. By default, all points are enabled. is_point_disabled :: (AStar :< cls, Object :< cls) => cls -> Int -> IO Bool is_point_disabled cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_is_point_disabled (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "is_point_disabled" '[Int] (IO Bool) where nodeMethod = Godot.Core.AStar.is_point_disabled # NOINLINE bindAStar_remove_point # -- | Removes the point associated with the given @id@ from the points pool. bindAStar_remove_point :: MethodBind bindAStar_remove_point = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "remove_point" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Removes the point associated with the given @id@ from the points pool. remove_point :: (AStar :< cls, Object :< cls) => cls -> Int -> IO () remove_point cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_remove_point (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "remove_point" '[Int] (IO ()) where nodeMethod = Godot.Core.AStar.remove_point # NOINLINE bindAStar_reserve_space # -- | Reserves space internally for @num_nodes@ points, useful if you're adding a known large number of points at once, for a grid for instance. New capacity must be greater or equals to old capacity. bindAStar_reserve_space :: MethodBind bindAStar_reserve_space = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "reserve_space" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Reserves space internally for @num_nodes@ points, useful if you're adding a known large number of points at once, for a grid for instance. New capacity must be greater or equals to old capacity. reserve_space :: (AStar :< cls, Object :< cls) => cls -> Int -> IO () reserve_space cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_reserve_space (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "reserve_space" '[Int] (IO ()) where nodeMethod = Godot.Core.AStar.reserve_space # NOINLINE bindAStar_set_point_disabled # -- | Disables or enables the specified point for pathfinding. Useful for making a temporary obstacle. bindAStar_set_point_disabled :: MethodBind bindAStar_set_point_disabled = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "set_point_disabled" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr -- | Disables or enables the specified point for pathfinding. Useful for making a temporary obstacle. set_point_disabled :: (AStar :< cls, Object :< cls) => cls -> Int -> Maybe Bool -> IO () set_point_disabled cls arg1 arg2 = withVariantArray [toVariant arg1, maybe (VariantBool True) toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_set_point_disabled (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "set_point_disabled" '[Int, Maybe Bool] (IO ()) where nodeMethod = Godot.Core.AStar.set_point_disabled # NOINLINE bindAStar_set_point_position # | Sets the @position@ for the point with the given bindAStar_set_point_position :: MethodBind bindAStar_set_point_position = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "set_point_position" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Sets the @position@ for the point with the given set_point_position :: (AStar :< cls, Object :< cls) => cls -> Int -> Vector3 -> IO () set_point_position cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_set_point_position (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "set_point_position" '[Int, Vector3] (IO ()) where nodeMethod = Godot.Core.AStar.set_point_position # NOINLINE bindAStar_set_point_weight_scale # | Sets the @weight_scale@ for the point with the given bindAStar_set_point_weight_scale :: MethodBind bindAStar_set_point_weight_scale = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "set_point_weight_scale" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Sets the @weight_scale@ for the point with the given set_point_weight_scale :: (AStar :< cls, Object :< cls) => cls -> Int -> Float -> IO () set_point_weight_scale cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_set_point_weight_scale (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "set_point_weight_scale" '[Int, Float] (IO ()) where nodeMethod = Godot.Core.AStar.set_point_weight_scale
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/AStar.hs
haskell
# NOINLINE bindAStar__estimate_cost # | Called when estimating the cost between a point and the path's ending point. | Called when estimating the cost between a point and the path's ending point. @ @ If there already exists a point for the given @id@, its position and weight scale are updated to the given values. @ @ If there already exists a point for the given @id@, its position and weight scale are updated to the given values. | Clears all the points and segments. | Clears all the points and segments. # NOINLINE bindAStar_connect_points # | Creates a segment between the given points. If @bidirectional@ is @false@, only movement from @id@ to @to_id@ is allowed, not the reverse direction. @ @ | Creates a segment between the given points. If @bidirectional@ is @false@, only movement from @id@ to @to_id@ is allowed, not the reverse direction. @ @ | Deletes the segment between the given points. If @bidirectional@ is @false@, only movement from @id@ to @to_id@ is prevented, and a unidirectional segment possibly remains. | Deletes the segment between the given points. If @bidirectional@ is @false@, only movement from @id@ to @to_id@ is prevented, and a unidirectional segment possibly remains. | Returns the next available point ID with no point associated to it. | Returns the next available point ID with no point associated to it. | Returns the ID of the closest point to @to_position@, optionally taking disabled points into account. Returns @-1@ if there are no points in the points pool. __Note:__ If several points are the closest to @to_position@, the one with the smallest ID will be returned, ensuring a deterministic result. | Returns the ID of the closest point to @to_position@, optionally taking disabled points into account. Returns @-1@ if there are no points in the points pool. __Note:__ If several points are the closest to @to_position@, the one with the smallest ID will be returned, ensuring a deterministic result. @ @ @ @ | Returns an array with the IDs of the points that form the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path. @ @ | Returns an array with the IDs of the points that form the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path. @ @ | Returns the capacity of the structure backing the points, useful in conjunction with @reserve_space@. | Returns the capacity of the structure backing the points, useful in conjunction with @reserve_space@. | Returns an array with the IDs of the points that form the connection with the given point. @ @ | Returns an array with the IDs of the points that form the connection with the given point. @ @ | Returns the number of points currently in the points pool. | Returns the number of points currently in the points pool. | Returns an array with the points that are in the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path. | Returns an array with the points that are in the path found by AStar between the given points. The array is ordered from the starting point to the ending point of the path. | Returns an array of all points. | Returns an array of all points. | Returns whether a point associated with the given @id@ exists. | Returns whether a point associated with the given @id@ exists. | Returns whether a point is disabled or not for pathfinding. By default, all points are enabled. | Returns whether a point is disabled or not for pathfinding. By default, all points are enabled. | Removes the point associated with the given @id@ from the points pool. | Removes the point associated with the given @id@ from the points pool. | Reserves space internally for @num_nodes@ points, useful if you're adding a known large number of points at once, for a grid for instance. New capacity must be greater or equals to old capacity. | Reserves space internally for @num_nodes@ points, useful if you're adding a known large number of points at once, for a grid for instance. New capacity must be greater or equals to old capacity. | Disables or enables the specified point for pathfinding. Useful for making a temporary obstacle. | Disables or enables the specified point for pathfinding. Useful for making a temporary obstacle.
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.AStar (Godot.Core.AStar._compute_cost, Godot.Core.AStar._estimate_cost, Godot.Core.AStar.add_point, Godot.Core.AStar.are_points_connected, Godot.Core.AStar.clear, Godot.Core.AStar.connect_points, Godot.Core.AStar.disconnect_points, Godot.Core.AStar.get_available_point_id, Godot.Core.AStar.get_closest_point, Godot.Core.AStar.get_closest_position_in_segment, Godot.Core.AStar.get_id_path, Godot.Core.AStar.get_point_capacity, Godot.Core.AStar.get_point_connections, Godot.Core.AStar.get_point_count, Godot.Core.AStar.get_point_path, Godot.Core.AStar.get_point_position, Godot.Core.AStar.get_point_weight_scale, Godot.Core.AStar.get_points, Godot.Core.AStar.has_point, Godot.Core.AStar.is_point_disabled, Godot.Core.AStar.remove_point, Godot.Core.AStar.reserve_space, Godot.Core.AStar.set_point_disabled, Godot.Core.AStar.set_point_position, Godot.Core.AStar.set_point_weight_scale) where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Reference() # NOINLINE bindAStar__compute_cost # | Called when computing the cost between two connected points . Note that this function is hidden in the default @AStar@ class . bindAStar__compute_cost :: MethodBind bindAStar__compute_cost = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "_compute_cost" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Called when computing the cost between two connected points . Note that this function is hidden in the default @AStar@ class . _compute_cost :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> IO Float _compute_cost cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar__compute_cost (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "_compute_cost" '[Int, Int] (IO Float) where nodeMethod = Godot.Core.AStar._compute_cost Note that this function is hidden in the default @AStar@ class . bindAStar__estimate_cost :: MethodBind bindAStar__estimate_cost = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "_estimate_cost" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr Note that this function is hidden in the default @AStar@ class . _estimate_cost :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> IO Float _estimate_cost cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar__estimate_cost (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "_estimate_cost" '[Int, Int] (IO Float) where nodeMethod = Godot.Core.AStar._estimate_cost # NOINLINE bindAStar_add_point # | Adds a new point at the given position with the given identifier . The algorithm prefers points with lower @weight_scale@ to form a path . The @id@ must be 0 or larger , and the @weight_scale@ must be 1 or larger . var astar = ( ) astar.add_point(1 , Vector3(1 , 0 , 0 ) , 4 ) # Adds the point ( 1 , 0 , 0 ) with weight_scale 4 and i d 1 bindAStar_add_point :: MethodBind bindAStar_add_point = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "add_point" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Adds a new point at the given position with the given identifier . The algorithm prefers points with lower @weight_scale@ to form a path . The @id@ must be 0 or larger , and the @weight_scale@ must be 1 or larger . var astar = ( ) astar.add_point(1 , Vector3(1 , 0 , 0 ) , 4 ) # Adds the point ( 1 , 0 , 0 ) with weight_scale 4 and i d 1 add_point :: (AStar :< cls, Object :< cls) => cls -> Int -> Vector3 -> Maybe Float -> IO () add_point cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, maybe (VariantReal (1)) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_add_point (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "add_point" '[Int, Vector3, Maybe Float] (IO ()) where nodeMethod = Godot.Core.AStar.add_point # NOINLINE bindAStar_are_points_connected # | Returns whether the two given points are directly connected by a segment . If @bidirectional@ is @false@ , returns whether movement from @id@ to @to_id@ is possible through this segment . bindAStar_are_points_connected :: MethodBind bindAStar_are_points_connected = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "are_points_connected" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns whether the two given points are directly connected by a segment . If @bidirectional@ is @false@ , returns whether movement from @id@ to @to_id@ is possible through this segment . are_points_connected :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> Maybe Bool -> IO Bool are_points_connected cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, maybe (VariantBool True) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_are_points_connected (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "are_points_connected" '[Int, Int, Maybe Bool] (IO Bool) where nodeMethod = Godot.Core.AStar.are_points_connected # NOINLINE bindAStar_clear # bindAStar_clear :: MethodBind bindAStar_clear = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "clear" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr clear :: (AStar :< cls, Object :< cls) => cls -> IO () clear cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_clear (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "clear" '[] (IO ()) where nodeMethod = Godot.Core.AStar.clear var astar = ( ) astar.add_point(1 , Vector3(1 , 1 , 0 ) ) astar.add_point(2 , Vector3(0 , 5 , 0 ) ) astar.connect_points(1 , 2 , false ) bindAStar_connect_points :: MethodBind bindAStar_connect_points = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "connect_points" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr var astar = ( ) astar.add_point(1 , Vector3(1 , 1 , 0 ) ) astar.add_point(2 , Vector3(0 , 5 , 0 ) ) astar.connect_points(1 , 2 , false ) connect_points :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> Maybe Bool -> IO () connect_points cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, maybe (VariantBool True) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_connect_points (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "connect_points" '[Int, Int, Maybe Bool] (IO ()) where nodeMethod = Godot.Core.AStar.connect_points # NOINLINE bindAStar_disconnect_points # bindAStar_disconnect_points :: MethodBind bindAStar_disconnect_points = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "disconnect_points" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr disconnect_points :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> Maybe Bool -> IO () disconnect_points cls arg1 arg2 arg3 = withVariantArray [toVariant arg1, toVariant arg2, maybe (VariantBool True) toVariant arg3] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_disconnect_points (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "disconnect_points" '[Int, Int, Maybe Bool] (IO ()) where nodeMethod = Godot.Core.AStar.disconnect_points # NOINLINE bindAStar_get_available_point_id # bindAStar_get_available_point_id :: MethodBind bindAStar_get_available_point_id = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_available_point_id" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_available_point_id :: (AStar :< cls, Object :< cls) => cls -> IO Int get_available_point_id cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_available_point_id (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_available_point_id" '[] (IO Int) where nodeMethod = Godot.Core.AStar.get_available_point_id # NOINLINE bindAStar_get_closest_point # bindAStar_get_closest_point :: MethodBind bindAStar_get_closest_point = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_closest_point" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_closest_point :: (AStar :< cls, Object :< cls) => cls -> Vector3 -> Maybe Bool -> IO Int get_closest_point cls arg1 arg2 = withVariantArray [toVariant arg1, maybe (VariantBool False) toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_closest_point (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_closest_point" '[Vector3, Maybe Bool] (IO Int) where nodeMethod = Godot.Core.AStar.get_closest_point # NOINLINE bindAStar_get_closest_position_in_segment # | Returns the closest position to @to_position@ that resides inside a segment between two connected points . var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 5 , 0 ) ) astar.connect_points(1 , 2 ) var res = astar.get_closest_position_in_segment(Vector3(3 , 3 , 0 ) ) # Returns ( 0 , 3 , 0 ) The result is in the segment that goes from @y = 0@ to @y = 5@. It 's the closest position in the segment to the given point . bindAStar_get_closest_position_in_segment :: MethodBind bindAStar_get_closest_position_in_segment = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_closest_position_in_segment" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the closest position to @to_position@ that resides inside a segment between two connected points . var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 5 , 0 ) ) astar.connect_points(1 , 2 ) var res = astar.get_closest_position_in_segment(Vector3(3 , 3 , 0 ) ) # Returns ( 0 , 3 , 0 ) The result is in the segment that goes from @y = 0@ to @y = 5@. It 's the closest position in the segment to the given point . get_closest_position_in_segment :: (AStar :< cls, Object :< cls) => cls -> Vector3 -> IO Vector3 get_closest_position_in_segment cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_closest_position_in_segment (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_closest_position_in_segment" '[Vector3] (IO Vector3) where nodeMethod = Godot.Core.AStar.get_closest_position_in_segment # NOINLINE bindAStar_get_id_path # var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 1 , 0 ) , 1 ) # Default weight is 1 astar.add_point(3 , Vector3(1 , 1 , 0 ) ) astar.add_point(4 , Vector3(2 , 0 , 0 ) ) astar.connect_points(1 , 2 , false ) astar.connect_points(2 , 3 , false ) astar.connect_points(4 , 3 , false ) astar.connect_points(1 , 4 , false ) var res = astar.get_id_path(1 , 3 ) # Returns @1 , 2 , 3@ If you change the 2nd point 's weight to 3 , then the result will be @@1 , 4 , 3@@ instead , because now even though the distance is longer , it 's " easier " to get through point 4 than through point 2 . bindAStar_get_id_path :: MethodBind bindAStar_get_id_path = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_id_path" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 1 , 0 ) , 1 ) # Default weight is 1 astar.add_point(3 , Vector3(1 , 1 , 0 ) ) astar.add_point(4 , Vector3(2 , 0 , 0 ) ) astar.connect_points(1 , 2 , false ) astar.connect_points(2 , 3 , false ) astar.connect_points(4 , 3 , false ) astar.connect_points(1 , 4 , false ) var res = astar.get_id_path(1 , 3 ) # Returns @1 , 2 , 3@ If you change the 2nd point 's weight to 3 , then the result will be @@1 , 4 , 3@@ instead , because now even though the distance is longer , it 's " easier " to get through point 4 than through point 2 . get_id_path :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> IO PoolIntArray get_id_path cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_id_path (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_id_path" '[Int, Int] (IO PoolIntArray) where nodeMethod = Godot.Core.AStar.get_id_path # NOINLINE bindAStar_get_point_capacity # bindAStar_get_point_capacity :: MethodBind bindAStar_get_point_capacity = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_capacity" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_point_capacity :: (AStar :< cls, Object :< cls) => cls -> IO Int get_point_capacity cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_capacity (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_capacity" '[] (IO Int) where nodeMethod = Godot.Core.AStar.get_point_capacity # NOINLINE bindAStar_get_point_connections # var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 1 , 0 ) ) astar.add_point(3 , Vector3(1 , 1 , 0 ) ) astar.add_point(4 , Vector3(2 , 0 , 0 ) ) astar.connect_points(1 , 2 , true ) astar.connect_points(1 , 3 , true ) var neighbors = astar.get_point_connections(1 ) # Returns @2 , 3@ bindAStar_get_point_connections :: MethodBind bindAStar_get_point_connections = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_connections" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr var astar = ( ) astar.add_point(1 , Vector3(0 , 0 , 0 ) ) astar.add_point(2 , Vector3(0 , 1 , 0 ) ) astar.add_point(3 , Vector3(1 , 1 , 0 ) ) astar.add_point(4 , Vector3(2 , 0 , 0 ) ) astar.connect_points(1 , 2 , true ) astar.connect_points(1 , 3 , true ) var neighbors = astar.get_point_connections(1 ) # Returns @2 , 3@ get_point_connections :: (AStar :< cls, Object :< cls) => cls -> Int -> IO PoolIntArray get_point_connections cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_connections (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_connections" '[Int] (IO PoolIntArray) where nodeMethod = Godot.Core.AStar.get_point_connections # NOINLINE bindAStar_get_point_count # bindAStar_get_point_count :: MethodBind bindAStar_get_point_count = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_count" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_point_count :: (AStar :< cls, Object :< cls) => cls -> IO Int get_point_count cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_count (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_count" '[] (IO Int) where nodeMethod = Godot.Core.AStar.get_point_count # NOINLINE bindAStar_get_point_path # bindAStar_get_point_path :: MethodBind bindAStar_get_point_path = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_path" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_point_path :: (AStar :< cls, Object :< cls) => cls -> Int -> Int -> IO PoolVector3Array get_point_path cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_path (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_path" '[Int, Int] (IO PoolVector3Array) where nodeMethod = Godot.Core.AStar.get_point_path # NOINLINE bindAStar_get_point_position # | Returns the position of the point associated with the given bindAStar_get_point_position :: MethodBind bindAStar_get_point_position = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_position" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the position of the point associated with the given get_point_position :: (AStar :< cls, Object :< cls) => cls -> Int -> IO Vector3 get_point_position cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_position (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_position" '[Int] (IO Vector3) where nodeMethod = Godot.Core.AStar.get_point_position # NOINLINE bindAStar_get_point_weight_scale # | Returns the weight scale of the point associated with the given bindAStar_get_point_weight_scale :: MethodBind bindAStar_get_point_weight_scale = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_point_weight_scale" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Returns the weight scale of the point associated with the given get_point_weight_scale :: (AStar :< cls, Object :< cls) => cls -> Int -> IO Float get_point_weight_scale cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_point_weight_scale (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_point_weight_scale" '[Int] (IO Float) where nodeMethod = Godot.Core.AStar.get_point_weight_scale # NOINLINE bindAStar_get_points # bindAStar_get_points :: MethodBind bindAStar_get_points = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "get_points" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr get_points :: (AStar :< cls, Object :< cls) => cls -> IO Array get_points cls = withVariantArray [] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_get_points (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "get_points" '[] (IO Array) where nodeMethod = Godot.Core.AStar.get_points # NOINLINE bindAStar_has_point # bindAStar_has_point :: MethodBind bindAStar_has_point = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "has_point" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr has_point :: (AStar :< cls, Object :< cls) => cls -> Int -> IO Bool has_point cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_has_point (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "has_point" '[Int] (IO Bool) where nodeMethod = Godot.Core.AStar.has_point # NOINLINE bindAStar_is_point_disabled # bindAStar_is_point_disabled :: MethodBind bindAStar_is_point_disabled = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "is_point_disabled" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr is_point_disabled :: (AStar :< cls, Object :< cls) => cls -> Int -> IO Bool is_point_disabled cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_is_point_disabled (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "is_point_disabled" '[Int] (IO Bool) where nodeMethod = Godot.Core.AStar.is_point_disabled # NOINLINE bindAStar_remove_point # bindAStar_remove_point :: MethodBind bindAStar_remove_point = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "remove_point" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr remove_point :: (AStar :< cls, Object :< cls) => cls -> Int -> IO () remove_point cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_remove_point (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "remove_point" '[Int] (IO ()) where nodeMethod = Godot.Core.AStar.remove_point # NOINLINE bindAStar_reserve_space # bindAStar_reserve_space :: MethodBind bindAStar_reserve_space = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "reserve_space" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr reserve_space :: (AStar :< cls, Object :< cls) => cls -> Int -> IO () reserve_space cls arg1 = withVariantArray [toVariant arg1] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_reserve_space (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "reserve_space" '[Int] (IO ()) where nodeMethod = Godot.Core.AStar.reserve_space # NOINLINE bindAStar_set_point_disabled # bindAStar_set_point_disabled :: MethodBind bindAStar_set_point_disabled = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "set_point_disabled" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr set_point_disabled :: (AStar :< cls, Object :< cls) => cls -> Int -> Maybe Bool -> IO () set_point_disabled cls arg1 arg2 = withVariantArray [toVariant arg1, maybe (VariantBool True) toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_set_point_disabled (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "set_point_disabled" '[Int, Maybe Bool] (IO ()) where nodeMethod = Godot.Core.AStar.set_point_disabled # NOINLINE bindAStar_set_point_position # | Sets the @position@ for the point with the given bindAStar_set_point_position :: MethodBind bindAStar_set_point_position = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "set_point_position" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Sets the @position@ for the point with the given set_point_position :: (AStar :< cls, Object :< cls) => cls -> Int -> Vector3 -> IO () set_point_position cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_set_point_position (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "set_point_position" '[Int, Vector3] (IO ()) where nodeMethod = Godot.Core.AStar.set_point_position # NOINLINE bindAStar_set_point_weight_scale # | Sets the @weight_scale@ for the point with the given bindAStar_set_point_weight_scale :: MethodBind bindAStar_set_point_weight_scale = unsafePerformIO $ withCString "AStar" $ \ clsNamePtr -> withCString "set_point_weight_scale" $ \ methodNamePtr -> godot_method_bind_get_method clsNamePtr methodNamePtr | Sets the @weight_scale@ for the point with the given set_point_weight_scale :: (AStar :< cls, Object :< cls) => cls -> Int -> Float -> IO () set_point_weight_scale cls arg1 arg2 = withVariantArray [toVariant arg1, toVariant arg2] (\ (arrPtr, len) -> godot_method_bind_call bindAStar_set_point_weight_scale (upcast cls) arrPtr len >>= \ (err, res) -> throwIfErr err >> fromGodotVariant res) instance NodeMethod AStar "set_point_weight_scale" '[Int, Float] (IO ()) where nodeMethod = Godot.Core.AStar.set_point_weight_scale
a3c70edcf717fbec7ac16b591dd03f82d1715427be6c96d4a621a32d5433769b
iconnect/ridley
Darwin.hs
# LANGUAGE RecordWildCards # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # # LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # module System.Metrics.Prometheus.Ridley.Metrics.Network.Darwin ( networkMetrics , getNetworkMetrics , mkInterfaceGauge ) where import Control.Monad import Control.Monad.IO.Class import qualified Data.Map.Strict as M import qualified Data.Text as T import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Foreign.Ptr import Foreign.Storable import qualified Language.C.Inline as C import qualified System.Metrics.Prometheus.Metric.Gauge as P import qualified System.Metrics.Prometheus.MetricId as P import qualified System.Metrics.Prometheus.RegistryT as P import System.Metrics.Prometheus.Ridley.Metrics.Network.Types import System.Metrics.Prometheus.Ridley.Types import Text.RawString.QQ (r) C.context (C.baseCtx <> C.vecCtx <> ifDataCtx) C.include "<sys/types.h>" C.include "<sys/socket.h>" C.include "<ifaddrs.h>" C.include "<regex.h>" C.include "<stddef.h>" C.include "helpers.h" C.include "<stdlib.h>" C.include "<string.h>" C.include "<net/if.h>" C.verbatim [r| void set_ridley_ifi_data(struct if_data* netData, ridley_if_data_t* devStats) { //devStats["receive_packets"] = convertFreeBSDCPUTime(uint64(netData.ifi_ipackets)); devStats->ridley_ifi_ipackets = (long)(netData->ifi_ipackets); //devStats["transmit_packets"] = convertFreeBSDCPUTime(uint64(netData.ifi_opackets)); devStats->ridley_ifi_opackets = (long)(netData->ifi_opackets); //devStats["receive_errs"] = convertFreeBSDCPUTime(uint64(netData.ifi_ierrors)); devStats->ridley_ifi_ierrors = (long)(netData->ifi_ierrors); //devStats["transmit_errs"] = convertFreeBSDCPUTime(uint64(netData.ifi_oerrors)); devStats->ridley_ifi_oerrors = (long)(netData->ifi_oerrors); //devStats["receive_bytes"] = convertFreeBSDCPUTime(uint64(netData.ifi_ibytes)); devStats->ridley_ifi_ibytes = (long)(netData->ifi_ibytes); //devStats["transmit_bytes"] = convertFreeBSDCPUTime(uint64(netData.ifi_obytes)); devStats->ridley_ifi_obytes = (long)(netData->ifi_obytes); //devStats["receive_multicast"] = convertFreeBSDCPUTime(uint64(netData.ifi_imcasts)); devStats->ridley_ifi_imcasts = (long)(netData->ifi_imcasts); //devStats["transmit_multicast"] = convertFreeBSDCPUTime(uint64(netData.ifi_omcasts)); devStats->ridley_ifi_omcasts = (long)(netData->ifi_omcasts); //devStats["receive_drop"] = convertFreeBSDCPUTime(uint64(netData.ifi_iqdrops)); devStats->ridley_ifi_iqdrops = (long)(netData->ifi_iqdrops); //devStats["transmit_drop"] = convertFreeBSDCPUTime(uint64(netData.ifi_oqdrops)); // Not present in this version of if_data } |] -------------------------------------------------------------------------------- getNetworkMetrics' :: IO (Ptr IfData, Ptr C.CInt) getNetworkMetrics' = do (totalInterfaces :: Ptr C.CInt) <- malloc res <- [C.block| ridley_if_data_t* { struct ifaddrs *ifap, *ifa; struct if_data *netData; ridley_if_data_t *netDev = malloc(30 * sizeof(ridley_if_data_t)); int interfaceIdx = 0; // Compile a regex to ignore certain devices regex_t regex; int ignoreDevice; ignoreDevice = regcomp(&regex, "^(ram|loop|fd|(h|s|v|xv)d[a-z]|nvme\\d+n\\d+p)\\d+$$", 0); if (ignoreDevice) { netDev[0].ridley_ifi_error = 1; return netDev; } if (getifaddrs(&ifap) == -1) { netDev[0].ridley_ifi_error = 1; return netDev; } // Iterate over all the network interfaces found for (ifa = ifap; ifa; ifa = ifa->ifa_next) { if (ifa->ifa_addr->sa_family == AF_LINK) { char* currentDevice = malloc((strlen(ifa->ifa_name) + 1) * sizeof(char)); strcpy(currentDevice, ifa->ifa_name); ignoreDevice = regexec(&regex, currentDevice, 0, NULL, 0); if (!ignoreDevice) { regfree(&regex); free(currentDevice); continue; } else { regfree(&regex); } ridley_if_data_t *devStats = &netDev[interfaceIdx]; netData = ifa->ifa_data; devStats->ridley_ifi_name = currentDevice; set_ridley_ifi_data(netData, devStats); devStats->ridley_ifi_error = 0; interfaceIdx++; } } freeifaddrs(ifap); *$(int* totalInterfaces) = interfaceIdx; return netDev; } |] return (res, totalInterfaces) foreign import ccall "helpers.h free_ridley_if_data" freeRidleyIFData :: Ptr IfData -> CInt -> IO () -------------------------------------------------------------------------------- getNetworkMetrics :: IO ([IfData], IO ()) getNetworkMetrics = do (raw, total) <- getNetworkMetrics' (CInt interfacesNum) <- peek total m <- peekArray (fromIntegral interfacesNum) raw let dtor = freeRidleyIFData raw (CInt interfacesNum) free total return (m, dtor) -------------------------------------------------------------------------------- -- | As this is a gauge, it makes no sense flushing it. updateNetworkMetric :: NetworkMetric -> IfData -> Bool -> IO () updateNetworkMetric NetworkMetric{..} IfData{..} _ = do P.set (fromIntegral ifi_ipackets) receive_packets P.set (fromIntegral ifi_opackets) transmit_packets P.set (fromIntegral ifi_ierrors) receive_errs P.set (fromIntegral ifi_oerrors) transmit_errs P.set (fromIntegral ifi_ibytes) receive_bytes P.set (fromIntegral ifi_obytes) transmit_bytes P.set (fromIntegral ifi_imcasts) receive_multicast P.set (fromIntegral ifi_omcasts) transmit_multicast P.set (fromIntegral ifi_iqdrops) receive_drop -------------------------------------------------------------------------------- updateNetworkMetrics :: NetworkMetrics -> Bool -> IO () updateNetworkMetrics nmetrics flush = do (ifaces, dtor) <- getNetworkMetrics forM_ ifaces $ \d@IfData{..} -> do key <- T.pack <$> peekCAString ifi_name case M.lookup key nmetrics of Nothing -> return () Just m -> updateNetworkMetric m d flush dtor -------------------------------------------------------------------------------- networkMetrics :: NetworkMetrics -> RidleyMetricHandler networkMetrics g = mkRidleyMetricHandler "ridley-network-metrics" g updateNetworkMetrics False -------------------------------------------------------------------------------- mkInterfaceGauge :: MonadIO m => P.Labels -> NetworkMetrics -> IfData -> P.RegistryT m NetworkMetrics mkInterfaceGauge currentLabels imap d@IfData{..} = do iname <- T.pack <$> liftIO (peekCAString ifi_name) let finalLabels = P.addLabel "interface" iname currentLabels metric <- NetworkMetric <$> P.registerGauge "network_receive_packets" finalLabels <*> P.registerGauge "network_transmit_packets" finalLabels <*> P.registerGauge "network_receive_errs" finalLabels <*> P.registerGauge "network_transmit_errs" finalLabels <*> P.registerGauge "network_receive_bytes" finalLabels <*> P.registerGauge "network_transmit_bytes" finalLabels <*> P.registerGauge "network_receive_multicast" finalLabels <*> P.registerGauge "network_transmit_multicast" finalLabels <*> P.registerGauge "network_receive_drop" finalLabels liftIO $ updateNetworkMetric metric d False return $! M.insert iname metric $! imap
null
https://raw.githubusercontent.com/iconnect/ridley/a7e7fa00db0c6e814734f520f8fb6eb0736e7f94/ridley/src/System/Metrics/Prometheus/Ridley/Metrics/Network/Darwin.hs
haskell
# LANGUAGE OverloadedStrings # ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ | As this is a gauge, it makes no sense flushing it. ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ ------------------------------------------------------------------------------
# LANGUAGE RecordWildCards # # LANGUAGE ScopedTypeVariables # # LANGUAGE QuasiQuotes # # LANGUAGE TemplateHaskell # module System.Metrics.Prometheus.Ridley.Metrics.Network.Darwin ( networkMetrics , getNetworkMetrics , mkInterfaceGauge ) where import Control.Monad import Control.Monad.IO.Class import qualified Data.Map.Strict as M import qualified Data.Text as T import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc import Foreign.Marshal.Array import Foreign.Ptr import Foreign.Storable import qualified Language.C.Inline as C import qualified System.Metrics.Prometheus.Metric.Gauge as P import qualified System.Metrics.Prometheus.MetricId as P import qualified System.Metrics.Prometheus.RegistryT as P import System.Metrics.Prometheus.Ridley.Metrics.Network.Types import System.Metrics.Prometheus.Ridley.Types import Text.RawString.QQ (r) C.context (C.baseCtx <> C.vecCtx <> ifDataCtx) C.include "<sys/types.h>" C.include "<sys/socket.h>" C.include "<ifaddrs.h>" C.include "<regex.h>" C.include "<stddef.h>" C.include "helpers.h" C.include "<stdlib.h>" C.include "<string.h>" C.include "<net/if.h>" C.verbatim [r| void set_ridley_ifi_data(struct if_data* netData, ridley_if_data_t* devStats) { //devStats["receive_packets"] = convertFreeBSDCPUTime(uint64(netData.ifi_ipackets)); devStats->ridley_ifi_ipackets = (long)(netData->ifi_ipackets); //devStats["transmit_packets"] = convertFreeBSDCPUTime(uint64(netData.ifi_opackets)); devStats->ridley_ifi_opackets = (long)(netData->ifi_opackets); //devStats["receive_errs"] = convertFreeBSDCPUTime(uint64(netData.ifi_ierrors)); devStats->ridley_ifi_ierrors = (long)(netData->ifi_ierrors); //devStats["transmit_errs"] = convertFreeBSDCPUTime(uint64(netData.ifi_oerrors)); devStats->ridley_ifi_oerrors = (long)(netData->ifi_oerrors); //devStats["receive_bytes"] = convertFreeBSDCPUTime(uint64(netData.ifi_ibytes)); devStats->ridley_ifi_ibytes = (long)(netData->ifi_ibytes); //devStats["transmit_bytes"] = convertFreeBSDCPUTime(uint64(netData.ifi_obytes)); devStats->ridley_ifi_obytes = (long)(netData->ifi_obytes); //devStats["receive_multicast"] = convertFreeBSDCPUTime(uint64(netData.ifi_imcasts)); devStats->ridley_ifi_imcasts = (long)(netData->ifi_imcasts); //devStats["transmit_multicast"] = convertFreeBSDCPUTime(uint64(netData.ifi_omcasts)); devStats->ridley_ifi_omcasts = (long)(netData->ifi_omcasts); //devStats["receive_drop"] = convertFreeBSDCPUTime(uint64(netData.ifi_iqdrops)); devStats->ridley_ifi_iqdrops = (long)(netData->ifi_iqdrops); //devStats["transmit_drop"] = convertFreeBSDCPUTime(uint64(netData.ifi_oqdrops)); // Not present in this version of if_data } |] getNetworkMetrics' :: IO (Ptr IfData, Ptr C.CInt) getNetworkMetrics' = do (totalInterfaces :: Ptr C.CInt) <- malloc res <- [C.block| ridley_if_data_t* { struct ifaddrs *ifap, *ifa; struct if_data *netData; ridley_if_data_t *netDev = malloc(30 * sizeof(ridley_if_data_t)); int interfaceIdx = 0; // Compile a regex to ignore certain devices regex_t regex; int ignoreDevice; ignoreDevice = regcomp(&regex, "^(ram|loop|fd|(h|s|v|xv)d[a-z]|nvme\\d+n\\d+p)\\d+$$", 0); if (ignoreDevice) { netDev[0].ridley_ifi_error = 1; return netDev; } if (getifaddrs(&ifap) == -1) { netDev[0].ridley_ifi_error = 1; return netDev; } // Iterate over all the network interfaces found for (ifa = ifap; ifa; ifa = ifa->ifa_next) { if (ifa->ifa_addr->sa_family == AF_LINK) { char* currentDevice = malloc((strlen(ifa->ifa_name) + 1) * sizeof(char)); strcpy(currentDevice, ifa->ifa_name); ignoreDevice = regexec(&regex, currentDevice, 0, NULL, 0); if (!ignoreDevice) { regfree(&regex); free(currentDevice); continue; } else { regfree(&regex); } ridley_if_data_t *devStats = &netDev[interfaceIdx]; netData = ifa->ifa_data; devStats->ridley_ifi_name = currentDevice; set_ridley_ifi_data(netData, devStats); devStats->ridley_ifi_error = 0; interfaceIdx++; } } freeifaddrs(ifap); *$(int* totalInterfaces) = interfaceIdx; return netDev; } |] return (res, totalInterfaces) foreign import ccall "helpers.h free_ridley_if_data" freeRidleyIFData :: Ptr IfData -> CInt -> IO () getNetworkMetrics :: IO ([IfData], IO ()) getNetworkMetrics = do (raw, total) <- getNetworkMetrics' (CInt interfacesNum) <- peek total m <- peekArray (fromIntegral interfacesNum) raw let dtor = freeRidleyIFData raw (CInt interfacesNum) free total return (m, dtor) updateNetworkMetric :: NetworkMetric -> IfData -> Bool -> IO () updateNetworkMetric NetworkMetric{..} IfData{..} _ = do P.set (fromIntegral ifi_ipackets) receive_packets P.set (fromIntegral ifi_opackets) transmit_packets P.set (fromIntegral ifi_ierrors) receive_errs P.set (fromIntegral ifi_oerrors) transmit_errs P.set (fromIntegral ifi_ibytes) receive_bytes P.set (fromIntegral ifi_obytes) transmit_bytes P.set (fromIntegral ifi_imcasts) receive_multicast P.set (fromIntegral ifi_omcasts) transmit_multicast P.set (fromIntegral ifi_iqdrops) receive_drop updateNetworkMetrics :: NetworkMetrics -> Bool -> IO () updateNetworkMetrics nmetrics flush = do (ifaces, dtor) <- getNetworkMetrics forM_ ifaces $ \d@IfData{..} -> do key <- T.pack <$> peekCAString ifi_name case M.lookup key nmetrics of Nothing -> return () Just m -> updateNetworkMetric m d flush dtor networkMetrics :: NetworkMetrics -> RidleyMetricHandler networkMetrics g = mkRidleyMetricHandler "ridley-network-metrics" g updateNetworkMetrics False mkInterfaceGauge :: MonadIO m => P.Labels -> NetworkMetrics -> IfData -> P.RegistryT m NetworkMetrics mkInterfaceGauge currentLabels imap d@IfData{..} = do iname <- T.pack <$> liftIO (peekCAString ifi_name) let finalLabels = P.addLabel "interface" iname currentLabels metric <- NetworkMetric <$> P.registerGauge "network_receive_packets" finalLabels <*> P.registerGauge "network_transmit_packets" finalLabels <*> P.registerGauge "network_receive_errs" finalLabels <*> P.registerGauge "network_transmit_errs" finalLabels <*> P.registerGauge "network_receive_bytes" finalLabels <*> P.registerGauge "network_transmit_bytes" finalLabels <*> P.registerGauge "network_receive_multicast" finalLabels <*> P.registerGauge "network_transmit_multicast" finalLabels <*> P.registerGauge "network_receive_drop" finalLabels liftIO $ updateNetworkMetric metric d False return $! M.insert iname metric $! imap
eb080de6857882f00b4f633552110db61fedb6f1f20a9fe4a9fb80371baab158
mbj/stratosphere
TrainingEnvironmentProperty.hs
module Stratosphere.SageMaker.ModelCard.TrainingEnvironmentProperty ( TrainingEnvironmentProperty(..), mkTrainingEnvironmentProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data TrainingEnvironmentProperty = TrainingEnvironmentProperty {containerImage :: (Prelude.Maybe (ValueList Prelude.Text))} mkTrainingEnvironmentProperty :: TrainingEnvironmentProperty mkTrainingEnvironmentProperty = TrainingEnvironmentProperty {containerImage = Prelude.Nothing} instance ToResourceProperties TrainingEnvironmentProperty where toResourceProperties TrainingEnvironmentProperty {..} = ResourceProperties {awsType = "AWS::SageMaker::ModelCard.TrainingEnvironment", supportsTags = Prelude.False, properties = Prelude.fromList (Prelude.catMaybes [(JSON..=) "ContainerImage" Prelude.<$> containerImage])} instance JSON.ToJSON TrainingEnvironmentProperty where toJSON TrainingEnvironmentProperty {..} = JSON.object (Prelude.fromList (Prelude.catMaybes [(JSON..=) "ContainerImage" Prelude.<$> containerImage])) instance Property "ContainerImage" TrainingEnvironmentProperty where type PropertyType "ContainerImage" TrainingEnvironmentProperty = ValueList Prelude.Text set newValue TrainingEnvironmentProperty {} = TrainingEnvironmentProperty {containerImage = Prelude.pure newValue, ..}
null
https://raw.githubusercontent.com/mbj/stratosphere/c70f301715425247efcda29af4f3fcf7ec04aa2f/services/sagemaker/gen/Stratosphere/SageMaker/ModelCard/TrainingEnvironmentProperty.hs
haskell
module Stratosphere.SageMaker.ModelCard.TrainingEnvironmentProperty ( TrainingEnvironmentProperty(..), mkTrainingEnvironmentProperty ) where import qualified Data.Aeson as JSON import qualified Stratosphere.Prelude as Prelude import Stratosphere.Property import Stratosphere.ResourceProperties import Stratosphere.Value data TrainingEnvironmentProperty = TrainingEnvironmentProperty {containerImage :: (Prelude.Maybe (ValueList Prelude.Text))} mkTrainingEnvironmentProperty :: TrainingEnvironmentProperty mkTrainingEnvironmentProperty = TrainingEnvironmentProperty {containerImage = Prelude.Nothing} instance ToResourceProperties TrainingEnvironmentProperty where toResourceProperties TrainingEnvironmentProperty {..} = ResourceProperties {awsType = "AWS::SageMaker::ModelCard.TrainingEnvironment", supportsTags = Prelude.False, properties = Prelude.fromList (Prelude.catMaybes [(JSON..=) "ContainerImage" Prelude.<$> containerImage])} instance JSON.ToJSON TrainingEnvironmentProperty where toJSON TrainingEnvironmentProperty {..} = JSON.object (Prelude.fromList (Prelude.catMaybes [(JSON..=) "ContainerImage" Prelude.<$> containerImage])) instance Property "ContainerImage" TrainingEnvironmentProperty where type PropertyType "ContainerImage" TrainingEnvironmentProperty = ValueList Prelude.Text set newValue TrainingEnvironmentProperty {} = TrainingEnvironmentProperty {containerImage = Prelude.pure newValue, ..}
94ae7b2d8a28b67213312ef6f3f8ff46387408217add94c81b3463113b8eda3a
Twinside/Rasterific
StrokeInternal.hs
module Graphics.Rasterific.StrokeInternal ( flatten , dashize , strokize , dashedStrokize , splitPrimitiveUntil , approximatePathLength , isPrimitivePoint , sanitize , sanitizeFilling ) where import Graphics.Rasterific.Linear ( V2( .. ) , (^-^) , (^+^) , (^*) , dot , nearZero ) import Graphics.Rasterific.Operators import Graphics.Rasterific.Types import Graphics.Rasterific.QuadraticBezier import Graphics.Rasterific.CubicBezier import Graphics.Rasterific.Line lastPoint :: Primitive -> Point lastPoint (LinePrim (Line _ x1)) = x1 lastPoint (BezierPrim (Bezier _ _ x2)) = x2 lastPoint (CubicBezierPrim (CubicBezier _ _ _ x3)) = x3 lastPointAndNormal :: Primitive -> (Point, Vector) lastPointAndNormal (LinePrim (Line a b)) = (b, a `normal` b) lastPointAndNormal (BezierPrim (Bezier _ b c)) = (c, b `normal` c) lastPointAndNormal (CubicBezierPrim (CubicBezier _ _ c d)) = (d, c `normal` d) firstPointAndNormal :: Primitive -> (Point, Vector) firstPointAndNormal (LinePrim (Line a b)) = (a, a `normal` b) firstPointAndNormal (BezierPrim (Bezier a b _)) = (a, a `normal` b) firstPointAndNormal (CubicBezierPrim (CubicBezier a b _ _)) = (a, a `normal` b) isPrimitivePoint :: Primitive -> Bool isPrimitivePoint p = case p of LinePrim l -> isLinePoint l BezierPrim b -> isBezierPoint b CubicBezierPrim c -> isCubicBezierPoint c reversePrimitive :: Primitive -> Primitive reversePrimitive (LinePrim (Line a b)) = LinePrim (Line b a) reversePrimitive (BezierPrim (Bezier a b c)) = BezierPrim (Bezier c b a) reversePrimitive (CubicBezierPrim (CubicBezier a b c d)) = CubicBezierPrim (CubicBezier d c b a) -- | Create a "rounded" join or cap roundJoin :: Float -> Point -> Vector -> Vector -> Container Primitive roundJoin offset p = go where go u v -- If we're already on a nice curvature, -- don't bother doing anything | u `dot` w >= 0.9 = pure . BezierPrim $ Bezier a b c | otherwise = go u w <> go w v where -- ^ -- |w -- a X---X c -- \ / -- Xp -- ^ / \ ^ -- u\/ \/v -- / \ . a = p ^+^ u ^* offset c = p ^+^ v ^* offset w = (a `normal` c) `ifZero` u -- Same as offseting n = p ^+^ w ^* offset b = n ^* 2 ^-^ (a `midPoint` c) -- | Put a cap at the end of a bezier curve, depending -- on the kind of cap wanted. cap :: Float -> Cap -> Primitive -> Container Primitive cap offset CapRound prim | nearZero u = cap offset (CapStraight 0) prim | otherwise = roundJoin offset p u (- u) where (p, u) = lastPointAndNormal prim cap offset (CapStraight cVal) prim = pure (d `lineFromTo` e) <> pure (e `lineFromTo` f) <> pure (f `lineFromTo` g) where -- The usual "normal" (p, u@(V2 ux uy)) = lastPointAndNormal prim -- Vector pointing in the direction of the curve of norm 1 v = V2 uy $ negate ux -- Finishing points around the edge -- -u*offset u*offset -- <-><-> -- d/ / /g -- / / / -- / / / -- / -- / curve -- d = p ^+^ u ^* offset g = p ^-^ u ^* offset -- Create the "far" points -- -- e f -- / / ^ / / / v * offset * -- d/ / /g -- / / / -- / / / -- / -- / curve -- e = d ^+^ v ^* (offset * cVal) f = g ^+^ v ^* (offset * cVal) lineFromTo :: Point -> Point -> Primitive lineFromTo a b = LinePrim (Line a b) miterJoin :: Float -> Float -> Point -> Vector -> Vector -> Container Primitive miterJoin offset l point u v | uDotW > l / max 1 l && uDotW > 0.01 = pure (a `lineFromTo` m) <> pure (m `lineFromTo` c) -- A simple straight junction | otherwise = pure $ a `lineFromTo` c where -- X m -- /\ -- /|w\ -- a X---X c -- \ / -- Xp -- ^ / \ ^ -- u\/ \/v -- / \ . a = point ^+^ u ^* offset c = point ^+^ v ^* offset w = (a `normal` c) `ifZero` u uDotW = u `dot` w -- Calculate the maximum distance on the -- u axis p = offset / uDotW -- middle point for "straight joining" m = point + w ^* p joinPrimitives :: StrokeWidth -> Join -> Primitive -> Primitive -> Container Primitive joinPrimitives offset join prim1 prim2 = case join of JoinRound | nearZero u || nearZero v -> miterJoin offset 0 p u v JoinRound -> roundJoin offset p u v JoinMiter l -> miterJoin offset l p u v where (p, u) = lastPointAndNormal prim1 (_, v) = firstPointAndNormal prim2 offsetPrimitives :: Float -> Primitive -> Container Primitive offsetPrimitives offset (LinePrim l) = offsetLine offset l offsetPrimitives offset (BezierPrim b) = offsetBezier offset b offsetPrimitives offset (CubicBezierPrim c) = offsetCubicBezier offset c offsetAndJoin :: Float -> Join -> Cap -> [Primitive] -> Container Primitive offsetAndJoin _ _ _ [] = mempty offsetAndJoin offset join caping (firstShape:rest) = go firstShape rest where joiner = joinPrimitives offset join offseter = offsetPrimitives offset (firstPoint, _) = firstPointAndNormal firstShape go prev [] | firstPoint `isNearby` lastPoint prev = offseter prev <> joiner prev firstShape | otherwise = offseter prev <> cap offset caping prev go prev (x:xs) = offseter prev <> joiner prev x <> go x xs approximateLength :: Primitive -> Float approximateLength (LinePrim l) = lineLength l approximateLength (BezierPrim b) = bezierLengthApproximation b approximateLength (CubicBezierPrim c) = cubicBezierLengthApproximation c sanitize :: Primitive -> Container Primitive sanitize (LinePrim l) = sanitizeLine l sanitize (BezierPrim b) = sanitizeBezier b sanitize (CubicBezierPrim c) = sanitizeCubicBezier c -- | Sanitizing that don't cull really small elements, only -- Degenerate case, to allow them to participate to the correct -- coverage, even if really small. sanitizeFilling :: Primitive -> Container Primitive sanitizeFilling (LinePrim l) = sanitizeLineFilling l sanitizeFilling (BezierPrim b) = sanitizeBezierFilling b sanitizeFilling (CubicBezierPrim c) = sanitizeCubicBezierFilling c strokize :: Geometry geom => StrokeWidth -> Join -> (Cap, Cap) -> geom -> Container Primitive strokize width join (capStart, capEnd) geom = foldMap pathOffseter sanitized where sanitized = foldMap (listOfContainer . sanitize) <$> resplit (toPrimitives geom) offseter = offsetAndJoin (width / 2) join pathOffseter v = offseter capEnd v <> offseter capStart (reverse $ reversePrimitive <$> v) flattenPrimitive :: Primitive -> Container Primitive flattenPrimitive (BezierPrim bezier) = flattenBezier bezier flattenPrimitive (CubicBezierPrim bezier) = flattenCubicBezier bezier flattenPrimitive (LinePrim line) = flattenLine line breakPrimitiveAt :: Primitive -> Float -> (Primitive, Primitive) breakPrimitiveAt (BezierPrim bezier) at = (BezierPrim a, BezierPrim b) where (a, b) = bezierBreakAt bezier at breakPrimitiveAt (CubicBezierPrim bezier) at = (CubicBezierPrim a, CubicBezierPrim b) where (a, b) = cubicBezierBreakAt bezier at breakPrimitiveAt (LinePrim line) at = (LinePrim a, LinePrim b) where (a, b) = lineBreakAt line at flatten :: Container Primitive -> Container Primitive flatten = foldMap flattenPrimitive splitPrimitiveUntil :: Float -> [Primitive] -> ([Primitive], [Primitive]) splitPrimitiveUntil = go where go _ [] = ([], []) go left lst | left <= 0 = ([], lst) go left (x : xs) | left > primLength = (x : inInterval, afterInterval) | otherwise = ([beforeStop], afterStop : xs) where primLength = approximateLength x (inInterval, afterInterval) = go (left - primLength) xs (beforeStop, afterStop) = breakPrimitiveAt x $ left / primLength dropPattern :: Float -> DashPattern -> DashPattern dropPattern = go where go _ [] = [] go offset (x:xs) | x < 0 = x:xs -- sanitizing | offset < x = x - offset : xs | otherwise {- offset >= x -} = go (offset - x) xs -- | Don't make them completly flat, but suficiently -- to assume they are. linearizePrimitives :: [Primitive] -> [Primitive] linearizePrimitives = listOfContainer . foldMap flattenPrimitive . foldMap sanitize -- | Return an approximation of the length of a given path. -- It's results is not precise but should be enough for -- rough calculations approximatePathLength :: Path -> Float approximatePathLength = approximatePrimitivesLength . pathToPrimitives approximatePrimitivesLength :: [Primitive] -> Float approximatePrimitivesLength prims = sum $ approximateLength <$> linearizePrimitives prims dashize :: Float -> DashPattern -> [Primitive] -> [[Primitive]] dashize offset pattern = taker infinitePattern . linearizePrimitives where realOffset | offset >= 0 = offset | otherwise = offset + sum pattern infinitePattern = dropPattern realOffset . cycle $ filter (> 0) pattern taker _ [] = [] taker [] _ = [] -- Impossible by construction, pattern is infinite taker (atValue:atRest) stream = toKeep : droper atRest next where (toKeep, next) = splitPrimitiveUntil atValue stream droper _ [] = [] droper [] _ = [] -- Impossible by construction, pattern is infinite droper (atValue:atRest) stream = taker atRest next where (_toKeep, next) = splitPrimitiveUntil atValue stream -- | Create a list of outlines corresponding to all the -- dashed elements. They can be then stroked -- > mapM _ ( stroke 3 ( JoinMiter 0 ) ( CapStraight 0 , 0 ) ) $ > 0 [ 10 , 5 ] > 40 JoinRound ( CapStraight 0 , CapStraight 0 ) $ > CubicBezier ( V2 40 160 ) ( V2 40 40 ) ( V2 160 40 ) ( V2 160 160 ) -- -- <<docimages/strokize_dashed_path.png>> -- dashedStrokize :: Geometry geom => Float -- ^ Starting offset -> DashPattern -- ^ Dashing pattern to use for stroking -> StrokeWidth -- ^ Stroke width -> Join -- ^ Which kind of join will be used -> (Cap, Cap) -- ^ Start and end capping. -> geom -- ^ Elements to transform -> [[Primitive]] dashedStrokize offset dashPattern width join capping geom = listOfContainer . strokize width join capping <$> dashize offset dashPattern (toPrimitives geom)
null
https://raw.githubusercontent.com/Twinside/Rasterific/eb07ea38aaad154e66de14a1b4a50fb70d0843bb/src/Graphics/Rasterific/StrokeInternal.hs
haskell
| Create a "rounded" join or cap If we're already on a nice curvature, don't bother doing anything ^ |w a X---X c \ / Xp ^ / \ ^ u\/ \/v / \ . Same as offseting | Put a cap at the end of a bezier curve, depending on the kind of cap wanted. The usual "normal" Vector pointing in the direction of the curve Finishing points around the edge -u*offset u*offset <-><-> d/ / /g / / / / / / / / curve Create the "far" points e f / / ^ d/ / /g / / / / / / / / curve A simple straight junction X m /\ /|w\ a X---X c \ / Xp ^ / \ ^ u\/ \/v / \ . Calculate the maximum distance on the u axis middle point for "straight joining" | Sanitizing that don't cull really small elements, only Degenerate case, to allow them to participate to the correct coverage, even if really small. sanitizing offset >= x | Don't make them completly flat, but suficiently to assume they are. | Return an approximation of the length of a given path. It's results is not precise but should be enough for rough calculations Impossible by construction, pattern is infinite Impossible by construction, pattern is infinite | Create a list of outlines corresponding to all the dashed elements. They can be then stroked <<docimages/strokize_dashed_path.png>> ^ Starting offset ^ Dashing pattern to use for stroking ^ Stroke width ^ Which kind of join will be used ^ Start and end capping. ^ Elements to transform
module Graphics.Rasterific.StrokeInternal ( flatten , dashize , strokize , dashedStrokize , splitPrimitiveUntil , approximatePathLength , isPrimitivePoint , sanitize , sanitizeFilling ) where import Graphics.Rasterific.Linear ( V2( .. ) , (^-^) , (^+^) , (^*) , dot , nearZero ) import Graphics.Rasterific.Operators import Graphics.Rasterific.Types import Graphics.Rasterific.QuadraticBezier import Graphics.Rasterific.CubicBezier import Graphics.Rasterific.Line lastPoint :: Primitive -> Point lastPoint (LinePrim (Line _ x1)) = x1 lastPoint (BezierPrim (Bezier _ _ x2)) = x2 lastPoint (CubicBezierPrim (CubicBezier _ _ _ x3)) = x3 lastPointAndNormal :: Primitive -> (Point, Vector) lastPointAndNormal (LinePrim (Line a b)) = (b, a `normal` b) lastPointAndNormal (BezierPrim (Bezier _ b c)) = (c, b `normal` c) lastPointAndNormal (CubicBezierPrim (CubicBezier _ _ c d)) = (d, c `normal` d) firstPointAndNormal :: Primitive -> (Point, Vector) firstPointAndNormal (LinePrim (Line a b)) = (a, a `normal` b) firstPointAndNormal (BezierPrim (Bezier a b _)) = (a, a `normal` b) firstPointAndNormal (CubicBezierPrim (CubicBezier a b _ _)) = (a, a `normal` b) isPrimitivePoint :: Primitive -> Bool isPrimitivePoint p = case p of LinePrim l -> isLinePoint l BezierPrim b -> isBezierPoint b CubicBezierPrim c -> isCubicBezierPoint c reversePrimitive :: Primitive -> Primitive reversePrimitive (LinePrim (Line a b)) = LinePrim (Line b a) reversePrimitive (BezierPrim (Bezier a b c)) = BezierPrim (Bezier c b a) reversePrimitive (CubicBezierPrim (CubicBezier a b c d)) = CubicBezierPrim (CubicBezier d c b a) roundJoin :: Float -> Point -> Vector -> Vector -> Container Primitive roundJoin offset p = go where go u v | u `dot` w >= 0.9 = pure . BezierPrim $ Bezier a b c | otherwise = go u w <> go w v a = p ^+^ u ^* offset c = p ^+^ v ^* offset w = (a `normal` c) `ifZero` u n = p ^+^ w ^* offset b = n ^* 2 ^-^ (a `midPoint` c) cap :: Float -> Cap -> Primitive -> Container Primitive cap offset CapRound prim | nearZero u = cap offset (CapStraight 0) prim | otherwise = roundJoin offset p u (- u) where (p, u) = lastPointAndNormal prim cap offset (CapStraight cVal) prim = pure (d `lineFromTo` e) <> pure (e `lineFromTo` f) <> pure (f `lineFromTo` g) (p, u@(V2 ux uy)) = lastPointAndNormal prim of norm 1 v = V2 uy $ negate ux d = p ^+^ u ^* offset g = p ^-^ u ^* offset / / / v * offset * e = d ^+^ v ^* (offset * cVal) f = g ^+^ v ^* (offset * cVal) lineFromTo :: Point -> Point -> Primitive lineFromTo a b = LinePrim (Line a b) miterJoin :: Float -> Float -> Point -> Vector -> Vector -> Container Primitive miterJoin offset l point u v | uDotW > l / max 1 l && uDotW > 0.01 = pure (a `lineFromTo` m) <> pure (m `lineFromTo` c) | otherwise = pure $ a `lineFromTo` c a = point ^+^ u ^* offset c = point ^+^ v ^* offset w = (a `normal` c) `ifZero` u uDotW = u `dot` w p = offset / uDotW m = point + w ^* p joinPrimitives :: StrokeWidth -> Join -> Primitive -> Primitive -> Container Primitive joinPrimitives offset join prim1 prim2 = case join of JoinRound | nearZero u || nearZero v -> miterJoin offset 0 p u v JoinRound -> roundJoin offset p u v JoinMiter l -> miterJoin offset l p u v where (p, u) = lastPointAndNormal prim1 (_, v) = firstPointAndNormal prim2 offsetPrimitives :: Float -> Primitive -> Container Primitive offsetPrimitives offset (LinePrim l) = offsetLine offset l offsetPrimitives offset (BezierPrim b) = offsetBezier offset b offsetPrimitives offset (CubicBezierPrim c) = offsetCubicBezier offset c offsetAndJoin :: Float -> Join -> Cap -> [Primitive] -> Container Primitive offsetAndJoin _ _ _ [] = mempty offsetAndJoin offset join caping (firstShape:rest) = go firstShape rest where joiner = joinPrimitives offset join offseter = offsetPrimitives offset (firstPoint, _) = firstPointAndNormal firstShape go prev [] | firstPoint `isNearby` lastPoint prev = offseter prev <> joiner prev firstShape | otherwise = offseter prev <> cap offset caping prev go prev (x:xs) = offseter prev <> joiner prev x <> go x xs approximateLength :: Primitive -> Float approximateLength (LinePrim l) = lineLength l approximateLength (BezierPrim b) = bezierLengthApproximation b approximateLength (CubicBezierPrim c) = cubicBezierLengthApproximation c sanitize :: Primitive -> Container Primitive sanitize (LinePrim l) = sanitizeLine l sanitize (BezierPrim b) = sanitizeBezier b sanitize (CubicBezierPrim c) = sanitizeCubicBezier c sanitizeFilling :: Primitive -> Container Primitive sanitizeFilling (LinePrim l) = sanitizeLineFilling l sanitizeFilling (BezierPrim b) = sanitizeBezierFilling b sanitizeFilling (CubicBezierPrim c) = sanitizeCubicBezierFilling c strokize :: Geometry geom => StrokeWidth -> Join -> (Cap, Cap) -> geom -> Container Primitive strokize width join (capStart, capEnd) geom = foldMap pathOffseter sanitized where sanitized = foldMap (listOfContainer . sanitize) <$> resplit (toPrimitives geom) offseter = offsetAndJoin (width / 2) join pathOffseter v = offseter capEnd v <> offseter capStart (reverse $ reversePrimitive <$> v) flattenPrimitive :: Primitive -> Container Primitive flattenPrimitive (BezierPrim bezier) = flattenBezier bezier flattenPrimitive (CubicBezierPrim bezier) = flattenCubicBezier bezier flattenPrimitive (LinePrim line) = flattenLine line breakPrimitiveAt :: Primitive -> Float -> (Primitive, Primitive) breakPrimitiveAt (BezierPrim bezier) at = (BezierPrim a, BezierPrim b) where (a, b) = bezierBreakAt bezier at breakPrimitiveAt (CubicBezierPrim bezier) at = (CubicBezierPrim a, CubicBezierPrim b) where (a, b) = cubicBezierBreakAt bezier at breakPrimitiveAt (LinePrim line) at = (LinePrim a, LinePrim b) where (a, b) = lineBreakAt line at flatten :: Container Primitive -> Container Primitive flatten = foldMap flattenPrimitive splitPrimitiveUntil :: Float -> [Primitive] -> ([Primitive], [Primitive]) splitPrimitiveUntil = go where go _ [] = ([], []) go left lst | left <= 0 = ([], lst) go left (x : xs) | left > primLength = (x : inInterval, afterInterval) | otherwise = ([beforeStop], afterStop : xs) where primLength = approximateLength x (inInterval, afterInterval) = go (left - primLength) xs (beforeStop, afterStop) = breakPrimitiveAt x $ left / primLength dropPattern :: Float -> DashPattern -> DashPattern dropPattern = go where go _ [] = [] go offset (x:xs) | offset < x = x - offset : xs linearizePrimitives :: [Primitive] -> [Primitive] linearizePrimitives = listOfContainer . foldMap flattenPrimitive . foldMap sanitize approximatePathLength :: Path -> Float approximatePathLength = approximatePrimitivesLength . pathToPrimitives approximatePrimitivesLength :: [Primitive] -> Float approximatePrimitivesLength prims = sum $ approximateLength <$> linearizePrimitives prims dashize :: Float -> DashPattern -> [Primitive] -> [[Primitive]] dashize offset pattern = taker infinitePattern . linearizePrimitives where realOffset | offset >= 0 = offset | otherwise = offset + sum pattern infinitePattern = dropPattern realOffset . cycle $ filter (> 0) pattern taker _ [] = [] taker (atValue:atRest) stream = toKeep : droper atRest next where (toKeep, next) = splitPrimitiveUntil atValue stream droper _ [] = [] droper (atValue:atRest) stream = taker atRest next where (_toKeep, next) = splitPrimitiveUntil atValue stream > mapM _ ( stroke 3 ( JoinMiter 0 ) ( CapStraight 0 , 0 ) ) $ > 0 [ 10 , 5 ] > 40 JoinRound ( CapStraight 0 , CapStraight 0 ) $ > CubicBezier ( V2 40 160 ) ( V2 40 40 ) ( V2 160 40 ) ( V2 160 160 ) dashedStrokize :: Geometry geom -> [[Primitive]] dashedStrokize offset dashPattern width join capping geom = listOfContainer . strokize width join capping <$> dashize offset dashPattern (toPrimitives geom)
eca406b1662ed7b1473beaaf87d6ad40bf0b3fb3aeb275147ac798bec934d479
dongcarl/guix
go-build-system.scm
;;; GNU Guix --- Functional package management for GNU Copyright © 2016 Petter < > Copyright © 2017 , 2019 < > Copyright © 2019 < > Copyright © 2020 < > Copyright © 2020 < > Copyright © 2020 < > ;;; ;;; This file is part of GNU Guix. ;;; GNU is free software ; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at ;;; your option) any later version. ;;; ;;; GNU Guix is distributed in the hope that it will be useful, but ;;; WITHOUT ANY WARRANTY; without even the implied warranty of ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ;;; GNU General Public License for more details. ;;; You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix build go-build-system) #:use-module ((guix build gnu-build-system) #:prefix gnu:) #:use-module (guix build union) #:use-module (guix build utils) #:use-module (ice-9 match) #:use-module (ice-9 ftw) #:use-module (srfi srfi-1) #:use-module (rnrs io ports) #:use-module (rnrs bytevectors) #:export (%standard-phases go-build)) ;; Commentary: ;; ;; Build procedures for Go packages. This is the builder-side code. ;; ;; Software written in Go is either a 'package' (i.e. library) or 'command' ;; (i.e. executable). Both types can be built with either the `go build` or `go ;; install` commands. However, `go build` discards the result of the build ;; process for Go libraries, so we use `go install`, which preserves the ;; results. [0] ;; Go software is developed and built within a particular file system hierarchy structure called a ' workspace ' [ 1 ] . This workspace can be found by Go via ;; the GOPATH environment variable. Typically, all Go source code and compiled ;; objects are kept in a single workspace, but GOPATH may be a list of directories [ 2 ] . In this go - build - system we create a file system union of ;; the Go-language dependencies. Previously, we made GOPATH a list of store ;; directories, but stopped because Go programs started keeping references to these directories in Go 1.11 : ;; <>. ;; ;; Go software, whether a package or a command, is uniquely named using an ;; 'import path'. The import path is based on the URL of the software's source. ;; Because most source code is provided over the internet, the import path is ;; typically a combination of the remote URL and the source repository's file ;; system structure. For example, the Go port of the common `du` command is ;; hosted on github.com, at <>. Thus, the import path is < github.com/calmh/du > . [ 3 ] ;; ;; It may be possible to automatically guess a package's import path based on ;; the source URL, but we don't try that in this revision of the ;; go-build-system. ;; ;; Modules of modular Go libraries are named uniquely with their ;; file system paths. For example, the supplemental but "standardized" ;; libraries developed by the Go upstream developers are available at < , et cetera } > . The Go IPv4 ;; library's import path is <golang.org/x/net/ipv4>. The source of ;; such modular libraries must be unpacked at the top-level of the file system structure of the library . So the IPv4 library should be ;; unpacked to <golang.org/x/net>. This is handled in the ;; go-build-system with the optional #:unpack-path key. ;; ;; In general, Go software is built using a standardized build mechanism that does not require any build scripts like . This means ;; that all modules of modular libraries cannot be built with a single ;; command. Each module must be built individually. This complicates ;; certain cases, and these issues are currently resolved by creating a ;; file system union of the required modules of such libraries. I think ;; this could be improved in future revisions of the go-build-system. ;; ;; TODO: ;; * Avoid copying dependencies into the build environment and / or avoid using ;; a tmpdir when creating the inputs union. * Use Go modules [ 4 ] * Re - use compiled packages [ 5 ] ;; * Avoid the go-inputs hack ;; * Stop needing remove-go-references (-trimpath ? ) ;; * Remove module packages, only offering the full Git repos? This is ;; more idiomatic, I think, because Go downloads Git repos, not modules. ;; What are the trade-offs? ;; ;; [0] `go build`: /#hdr-Compile_packages_and_dependencies ;; `go install`: ;; /#hdr-Compile_and_install_packages_and_dependencies [ 1 ] Go workspace example , from < #Workspaces > : ;; bin/ ;; hello # command executable ;; outyet # command executable ;; pkg/ ;; linux_amd64/ ;; github.com/golang/example/ ;; stringutil.a # package object ;; src/ ;; github.com/golang/example/ ;; .git/ # Git repository metadata ;; hello/ ;; hello.go # command source ;; outyet/ ;; main.go # command source ;; main_test.go # test source ;; stringutil/ ;; reverse.go # package source ;; reverse_test.go # test source golang.org/x/image/ ;; .git/ # Git repository metadata ;; bmp/ ;; reader.go # package source writer.go # package source ;; ... (many more repositories and packages omitted) ... ;; [ 2 ] #GOPATH [ 3 ] #ImportPaths ;; [4] /#hdr-Modules__module_versions__and_more [ 5 ] ;; ;; Code: (define* (setup-go-environment #:key inputs outputs #:allow-other-keys) "Prepare a Go build environment for INPUTS and OUTPUTS. Build a file system union of INPUTS. Export GOPATH, which helps the compiler find the source code of the package being built and its dependencies, and GOBIN, which determines where executables (\"commands\") are installed to. This phase is sometimes used by packages that use (guix build-system gnu) but have a handful of Go dependencies, so it should be self-contained." The Go cache is required starting in Go 1.12 . We do n't actually use it but ;; we need it to be a writable directory. (setenv "GOCACHE" "/tmp/go-cache") ;; Using the current working directory as GOPATH makes it easier for packagers ;; who need to manipulate the unpacked source code. (setenv "GOPATH" (getcwd)) Go 1.13 uses go modules by default . The go build system does not ;; currently support modules, so turn modules off to continue using the old ;; GOPATH behavior. (setenv "GO111MODULE" "off") (setenv "GOBIN" (string-append (assoc-ref outputs "out") "/bin")) (let ((tmpdir (tmpnam))) (match (go-inputs inputs) (((names . directories) ...) (union-build tmpdir (filter directory-exists? directories) #:create-all-directories? #t #:log-port (%make-void-port "w")))) XXX A little dance because ( guix build union ) does n't use mkdir - p. (copy-recursively tmpdir (string-append (getenv "GOPATH")) #:keep-mtime? #t) (delete-file-recursively tmpdir)) #t) (define* (unpack #:key source import-path unpack-path #:allow-other-keys) "Relative to $GOPATH, unpack SOURCE in UNPACK-PATH, or IMPORT-PATH when UNPACK-PATH is unset. If the SOURCE archive has a single top level directory, it is stripped so that the sources appear directly under UNPACK-PATH. When SOURCE is a directory, copy its content into UNPACK-PATH instead of unpacking." (define (unpack-maybe-strip source dest) (let* ((scratch-dir (string-append (or (getenv "TMPDIR") "/tmp") "/scratch-dir")) (out (mkdir-p scratch-dir))) (with-directory-excursion scratch-dir (if (string-suffix? ".zip" source) (invoke "unzip" source) (invoke "tar" "-xvf" source)) (let ((top-level-files (remove (lambda (x) (member x '("." ".."))) (scandir ".")))) (match top-level-files ((top-level-file) (when (file-is-directory? top-level-file) (copy-recursively top-level-file dest #:keep-mtime? #t))) (_ (copy-recursively "." dest #:keep-mtime? #t))))) (delete-file-recursively scratch-dir))) (when (string-null? import-path) (display "WARNING: The Go import path is unset.\n")) (when (string-null? unpack-path) (set! unpack-path import-path)) (let ((dest (string-append (getenv "GOPATH") "/src/" unpack-path))) (mkdir-p dest) (if (file-is-directory? source) (copy-recursively source dest #:keep-mtime? #t) (unpack-maybe-strip source dest))) #t) (define (go-package? name) (string-prefix? "go-" name)) (define (go-inputs inputs) "Return the alist of INPUTS that are Go software." ;; XXX This should not check the file name of the store item. Instead we ;; should pass, from the host side, the list of inputs that are packages using ;; the go-build-system. (alist-delete "go" ; Exclude the Go compiler (alist-delete "source" ; Exclude the source code of the package being built (filter (match-lambda ((label . directory) (go-package? ((compose package-name->name+version strip-store-file-name) directory))) (_ #f)) inputs)))) (define* (build #:key import-path build-flags #:allow-other-keys) "Build the package named by IMPORT-PATH." (with-throw-handler #t (lambda _ (apply invoke "go" "install" "-v" ; print the name of packages as they are compiled "-x" ; print each command as it is invoked ;; Respectively, strip the symbol table and debug ;; information, and the DWARF symbol table. "-ldflags=-s -w" `(,@build-flags ,import-path))) (lambda (key . args) (display (string-append "Building '" import-path "' failed.\n" "Here are the results of `go env`:\n")) (invoke "go" "env")))) ;; Can this also install commands??? (define* (check #:key tests? import-path #:allow-other-keys) "Run the tests for the package named by IMPORT-PATH." (when tests? (invoke "go" "test" import-path)) #t) (define* (install #:key install-source? outputs import-path unpack-path #:allow-other-keys) "Install the source code of IMPORT-PATH to the primary output directory. Compiled executable files (Go \"commands\") should have already been installed to the store based on $GOBIN in the build phase. XXX We can't make use of compiled libraries (Go \"packages\")." (when install-source? (if (string-null? import-path) ((display "WARNING: The Go import path is unset.\n"))) (let* ((out (assoc-ref outputs "out")) (source (string-append (getenv "GOPATH") "/src/" import-path)) (dest (string-append out "/src/" import-path))) (mkdir-p dest) (copy-recursively source dest #:keep-mtime? #t))) #t) (define* (install-license-files #:key unpack-path import-path #:allow-other-keys #:rest args) "Install license files matching LICENSE-FILE-REGEXP to 'share/doc'. Adjust the standard install-license-files phase to first enter the correct directory." (with-directory-excursion (string-append "src/" (if (string-null? unpack-path) import-path unpack-path)) (apply (assoc-ref gnu:%standard-phases 'install-license-files) args))) (define* (remove-store-reference file file-name #:optional (store (%store-directory))) "Remove from FILE occurrences of FILE-NAME in STORE; return #t when FILE-NAME is encountered in FILE, #f otherwise. This implementation reads FILE one byte at a time, which is slow. Instead, we should use the Boyer-Moore string search algorithm; there is an example in (guix build grafts)." (define pattern (string-take file-name (+ 34 (string-length (%store-directory))))) (with-fluids ((%default-port-encoding #f)) (with-atomic-file-replacement file (lambda (in out) ;; We cannot use `regexp-exec' here because it cannot deal with strings containing NUL characters . (format #t "removing references to `~a' from `~a'...~%" file-name file) (setvbuf in 'block 65536) (setvbuf out 'block 65536) (fold-port-matches (lambda (match result) (put-bytevector out (string->utf8 store)) (put-u8 out (char->integer #\/)) (put-bytevector out (string->utf8 "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-")) #t) #f pattern in (lambda (char result) (put-u8 out (char->integer char)) result)))))) (define* (remove-go-references #:key allow-go-reference? inputs outputs #:allow-other-keys) "Remove any references to the Go compiler from the compiled Go executable files in OUTPUTS." ;; We remove this spurious reference to save bandwidth when installing Go executables . It would be better to not embed the reference in the first ;; place, but I'm not sure how to do that. The subject was discussed at: ;; <-devel/2017-10/msg00207.html> (if allow-go-reference? #t (let ((go (assoc-ref inputs "go")) (bin "/bin")) (for-each (lambda (output) (when (file-exists? (string-append (cdr output) bin)) (for-each (lambda (file) (remove-store-reference file go)) (find-files (string-append (cdr output) bin))))) outputs) #t))) (define %standard-phases (modify-phases gnu:%standard-phases (delete 'bootstrap) (delete 'configure) (delete 'patch-generated-file-shebangs) (add-before 'unpack 'setup-go-environment setup-go-environment) (replace 'unpack unpack) (replace 'build build) (replace 'check check) (replace 'install install) (replace 'install-license-files install-license-files) (add-after 'install 'remove-go-references remove-go-references))) (define* (go-build #:key inputs (phases %standard-phases) #:allow-other-keys #:rest args) "Build the given Go package, applying all of PHASES in order." (apply gnu:gnu-build #:inputs inputs #:phases phases args))
null
https://raw.githubusercontent.com/dongcarl/guix/82543e9649da2da9a5285ede4ec4f718fd740fcb/guix/build/go-build-system.scm
scheme
GNU Guix --- Functional package management for GNU This file is part of GNU Guix. you can redistribute it and/or modify it either version 3 of the License , or ( at your option) any later version. GNU Guix is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. Commentary: Build procedures for Go packages. This is the builder-side code. Software written in Go is either a 'package' (i.e. library) or 'command' (i.e. executable). Both types can be built with either the `go build` or `go install` commands. However, `go build` discards the result of the build process for Go libraries, so we use `go install`, which preserves the results. [0] Go software is developed and built within a particular file system hierarchy the GOPATH environment variable. Typically, all Go source code and compiled objects are kept in a single workspace, but GOPATH may be a list of the Go-language dependencies. Previously, we made GOPATH a list of store directories, but stopped because Go programs started keeping references to <>. Go software, whether a package or a command, is uniquely named using an 'import path'. The import path is based on the URL of the software's source. Because most source code is provided over the internet, the import path is typically a combination of the remote URL and the source repository's file system structure. For example, the Go port of the common `du` command is hosted on github.com, at <>. Thus, the import It may be possible to automatically guess a package's import path based on the source URL, but we don't try that in this revision of the go-build-system. Modules of modular Go libraries are named uniquely with their file system paths. For example, the supplemental but "standardized" libraries developed by the Go upstream developers are available at library's import path is <golang.org/x/net/ipv4>. The source of such modular libraries must be unpacked at the top-level of the unpacked to <golang.org/x/net>. This is handled in the go-build-system with the optional #:unpack-path key. In general, Go software is built using a standardized build mechanism that all modules of modular libraries cannot be built with a single command. Each module must be built individually. This complicates certain cases, and these issues are currently resolved by creating a file system union of the required modules of such libraries. I think this could be improved in future revisions of the go-build-system. TODO: * Avoid copying dependencies into the build environment and / or avoid using a tmpdir when creating the inputs union. * Avoid the go-inputs hack * Stop needing remove-go-references (-trimpath ? ) * Remove module packages, only offering the full Git repos? This is more idiomatic, I think, because Go downloads Git repos, not modules. What are the trade-offs? [0] `go build`: `go install`: /#hdr-Compile_and_install_packages_and_dependencies bin/ hello # command executable outyet # command executable pkg/ linux_amd64/ github.com/golang/example/ stringutil.a # package object src/ github.com/golang/example/ .git/ # Git repository metadata hello/ hello.go # command source outyet/ main.go # command source main_test.go # test source stringutil/ reverse.go # package source reverse_test.go # test source .git/ # Git repository metadata bmp/ reader.go # package source ... (many more repositories and packages omitted) ... [4] /#hdr-Modules__module_versions__and_more Code: we need it to be a writable directory. Using the current working directory as GOPATH makes it easier for packagers who need to manipulate the unpacked source code. currently support modules, so turn modules off to continue using the old GOPATH behavior. XXX This should not check the file name of the store item. Instead we should pass, from the host side, the list of inputs that are packages using the go-build-system. Exclude the Go compiler Exclude the source code of the package being built print the name of packages as they are compiled print each command as it is invoked Respectively, strip the symbol table and debug information, and the DWARF symbol table. Can this also install commands??? return #t when FILE-NAME there is an example in (guix build grafts)." We cannot use `regexp-exec' here because it cannot deal with We remove this spurious reference to save bandwidth when installing Go place, but I'm not sure how to do that. The subject was discussed at: <-devel/2017-10/msg00207.html>
Copyright © 2016 Petter < > Copyright © 2017 , 2019 < > Copyright © 2019 < > Copyright © 2020 < > Copyright © 2020 < > Copyright © 2020 < > under the terms of the GNU General Public License as published by You should have received a copy of the GNU General Public License along with GNU . If not , see < / > . (define-module (guix build go-build-system) #:use-module ((guix build gnu-build-system) #:prefix gnu:) #:use-module (guix build union) #:use-module (guix build utils) #:use-module (ice-9 match) #:use-module (ice-9 ftw) #:use-module (srfi srfi-1) #:use-module (rnrs io ports) #:use-module (rnrs bytevectors) #:export (%standard-phases go-build)) structure called a ' workspace ' [ 1 ] . This workspace can be found by Go via directories [ 2 ] . In this go - build - system we create a file system union of these directories in Go 1.11 : path is < github.com/calmh/du > . [ 3 ] < , et cetera } > . The Go IPv4 file system structure of the library . So the IPv4 library should be that does not require any build scripts like . This means * Use Go modules [ 4 ] * Re - use compiled packages [ 5 ] /#hdr-Compile_packages_and_dependencies [ 1 ] Go workspace example , from < #Workspaces > : golang.org/x/image/ writer.go # package source [ 2 ] #GOPATH [ 3 ] #ImportPaths [ 5 ] (define* (setup-go-environment #:key inputs outputs #:allow-other-keys) "Prepare a Go build environment for INPUTS and OUTPUTS. Build a file system union of INPUTS. Export GOPATH, which helps the compiler find the source code of the package being built and its dependencies, and GOBIN, which determines where executables (\"commands\") are installed to. This phase is sometimes used by packages that use (guix build-system gnu) but have a handful of Go dependencies, so it should be self-contained." The Go cache is required starting in Go 1.12 . We do n't actually use it but (setenv "GOCACHE" "/tmp/go-cache") (setenv "GOPATH" (getcwd)) Go 1.13 uses go modules by default . The go build system does not (setenv "GO111MODULE" "off") (setenv "GOBIN" (string-append (assoc-ref outputs "out") "/bin")) (let ((tmpdir (tmpnam))) (match (go-inputs inputs) (((names . directories) ...) (union-build tmpdir (filter directory-exists? directories) #:create-all-directories? #t #:log-port (%make-void-port "w")))) XXX A little dance because ( guix build union ) does n't use mkdir - p. (copy-recursively tmpdir (string-append (getenv "GOPATH")) #:keep-mtime? #t) (delete-file-recursively tmpdir)) #t) (define* (unpack #:key source import-path unpack-path #:allow-other-keys) "Relative to $GOPATH, unpack SOURCE in UNPACK-PATH, or IMPORT-PATH when UNPACK-PATH is unset. If the SOURCE archive has a single top level directory, it is stripped so that the sources appear directly under UNPACK-PATH. When SOURCE is a directory, copy its content into UNPACK-PATH instead of unpacking." (define (unpack-maybe-strip source dest) (let* ((scratch-dir (string-append (or (getenv "TMPDIR") "/tmp") "/scratch-dir")) (out (mkdir-p scratch-dir))) (with-directory-excursion scratch-dir (if (string-suffix? ".zip" source) (invoke "unzip" source) (invoke "tar" "-xvf" source)) (let ((top-level-files (remove (lambda (x) (member x '("." ".."))) (scandir ".")))) (match top-level-files ((top-level-file) (when (file-is-directory? top-level-file) (copy-recursively top-level-file dest #:keep-mtime? #t))) (_ (copy-recursively "." dest #:keep-mtime? #t))))) (delete-file-recursively scratch-dir))) (when (string-null? import-path) (display "WARNING: The Go import path is unset.\n")) (when (string-null? unpack-path) (set! unpack-path import-path)) (let ((dest (string-append (getenv "GOPATH") "/src/" unpack-path))) (mkdir-p dest) (if (file-is-directory? source) (copy-recursively source dest #:keep-mtime? #t) (unpack-maybe-strip source dest))) #t) (define (go-package? name) (string-prefix? "go-" name)) (define (go-inputs inputs) "Return the alist of INPUTS that are Go software." (filter (match-lambda ((label . directory) (go-package? ((compose package-name->name+version strip-store-file-name) directory))) (_ #f)) inputs)))) (define* (build #:key import-path build-flags #:allow-other-keys) "Build the package named by IMPORT-PATH." (with-throw-handler #t (lambda _ (apply invoke "go" "install" "-ldflags=-s -w" `(,@build-flags ,import-path))) (lambda (key . args) (display (string-append "Building '" import-path "' failed.\n" "Here are the results of `go env`:\n")) (invoke "go" "env")))) (define* (check #:key tests? import-path #:allow-other-keys) "Run the tests for the package named by IMPORT-PATH." (when tests? (invoke "go" "test" import-path)) #t) (define* (install #:key install-source? outputs import-path unpack-path #:allow-other-keys) "Install the source code of IMPORT-PATH to the primary output directory. Compiled executable files (Go \"commands\") should have already been installed to the store based on $GOBIN in the build phase. XXX We can't make use of compiled libraries (Go \"packages\")." (when install-source? (if (string-null? import-path) ((display "WARNING: The Go import path is unset.\n"))) (let* ((out (assoc-ref outputs "out")) (source (string-append (getenv "GOPATH") "/src/" import-path)) (dest (string-append out "/src/" import-path))) (mkdir-p dest) (copy-recursively source dest #:keep-mtime? #t))) #t) (define* (install-license-files #:key unpack-path import-path #:allow-other-keys #:rest args) "Install license files matching LICENSE-FILE-REGEXP to 'share/doc'. Adjust the standard install-license-files phase to first enter the correct directory." (with-directory-excursion (string-append "src/" (if (string-null? unpack-path) import-path unpack-path)) (apply (assoc-ref gnu:%standard-phases 'install-license-files) args))) (define* (remove-store-reference file file-name #:optional (store (%store-directory))) is encountered in FILE, #f otherwise. This implementation reads FILE one byte at a time, which is slow. Instead, we should use the Boyer-Moore string search (define pattern (string-take file-name (+ 34 (string-length (%store-directory))))) (with-fluids ((%default-port-encoding #f)) (with-atomic-file-replacement file (lambda (in out) strings containing NUL characters . (format #t "removing references to `~a' from `~a'...~%" file-name file) (setvbuf in 'block 65536) (setvbuf out 'block 65536) (fold-port-matches (lambda (match result) (put-bytevector out (string->utf8 store)) (put-u8 out (char->integer #\/)) (put-bytevector out (string->utf8 "eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee-")) #t) #f pattern in (lambda (char result) (put-u8 out (char->integer char)) result)))))) (define* (remove-go-references #:key allow-go-reference? inputs outputs #:allow-other-keys) "Remove any references to the Go compiler from the compiled Go executable files in OUTPUTS." executables . It would be better to not embed the reference in the first (if allow-go-reference? #t (let ((go (assoc-ref inputs "go")) (bin "/bin")) (for-each (lambda (output) (when (file-exists? (string-append (cdr output) bin)) (for-each (lambda (file) (remove-store-reference file go)) (find-files (string-append (cdr output) bin))))) outputs) #t))) (define %standard-phases (modify-phases gnu:%standard-phases (delete 'bootstrap) (delete 'configure) (delete 'patch-generated-file-shebangs) (add-before 'unpack 'setup-go-environment setup-go-environment) (replace 'unpack unpack) (replace 'build build) (replace 'check check) (replace 'install install) (replace 'install-license-files install-license-files) (add-after 'install 'remove-go-references remove-go-references))) (define* (go-build #:key inputs (phases %standard-phases) #:allow-other-keys #:rest args) "Build the given Go package, applying all of PHASES in order." (apply gnu:gnu-build #:inputs inputs #:phases phases args))
2d0765df7e935d6af3cfe0464426b5283149f6fe75d9a4d25cccea40df0cc19b
jrslepak/Remora
dsp.rkt
#lang remora/dynamic (require racket/math) (require "idioms.rkt") (require "kernels.rkt") ;;; a simple yet naieve low pass filter ;;; y(n) = x(n) + x(n - 1) (define (simple-low-pass (seed 0) (data 1)) (define lpblock (append (curtail (rotate data 1)) [0])) (+ data lpblock)) ;;; a simple yet naieve high pass filter ;;; y(n) = x(n) - x(n - 1) (define (simple-high-pass (seed 0) (data 1)) (define hpblock (append (curtail (rotate data 1)) [0])) (- data hpblock)) ;;; a more reasonable low pass filter y(n ) = y(n - 1 ) - alpha * ( x(n - 1 ) - x(n ) ) (define (low-pass (seed 0) (alpha 0) (data 1)) (define (lp-step (x 0) (acc 2)) (define lx (head (head acc))) (define ly (tail (head acc))) (define ny (- ly (* alpha (- lx x)))) (append [[x ny]] acc)) (curtail (#r(1)tail (foldr lp-step [(reshape [2] seed)] data)))) ;;; a more reasonalbe high pass filter ;;; y(n) = α * (y(n - 1) + x(n) - x(n - 1)) (define (high-pass (seed 0) (alpha 0) (data 1)) (define (hp-step (x 0) (acc 2)) (define lx (head (head acc))) (define ly (tail (head acc))) (define ny (* alpha (- (+ ly x) lx))) (append [[x ny]] acc)) (curtail (#r(1)tail (foldr hp-step [(reshape [2] seed)] data)))) general FIR filter y(n ) = sum - > M - 1 of h(k ) * x(n - k ) (define (dot (a all) (b all)) (foldr + 0 (* a b))) sample FIR coefficients based on (define low-pass-kernel [-0.02010411882885732 -0.05842798004352509 -0.061178403647821976 -0.010939393385338943 0.05125096443534972 0.033220867678947885 -0.05655276971833928 -0.08565500737264514 0.0633795996605449 0.310854403656636 0.4344309124179415 0.310854403656636 0.0633795996605449 -0.08565500737264514 -0.05655276971833928 0.033220867678947885 0.05125096443534972 -0.010939393385338943 -0.061178403647821976 -0.05842798004352509 -0.02010411882885734]) (define high-pass-kernel [0.02857983994169657 -0.07328836181028245 0.04512928732568175 0.03422632401030237 -0.034724262386629436 -0.05343090761376418 0.032914528649623416 0.09880818246272206 -0.034135422078843417 -0.3160339484471911 0.5341936566511765 -0.3160339484471911 -0.034135422078843417 0.09880818246272206 0.03291452864962342 -0.0534309076137642 -0.034724262386629436 0.03422632401030237 0.04512928732568176 -0.07328836181028245 0.02857983994169657]) (define band-pass-kernel [0.008315515510919604 0.013703008819203135 -0.008125257257844711 -0.01649214060817737 -0.0016884593471476288 -0.006913035271285468 -0.03139161346522045 0.022740863526439097 0.11984908724116743 0.05186355035523461 -0.17137740316854042 -0.20124347467075893 0.08441813048666601 0.2816314309336389 0.08441813048666601 -0.20124347467075893 -0.17137740316854042 0.05186355035523461 0.1198490872411674 0.022740863526439097 -0.03139161346522045 -0.006913035271285468 -0.0016884593471476288 -0.01649214060817737 -0.008125257257844711 0.013703008819203135 0.008315515510919604]) (define band-stop-kernel [0.037391727827352596 -0.03299884552335981 0.04423058396732136 0.0023050970833628126 -0.06768087195950102 -0.04634710540912466 -0.011717387509232449 -0.07073422841851829 -0.04976651728299956 0.16086413543836361 0.21561058688743148 -0.10159456907827959 0.6638637561392535 -0.10159456907827963 0.21561058688743148 0.16086413543836361 -0.049766517282999544 -0.07073422841851829 -0.011717387509232449 -0.0463471054091247 -0.06768087195950102 0.0023050970833628126 0.04423058396732135 -0.0329988455233598 0.037391727827352596]) general FIR filter (define (fir-filter (coeffs 1) (data 1)) (dot coeffs (rotate data (iota [(length coeffs)])))) DFT (define (dft-angles (len 0)) (define transforms (position-matrix len)) (/ (* 2 pi (#r(1)head transforms) (#r(1)tail transforms)) len))
null
https://raw.githubusercontent.com/jrslepak/Remora/1a831dec554df9a7ef3eeb10f0d22036f1f86dbd/remora/examples/dsp.rkt
racket
a simple yet naieve low pass filter y(n) = x(n) + x(n - 1) a simple yet naieve high pass filter y(n) = x(n) - x(n - 1) a more reasonable low pass filter a more reasonalbe high pass filter y(n) = α * (y(n - 1) + x(n) - x(n - 1))
#lang remora/dynamic (require racket/math) (require "idioms.rkt") (require "kernels.rkt") (define (simple-low-pass (seed 0) (data 1)) (define lpblock (append (curtail (rotate data 1)) [0])) (+ data lpblock)) (define (simple-high-pass (seed 0) (data 1)) (define hpblock (append (curtail (rotate data 1)) [0])) (- data hpblock)) y(n ) = y(n - 1 ) - alpha * ( x(n - 1 ) - x(n ) ) (define (low-pass (seed 0) (alpha 0) (data 1)) (define (lp-step (x 0) (acc 2)) (define lx (head (head acc))) (define ly (tail (head acc))) (define ny (- ly (* alpha (- lx x)))) (append [[x ny]] acc)) (curtail (#r(1)tail (foldr lp-step [(reshape [2] seed)] data)))) (define (high-pass (seed 0) (alpha 0) (data 1)) (define (hp-step (x 0) (acc 2)) (define lx (head (head acc))) (define ly (tail (head acc))) (define ny (* alpha (- (+ ly x) lx))) (append [[x ny]] acc)) (curtail (#r(1)tail (foldr hp-step [(reshape [2] seed)] data)))) general FIR filter y(n ) = sum - > M - 1 of h(k ) * x(n - k ) (define (dot (a all) (b all)) (foldr + 0 (* a b))) sample FIR coefficients based on (define low-pass-kernel [-0.02010411882885732 -0.05842798004352509 -0.061178403647821976 -0.010939393385338943 0.05125096443534972 0.033220867678947885 -0.05655276971833928 -0.08565500737264514 0.0633795996605449 0.310854403656636 0.4344309124179415 0.310854403656636 0.0633795996605449 -0.08565500737264514 -0.05655276971833928 0.033220867678947885 0.05125096443534972 -0.010939393385338943 -0.061178403647821976 -0.05842798004352509 -0.02010411882885734]) (define high-pass-kernel [0.02857983994169657 -0.07328836181028245 0.04512928732568175 0.03422632401030237 -0.034724262386629436 -0.05343090761376418 0.032914528649623416 0.09880818246272206 -0.034135422078843417 -0.3160339484471911 0.5341936566511765 -0.3160339484471911 -0.034135422078843417 0.09880818246272206 0.03291452864962342 -0.0534309076137642 -0.034724262386629436 0.03422632401030237 0.04512928732568176 -0.07328836181028245 0.02857983994169657]) (define band-pass-kernel [0.008315515510919604 0.013703008819203135 -0.008125257257844711 -0.01649214060817737 -0.0016884593471476288 -0.006913035271285468 -0.03139161346522045 0.022740863526439097 0.11984908724116743 0.05186355035523461 -0.17137740316854042 -0.20124347467075893 0.08441813048666601 0.2816314309336389 0.08441813048666601 -0.20124347467075893 -0.17137740316854042 0.05186355035523461 0.1198490872411674 0.022740863526439097 -0.03139161346522045 -0.006913035271285468 -0.0016884593471476288 -0.01649214060817737 -0.008125257257844711 0.013703008819203135 0.008315515510919604]) (define band-stop-kernel [0.037391727827352596 -0.03299884552335981 0.04423058396732136 0.0023050970833628126 -0.06768087195950102 -0.04634710540912466 -0.011717387509232449 -0.07073422841851829 -0.04976651728299956 0.16086413543836361 0.21561058688743148 -0.10159456907827959 0.6638637561392535 -0.10159456907827963 0.21561058688743148 0.16086413543836361 -0.049766517282999544 -0.07073422841851829 -0.011717387509232449 -0.0463471054091247 -0.06768087195950102 0.0023050970833628126 0.04423058396732135 -0.0329988455233598 0.037391727827352596]) general FIR filter (define (fir-filter (coeffs 1) (data 1)) (dot coeffs (rotate data (iota [(length coeffs)])))) DFT (define (dft-angles (len 0)) (define transforms (position-matrix len)) (/ (* 2 pi (#r(1)head transforms) (#r(1)tail transforms)) len))
232a1eb0b3558e6f67467cf32719b7957ae8653a32c63a913a072be1de0da253
denibertovic/denv
Utils.hs
{-# LANGUAGE OverloadedStrings #-} # LANGUAGE ScopedTypeVariables # module Denv.Aws.Utils where import RIO import qualified Data.Text as T import qualified Network.AWS as AWS import qualified Data.Text.Encoding as TE import qualified Network.AWS as AWS import qualified Network.AWS.STS.Types as STS import System.FilePath ((</>)) import System.Directory (createDirectory, doesDirectoryExist, getHomeDirectory) import Denv.Aws.Types mkAwsSessionFileName :: AwsProfile -> Maybe AwsSourceProfile -> MfaSerial -> IO FilePath mkAwsSessionFileName p sourceProfile (MfaSerial mfaSerial) = do cacheDir <- makeCacheDir let profile = maybe (fromAwsProfile p) fromAwsSourceProfile sourceProfile return $ cacheDir </> (T.unpack $ profile <> "." <> normalize mfaSerial <> ".session_credentials.json") mkAwsRoleFileName :: AwsProfile -> RoleArn -> IO FilePath mkAwsRoleFileName p (RoleArn roleArn) = do cacheDir <- makeCacheDir return $ cacheDir </> (T.unpack $ (fromAwsProfile p) <> "." <> normalize roleArn <> ".role_credentials.json") makeCacheDir :: IO FilePath makeCacheDir = do h <- getHomeDirectory let dir = h </> ".aws-env" exists <- doesDirectoryExist dir unless exists (createDirectory dir) return dir normalize :: T.Text -> T.Text normalize t = T.replace "/" "_" $ T.replace ":" "_" t mkAwsAccessKey :: T.Text -> AWS.AccessKey mkAwsAccessKey t = AWS.AccessKey . TE.encodeUtf8 $ t mkAwsSecretKey :: T.Text -> AWS.SecretKey mkAwsSecretKey t = AWS.SecretKey . TE.encodeUtf8 $ t toRoleCache :: AWS.AuthEnv -> STS.AssumedRoleUser -> AwsEnvRoleCache toRoleCache creds ars = AwsEnvRoleCache { roleCacheAccessKeyId = creds ^. AWS.accessKeyId , roleCacheSecretAccessKey = creds ^. AWS.secretAccessKey , roleCacheSessionToken = creds ^. AWS.sessionToken , roleCacheExpiration = creds ^. AWS.expiration , roleCacheAssumedRoleUser = Just $ AwsEnvAssumedRoleUser { awsEnvAssumedRoleUserId = ars ^. STS.aruAssumedRoleId , awsEnvAssumedRoleUserArn = ars ^. STS.aruARN } } toSessionCache :: AWS.AuthEnv -> AwsEnvSessionCache toSessionCache creds = AwsEnvSessionCache { sessionCacheAccessKeyId = creds ^. AWS.accessKeyId , sessionCacheSecretAccessKey = creds ^. AWS.secretAccessKey , sessionCacheSessionToken = creds ^. AWS.sessionToken , sessionCacheExpiration = creds ^. AWS.expiration }
null
https://raw.githubusercontent.com/denibertovic/denv/86a3d612d8207daad75ad38a1711ad048e8f6113/src/Denv/Aws/Utils.hs
haskell
# LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables # module Denv.Aws.Utils where import RIO import qualified Data.Text as T import qualified Network.AWS as AWS import qualified Data.Text.Encoding as TE import qualified Network.AWS as AWS import qualified Network.AWS.STS.Types as STS import System.FilePath ((</>)) import System.Directory (createDirectory, doesDirectoryExist, getHomeDirectory) import Denv.Aws.Types mkAwsSessionFileName :: AwsProfile -> Maybe AwsSourceProfile -> MfaSerial -> IO FilePath mkAwsSessionFileName p sourceProfile (MfaSerial mfaSerial) = do cacheDir <- makeCacheDir let profile = maybe (fromAwsProfile p) fromAwsSourceProfile sourceProfile return $ cacheDir </> (T.unpack $ profile <> "." <> normalize mfaSerial <> ".session_credentials.json") mkAwsRoleFileName :: AwsProfile -> RoleArn -> IO FilePath mkAwsRoleFileName p (RoleArn roleArn) = do cacheDir <- makeCacheDir return $ cacheDir </> (T.unpack $ (fromAwsProfile p) <> "." <> normalize roleArn <> ".role_credentials.json") makeCacheDir :: IO FilePath makeCacheDir = do h <- getHomeDirectory let dir = h </> ".aws-env" exists <- doesDirectoryExist dir unless exists (createDirectory dir) return dir normalize :: T.Text -> T.Text normalize t = T.replace "/" "_" $ T.replace ":" "_" t mkAwsAccessKey :: T.Text -> AWS.AccessKey mkAwsAccessKey t = AWS.AccessKey . TE.encodeUtf8 $ t mkAwsSecretKey :: T.Text -> AWS.SecretKey mkAwsSecretKey t = AWS.SecretKey . TE.encodeUtf8 $ t toRoleCache :: AWS.AuthEnv -> STS.AssumedRoleUser -> AwsEnvRoleCache toRoleCache creds ars = AwsEnvRoleCache { roleCacheAccessKeyId = creds ^. AWS.accessKeyId , roleCacheSecretAccessKey = creds ^. AWS.secretAccessKey , roleCacheSessionToken = creds ^. AWS.sessionToken , roleCacheExpiration = creds ^. AWS.expiration , roleCacheAssumedRoleUser = Just $ AwsEnvAssumedRoleUser { awsEnvAssumedRoleUserId = ars ^. STS.aruAssumedRoleId , awsEnvAssumedRoleUserArn = ars ^. STS.aruARN } } toSessionCache :: AWS.AuthEnv -> AwsEnvSessionCache toSessionCache creds = AwsEnvSessionCache { sessionCacheAccessKeyId = creds ^. AWS.accessKeyId , sessionCacheSecretAccessKey = creds ^. AWS.secretAccessKey , sessionCacheSessionToken = creds ^. AWS.sessionToken , sessionCacheExpiration = creds ^. AWS.expiration }
116874113dfd0b63dec49792850d8d252328c747ec267bc08b867d4ba257c825
paf31/typescript-docs
Docs.hs
----------------------------------------------------------------------------- -- -- Module : Language.TypeScript.Docs Copyright : ( c ) DICOM Grid Inc. 2013 License : MIT -- Maintainer : < > -- Stability : experimental -- Portability : -- -- | -- ----------------------------------------------------------------------------- module Language.TypeScript.Docs ( convertDeclarationsToHtml, module Language.TypeScript.Docs.Comments, module Language.TypeScript.Docs.Html ) where import Language.TypeScript.Docs.Comments import Language.TypeScript.Docs.Html import Language.TypeScript.Parser import Text.Parsec import Text.Blaze.Html.Renderer.String import qualified Data.Map as M import Data.Maybe (fromMaybe) convertDeclarationsToHtml :: String -> Either String String convertDeclarationsToHtml dts = do decls <- either (Left . show) Right $ parse declarationSourceFile "TypeScript Declaration File" dts return . renderHtml . generateDocument $ appendComments dts decls
null
https://raw.githubusercontent.com/paf31/typescript-docs/d7fb77e3ffa7eb61a58835377b63aa6cc83d450d/src/Language/TypeScript/Docs.hs
haskell
--------------------------------------------------------------------------- Module : Language.TypeScript.Docs Stability : experimental Portability : | ---------------------------------------------------------------------------
Copyright : ( c ) DICOM Grid Inc. 2013 License : MIT Maintainer : < > module Language.TypeScript.Docs ( convertDeclarationsToHtml, module Language.TypeScript.Docs.Comments, module Language.TypeScript.Docs.Html ) where import Language.TypeScript.Docs.Comments import Language.TypeScript.Docs.Html import Language.TypeScript.Parser import Text.Parsec import Text.Blaze.Html.Renderer.String import qualified Data.Map as M import Data.Maybe (fromMaybe) convertDeclarationsToHtml :: String -> Either String String convertDeclarationsToHtml dts = do decls <- either (Left . show) Right $ parse declarationSourceFile "TypeScript Declaration File" dts return . renderHtml . generateDocument $ appendComments dts decls
b30f20f56558e478b96ea1eb28b4e097d571b58b0f749973cc60b0ef89f1b4e5
tweag/inline-js
Exception.hs
module Language.JavaScript.Inline.Core.Exception where import Control.Exception data NotThreadedRTS = NotThreadedRTS deriving (Show) instance Exception NotThreadedRTS data NodeVersionUnsupported = NodeVersionUnsupported deriving (Show) instance Exception NodeVersionUnsupported newtype EvalError = EvalError { evalErrorMessage :: String } deriving (Show) instance Exception EvalError data SessionClosed = SessionClosed deriving (Show) instance Exception SessionClosed
null
https://raw.githubusercontent.com/tweag/inline-js/ef675745e84d23d51c50660d40acf9e684fbb2d6/inline-js-core/src/Language/JavaScript/Inline/Core/Exception.hs
haskell
module Language.JavaScript.Inline.Core.Exception where import Control.Exception data NotThreadedRTS = NotThreadedRTS deriving (Show) instance Exception NotThreadedRTS data NodeVersionUnsupported = NodeVersionUnsupported deriving (Show) instance Exception NodeVersionUnsupported newtype EvalError = EvalError { evalErrorMessage :: String } deriving (Show) instance Exception EvalError data SessionClosed = SessionClosed deriving (Show) instance Exception SessionClosed
c694916f887b5c61fce451ff33a5b9fded4b033a358222fc36abd65d60a825fb
privet-kitty/cl-competitive
static-mod.lisp
(defpackage :cp/static-mod (:use :cl) (:export #:+mod+ #:mint #:mint-vector)) (in-package :cp/static-mod) (defconstant +mod+ (if (boundp 'cl-user::+mod+) (symbol-value 'cl-user::+mod+) 998244353)) (deftype mint () '(unsigned-byte 31)) (deftype mint-vector () '(simple-array mint (*)))
null
https://raw.githubusercontent.com/privet-kitty/cl-competitive/a2e4156e66417c051404ade181ce6305cb0c2824/module/static-mod.lisp
lisp
(defpackage :cp/static-mod (:use :cl) (:export #:+mod+ #:mint #:mint-vector)) (in-package :cp/static-mod) (defconstant +mod+ (if (boundp 'cl-user::+mod+) (symbol-value 'cl-user::+mod+) 998244353)) (deftype mint () '(unsigned-byte 31)) (deftype mint-vector () '(simple-array mint (*)))
7df680095c0296bf8c85f8091a1aca4087b56ce88301505387193d295fc6aa00
supermario/oak
Schema.hs
-- This is necessary to allow us to have the same field name in multiple records # LANGUAGE DuplicateRecordFields # module Schema where import Evergreen data ColorX = ColorX { id :: PrimaryInt , hex :: String , user :: User , createdAt :: Datetime , updatedAt :: Datetime } data Message = Message { id :: PrimaryInt , user :: User , createdAt :: Datetime , updatedAt :: Datetime } data User = User { id :: PrimaryInt , firstName :: String , lastName :: String , color :: ColorX , createdAt :: Datetime , updatedAt :: Datetime }
null
https://raw.githubusercontent.com/supermario/oak/220a4d378dd192aeebec6c10aa71d630669f7413/evergreen/Schema.hs
haskell
This is necessary to allow us to have the same field name in multiple records
# LANGUAGE DuplicateRecordFields # module Schema where import Evergreen data ColorX = ColorX { id :: PrimaryInt , hex :: String , user :: User , createdAt :: Datetime , updatedAt :: Datetime } data Message = Message { id :: PrimaryInt , user :: User , createdAt :: Datetime , updatedAt :: Datetime } data User = User { id :: PrimaryInt , firstName :: String , lastName :: String , color :: ColorX , createdAt :: Datetime , updatedAt :: Datetime }
27aa37c704eed4c52ae2d75358cb8fb68e5055c21f5d7bc2c6dc57296b85f0bd
finnishtransportagency/harja
yhteiset.cljs
(ns harja.tiedot.urakka.kulut.yhteiset (:require [harja.domain.kulut.valikatselmus :as valikatselmus] [harja.domain.muokkaustiedot :as muokkaustiedot] [harja.tiedot.urakka :as urakka-tiedot] [harja.pvm :as pvm] [harja.tiedot.urakka.urakka :as tila] [tuck.core :as tuck])) (def manuaalisen-kattohinnan-syoton-vuodet [2019 2020]) (defn oikaisujen-summa [oikaisut hoitokauden-alkuvuosi] (or (apply + (map ::valikatselmus/summa (filter #(and (not (or (:poistettu %) (::muokkaustiedot/poistettu? %)))) (-> oikaisut (get hoitokauden-alkuvuosi) vals)))) 0)) (defn budjettitavoite-valitulle-hoitokaudelle [app] (some->> app :budjettitavoite (filter #(= (:hoitokauden-alkuvuosi app) (:hoitokauden-alkuvuosi %))) first)) (defn oikaistu-tavoitehinta-valitulle-hoitokaudelle [app] (-> app budjettitavoite-valitulle-hoitokaudelle :tavoitehinta-oikaistu)) (defn hoitokauden-tavoitehinta ([hoitokauden-nro app oletusarvo] (let [tavoitehinta (some #(when (= hoitokauden-nro (:hoitokausi %)) (let [indeksikorjattu? (pos? (:tavoitehinta-indeksikorjattu %))] {:tavoitehinta (or (if indeksikorjattu? (:tavoitehinta-indeksikorjattu %) (:tavoitehinta %)) oletusarvo) :indeksikorjattu? indeksikorjattu?})) (:budjettitavoite app))] tavoitehinta)) ([hoitokauden-nro app] (hoitokauden-tavoitehinta hoitokauden-nro app nil))) (defn hoitokauden-tavoitehinta-vuodelle [hoitokauden-alkuvuosi app] (let [tavoitehinta (some #(when (= hoitokauden-alkuvuosi (:hoitokauden-alkuvuosi %)) (:tavoitehinta-indeksikorjattu %)) (:budjettitavoite app))] tavoitehinta)) (defn hoitokauden-oikaistu-tavoitehinta [hoitokauden-nro app] (let [tavoitehinta (some #(when (= hoitokauden-nro (:hoitokausi %)) (:tavoitehinta-oikaistu %)) (:budjettitavoite app))] tavoitehinta)) (defn hoitokauden-kattohinta ([hoitokauden-nro app oletusarvo] (let [kattohinta (some #(when (= hoitokauden-nro (:hoitokausi %)) (let [indeksikorjattu? (pos? (:kattohinta-indeksikorjattu %))] {:kattohinta (or (if indeksikorjattu? (:kattohinta-indeksikorjattu %) (:kattohinta %)) oletusarvo) :indeksikorjattu? indeksikorjattu?})) (:budjettitavoite app))] kattohinta)) ([hoitokauden-nro app] (hoitokauden-kattohinta hoitokauden-nro app nil))) (defn hoitokauden-oikaistu-kattohinta [hoitokauden-nro app] (let [kattohinta (some #(when (= hoitokauden-nro (:hoitokausi %)) (:kattohinta-oikaistu %)) (:budjettitavoite app))] kattohinta)) (defn valikatselmus-tekematta? [app] (let [valittu-hoitokauden-alkuvuosi (:hoitokauden-alkuvuosi app) valittu-hoitovuosi-nro (urakka-tiedot/hoitokauden-jarjestysnumero valittu-hoitokauden-alkuvuosi (-> @tila/yleiset :urakka :loppupvm)) {:keys [tavoitehinta]} (hoitokauden-tavoitehinta valittu-hoitovuosi-nro app 0) kattohinta (or (hoitokauden-oikaistu-kattohinta valittu-hoitovuosi-nro app) 0) toteuma (or (get-in app [:kustannukset-yhteensa :yht-toteutunut-summa]) 0) oikaisujen-summa (oikaisujen-summa (:tavoitehinnan-oikaisut app) valittu-hoitokauden-alkuvuosi) oikaistu-tavoitehinta (+ tavoitehinta oikaisujen-summa) oikaistu-kattohinta (+ kattohinta oikaisujen-summa) urakan-paatokset (:urakan-paatokset app) filtteroi-paatos-fn (fn [paatoksen-tyyppi] (first (filter #(and (= (::valikatselmus/hoitokauden-alkuvuosi %) valittu-hoitokauden-alkuvuosi) (= (::valikatselmus/tyyppi %) (name paatoksen-tyyppi))) urakan-paatokset))) tavoitehinta-alitettu? (> oikaistu-tavoitehinta toteuma) tavoitehinta-ylitetty? (> toteuma oikaistu-tavoitehinta) kattohinta-ylitetty? (> toteuma oikaistu-kattohinta) tavoitehinnan-alitus-paatos (filtteroi-paatos-fn :tavoitehinnan-alitus) tavoitehinnan-ylitys-paatos (filtteroi-paatos-fn :tavoitehinnan-ylitys) kattohinnan-ylitys-paatos (filtteroi-paatos-fn :kattohinnan-ylitys) lupausbonus-paatos (filtteroi-paatos-fn :lupausbonus) lupaussanktio-paatos (filtteroi-paatos-fn :lupaussanktio)] (and (<= valittu-hoitokauden-alkuvuosi (pvm/vuosi (pvm/nyt))) (or (and tavoitehinta-alitettu? (nil? tavoitehinnan-alitus-paatos)) (and tavoitehinta-ylitetty? (nil? tavoitehinnan-ylitys-paatos)) (and kattohinta-ylitetty? (nil? kattohinnan-ylitys-paatos)) (and (nil? lupaussanktio-paatos) (nil? lupausbonus-paatos)))))) (defrecord NollaaValikatselmuksenPaatokset []) (extend-protocol tuck/Event NollaaValikatselmuksenPaatokset (process-event [_ app] (dissoc app :kattohinnan-ylitys-lomake :lupausbonus-lomake :lupaussanktio-lomake :kattohinnan-oikaisu)))
null
https://raw.githubusercontent.com/finnishtransportagency/harja/11b8a2a6cf5737336bfa04d351583646c8050f15/src/cljs/harja/tiedot/urakka/kulut/yhteiset.cljs
clojure
(ns harja.tiedot.urakka.kulut.yhteiset (:require [harja.domain.kulut.valikatselmus :as valikatselmus] [harja.domain.muokkaustiedot :as muokkaustiedot] [harja.tiedot.urakka :as urakka-tiedot] [harja.pvm :as pvm] [harja.tiedot.urakka.urakka :as tila] [tuck.core :as tuck])) (def manuaalisen-kattohinnan-syoton-vuodet [2019 2020]) (defn oikaisujen-summa [oikaisut hoitokauden-alkuvuosi] (or (apply + (map ::valikatselmus/summa (filter #(and (not (or (:poistettu %) (::muokkaustiedot/poistettu? %)))) (-> oikaisut (get hoitokauden-alkuvuosi) vals)))) 0)) (defn budjettitavoite-valitulle-hoitokaudelle [app] (some->> app :budjettitavoite (filter #(= (:hoitokauden-alkuvuosi app) (:hoitokauden-alkuvuosi %))) first)) (defn oikaistu-tavoitehinta-valitulle-hoitokaudelle [app] (-> app budjettitavoite-valitulle-hoitokaudelle :tavoitehinta-oikaistu)) (defn hoitokauden-tavoitehinta ([hoitokauden-nro app oletusarvo] (let [tavoitehinta (some #(when (= hoitokauden-nro (:hoitokausi %)) (let [indeksikorjattu? (pos? (:tavoitehinta-indeksikorjattu %))] {:tavoitehinta (or (if indeksikorjattu? (:tavoitehinta-indeksikorjattu %) (:tavoitehinta %)) oletusarvo) :indeksikorjattu? indeksikorjattu?})) (:budjettitavoite app))] tavoitehinta)) ([hoitokauden-nro app] (hoitokauden-tavoitehinta hoitokauden-nro app nil))) (defn hoitokauden-tavoitehinta-vuodelle [hoitokauden-alkuvuosi app] (let [tavoitehinta (some #(when (= hoitokauden-alkuvuosi (:hoitokauden-alkuvuosi %)) (:tavoitehinta-indeksikorjattu %)) (:budjettitavoite app))] tavoitehinta)) (defn hoitokauden-oikaistu-tavoitehinta [hoitokauden-nro app] (let [tavoitehinta (some #(when (= hoitokauden-nro (:hoitokausi %)) (:tavoitehinta-oikaistu %)) (:budjettitavoite app))] tavoitehinta)) (defn hoitokauden-kattohinta ([hoitokauden-nro app oletusarvo] (let [kattohinta (some #(when (= hoitokauden-nro (:hoitokausi %)) (let [indeksikorjattu? (pos? (:kattohinta-indeksikorjattu %))] {:kattohinta (or (if indeksikorjattu? (:kattohinta-indeksikorjattu %) (:kattohinta %)) oletusarvo) :indeksikorjattu? indeksikorjattu?})) (:budjettitavoite app))] kattohinta)) ([hoitokauden-nro app] (hoitokauden-kattohinta hoitokauden-nro app nil))) (defn hoitokauden-oikaistu-kattohinta [hoitokauden-nro app] (let [kattohinta (some #(when (= hoitokauden-nro (:hoitokausi %)) (:kattohinta-oikaistu %)) (:budjettitavoite app))] kattohinta)) (defn valikatselmus-tekematta? [app] (let [valittu-hoitokauden-alkuvuosi (:hoitokauden-alkuvuosi app) valittu-hoitovuosi-nro (urakka-tiedot/hoitokauden-jarjestysnumero valittu-hoitokauden-alkuvuosi (-> @tila/yleiset :urakka :loppupvm)) {:keys [tavoitehinta]} (hoitokauden-tavoitehinta valittu-hoitovuosi-nro app 0) kattohinta (or (hoitokauden-oikaistu-kattohinta valittu-hoitovuosi-nro app) 0) toteuma (or (get-in app [:kustannukset-yhteensa :yht-toteutunut-summa]) 0) oikaisujen-summa (oikaisujen-summa (:tavoitehinnan-oikaisut app) valittu-hoitokauden-alkuvuosi) oikaistu-tavoitehinta (+ tavoitehinta oikaisujen-summa) oikaistu-kattohinta (+ kattohinta oikaisujen-summa) urakan-paatokset (:urakan-paatokset app) filtteroi-paatos-fn (fn [paatoksen-tyyppi] (first (filter #(and (= (::valikatselmus/hoitokauden-alkuvuosi %) valittu-hoitokauden-alkuvuosi) (= (::valikatselmus/tyyppi %) (name paatoksen-tyyppi))) urakan-paatokset))) tavoitehinta-alitettu? (> oikaistu-tavoitehinta toteuma) tavoitehinta-ylitetty? (> toteuma oikaistu-tavoitehinta) kattohinta-ylitetty? (> toteuma oikaistu-kattohinta) tavoitehinnan-alitus-paatos (filtteroi-paatos-fn :tavoitehinnan-alitus) tavoitehinnan-ylitys-paatos (filtteroi-paatos-fn :tavoitehinnan-ylitys) kattohinnan-ylitys-paatos (filtteroi-paatos-fn :kattohinnan-ylitys) lupausbonus-paatos (filtteroi-paatos-fn :lupausbonus) lupaussanktio-paatos (filtteroi-paatos-fn :lupaussanktio)] (and (<= valittu-hoitokauden-alkuvuosi (pvm/vuosi (pvm/nyt))) (or (and tavoitehinta-alitettu? (nil? tavoitehinnan-alitus-paatos)) (and tavoitehinta-ylitetty? (nil? tavoitehinnan-ylitys-paatos)) (and kattohinta-ylitetty? (nil? kattohinnan-ylitys-paatos)) (and (nil? lupaussanktio-paatos) (nil? lupausbonus-paatos)))))) (defrecord NollaaValikatselmuksenPaatokset []) (extend-protocol tuck/Event NollaaValikatselmuksenPaatokset (process-event [_ app] (dissoc app :kattohinnan-ylitys-lomake :lupausbonus-lomake :lupaussanktio-lomake :kattohinnan-oikaisu)))
fb54f909d56735c80c9bec7d9fa54262418adc06b43ed8aaf1c3ca0985040175
rudolph-miller/clipper
1.usage.lisp
(in-package :cl-user) (defpackage clipper.sample (:use :cl :integral :clipper)) (in-package :clipper.sample) (connect-toplevel :mysql :database-name "clipper_sample" :username "root") (defclass picture () ((id :col-type (:integer 11) :primary-key t :auto-increment t :not-null t :initarg :id) (image-file-name :col-type (:varchar 255) :initarg :image-file-name) (image-content-type :col-type (:varchar 255) :initarg :image-content-type) (image-file-size :col-type (:integer 11) :initarg :image-file-size) (url :type string :initarg :url)) (:metaclass <dao-table-class>) (:table-name "pictures")) (setup-clipper :store-type :s3 :aws-access-key (asdf::getenv "AWS_ACCESS_KEY") :aws-secret-key (asdf::getenv "AWS_SECRET_KEY") :s3-endpoint "s3-ap-northeast-1.amazonaws.com" :s3-bucket-name "clipper-sample" :clipper-class (find-class 'picture) :format ":ID/:FILE-NAME.:EXTENSION") (let ((object (create-dao 'picture))) (save-dao (attach-image object :url "")) (image-url object)) => "-ap-northeast-1.amazonaws.com/clipper-sample/1/lisplogo_alien_256.png" (setup-clipper :store-type :local :image-directory #P"/home/cl-user/common-lisp/clipper/images/" :relative #P"/home/cl-user/common-lisp/clipper/" :prefix ":3000/" :clipper-class (find-class 'picture) :format ":ID/:FILE-NAME.:EXTENSION") (let ((object (create-dao 'picture))) (save-dao (attach-image object :url "")) (image-url object)) => ":3000/images/2/lisplogo_alien_256.png"
null
https://raw.githubusercontent.com/rudolph-miller/clipper/b07a1be210d5504cd67c8e303168cb4bc09f642e/examples/1.usage.lisp
lisp
(in-package :cl-user) (defpackage clipper.sample (:use :cl :integral :clipper)) (in-package :clipper.sample) (connect-toplevel :mysql :database-name "clipper_sample" :username "root") (defclass picture () ((id :col-type (:integer 11) :primary-key t :auto-increment t :not-null t :initarg :id) (image-file-name :col-type (:varchar 255) :initarg :image-file-name) (image-content-type :col-type (:varchar 255) :initarg :image-content-type) (image-file-size :col-type (:integer 11) :initarg :image-file-size) (url :type string :initarg :url)) (:metaclass <dao-table-class>) (:table-name "pictures")) (setup-clipper :store-type :s3 :aws-access-key (asdf::getenv "AWS_ACCESS_KEY") :aws-secret-key (asdf::getenv "AWS_SECRET_KEY") :s3-endpoint "s3-ap-northeast-1.amazonaws.com" :s3-bucket-name "clipper-sample" :clipper-class (find-class 'picture) :format ":ID/:FILE-NAME.:EXTENSION") (let ((object (create-dao 'picture))) (save-dao (attach-image object :url "")) (image-url object)) => "-ap-northeast-1.amazonaws.com/clipper-sample/1/lisplogo_alien_256.png" (setup-clipper :store-type :local :image-directory #P"/home/cl-user/common-lisp/clipper/images/" :relative #P"/home/cl-user/common-lisp/clipper/" :prefix ":3000/" :clipper-class (find-class 'picture) :format ":ID/:FILE-NAME.:EXTENSION") (let ((object (create-dao 'picture))) (save-dao (attach-image object :url "")) (image-url object)) => ":3000/images/2/lisplogo_alien_256.png"
8e7d8fea2f34004af0ebd91a577742be26d009e255b6d8983a3085d1cdf112e6
rescript-lang/rescript-compiler
parsetree.ml
(**************************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt (* *) Copyright 1996 Institut National de Recherche en Informatique et (* en Automatique. *) (* *) (* All rights reserved. This file is distributed under the terms of *) the GNU Lesser General Public License version 2.1 , with the (* special exception on linking described in the file LICENSE. *) (* *) (**************************************************************************) (** Abstract syntax tree produced by parsing *) open Asttypes type constant = Pconst_integer of string * char option 3 3l 3L 3n Suffixes [ g - z][G - Z ] are accepted by the parser . Suffixes except ' l ' , ' L ' and ' n ' are rejected by the typechecker Suffixes [g-z][G-Z] are accepted by the parser. Suffixes except 'l', 'L' and 'n' are rejected by the typechecker *) | Pconst_char of int (* 'c' *) | Pconst_string of string * string option " constant " { } {delim|other constant|delim} *) | Pconst_float of string * char option (* 3.4 2e5 1.4e-4 Suffixes [g-z][G-Z] are accepted by the parser. Suffixes are rejected by the typechecker. *) * { 1 Extension points } type attribute = string loc * payload (* [@id ARG] [@@id ARG] Metadata containers passed around within the AST. The compiler ignores unknown attributes. *) and extension = string loc * payload (* [%id ARG] [%%id ARG] Sub-language placeholder -- rejected by the typechecker. *) and attributes = attribute list and payload = | PStr of structure : SIG | PTyp of core_type (* : T *) | PPat of pattern * expression option (* ? P or ? P when E *) * { 1 Core language } (* Type expressions *) and core_type = { ptyp_desc: core_type_desc; ptyp_loc: Location.t; ptyp_attributes: attributes; (* ... [@id1] [@id2] *) } and core_type_desc = | Ptyp_any (* _ *) | Ptyp_var of string (* 'a *) | Ptyp_arrow of arg_label * core_type * core_type (* T1 -> T2 Simple ~l:T1 -> T2 Labelled ?l:T1 -> T2 Optional *) | Ptyp_tuple of core_type list T1 * ... * Tn Invariant : n > = 2 Invariant: n >= 2 *) | Ptyp_constr of Longident.t loc * core_type list (* tconstr T tconstr (T1, ..., Tn) tconstr *) | Ptyp_object of object_field list * closed_flag (* < l1:T1; ...; ln:Tn > (flag = Closed) < l1:T1; ...; ln:Tn; .. > (flag = Open) *) | Ptyp_class of Longident.t loc * core_type list # tconstr T # tconstr ( T1 , ... , Tn ) # tconstr T #tconstr (T1, ..., Tn) #tconstr *) | Ptyp_alias of core_type * string (* T as 'a *) | Ptyp_variant of row_field list * closed_flag * label list option (* [ `A|`B ] (flag = Closed; labels = None) [> `A|`B ] (flag = Open; labels = None) [< `A|`B ] (flag = Closed; labels = Some []) [< `A|`B > `X `Y ](flag = Closed; labels = Some ["X";"Y"]) *) | Ptyp_poly of string loc list * core_type ' a1 ... ' an . T Can only appear in the following context : - As the core_type of a Ppat_constraint node corresponding to a constraint on a let - binding : let x : ' a1 ... ' an . T = e ... - Under Cfk_virtual for methods ( not values ) . - As the core_type of a Pctf_method node . - As the core_type of a Pexp_poly node . - As the pld_type field of a label_declaration . - As a core_type of a Ptyp_object node . Can only appear in the following context: - As the core_type of a Ppat_constraint node corresponding to a constraint on a let-binding: let x : 'a1 ... 'an. T = e ... - Under Cfk_virtual for methods (not values). - As the core_type of a Pctf_method node. - As the core_type of a Pexp_poly node. - As the pld_type field of a label_declaration. - As a core_type of a Ptyp_object node. *) | Ptyp_package of package_type (* (module S) *) | Ptyp_extension of extension (* [%id] *) and package_type = Longident.t loc * (Longident.t loc * core_type) list (* (module S) (module S with type t1 = T1 and ... and tn = Tn) *) and row_field = | Rtag of label loc * attributes * bool * core_type list [ ` A ] ( true , [ ] ) [ ` A of T ] ( false , [ T ] ) [ ` A of T1 & .. & Tn ] ( false , [ T1; ... Tn ] ) [ ` A of & T1 & .. & Tn ] ( true , [ T1; ... Tn ] ) - The 2nd field is true if the tag contains a constant ( empty ) constructor . - ' & ' occurs when several types are used for the same constructor ( see 4.2 in the manual ) - TODO : switch to a record representation , and keep location [`A of T] ( false, [T] ) [`A of T1 & .. & Tn] ( false, [T1;...Tn] ) [`A of & T1 & .. & Tn] ( true, [T1;...Tn] ) - The 2nd field is true if the tag contains a constant (empty) constructor. - '&' occurs when several types are used for the same constructor (see 4.2 in the manual) - TODO: switch to a record representation, and keep location *) | Rinherit of core_type (* [ T ] *) and object_field = | Otag of label loc * attributes * core_type | Oinherit of core_type (* Patterns *) and pattern = { ppat_desc: pattern_desc; ppat_loc: Location.t; ppat_attributes: attributes; (* ... [@id1] [@id2] *) } and pattern_desc = | Ppat_any (* _ *) | Ppat_var of string loc (* x *) | Ppat_alias of pattern * string loc (* P as 'a *) | Ppat_constant of constant 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n | Ppat_interval of constant * constant (* 'a'..'z' Other forms of interval are recognized by the parser but rejected by the type-checker. *) | Ppat_tuple of pattern list ( P1 , ... , Pn ) Invariant : n > = 2 Invariant: n >= 2 *) | Ppat_construct of Longident.t loc * pattern option C None C P Some P C ( P1 , ... , Pn ) Some ( Ppat_tuple [ P1 ; ... ; Pn ] ) C P Some P C (P1, ..., Pn) Some (Ppat_tuple [P1; ...; Pn]) *) | Ppat_variant of label * pattern option (* `A (None) `A P (Some P) *) | Ppat_record of (Longident.t loc * pattern) list * closed_flag { l1 = P1 ; ... ; ln = Pn } ( flag = Closed ) { l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open ) Invariant : n > 0 { l1=P1; ...; ln=Pn; _} (flag = Open) Invariant: n > 0 *) | Ppat_array of pattern list (* [| P1; ...; Pn |] *) | Ppat_or of pattern * pattern P1 | P2 | Ppat_constraint of pattern * core_type (* (P : T) *) | Ppat_type of Longident.t loc (* #tconst *) | Ppat_lazy of pattern (* lazy P *) | Ppat_unpack of string loc (* (module P) Note: (module P : S) is represented as Ppat_constraint(Ppat_unpack, Ptyp_package) *) | Ppat_exception of pattern (* exception P *) | Ppat_extension of extension (* [%id] *) | Ppat_open of Longident.t loc * pattern (* M.(P) *) (* Value expressions *) and expression = { pexp_desc: expression_desc; pexp_loc: Location.t; pexp_attributes: attributes; (* ... [@id1] [@id2] *) } and expression_desc = | Pexp_ident of Longident.t loc (* x M.x *) | Pexp_constant of constant 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n | Pexp_let of rec_flag * value_binding list * expression let P1 = E1 and ... and Pn = EN in E ( flag = ) let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive ) let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive) *) | Pexp_function of case list (* function P1 -> E1 | ... | Pn -> En *) | Pexp_fun of arg_label * expression option * pattern * expression fun P - > E1 ( Simple , None ) fun ~l :P - > E1 ( Labelled l , None ) fun ? l :P - > E1 ( Optional l , None ) fun ? l:(P = E0 ) - > E1 ( Optional l , Some E0 ) Notes : - If E0 is provided , only Optional is allowed . - " fun P1 P2 .. Pn - > E1 " is represented as nested Pexp_fun . - " let f P = E " is represented using Pexp_fun . fun ~l:P -> E1 (Labelled l, None) fun ?l:P -> E1 (Optional l, None) fun ?l:(P = E0) -> E1 (Optional l, Some E0) Notes: - If E0 is provided, only Optional is allowed. - "fun P1 P2 .. Pn -> E1" is represented as nested Pexp_fun. - "let f P = E" is represented using Pexp_fun. *) | Pexp_apply of expression * (arg_label * expression) list E0 ~l1 : E1 ... ~ln : En li can be empty ( non labeled argument ) or start with ' ? ' ( optional argument ) . Invariant : n > 0 li can be empty (non labeled argument) or start with '?' (optional argument). Invariant: n > 0 *) | Pexp_match of expression * case list match E0 with P1 - > E1 | ... | Pn - > En | Pexp_try of expression * case list try E0 with P1 - > E1 | ... | Pn - > En | Pexp_tuple of expression list ( E1 , ... , En ) Invariant : n > = 2 Invariant: n >= 2 *) | Pexp_construct of Longident.t loc * expression option (* C None C E Some E C (E1, ..., En) Some (Pexp_tuple[E1;...;En]) *) | Pexp_variant of label * expression option (* `A (None) `A E (Some E) *) | Pexp_record of (Longident.t loc * expression) list * expression option { l1 = P1 ; ... ; ln = Pn } ( None ) { E0 with l1 = P1 ; ... ; ln = Pn } ( Some E0 ) Invariant : n > 0 { E0 with l1=P1; ...; ln=Pn } (Some E0) Invariant: n > 0 *) | Pexp_field of expression * Longident.t loc (* E.l *) | Pexp_setfield of expression * Longident.t loc * expression E1.l < - E2 | Pexp_array of expression list (* [| E1; ...; En |] *) | Pexp_ifthenelse of expression * expression * expression option if E1 then E2 else E3 | Pexp_sequence of expression * expression (* E1; E2 *) | Pexp_while of expression * expression (* while E1 do E2 done *) | Pexp_for of pattern * expression * expression * direction_flag * expression for i = E1 to E2 do E3 done ( flag = Upto ) for i = E1 downto E2 do E3 done ( flag = ) for i = E1 downto E2 do E3 done (flag = Downto) *) | Pexp_constraint of expression * core_type (* (E : T) *) | Pexp_coerce of expression * core_type option * core_type (* (E :> T) (None, T) (E : T0 :> T) (Some T0, T) *) | Pexp_send of expression * label loc (* E # m *) | Pexp_new of Longident.t loc (* new M.c *) | Pexp_setinstvar of label loc * expression (* x <- 2 *) | Pexp_override of (label loc * expression) list { < x1 = E1 ; ... ; > } | Pexp_letmodule of string loc * module_expr * expression (* let module M = ME in E *) | Pexp_letexception of extension_constructor * expression (* let exception C in E *) | Pexp_assert of expression (* assert E Note: "assert false" is treated in a special way by the type-checker. *) | Pexp_lazy of expression (* lazy E *) | Pexp_poly of expression * core_type option Used for method bodies . Can only be used as the expression under for methods ( not values ) . Can only be used as the expression under Cfk_concrete for methods (not values). *) | Pexp_object of class_structure (* object ... end *) | Pexp_newtype of string loc * expression (* fun (type t) -> E *) | Pexp_pack of module_expr (* (module ME) (module ME : S) is represented as Pexp_constraint(Pexp_pack, Ptyp_package S) *) | Pexp_open of override_flag * Longident.t loc * expression (* M.(E) let open M in E let! open M in E *) | Pexp_extension of extension (* [%id] *) | Pexp_unreachable (* . *) and case = (* (P -> E) or (P when E0 -> E) *) { pc_lhs: pattern; pc_guard: expression option; pc_rhs: expression; } (* Value descriptions *) and value_description = { pval_name: string loc; pval_type: core_type; pval_prim: string list; pval_attributes: attributes; (* ... [@@id1] [@@id2] *) pval_loc: Location.t; } (* val x: T (prim = []) external x: T = "s1" ... "sn" (prim = ["s1";..."sn"]) *) (* Type declarations *) and type_declaration = { ptype_name: string loc; ptype_params: (core_type * variance) list; (* ('a1,...'an) t; None represents _*) ptype_cstrs: (core_type * core_type * Location.t) list; ... constraint T1 = T1 ' ... constraint ptype_kind: type_kind; ptype_private: private_flag; (* = private ... *) ptype_manifest: core_type option; (* = T *) ptype_attributes: attributes; (* ... [@@id1] [@@id2] *) ptype_loc: Location.t; } (* type t (abstract, no manifest) type t = T0 (abstract, manifest=T0) type t = C of T | ... (variant, no manifest) type t = T0 = C of T | ... (variant, manifest=T0) type t = {l: T; ...} (record, no manifest) type t = T0 = {l : T; ...} (record, manifest=T0) type t = .. (open, no manifest) *) and type_kind = | Ptype_abstract | Ptype_variant of constructor_declaration list (* Invariant: non-empty list *) | Ptype_record of label_declaration list (* Invariant: non-empty list *) | Ptype_open and label_declaration = { pld_name: string loc; pld_mutable: mutable_flag; pld_type: core_type; pld_loc: Location.t; pld_attributes: attributes; (* l : T [@id1] [@id2] *) } (* { ...; l: T; ... } (mutable=Immutable) { ...; mutable l: T; ... } (mutable=Mutable) Note: T can be a Ptyp_poly. *) and constructor_declaration = { pcd_name: string loc; pcd_args: constructor_arguments; pcd_res: core_type option; pcd_loc: Location.t; pcd_attributes: attributes; (* C of ... [@id1] [@id2] *) } and constructor_arguments = | Pcstr_tuple of core_type list | Pcstr_record of label_declaration list (* | C of T1 * ... * Tn (res = None, args = Pcstr_tuple []) | C: T0 (res = Some T0, args = []) | C: T1 * ... * Tn -> T0 (res = Some T0, args = Pcstr_tuple) | C of {...} (res = None, args = Pcstr_record) | C: {...} -> T0 (res = Some T0, args = Pcstr_record) | C of {...} as t (res = None, args = Pcstr_record) *) and type_extension = { ptyext_path: Longident.t loc; ptyext_params: (core_type * variance) list; ptyext_constructors: extension_constructor list; ptyext_private: private_flag; ptyext_attributes: attributes; (* ... [@@id1] [@@id2] *) } (* type t += ... *) and extension_constructor = { pext_name: string loc; pext_kind : extension_constructor_kind; pext_loc : Location.t; pext_attributes: attributes; (* C of ... [@id1] [@id2] *) } and extension_constructor_kind = Pext_decl of constructor_arguments * core_type option (* | C of T1 * ... * Tn ([T1; ...; Tn], None) | C: T0 ([], Some T0) | C: T1 * ... * Tn -> T0 ([T1; ...; Tn], Some T0) *) | Pext_rebind of Longident.t loc (* | C = D *) (** {1 Class language} *) (* Type expressions for the class language *) and class_type = { pcty_desc: class_type_desc; pcty_loc: Location.t; pcty_attributes: attributes; (* ... [@id1] [@id2] *) } and class_type_desc = | Pcty_constr of Longident.t loc * core_type list (* c ['a1, ..., 'an] c *) | Pcty_signature of class_signature (* object ... end *) | Pcty_arrow of arg_label * core_type * class_type (* T -> CT Simple ~l:T -> CT Labelled l ?l:T -> CT Optional l *) | Pcty_extension of extension (* [%id] *) | Pcty_open of override_flag * Longident.t loc * class_type (* let open M in CT *) and class_signature = { pcsig_self: core_type; pcsig_fields: class_type_field list; } (* object('selfpat) ... end object ... end (self = Ptyp_any) *) and class_type_field = { pctf_desc: class_type_field_desc; pctf_loc: Location.t; pctf_attributes: attributes; (* ... [@@id1] [@@id2] *) } and class_type_field_desc = | Pctf_inherit of class_type (* inherit CT *) | Pctf_val of (label loc * mutable_flag * virtual_flag * core_type) (* val x: T *) | Pctf_method of (label loc * private_flag * virtual_flag * core_type) (* method x: T Note: T can be a Ptyp_poly. *) | Pctf_constraint of (core_type * core_type) (* constraint T1 = T2 *) | Pctf_attribute of attribute (* [@@@id] *) | Pctf_extension of extension (* [%%id] *) and 'a class_infos = { pci_virt: virtual_flag; pci_params: (core_type * variance) list; pci_name: string loc; pci_expr: 'a; pci_loc: Location.t; pci_attributes: attributes; (* ... [@@id1] [@@id2] *) } (* class c = ... class ['a1,...,'an] c = ... class virtual c = ... Also used for "class type" declaration. *) and class_type_declaration = class_type class_infos (* Value expressions for the class language *) and class_expr = { pcl_desc: class_expr_desc; pcl_loc: Location.t; pcl_attributes: attributes; (* ... [@id1] [@id2] *) } and class_expr_desc = | Pcl_constr of Longident.t loc * core_type list (* c ['a1, ..., 'an] c *) | Pcl_structure of class_structure (* object ... end *) | Pcl_fun of arg_label * expression option * pattern * class_expr (* fun P -> CE (Simple, None) fun ~l:P -> CE (Labelled l, None) fun ?l:P -> CE (Optional l, None) fun ?l:(P = E0) -> CE (Optional l, Some E0) *) | Pcl_apply of class_expr * (arg_label * expression) list (* CE ~l1:E1 ... ~ln:En li can be empty (non labeled argument) or start with '?' (optional argument). Invariant: n > 0 *) | Pcl_let of rec_flag * value_binding list * class_expr let P1 = E1 and ... and Pn = EN in CE ( flag = ) let rec P1 = E1 and ... and Pn = EN in CE ( flag = Recursive ) let rec P1 = E1 and ... and Pn = EN in CE (flag = Recursive) *) | Pcl_constraint of class_expr * class_type (* (CE : CT) *) | Pcl_extension of extension (* [%id] *) | Pcl_open of override_flag * Longident.t loc * class_expr (* let open M in CE *) and class_structure = { pcstr_self: pattern; pcstr_fields: class_field list; } (* object(selfpat) ... end object ... end (self = Ppat_any) *) and class_field = { pcf_desc: class_field_desc; pcf_loc: Location.t; pcf_attributes: attributes; (* ... [@@id1] [@@id2] *) } and class_field_desc = | Pcf_inherit of unit (* inherit CE inherit CE as x inherit! CE inherit! CE as x *) | Pcf_val of (label loc * mutable_flag * class_field_kind) (* val x = E val virtual x: T *) | Pcf_method of (label loc * private_flag * class_field_kind) method x = E ( E can be a Pexp_poly ) method virtual x : T ( T can be a Ptyp_poly ) method virtual x: T (T can be a Ptyp_poly) *) | Pcf_constraint of (core_type * core_type) (* constraint T1 = T2 *) | Pcf_initializer of expression (* initializer E *) | Pcf_attribute of attribute (* [@@@id] *) | Pcf_extension of extension (* [%%id] *) and class_field_kind = | Cfk_virtual of core_type | Cfk_concrete of override_flag * expression (** {1 Module language} *) (* Type expressions for the module language *) and module_type = { pmty_desc: module_type_desc; pmty_loc: Location.t; pmty_attributes: attributes; (* ... [@id1] [@id2] *) } and module_type_desc = | Pmty_ident of Longident.t loc (* S *) | Pmty_signature of signature (* sig ... end *) | Pmty_functor of string loc * module_type option * module_type functor(X : ) - > MT2 | Pmty_with of module_type * with_constraint list (* MT with ... *) | Pmty_typeof of module_expr (* module type of ME *) | Pmty_extension of extension (* [%id] *) | Pmty_alias of Longident.t loc (* (module M) *) and signature = signature_item list and signature_item = { psig_desc: signature_item_desc; psig_loc: Location.t; } and signature_item_desc = | Psig_value of value_description x : T external x : T = " s1 " ... " sn " val x: T external x: T = "s1" ... "sn" *) | Psig_type of rec_flag * type_declaration list (* type t1 = ... and ... and tn = ... *) | Psig_typext of type_extension (* type t1 += ... *) | Psig_exception of extension_constructor (* exception C of T *) | Psig_module of module_declaration (* module X : MT *) | Psig_recmodule of module_declaration list module rec X1 : and ... and Xn : MTn | Psig_modtype of module_type_declaration (* module type S = MT module type S *) | Psig_open of open_description (* open X *) | Psig_include of include_description include MT | Psig_class of unit (* class c1 : ... and ... and cn : ... *) | Psig_class_type of class_type_declaration list (* class type ct1 = ... and ... and ctn = ... *) | Psig_attribute of attribute (* [@@@id] *) | Psig_extension of extension * attributes (* [%%id] *) and module_declaration = { pmd_name: string loc; pmd_type: module_type; pmd_attributes: attributes; (* ... [@@id1] [@@id2] *) pmd_loc: Location.t; } (* S : MT *) and module_type_declaration = { pmtd_name: string loc; pmtd_type: module_type option; pmtd_attributes: attributes; (* ... [@@id1] [@@id2] *) pmtd_loc: Location.t; } S = MT S ( abstract module type declaration , pmtd_type = None ) S (abstract module type declaration, pmtd_type = None) *) and open_description = { popen_lid: Longident.t loc; popen_override: override_flag; popen_loc: Location.t; popen_attributes: attributes; } (* open! X - popen_override = Override (silences the 'used identifier shadowing' warning) open X - popen_override = Fresh *) and 'a include_infos = { pincl_mod: 'a; pincl_loc: Location.t; pincl_attributes: attributes; } and include_description = module_type include_infos include MT and include_declaration = module_expr include_infos (* include ME *) and with_constraint = | Pwith_type of Longident.t loc * type_declaration (* with type X.t = ... Note: the last component of the longident must match the name of the type_declaration. *) | Pwith_module of Longident.t loc * Longident.t loc (* with module X.Y = Z *) | Pwith_typesubst of Longident.t loc * type_declaration (* with type X.t := ..., same format as [Pwith_type] *) | Pwith_modsubst of Longident.t loc * Longident.t loc (* with module X.Y := Z *) (* Value expressions for the module language *) and module_expr = { pmod_desc: module_expr_desc; pmod_loc: Location.t; pmod_attributes: attributes; (* ... [@id1] [@id2] *) } and module_expr_desc = | Pmod_ident of Longident.t loc (* X *) | Pmod_structure of structure (* struct ... end *) | Pmod_functor of string loc * module_type option * module_expr functor(X : ) - > ME | Pmod_apply of module_expr * module_expr (* ME1(ME2) *) | Pmod_constraint of module_expr * module_type (* (ME : MT) *) | Pmod_unpack of expression ( E ) | Pmod_extension of extension (* [%id] *) and structure = structure_item list and structure_item = { pstr_desc: structure_item_desc; pstr_loc: Location.t; } and structure_item_desc = | Pstr_eval of expression * attributes (* E *) | Pstr_value of rec_flag * value_binding list let P1 = E1 and ... and Pn = EN ( flag = ) let rec P1 = E1 and ... and Pn = EN ( flag = Recursive ) let rec P1 = E1 and ... and Pn = EN (flag = Recursive) *) | Pstr_primitive of value_description x : T external x : T = " s1 " ... " sn " external x: T = "s1" ... "sn" *) | Pstr_type of rec_flag * type_declaration list (* type t1 = ... and ... and tn = ... *) | Pstr_typext of type_extension (* type t1 += ... *) | Pstr_exception of extension_constructor exception C of T exception C = exception C = M.X *) | Pstr_module of module_binding (* module X = ME *) | Pstr_recmodule of module_binding list (* module rec X1 = ME1 and ... and Xn = MEn *) | Pstr_modtype of module_type_declaration (* module type S = MT *) | Pstr_open of open_description (* open X *) | Pstr_class of unit (* Dummy AST node *) | Pstr_class_type of class_type_declaration list (* class type ct1 = ... and ... and ctn = ... *) | Pstr_include of include_declaration (* include ME *) | Pstr_attribute of attribute (* [@@@id] *) | Pstr_extension of extension * attributes (* [%%id] *) and value_binding = { pvb_pat: pattern; pvb_expr: expression; pvb_attributes: attributes; pvb_loc: Location.t; } and module_binding = { pmb_name: string loc; pmb_expr: module_expr; pmb_attributes: attributes; pmb_loc: Location.t; } (* X = ME *)
null
https://raw.githubusercontent.com/rescript-lang/rescript-compiler/5da6c88fb9237fbc4d61640187b82627690ccf39/jscomp/ml/parsetree.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. ************************************************************************ * Abstract syntax tree produced by parsing 'c' 3.4 2e5 1.4e-4 Suffixes [g-z][G-Z] are accepted by the parser. Suffixes are rejected by the typechecker. [@id ARG] [@@id ARG] Metadata containers passed around within the AST. The compiler ignores unknown attributes. [%id ARG] [%%id ARG] Sub-language placeholder -- rejected by the typechecker. : T ? P or ? P when E Type expressions ... [@id1] [@id2] _ 'a T1 -> T2 Simple ~l:T1 -> T2 Labelled ?l:T1 -> T2 Optional tconstr T tconstr (T1, ..., Tn) tconstr < l1:T1; ...; ln:Tn > (flag = Closed) < l1:T1; ...; ln:Tn; .. > (flag = Open) T as 'a [ `A|`B ] (flag = Closed; labels = None) [> `A|`B ] (flag = Open; labels = None) [< `A|`B ] (flag = Closed; labels = Some []) [< `A|`B > `X `Y ](flag = Closed; labels = Some ["X";"Y"]) (module S) [%id] (module S) (module S with type t1 = T1 and ... and tn = Tn) [ T ] Patterns ... [@id1] [@id2] _ x P as 'a 'a'..'z' Other forms of interval are recognized by the parser but rejected by the type-checker. `A (None) `A P (Some P) [| P1; ...; Pn |] (P : T) #tconst lazy P (module P) Note: (module P : S) is represented as Ppat_constraint(Ppat_unpack, Ptyp_package) exception P [%id] M.(P) Value expressions ... [@id1] [@id2] x M.x function P1 -> E1 | ... | Pn -> En C None C E Some E C (E1, ..., En) Some (Pexp_tuple[E1;...;En]) `A (None) `A E (Some E) E.l [| E1; ...; En |] E1; E2 while E1 do E2 done (E : T) (E :> T) (None, T) (E : T0 :> T) (Some T0, T) E # m new M.c x <- 2 let module M = ME in E let exception C in E assert E Note: "assert false" is treated in a special way by the type-checker. lazy E object ... end fun (type t) -> E (module ME) (module ME : S) is represented as Pexp_constraint(Pexp_pack, Ptyp_package S) M.(E) let open M in E let! open M in E [%id] . (P -> E) or (P when E0 -> E) Value descriptions ... [@@id1] [@@id2] val x: T (prim = []) external x: T = "s1" ... "sn" (prim = ["s1";..."sn"]) Type declarations ('a1,...'an) t; None represents _ = private ... = T ... [@@id1] [@@id2] type t (abstract, no manifest) type t = T0 (abstract, manifest=T0) type t = C of T | ... (variant, no manifest) type t = T0 = C of T | ... (variant, manifest=T0) type t = {l: T; ...} (record, no manifest) type t = T0 = {l : T; ...} (record, manifest=T0) type t = .. (open, no manifest) Invariant: non-empty list Invariant: non-empty list l : T [@id1] [@id2] { ...; l: T; ... } (mutable=Immutable) { ...; mutable l: T; ... } (mutable=Mutable) Note: T can be a Ptyp_poly. C of ... [@id1] [@id2] | C of T1 * ... * Tn (res = None, args = Pcstr_tuple []) | C: T0 (res = Some T0, args = []) | C: T1 * ... * Tn -> T0 (res = Some T0, args = Pcstr_tuple) | C of {...} (res = None, args = Pcstr_record) | C: {...} -> T0 (res = Some T0, args = Pcstr_record) | C of {...} as t (res = None, args = Pcstr_record) ... [@@id1] [@@id2] type t += ... C of ... [@id1] [@id2] | C of T1 * ... * Tn ([T1; ...; Tn], None) | C: T0 ([], Some T0) | C: T1 * ... * Tn -> T0 ([T1; ...; Tn], Some T0) | C = D * {1 Class language} Type expressions for the class language ... [@id1] [@id2] c ['a1, ..., 'an] c object ... end T -> CT Simple ~l:T -> CT Labelled l ?l:T -> CT Optional l [%id] let open M in CT object('selfpat) ... end object ... end (self = Ptyp_any) ... [@@id1] [@@id2] inherit CT val x: T method x: T Note: T can be a Ptyp_poly. constraint T1 = T2 [@@@id] [%%id] ... [@@id1] [@@id2] class c = ... class ['a1,...,'an] c = ... class virtual c = ... Also used for "class type" declaration. Value expressions for the class language ... [@id1] [@id2] c ['a1, ..., 'an] c object ... end fun P -> CE (Simple, None) fun ~l:P -> CE (Labelled l, None) fun ?l:P -> CE (Optional l, None) fun ?l:(P = E0) -> CE (Optional l, Some E0) CE ~l1:E1 ... ~ln:En li can be empty (non labeled argument) or start with '?' (optional argument). Invariant: n > 0 (CE : CT) [%id] let open M in CE object(selfpat) ... end object ... end (self = Ppat_any) ... [@@id1] [@@id2] inherit CE inherit CE as x inherit! CE inherit! CE as x val x = E val virtual x: T constraint T1 = T2 initializer E [@@@id] [%%id] * {1 Module language} Type expressions for the module language ... [@id1] [@id2] S sig ... end MT with ... module type of ME [%id] (module M) type t1 = ... and ... and tn = ... type t1 += ... exception C of T module X : MT module type S = MT module type S open X class c1 : ... and ... and cn : ... class type ct1 = ... and ... and ctn = ... [@@@id] [%%id] ... [@@id1] [@@id2] S : MT ... [@@id1] [@@id2] open! X - popen_override = Override (silences the 'used identifier shadowing' warning) open X - popen_override = Fresh include ME with type X.t = ... Note: the last component of the longident must match the name of the type_declaration. with module X.Y = Z with type X.t := ..., same format as [Pwith_type] with module X.Y := Z Value expressions for the module language ... [@id1] [@id2] X struct ... end ME1(ME2) (ME : MT) [%id] E type t1 = ... and ... and tn = ... type t1 += ... module X = ME module rec X1 = ME1 and ... and Xn = MEn module type S = MT open X Dummy AST node class type ct1 = ... and ... and ctn = ... include ME [@@@id] [%%id] X = ME
, projet Cristal , INRIA Rocquencourt Copyright 1996 Institut National de Recherche en Informatique et the GNU Lesser General Public License version 2.1 , with the open Asttypes type constant = Pconst_integer of string * char option 3 3l 3L 3n Suffixes [ g - z][G - Z ] are accepted by the parser . Suffixes except ' l ' , ' L ' and ' n ' are rejected by the typechecker Suffixes [g-z][G-Z] are accepted by the parser. Suffixes except 'l', 'L' and 'n' are rejected by the typechecker *) | Pconst_char of int | Pconst_string of string * string option " constant " { } {delim|other constant|delim} *) | Pconst_float of string * char option * { 1 Extension points } type attribute = string loc * payload and extension = string loc * payload and attributes = attribute list and payload = | PStr of structure : SIG * { 1 Core language } and core_type = { ptyp_desc: core_type_desc; ptyp_loc: Location.t; } and core_type_desc = | Ptyp_any | Ptyp_var of string | Ptyp_arrow of arg_label * core_type * core_type | Ptyp_tuple of core_type list T1 * ... * Tn Invariant : n > = 2 Invariant: n >= 2 *) | Ptyp_constr of Longident.t loc * core_type list | Ptyp_object of object_field list * closed_flag | Ptyp_class of Longident.t loc * core_type list # tconstr T # tconstr ( T1 , ... , Tn ) # tconstr T #tconstr (T1, ..., Tn) #tconstr *) | Ptyp_alias of core_type * string | Ptyp_variant of row_field list * closed_flag * label list option | Ptyp_poly of string loc list * core_type ' a1 ... ' an . T Can only appear in the following context : - As the core_type of a Ppat_constraint node corresponding to a constraint on a let - binding : let x : ' a1 ... ' an . T = e ... - Under Cfk_virtual for methods ( not values ) . - As the core_type of a Pctf_method node . - As the core_type of a Pexp_poly node . - As the pld_type field of a label_declaration . - As a core_type of a Ptyp_object node . Can only appear in the following context: - As the core_type of a Ppat_constraint node corresponding to a constraint on a let-binding: let x : 'a1 ... 'an. T = e ... - Under Cfk_virtual for methods (not values). - As the core_type of a Pctf_method node. - As the core_type of a Pexp_poly node. - As the pld_type field of a label_declaration. - As a core_type of a Ptyp_object node. *) | Ptyp_package of package_type | Ptyp_extension of extension and package_type = Longident.t loc * (Longident.t loc * core_type) list and row_field = | Rtag of label loc * attributes * bool * core_type list [ ` A ] ( true , [ ] ) [ ` A of T ] ( false , [ T ] ) [ ` A of T1 & .. & Tn ] ( false , [ T1; ... Tn ] ) [ ` A of & T1 & .. & Tn ] ( true , [ T1; ... Tn ] ) - The 2nd field is true if the tag contains a constant ( empty ) constructor . - ' & ' occurs when several types are used for the same constructor ( see 4.2 in the manual ) - TODO : switch to a record representation , and keep location [`A of T] ( false, [T] ) [`A of T1 & .. & Tn] ( false, [T1;...Tn] ) [`A of & T1 & .. & Tn] ( true, [T1;...Tn] ) - The 2nd field is true if the tag contains a constant (empty) constructor. - '&' occurs when several types are used for the same constructor (see 4.2 in the manual) - TODO: switch to a record representation, and keep location *) | Rinherit of core_type and object_field = | Otag of label loc * attributes * core_type | Oinherit of core_type and pattern = { ppat_desc: pattern_desc; ppat_loc: Location.t; } and pattern_desc = | Ppat_any | Ppat_var of string loc | Ppat_alias of pattern * string loc | Ppat_constant of constant 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n | Ppat_interval of constant * constant | Ppat_tuple of pattern list ( P1 , ... , Pn ) Invariant : n > = 2 Invariant: n >= 2 *) | Ppat_construct of Longident.t loc * pattern option C None C P Some P C ( P1 , ... , Pn ) Some ( Ppat_tuple [ P1 ; ... ; Pn ] ) C P Some P C (P1, ..., Pn) Some (Ppat_tuple [P1; ...; Pn]) *) | Ppat_variant of label * pattern option | Ppat_record of (Longident.t loc * pattern) list * closed_flag { l1 = P1 ; ... ; ln = Pn } ( flag = Closed ) { l1 = P1 ; ... ; ln = Pn ; _ } ( flag = Open ) Invariant : n > 0 { l1=P1; ...; ln=Pn; _} (flag = Open) Invariant: n > 0 *) | Ppat_array of pattern list | Ppat_or of pattern * pattern P1 | P2 | Ppat_constraint of pattern * core_type | Ppat_type of Longident.t loc | Ppat_lazy of pattern | Ppat_unpack of string loc | Ppat_exception of pattern | Ppat_extension of extension | Ppat_open of Longident.t loc * pattern and expression = { pexp_desc: expression_desc; pexp_loc: Location.t; } and expression_desc = | Pexp_ident of Longident.t loc | Pexp_constant of constant 1 , ' a ' , " true " , 1.0 , 1l , 1L , 1n | Pexp_let of rec_flag * value_binding list * expression let P1 = E1 and ... and Pn = EN in E ( flag = ) let rec P1 = E1 and ... and Pn = EN in E ( flag = Recursive ) let rec P1 = E1 and ... and Pn = EN in E (flag = Recursive) *) | Pexp_function of case list | Pexp_fun of arg_label * expression option * pattern * expression fun P - > E1 ( Simple , None ) fun ~l :P - > E1 ( Labelled l , None ) fun ? l :P - > E1 ( Optional l , None ) fun ? l:(P = E0 ) - > E1 ( Optional l , Some E0 ) Notes : - If E0 is provided , only Optional is allowed . - " fun P1 P2 .. Pn - > E1 " is represented as nested Pexp_fun . - " let f P = E " is represented using Pexp_fun . fun ~l:P -> E1 (Labelled l, None) fun ?l:P -> E1 (Optional l, None) fun ?l:(P = E0) -> E1 (Optional l, Some E0) Notes: - If E0 is provided, only Optional is allowed. - "fun P1 P2 .. Pn -> E1" is represented as nested Pexp_fun. - "let f P = E" is represented using Pexp_fun. *) | Pexp_apply of expression * (arg_label * expression) list E0 ~l1 : E1 ... ~ln : En li can be empty ( non labeled argument ) or start with ' ? ' ( optional argument ) . Invariant : n > 0 li can be empty (non labeled argument) or start with '?' (optional argument). Invariant: n > 0 *) | Pexp_match of expression * case list match E0 with P1 - > E1 | ... | Pn - > En | Pexp_try of expression * case list try E0 with P1 - > E1 | ... | Pn - > En | Pexp_tuple of expression list ( E1 , ... , En ) Invariant : n > = 2 Invariant: n >= 2 *) | Pexp_construct of Longident.t loc * expression option | Pexp_variant of label * expression option | Pexp_record of (Longident.t loc * expression) list * expression option { l1 = P1 ; ... ; ln = Pn } ( None ) { E0 with l1 = P1 ; ... ; ln = Pn } ( Some E0 ) Invariant : n > 0 { E0 with l1=P1; ...; ln=Pn } (Some E0) Invariant: n > 0 *) | Pexp_field of expression * Longident.t loc | Pexp_setfield of expression * Longident.t loc * expression E1.l < - E2 | Pexp_array of expression list | Pexp_ifthenelse of expression * expression * expression option if E1 then E2 else E3 | Pexp_sequence of expression * expression | Pexp_while of expression * expression | Pexp_for of pattern * expression * expression * direction_flag * expression for i = E1 to E2 do E3 done ( flag = Upto ) for i = E1 downto E2 do E3 done ( flag = ) for i = E1 downto E2 do E3 done (flag = Downto) *) | Pexp_constraint of expression * core_type | Pexp_coerce of expression * core_type option * core_type | Pexp_send of expression * label loc | Pexp_new of Longident.t loc | Pexp_setinstvar of label loc * expression | Pexp_override of (label loc * expression) list { < x1 = E1 ; ... ; > } | Pexp_letmodule of string loc * module_expr * expression | Pexp_letexception of extension_constructor * expression | Pexp_assert of expression | Pexp_lazy of expression | Pexp_poly of expression * core_type option Used for method bodies . Can only be used as the expression under for methods ( not values ) . Can only be used as the expression under Cfk_concrete for methods (not values). *) | Pexp_object of class_structure | Pexp_newtype of string loc * expression | Pexp_pack of module_expr | Pexp_open of override_flag * Longident.t loc * expression | Pexp_extension of extension | Pexp_unreachable { pc_lhs: pattern; pc_guard: expression option; pc_rhs: expression; } and value_description = { pval_name: string loc; pval_type: core_type; pval_prim: string list; pval_loc: Location.t; } and type_declaration = { ptype_name: string loc; ptype_params: (core_type * variance) list; ptype_cstrs: (core_type * core_type * Location.t) list; ... constraint T1 = T1 ' ... constraint ptype_kind: type_kind; ptype_loc: Location.t; } and type_kind = | Ptype_abstract | Ptype_variant of constructor_declaration list | Ptype_record of label_declaration list | Ptype_open and label_declaration = { pld_name: string loc; pld_mutable: mutable_flag; pld_type: core_type; pld_loc: Location.t; } and constructor_declaration = { pcd_name: string loc; pcd_args: constructor_arguments; pcd_res: core_type option; pcd_loc: Location.t; } and constructor_arguments = | Pcstr_tuple of core_type list | Pcstr_record of label_declaration list and type_extension = { ptyext_path: Longident.t loc; ptyext_params: (core_type * variance) list; ptyext_constructors: extension_constructor list; ptyext_private: private_flag; } and extension_constructor = { pext_name: string loc; pext_kind : extension_constructor_kind; pext_loc : Location.t; } and extension_constructor_kind = Pext_decl of constructor_arguments * core_type option | Pext_rebind of Longident.t loc and class_type = { pcty_desc: class_type_desc; pcty_loc: Location.t; } and class_type_desc = | Pcty_constr of Longident.t loc * core_type list | Pcty_signature of class_signature | Pcty_arrow of arg_label * core_type * class_type | Pcty_extension of extension | Pcty_open of override_flag * Longident.t loc * class_type and class_signature = { pcsig_self: core_type; pcsig_fields: class_type_field list; } and class_type_field = { pctf_desc: class_type_field_desc; pctf_loc: Location.t; } and class_type_field_desc = | Pctf_inherit of class_type | Pctf_val of (label loc * mutable_flag * virtual_flag * core_type) | Pctf_method of (label loc * private_flag * virtual_flag * core_type) | Pctf_constraint of (core_type * core_type) | Pctf_attribute of attribute | Pctf_extension of extension and 'a class_infos = { pci_virt: virtual_flag; pci_params: (core_type * variance) list; pci_name: string loc; pci_expr: 'a; pci_loc: Location.t; } and class_type_declaration = class_type class_infos and class_expr = { pcl_desc: class_expr_desc; pcl_loc: Location.t; } and class_expr_desc = | Pcl_constr of Longident.t loc * core_type list | Pcl_structure of class_structure | Pcl_fun of arg_label * expression option * pattern * class_expr | Pcl_apply of class_expr * (arg_label * expression) list | Pcl_let of rec_flag * value_binding list * class_expr let P1 = E1 and ... and Pn = EN in CE ( flag = ) let rec P1 = E1 and ... and Pn = EN in CE ( flag = Recursive ) let rec P1 = E1 and ... and Pn = EN in CE (flag = Recursive) *) | Pcl_constraint of class_expr * class_type | Pcl_extension of extension | Pcl_open of override_flag * Longident.t loc * class_expr and class_structure = { pcstr_self: pattern; pcstr_fields: class_field list; } and class_field = { pcf_desc: class_field_desc; pcf_loc: Location.t; } and class_field_desc = | Pcf_inherit of unit | Pcf_val of (label loc * mutable_flag * class_field_kind) | Pcf_method of (label loc * private_flag * class_field_kind) method x = E ( E can be a Pexp_poly ) method virtual x : T ( T can be a Ptyp_poly ) method virtual x: T (T can be a Ptyp_poly) *) | Pcf_constraint of (core_type * core_type) | Pcf_initializer of expression | Pcf_attribute of attribute | Pcf_extension of extension and class_field_kind = | Cfk_virtual of core_type | Cfk_concrete of override_flag * expression and module_type = { pmty_desc: module_type_desc; pmty_loc: Location.t; } and module_type_desc = | Pmty_ident of Longident.t loc | Pmty_signature of signature | Pmty_functor of string loc * module_type option * module_type functor(X : ) - > MT2 | Pmty_with of module_type * with_constraint list | Pmty_typeof of module_expr | Pmty_extension of extension | Pmty_alias of Longident.t loc and signature = signature_item list and signature_item = { psig_desc: signature_item_desc; psig_loc: Location.t; } and signature_item_desc = | Psig_value of value_description x : T external x : T = " s1 " ... " sn " val x: T external x: T = "s1" ... "sn" *) | Psig_type of rec_flag * type_declaration list | Psig_typext of type_extension | Psig_exception of extension_constructor | Psig_module of module_declaration | Psig_recmodule of module_declaration list module rec X1 : and ... and Xn : MTn | Psig_modtype of module_type_declaration | Psig_open of open_description | Psig_include of include_description include MT | Psig_class of unit | Psig_class_type of class_type_declaration list | Psig_attribute of attribute | Psig_extension of extension * attributes and module_declaration = { pmd_name: string loc; pmd_type: module_type; pmd_loc: Location.t; } and module_type_declaration = { pmtd_name: string loc; pmtd_type: module_type option; pmtd_loc: Location.t; } S = MT S ( abstract module type declaration , pmtd_type = None ) S (abstract module type declaration, pmtd_type = None) *) and open_description = { popen_lid: Longident.t loc; popen_override: override_flag; popen_loc: Location.t; popen_attributes: attributes; } and 'a include_infos = { pincl_mod: 'a; pincl_loc: Location.t; pincl_attributes: attributes; } and include_description = module_type include_infos include MT and include_declaration = module_expr include_infos and with_constraint = | Pwith_type of Longident.t loc * type_declaration | Pwith_module of Longident.t loc * Longident.t loc | Pwith_typesubst of Longident.t loc * type_declaration | Pwith_modsubst of Longident.t loc * Longident.t loc and module_expr = { pmod_desc: module_expr_desc; pmod_loc: Location.t; } and module_expr_desc = | Pmod_ident of Longident.t loc | Pmod_structure of structure | Pmod_functor of string loc * module_type option * module_expr functor(X : ) - > ME | Pmod_apply of module_expr * module_expr | Pmod_constraint of module_expr * module_type | Pmod_unpack of expression ( E ) | Pmod_extension of extension and structure = structure_item list and structure_item = { pstr_desc: structure_item_desc; pstr_loc: Location.t; } and structure_item_desc = | Pstr_eval of expression * attributes | Pstr_value of rec_flag * value_binding list let P1 = E1 and ... and Pn = EN ( flag = ) let rec P1 = E1 and ... and Pn = EN ( flag = Recursive ) let rec P1 = E1 and ... and Pn = EN (flag = Recursive) *) | Pstr_primitive of value_description x : T external x : T = " s1 " ... " sn " external x: T = "s1" ... "sn" *) | Pstr_type of rec_flag * type_declaration list | Pstr_typext of type_extension | Pstr_exception of extension_constructor exception C of T exception C = exception C = M.X *) | Pstr_module of module_binding | Pstr_recmodule of module_binding list | Pstr_modtype of module_type_declaration | Pstr_open of open_description | Pstr_class of unit | Pstr_class_type of class_type_declaration list | Pstr_include of include_declaration | Pstr_attribute of attribute | Pstr_extension of extension * attributes and value_binding = { pvb_pat: pattern; pvb_expr: expression; pvb_attributes: attributes; pvb_loc: Location.t; } and module_binding = { pmb_name: string loc; pmb_expr: module_expr; pmb_attributes: attributes; pmb_loc: Location.t; }
da0322c41448b70287c5b58f5cefd32193c2fdb210f3d7aafea1b8b9576083f4
clutter-lang/clutter
eval.lisp
;;;; -*- Mode: Lisp; indent-tabs-mode: nil -*- (in-package #:clutter) (declaim (optimize debug)) ;;; ;;; Primitive Constants ;;; (defparameter *true* (cs "#t")) (defparameter *false* (cs "#f")) (defun clutter-load (filespec) (with-open-file (stream filespec) (loop for expr = (clutter-read stream nil) while expr do (clutter-eval expr))) t) (defun clutter-eval (expression &optional (environment *global-env*)) (cond ((clutter-symbol-p expression) (eval/symbol expression environment)) ((consp expression) (eval/combiner expression environment)) (t expression))) (defun eval/symbol (symbol env) (if (or (eq symbol *ignore*) (eq symbol *true*) (eq symbol *false*)) symbol (let ((val (lookup symbol env))) (if (clutter-symbol-operative-p val) (invoke (clutter-symbol-operative-operative val) env nil) val)))) (defun eval/combiner (expression env) (let ((f (clutter-eval (car expression) env))) (cond ((clutter-operative-p f) (invoke f env (cdr expression))) ((clutter-function-p f) (let ((op (clutter-function-operative f)) (values (mapcar (rcurry #'clutter-eval env) (cdr expression)))) (clutter-eval (cons op values) env))) (t (error "Not an operative: ~A." f)))))
null
https://raw.githubusercontent.com/clutter-lang/clutter/a198828cc9e9fc44d809fd073392d25e0df13d7d/src/eval.lisp
lisp
-*- Mode: Lisp; indent-tabs-mode: nil -*- Primitive Constants
(in-package #:clutter) (declaim (optimize debug)) (defparameter *true* (cs "#t")) (defparameter *false* (cs "#f")) (defun clutter-load (filespec) (with-open-file (stream filespec) (loop for expr = (clutter-read stream nil) while expr do (clutter-eval expr))) t) (defun clutter-eval (expression &optional (environment *global-env*)) (cond ((clutter-symbol-p expression) (eval/symbol expression environment)) ((consp expression) (eval/combiner expression environment)) (t expression))) (defun eval/symbol (symbol env) (if (or (eq symbol *ignore*) (eq symbol *true*) (eq symbol *false*)) symbol (let ((val (lookup symbol env))) (if (clutter-symbol-operative-p val) (invoke (clutter-symbol-operative-operative val) env nil) val)))) (defun eval/combiner (expression env) (let ((f (clutter-eval (car expression) env))) (cond ((clutter-operative-p f) (invoke f env (cdr expression))) ((clutter-function-p f) (let ((op (clutter-function-operative f)) (values (mapcar (rcurry #'clutter-eval env) (cdr expression)))) (clutter-eval (cons op values) env))) (t (error "Not an operative: ~A." f)))))
6aaa9c21ce2b3a7076630c7bcf67c5e769f6b907ca3eee64ca6965c2f711b09e
bytekid/mkbtt
graph.ml
Copyright 2008 , Christian Sternagel , * GNU Lesser General Public License * * This file is part of TTT2 . * * TTT2 is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version . * * TTT2 is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with TTT2 . If not , see < / > . * GNU Lesser General Public License * * This file is part of TTT2. * * TTT2 is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * TTT2 is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with TTT2. If not, see </>. *) (*** OPENS ********************************************************************) open Prelude;; (*** MODULES ******************************************************************) module F = Format;; module O = Option;; module T = Triple;; (*** MODULE TYPES *************************************************************) module type LABEL = sig type t val combine : t -> t -> t val compare : t -> t -> int val copy : t -> t val fprintf : F.formatter -> t -> unit end module type NODE = sig type t val compare : t -> t -> int val copy : t -> t val hash : t -> int val fprintf : F.formatter -> t -> unit end module type SIGNATURE = sig type node type edge type t val make : node list -> edge list -> t val add_edge : edge -> t -> t val add_node : node -> t -> t val edges : t -> edge list val empty : t val generate : (node -> node -> edge list) -> node list -> t val in_nodes : t -> node list val nodes : t -> node list val of_list : edge list -> t val out_nodes : t -> node list val remove_edge : edge -> t -> t val remove_node : node -> t -> t val restrict : node list -> t -> t val successors : node -> t -> node list val to_list : t -> edge list val fold_edges : (edge -> 'a -> 'a) -> t -> 'a -> 'a val foldi_edges : (int -> edge -> 'a -> 'a) -> t -> 'a -> 'a val fold_nodes : (node -> 'a -> 'a) -> t -> 'a -> 'a val foldi_nodes : (int -> node -> 'a -> 'a) -> t -> 'a -> 'a val iter_edges : (edge -> unit) -> t -> unit val iteri_edges : (int -> edge -> unit) -> t -> unit val iter_nodes : (node -> unit) -> t -> unit val iteri_nodes : (int -> node -> unit) -> t -> unit val cycles : t -> node list list val paths : node -> node -> t -> node list list val sccs : ?trivial:bool -> t -> node list list val filter_edges : (edge -> bool) -> t -> t val filter_nodes : (node -> bool) -> t -> t val find_edge : (edge -> bool) -> t -> edge val find_node : (node -> bool) -> t -> node val mem_edge : edge -> t -> bool val mem_node : node -> t -> bool val for_all_edges : (edge -> bool) -> t -> bool val for_all_nodes : (node -> bool) -> t -> bool val exists_edge : (edge -> bool) -> t -> bool val exists_node : (node -> bool) -> t -> bool val is_empty : t -> bool val is_trivial_scc : node list -> t -> bool val bypass : node -> t -> t val partition : (edge -> bool) -> t -> t * t val size_edges : t -> int val size_nodes : t -> int val compare : t -> t -> int val equal : t -> t -> bool val fprintf : F.formatter -> t -> unit val to_string : t -> string end module type UNLABELED = sig include SIGNATURE val add : node -> node list -> t -> t val replace : node -> node list -> t -> t val fold : (node -> node list -> 'a -> 'a) -> t -> 'a -> 'a val foldi : (int -> node -> node list -> 'a -> 'a) -> t -> 'a -> 'a val iter : (node -> node list -> unit) -> t -> unit val iteri : (int -> node -> node list -> unit) -> t -> unit val is_acyclic : t -> bool val floyd_warshall : t -> ((node * int)list * int option array array) val transitive_closure : t -> t end module type LABELED = sig type label include SIGNATURE val add : node -> (label option * node) list -> t -> t val replace : node -> (label option * node) list -> t -> t val fold : (node -> (label option * node) list -> 'a -> 'a) -> t -> 'a -> 'a val foldi : (int -> node -> (label option * node) list -> 'a -> 'a) -> t -> 'a -> 'a val iter : (node -> (label option * node) list -> unit) -> t -> unit val iteri : (int -> node -> (label option * node) list -> unit) -> t -> unit val labels : node -> node -> t -> label list val combine_edges : t -> t val transitive_closure : ?n:int -> t -> t end (*** MODULES ******************************************************************) module Labeled (L : LABEL) (N : NODE) = struct (*** MODULES *****************************************************************) module Label = struct type t = L.t option;; let combine l l' = match (l,l') with | None,_ -> l' | _,None -> l | Some l,Some l' -> Some (L.combine l l') ;; let compare = O.compare L.compare;; let equal l l' = compare l l' = 0;; end module N = struct include N let equal n m = N.compare n m = 0;; end module R = struct type t = (Label.t * N.t) list;; (* Scan Functions *) let mem = Listx.mem;; let exists = Listx.exists <.> Pair.uncurry;; let for_all p = Listx.for_all (Pair.uncurry p);; Constructors and Destructors let empty = [];; let singleton n = [n];; let add n ns = if mem n ns then ns else n :: ns;; let strip ns = Listx.map snd ns;; let remove l = let compare (l,n) (l',m) = let c = N.compare n m in if c = 0 then Label.compare l l' else c in Listx.remove_all ~c:compare <.> Pair.make l ;; (* Iterators *) let iter = Listx.iter;; let iteri = Listx.iteri;; let fold = Listx.foldl;; (* Search Functions *) let find = Listx.find;; let filter_nodes p = Listx.filter (p <.> snd);; let labels n = fold (fun ls (l,m) -> if N.equal n m then O.fold (flip Listx.cons ls) ls l else ls) [] ;; (* Compare Functions *) let compare ns ms = let rec compare ns ms = match (ns,ms) with | [], [] -> 0 | (l,n) :: ns, (l',m) :: ms -> let c = N.compare n m in if c <> 0 then c else let c = Label.compare l l' in if c = 0 then compare ns ms else c | _, _ -> failwith "unequal lengths" in let c = Listx.length ns - Listx.length ms in if c = 0 then compare ns ms else c ;; (* Miscellaneous *) let size = Listx.length;; let combine = let rec combine ns = function | [] -> ns | m :: ms -> let equal n = N.equal (snd n) <.> snd in let max n m = if Label.compare (fst n) (fst m) > 0 then n else m in let max (m,ms) n = if equal n m then (max n m,ms) else (m,n::ms) in let (m,ms) = fold max (m,[]) ms in combine (m::ns) ms in combine [] ;; (* Printers *) let fprintf fmt = let print fmt (l,n) = match l with | None -> F.fprintf fmt "@[%a@]" N.fprintf n | Some l -> F.fprintf fmt "@[%a(l:@ %a)@]" N.fprintf n L.fprintf l in F.fprintf fmt "@[%a@]" (Listx.fprintf print "@ |@ ") ;; end module H = Hashtblx.Partial (N);; module M = Mapx.Make (N) (R);; (*** TYPES *******************************************************************) type label = L.t;; type node = N.t;; type edge = node * label option * node;; type t = M.t;; type state = { mutable stacked : unit H.t; (* stacked nodes *) mutable graph : t; (* input-graph *) mutable gidx : int; (* global index *) mutable llnn : int H.t; (* low-link numbers of nodes *) mutable nidx : int H.t; (* node index *) mutable result : (node list) Queue.t; (* queue of SCCs *) mutable stack : node Stack.t; (* stack of visited nodes *) };; (*** EXCEPTIONS **************************************************************) exception Found of edge;; (*** FUNCTIONS ***************************************************************) (* Iterators *) let fold = M.fold;; let foldi = M.foldi;; let iter = M.iter;; let iteri = M.iteri;; let iteri_edges f g = ignore (fold (fun n ns i -> R.fold (fun i (l,m) -> f i (T.make n l m); i + 1) i ns) g 0) ;; let iter_edges f = iteri_edges (const f);; let iteri_nodes f g = iteri (fun i n _ -> f i n) g;; let iter_nodes f = iteri_nodes (const f);; let foldi_edges f g d = snd (fold (fun n ns x -> R.fold (fun (i,x) (l,m) -> (i + 1,f i (T.make n l m) x)) x ns) g (0,d)) ;; let fold_edges f = foldi_edges (const f);; let foldi_nodes f g d = foldi (fun i n _ x -> f i n x) g d;; let fold_nodes f = foldi_nodes (const f);; Constructors and Destructors let add = M.add;; let replace = M.replace;; let add_edge e g = let n = T.fst e and l = T.snd e and m = T.thd e in let g = if M.mem m g then g else add m R.empty g in try replace n (R.add (l,m) (M.find n g)) g with Not_found -> add n (R.singleton (l,m)) g ;; let add_node n g = if M.mem n g then g else add n R.empty g;; let edges = flip (fold_edges Listx.cons) [];; let empty = M.empty;; let of_list es = Listx.foldr add_edge empty es;; let make ns es = Listx.foldr add_node (of_list es) ns;; let to_list = edges;; let nodes g = fold (drop Listx.cons) g [];; let in_nodes g = let mem n ns = Listx.mem ~c:N.compare n ns in let add ns (_,n) = if mem n ns then ns else n :: ns in fold (fun _ ms ns -> R.fold add ns ms) g [] ;; let out_nodes g = fold (fun n ms ns -> if R.size ms > 0 then n :: ns else ns) g [] ;; let remove_edge e g = let n = T.fst e and l = T.snd e and m = T.thd e in try replace n (R.remove l m (M.find n g)) g with Not_found -> g ;; let filter_nodes p g = fold (fun n ns g -> if p n then add n (R.filter_nodes p ns) g else g) g empty ;; let remove_node n = filter_nodes (not <.> N.equal n);; let restrict ns = let t = Hashtblx.create 1000 in Listx.iter (flip (Hashtblx.add t) ()) ns; filter_nodes (Hashtblx.mem t) ;; let generate f ns = Listx.foldl (fun g n -> add n (Listx.flat_map (Listx.map T.drop_fst <.> f n) ns) g) empty ns ;; (* Search Functions *) let filter_edges p g = fold (fun n ns g -> let add ns (l,m) = if p (T.make n l m) then R.add (l,m) ns else ns in M.add n (R.fold add [] ns) g) g empty ;; let find_edge p g = try iter (fun n ns -> let p (l,m) = p (T.make n l m) in try raise (Found (T.insert_fst n (R.find p ns))) with Not_found -> ()) g; raise Not_found with Found e -> e ;; let find_node p = fst <.> M.search (fun n -> p <.> const n);; let successors n g = try R.strip (M.find n g) with Not_found -> [];; let labels n m = R.labels m <.> M.find n;; let in_edges n g = Listx.filter (fun e -> T.thd e = n) (edges g);; let out_edges n g = Listx.filter (fun e -> T.fst e = n) (edges g);; (* Scan Functions *) let exists_edge p = M.exists (fun n ns -> R.exists (fun l -> p <.> T.make n l) ns) ;; let for_all_edges p = M.for_all (fun n ns -> R.for_all (fun l -> p <.> T.make n l) ns) ;; let mem_edge e = let n = T.fst e and l = T.snd e and m = T.thd e in exists_edge (T.for_all (N.equal n) (Label.equal l) (N.equal m)) ;; let exists_node p = M.exists (fun n -> p <.> const n);; let for_all_nodes p = M.for_all (fun n -> p <.> const n);; let mem_node n = exists_node (N.equal n);; (* Properties *) let is_empty = not <.> exists_edge (const true);; let is_trivial_scc = function | [] -> failwith "the list of SCCs should never contain empty components" | [n] -> not <.> Listx.mem ~c:N.compare n <.> successors n | _ -> const false ;; (* Graph Analysis *) let paths n m g = let rec paths ns n m g = if N.equal n m then [[n]] else subpaths ns n m g and subpaths ns n m g = Listx.flat_map (fun l -> if Listx.mem ~c:N.compare l ns then [] else Listx.map (Listx.cons n) (paths (l :: ns) l m g)) (successors n g) in if is_empty g then [] else if N.equal n m then subpaths [n] n m g else paths [n] n m g ;; let cycles g = Listx.flat_map (fun n -> paths n n g) (nodes g);; (* scc computation (tarjan algorithm) *) let rec tarjan s n = let rec add n scc = let n' = Stack.pop !s.stack in H.remove !s.stacked n'; if N.equal n' n then n' :: scc else add n (n' :: scc) in H.add !s.nidx n !s.gidx; H.add !s.llnn n !s.gidx; !s.gidx <- !s.gidx + 1; Stack.push n !s.stack; H.add !s.stacked n (); Listx.iter (fun n' -> let undefined = not (H.mem !s.nidx n') in if undefined || H.mem !s.stacked n' then ( if undefined then tarjan s n'; H.add !s.llnn n (min (H.find !s.llnn n) (H.find !s.llnn n'))) ) (successors n !s.graph); if H.find !s.llnn n = H.find !s.nidx n then Queue.add (add n []) !s.result ;; let sccs ?(trivial = true) g = let s = ref { stacked = H.create 1000; graph = g; gidx = 0; llnn = H.create 1000; nidx = H.create 1000; stack = Stack.create (); result = Queue.create () } in Listx.iter (fun n -> if not (H.mem !s.nidx n) then (tarjan s n)) (nodes g); let filter sccs scc = if is_trivial_scc scc g then sccs else scc :: sccs in if trivial then Queue.fold (flip Listx.cons) [] !s.result else Queue.fold filter [] !s.result ;; (* Miscellaneous *) let size_edges g = fold (fun n ns s -> s + R.size ns) g 0;; let size_nodes = M.size;; let combine_edges g = fold (fun n -> add n <.> R.combine) g empty;; let partition p g = fold (fun n ns (g,g') -> let add (ns,ns') (l,m) = if p (T.make n l m) then (R.add (l,m) ns,ns') else (ns,R.add (l,m) ns') in let (ns,ns') = R.fold add ([],[]) ns in (M.add n ns g, M.add n ns' g')) g (empty,empty) ;; let bypass n g = let es = Listx.product (in_edges n g) (out_edges n g) in let add g (e,e') = let u = T.fst e and l = T.snd e and l' = T.snd e' and v = T.thd e' in if N.equal u n then failwith "looping edge" else replace u (R.add (Label.combine l l',v) (M.find u g)) g in Listx.foldl add (remove_node n g) es ;; let rec transitive_closure ?(n = ~-1) g = let add g n = let es = Listx.product (in_edges n g) (out_edges n g) in Listx.foldl (fun g (e,e') -> let n = T.fst e and l = T.snd e and l' = T.snd e' and m = T.thd e' in replace n (R.add (Label.combine l l',m) (M.find n g)) g) g es in if n = 0 then g else let n = if n < 0 then n else n - 1 and g' = Listx.foldl add g (nodes g) in if size_edges g = size_edges g' then g else transitive_closure ~n:n g' ;; (* Compare Function *) let compare = M.compare;; let equal = M.equal;; (* Printers *) let fprintf fmt g = Format.fprintf fmt "@["; iteri_edges (fun i e -> let n = T.fst e and l = T.snd e and m = T.thd e in if i > 0 then F.fprintf fmt "@\n"; match l with | None -> F.fprintf fmt "@[%a@ ->@ %a@]" N.fprintf n N.fprintf m | Some l -> F.fprintf fmt "@[%a@ ->(%a)@ %a@]" N.fprintf n L.fprintf l N.fprintf m) g; Format.fprintf fmt "@]" ;; let to_string = F.flush_str_formatter <.> fprintf F.str_formatter;; end module Make (N : NODE) = struct (*** MODULE ******************************************************************) module Label = struct type t = unit let add _ _ = ();; let combine _ _ = ();; let compare _ _ = 0;; let copy _ = ();; let fprintf fmt _ = F.fprintf fmt "@[@]";; end module G = Labeled (Label) (N);; (*** TYPES *******************************************************************) type node = G.node;; type edge = node * node;; type t = G.t;; (*** FUNCTIONS ***************************************************************) let to_edge = T.drop_snd;; let to_ledge e = T.insert_snd None e;; Constructors and Destructors let add n = G.add n <.> List.map (Pair.make None);; let add_edge e = G.add_edge (to_ledge e);; let add_node = G.add_node;; let edges g = Listx.map to_edge (G.edges g);; let empty = G.empty;; let generate f = G.generate (fun n -> Listx.map to_ledge <.> f n);; let in_nodes = G.in_nodes;; let nodes = G.nodes;; let of_list = G.of_list <.> Listx.map to_ledge;; let make ns es = Listx.foldr add_node (of_list es) ns;; let out_nodes = G.out_nodes;; let remove_edge = G.remove_edge <.> to_ledge;; let remove_node = G.remove_node;; let replace n = G.replace n <.> List.map (Pair.make None);; let restrict = G.restrict;; let successors = G.successors;; let to_list g = Listx.map to_edge (G.to_list g);; (* Iterators *) let fold f = G.fold (fun n -> f n <.> List.map snd);; let foldi f = G.foldi (fun i n -> f i n <.> List.map snd);; let fold_edges f = G.fold_edges (f <.> to_edge);; let foldi_edges f = G.foldi_edges (fun i -> f i <.> to_edge);; let fold_nodes = G.fold_nodes;; let foldi_nodes = G.foldi_nodes;; let iter f = G.iter (fun n -> f n <.> List.map snd);; let iteri f = G.iteri (fun i n -> f i n <.> List.map snd);; let iter_edges f = G.iter_edges (f <.> to_edge);; let iteri_edges f = G.iteri_edges (fun i -> f i <.> to_edge);; let iter_nodes = G.iter_nodes;; let iteri_nodes = G.iteri_nodes;; (* Graph Analysis *) let cycles = G.cycles;; let paths = G.paths;; let sccs = G.sccs;; (* Search Functions *) let filter_edges p = G.filter_edges (p <.> to_edge);; let filter_nodes = G.filter_nodes;; let find_edge p = to_edge <.> G.find_edge (p <.> to_edge);; let find_node = G.find_node;; (* Scan Functions *) let mem_edge = G.mem_edge <.> to_ledge;; let mem_node = G.mem_node;; let for_all_edges p = G.for_all_edges (p <.> to_edge);; let for_all_nodes = G.for_all_nodes;; let exists_edge p = G.exists_edge (p <.> to_edge);; let exists_node = G.exists_node;; (* Properties *) let is_empty = G.is_empty;; let is_trivial_scc = G.is_trivial_scc;; (* Miscellaneous *) let bypass = G.bypass;; let partition p = G.partition (p <.> to_edge);; let size_edges = G.size_edges;; let size_nodes = G.size_nodes;; let transitive_closure g = G.transitive_closure g;; let floyd_warshall g = let floyd_warshall n m = for k = 0 to n - 1 do for i = 0 to n - 1 do for j = 0 to n - 1 do m.(i).(j) <- match (m.(i).(j),m.(i).(k),m.(k).(j)) with | (Some ij,Some ik,Some kj) -> let ikj = ik + kj in if ij < ikj then Some ij else Some ikj | (None,Some ik,Some kj) -> Some(ik + kj) | (Some ij,_,_) -> Some ij | _ -> None done done done in let (ns,n) = foldi_nodes (fun i n (xs,_) -> ((n,i)::xs,i+1)) g ([],0) in let n = size_nodes g in let path = Array.make_matrix n n None in iter_edges (fun (x,y) -> path.(List.assoc x ns).(List.assoc y ns) <- Some 1) g; floyd_warshall n path; (ns,path) ;; let is_acyclic g = let (_,path) = floyd_warshall g in List.exists (fun i -> path.(i).(i) <> None) (Listx.range 0 (Array.length path)) ;; (* Compare Functions *) let compare = G.compare;; let equal = G.equal;; (* Printers *) let fprintf = G.fprintf;; let to_string = G.to_string;; end
null
https://raw.githubusercontent.com/bytekid/mkbtt/c2f8e0615389b52eabd12655fe48237aa0fe83fd/src/util/src/graph.ml
ocaml
** OPENS ******************************************************************* ** MODULES ***************************************************************** ** MODULE TYPES ************************************************************ ** MODULES ***************************************************************** ** MODULES **************************************************************** Scan Functions Iterators Search Functions Compare Functions Miscellaneous Printers ** TYPES ****************************************************************** stacked nodes input-graph global index low-link numbers of nodes node index queue of SCCs stack of visited nodes ** EXCEPTIONS ************************************************************* ** FUNCTIONS ************************************************************** Iterators Search Functions Scan Functions Properties Graph Analysis scc computation (tarjan algorithm) Miscellaneous Compare Function Printers ** MODULE ***************************************************************** ** TYPES ****************************************************************** ** FUNCTIONS ************************************************************** Iterators Graph Analysis Search Functions Scan Functions Properties Miscellaneous Compare Functions Printers
Copyright 2008 , Christian Sternagel , * GNU Lesser General Public License * * This file is part of TTT2 . * * TTT2 is free software : you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation , either version 3 of the License , or ( at your * option ) any later version . * * TTT2 is distributed in the hope that it will be useful , but WITHOUT * ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public * License for more details . * * You should have received a copy of the GNU Lesser General Public * License along with TTT2 . If not , see < / > . * GNU Lesser General Public License * * This file is part of TTT2. * * TTT2 is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * TTT2 is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with TTT2. If not, see </>. *) open Prelude;; module F = Format;; module O = Option;; module T = Triple;; module type LABEL = sig type t val combine : t -> t -> t val compare : t -> t -> int val copy : t -> t val fprintf : F.formatter -> t -> unit end module type NODE = sig type t val compare : t -> t -> int val copy : t -> t val hash : t -> int val fprintf : F.formatter -> t -> unit end module type SIGNATURE = sig type node type edge type t val make : node list -> edge list -> t val add_edge : edge -> t -> t val add_node : node -> t -> t val edges : t -> edge list val empty : t val generate : (node -> node -> edge list) -> node list -> t val in_nodes : t -> node list val nodes : t -> node list val of_list : edge list -> t val out_nodes : t -> node list val remove_edge : edge -> t -> t val remove_node : node -> t -> t val restrict : node list -> t -> t val successors : node -> t -> node list val to_list : t -> edge list val fold_edges : (edge -> 'a -> 'a) -> t -> 'a -> 'a val foldi_edges : (int -> edge -> 'a -> 'a) -> t -> 'a -> 'a val fold_nodes : (node -> 'a -> 'a) -> t -> 'a -> 'a val foldi_nodes : (int -> node -> 'a -> 'a) -> t -> 'a -> 'a val iter_edges : (edge -> unit) -> t -> unit val iteri_edges : (int -> edge -> unit) -> t -> unit val iter_nodes : (node -> unit) -> t -> unit val iteri_nodes : (int -> node -> unit) -> t -> unit val cycles : t -> node list list val paths : node -> node -> t -> node list list val sccs : ?trivial:bool -> t -> node list list val filter_edges : (edge -> bool) -> t -> t val filter_nodes : (node -> bool) -> t -> t val find_edge : (edge -> bool) -> t -> edge val find_node : (node -> bool) -> t -> node val mem_edge : edge -> t -> bool val mem_node : node -> t -> bool val for_all_edges : (edge -> bool) -> t -> bool val for_all_nodes : (node -> bool) -> t -> bool val exists_edge : (edge -> bool) -> t -> bool val exists_node : (node -> bool) -> t -> bool val is_empty : t -> bool val is_trivial_scc : node list -> t -> bool val bypass : node -> t -> t val partition : (edge -> bool) -> t -> t * t val size_edges : t -> int val size_nodes : t -> int val compare : t -> t -> int val equal : t -> t -> bool val fprintf : F.formatter -> t -> unit val to_string : t -> string end module type UNLABELED = sig include SIGNATURE val add : node -> node list -> t -> t val replace : node -> node list -> t -> t val fold : (node -> node list -> 'a -> 'a) -> t -> 'a -> 'a val foldi : (int -> node -> node list -> 'a -> 'a) -> t -> 'a -> 'a val iter : (node -> node list -> unit) -> t -> unit val iteri : (int -> node -> node list -> unit) -> t -> unit val is_acyclic : t -> bool val floyd_warshall : t -> ((node * int)list * int option array array) val transitive_closure : t -> t end module type LABELED = sig type label include SIGNATURE val add : node -> (label option * node) list -> t -> t val replace : node -> (label option * node) list -> t -> t val fold : (node -> (label option * node) list -> 'a -> 'a) -> t -> 'a -> 'a val foldi : (int -> node -> (label option * node) list -> 'a -> 'a) -> t -> 'a -> 'a val iter : (node -> (label option * node) list -> unit) -> t -> unit val iteri : (int -> node -> (label option * node) list -> unit) -> t -> unit val labels : node -> node -> t -> label list val combine_edges : t -> t val transitive_closure : ?n:int -> t -> t end module Labeled (L : LABEL) (N : NODE) = struct module Label = struct type t = L.t option;; let combine l l' = match (l,l') with | None,_ -> l' | _,None -> l | Some l,Some l' -> Some (L.combine l l') ;; let compare = O.compare L.compare;; let equal l l' = compare l l' = 0;; end module N = struct include N let equal n m = N.compare n m = 0;; end module R = struct type t = (Label.t * N.t) list;; let mem = Listx.mem;; let exists = Listx.exists <.> Pair.uncurry;; let for_all p = Listx.for_all (Pair.uncurry p);; Constructors and Destructors let empty = [];; let singleton n = [n];; let add n ns = if mem n ns then ns else n :: ns;; let strip ns = Listx.map snd ns;; let remove l = let compare (l,n) (l',m) = let c = N.compare n m in if c = 0 then Label.compare l l' else c in Listx.remove_all ~c:compare <.> Pair.make l ;; let iter = Listx.iter;; let iteri = Listx.iteri;; let fold = Listx.foldl;; let find = Listx.find;; let filter_nodes p = Listx.filter (p <.> snd);; let labels n = fold (fun ls (l,m) -> if N.equal n m then O.fold (flip Listx.cons ls) ls l else ls) [] ;; let compare ns ms = let rec compare ns ms = match (ns,ms) with | [], [] -> 0 | (l,n) :: ns, (l',m) :: ms -> let c = N.compare n m in if c <> 0 then c else let c = Label.compare l l' in if c = 0 then compare ns ms else c | _, _ -> failwith "unequal lengths" in let c = Listx.length ns - Listx.length ms in if c = 0 then compare ns ms else c ;; let size = Listx.length;; let combine = let rec combine ns = function | [] -> ns | m :: ms -> let equal n = N.equal (snd n) <.> snd in let max n m = if Label.compare (fst n) (fst m) > 0 then n else m in let max (m,ms) n = if equal n m then (max n m,ms) else (m,n::ms) in let (m,ms) = fold max (m,[]) ms in combine (m::ns) ms in combine [] ;; let fprintf fmt = let print fmt (l,n) = match l with | None -> F.fprintf fmt "@[%a@]" N.fprintf n | Some l -> F.fprintf fmt "@[%a(l:@ %a)@]" N.fprintf n L.fprintf l in F.fprintf fmt "@[%a@]" (Listx.fprintf print "@ |@ ") ;; end module H = Hashtblx.Partial (N);; module M = Mapx.Make (N) (R);; type label = L.t;; type node = N.t;; type edge = node * label option * node;; type t = M.t;; type state = { };; exception Found of edge;; let fold = M.fold;; let foldi = M.foldi;; let iter = M.iter;; let iteri = M.iteri;; let iteri_edges f g = ignore (fold (fun n ns i -> R.fold (fun i (l,m) -> f i (T.make n l m); i + 1) i ns) g 0) ;; let iter_edges f = iteri_edges (const f);; let iteri_nodes f g = iteri (fun i n _ -> f i n) g;; let iter_nodes f = iteri_nodes (const f);; let foldi_edges f g d = snd (fold (fun n ns x -> R.fold (fun (i,x) (l,m) -> (i + 1,f i (T.make n l m) x)) x ns) g (0,d)) ;; let fold_edges f = foldi_edges (const f);; let foldi_nodes f g d = foldi (fun i n _ x -> f i n x) g d;; let fold_nodes f = foldi_nodes (const f);; Constructors and Destructors let add = M.add;; let replace = M.replace;; let add_edge e g = let n = T.fst e and l = T.snd e and m = T.thd e in let g = if M.mem m g then g else add m R.empty g in try replace n (R.add (l,m) (M.find n g)) g with Not_found -> add n (R.singleton (l,m)) g ;; let add_node n g = if M.mem n g then g else add n R.empty g;; let edges = flip (fold_edges Listx.cons) [];; let empty = M.empty;; let of_list es = Listx.foldr add_edge empty es;; let make ns es = Listx.foldr add_node (of_list es) ns;; let to_list = edges;; let nodes g = fold (drop Listx.cons) g [];; let in_nodes g = let mem n ns = Listx.mem ~c:N.compare n ns in let add ns (_,n) = if mem n ns then ns else n :: ns in fold (fun _ ms ns -> R.fold add ns ms) g [] ;; let out_nodes g = fold (fun n ms ns -> if R.size ms > 0 then n :: ns else ns) g [] ;; let remove_edge e g = let n = T.fst e and l = T.snd e and m = T.thd e in try replace n (R.remove l m (M.find n g)) g with Not_found -> g ;; let filter_nodes p g = fold (fun n ns g -> if p n then add n (R.filter_nodes p ns) g else g) g empty ;; let remove_node n = filter_nodes (not <.> N.equal n);; let restrict ns = let t = Hashtblx.create 1000 in Listx.iter (flip (Hashtblx.add t) ()) ns; filter_nodes (Hashtblx.mem t) ;; let generate f ns = Listx.foldl (fun g n -> add n (Listx.flat_map (Listx.map T.drop_fst <.> f n) ns) g) empty ns ;; let filter_edges p g = fold (fun n ns g -> let add ns (l,m) = if p (T.make n l m) then R.add (l,m) ns else ns in M.add n (R.fold add [] ns) g) g empty ;; let find_edge p g = try iter (fun n ns -> let p (l,m) = p (T.make n l m) in try raise (Found (T.insert_fst n (R.find p ns))) with Not_found -> ()) g; raise Not_found with Found e -> e ;; let find_node p = fst <.> M.search (fun n -> p <.> const n);; let successors n g = try R.strip (M.find n g) with Not_found -> [];; let labels n m = R.labels m <.> M.find n;; let in_edges n g = Listx.filter (fun e -> T.thd e = n) (edges g);; let out_edges n g = Listx.filter (fun e -> T.fst e = n) (edges g);; let exists_edge p = M.exists (fun n ns -> R.exists (fun l -> p <.> T.make n l) ns) ;; let for_all_edges p = M.for_all (fun n ns -> R.for_all (fun l -> p <.> T.make n l) ns) ;; let mem_edge e = let n = T.fst e and l = T.snd e and m = T.thd e in exists_edge (T.for_all (N.equal n) (Label.equal l) (N.equal m)) ;; let exists_node p = M.exists (fun n -> p <.> const n);; let for_all_nodes p = M.for_all (fun n -> p <.> const n);; let mem_node n = exists_node (N.equal n);; let is_empty = not <.> exists_edge (const true);; let is_trivial_scc = function | [] -> failwith "the list of SCCs should never contain empty components" | [n] -> not <.> Listx.mem ~c:N.compare n <.> successors n | _ -> const false ;; let paths n m g = let rec paths ns n m g = if N.equal n m then [[n]] else subpaths ns n m g and subpaths ns n m g = Listx.flat_map (fun l -> if Listx.mem ~c:N.compare l ns then [] else Listx.map (Listx.cons n) (paths (l :: ns) l m g)) (successors n g) in if is_empty g then [] else if N.equal n m then subpaths [n] n m g else paths [n] n m g ;; let cycles g = Listx.flat_map (fun n -> paths n n g) (nodes g);; let rec tarjan s n = let rec add n scc = let n' = Stack.pop !s.stack in H.remove !s.stacked n'; if N.equal n' n then n' :: scc else add n (n' :: scc) in H.add !s.nidx n !s.gidx; H.add !s.llnn n !s.gidx; !s.gidx <- !s.gidx + 1; Stack.push n !s.stack; H.add !s.stacked n (); Listx.iter (fun n' -> let undefined = not (H.mem !s.nidx n') in if undefined || H.mem !s.stacked n' then ( if undefined then tarjan s n'; H.add !s.llnn n (min (H.find !s.llnn n) (H.find !s.llnn n'))) ) (successors n !s.graph); if H.find !s.llnn n = H.find !s.nidx n then Queue.add (add n []) !s.result ;; let sccs ?(trivial = true) g = let s = ref { stacked = H.create 1000; graph = g; gidx = 0; llnn = H.create 1000; nidx = H.create 1000; stack = Stack.create (); result = Queue.create () } in Listx.iter (fun n -> if not (H.mem !s.nidx n) then (tarjan s n)) (nodes g); let filter sccs scc = if is_trivial_scc scc g then sccs else scc :: sccs in if trivial then Queue.fold (flip Listx.cons) [] !s.result else Queue.fold filter [] !s.result ;; let size_edges g = fold (fun n ns s -> s + R.size ns) g 0;; let size_nodes = M.size;; let combine_edges g = fold (fun n -> add n <.> R.combine) g empty;; let partition p g = fold (fun n ns (g,g') -> let add (ns,ns') (l,m) = if p (T.make n l m) then (R.add (l,m) ns,ns') else (ns,R.add (l,m) ns') in let (ns,ns') = R.fold add ([],[]) ns in (M.add n ns g, M.add n ns' g')) g (empty,empty) ;; let bypass n g = let es = Listx.product (in_edges n g) (out_edges n g) in let add g (e,e') = let u = T.fst e and l = T.snd e and l' = T.snd e' and v = T.thd e' in if N.equal u n then failwith "looping edge" else replace u (R.add (Label.combine l l',v) (M.find u g)) g in Listx.foldl add (remove_node n g) es ;; let rec transitive_closure ?(n = ~-1) g = let add g n = let es = Listx.product (in_edges n g) (out_edges n g) in Listx.foldl (fun g (e,e') -> let n = T.fst e and l = T.snd e and l' = T.snd e' and m = T.thd e' in replace n (R.add (Label.combine l l',m) (M.find n g)) g) g es in if n = 0 then g else let n = if n < 0 then n else n - 1 and g' = Listx.foldl add g (nodes g) in if size_edges g = size_edges g' then g else transitive_closure ~n:n g' ;; let compare = M.compare;; let equal = M.equal;; let fprintf fmt g = Format.fprintf fmt "@["; iteri_edges (fun i e -> let n = T.fst e and l = T.snd e and m = T.thd e in if i > 0 then F.fprintf fmt "@\n"; match l with | None -> F.fprintf fmt "@[%a@ ->@ %a@]" N.fprintf n N.fprintf m | Some l -> F.fprintf fmt "@[%a@ ->(%a)@ %a@]" N.fprintf n L.fprintf l N.fprintf m) g; Format.fprintf fmt "@]" ;; let to_string = F.flush_str_formatter <.> fprintf F.str_formatter;; end module Make (N : NODE) = struct module Label = struct type t = unit let add _ _ = ();; let combine _ _ = ();; let compare _ _ = 0;; let copy _ = ();; let fprintf fmt _ = F.fprintf fmt "@[@]";; end module G = Labeled (Label) (N);; type node = G.node;; type edge = node * node;; type t = G.t;; let to_edge = T.drop_snd;; let to_ledge e = T.insert_snd None e;; Constructors and Destructors let add n = G.add n <.> List.map (Pair.make None);; let add_edge e = G.add_edge (to_ledge e);; let add_node = G.add_node;; let edges g = Listx.map to_edge (G.edges g);; let empty = G.empty;; let generate f = G.generate (fun n -> Listx.map to_ledge <.> f n);; let in_nodes = G.in_nodes;; let nodes = G.nodes;; let of_list = G.of_list <.> Listx.map to_ledge;; let make ns es = Listx.foldr add_node (of_list es) ns;; let out_nodes = G.out_nodes;; let remove_edge = G.remove_edge <.> to_ledge;; let remove_node = G.remove_node;; let replace n = G.replace n <.> List.map (Pair.make None);; let restrict = G.restrict;; let successors = G.successors;; let to_list g = Listx.map to_edge (G.to_list g);; let fold f = G.fold (fun n -> f n <.> List.map snd);; let foldi f = G.foldi (fun i n -> f i n <.> List.map snd);; let fold_edges f = G.fold_edges (f <.> to_edge);; let foldi_edges f = G.foldi_edges (fun i -> f i <.> to_edge);; let fold_nodes = G.fold_nodes;; let foldi_nodes = G.foldi_nodes;; let iter f = G.iter (fun n -> f n <.> List.map snd);; let iteri f = G.iteri (fun i n -> f i n <.> List.map snd);; let iter_edges f = G.iter_edges (f <.> to_edge);; let iteri_edges f = G.iteri_edges (fun i -> f i <.> to_edge);; let iter_nodes = G.iter_nodes;; let iteri_nodes = G.iteri_nodes;; let cycles = G.cycles;; let paths = G.paths;; let sccs = G.sccs;; let filter_edges p = G.filter_edges (p <.> to_edge);; let filter_nodes = G.filter_nodes;; let find_edge p = to_edge <.> G.find_edge (p <.> to_edge);; let find_node = G.find_node;; let mem_edge = G.mem_edge <.> to_ledge;; let mem_node = G.mem_node;; let for_all_edges p = G.for_all_edges (p <.> to_edge);; let for_all_nodes = G.for_all_nodes;; let exists_edge p = G.exists_edge (p <.> to_edge);; let exists_node = G.exists_node;; let is_empty = G.is_empty;; let is_trivial_scc = G.is_trivial_scc;; let bypass = G.bypass;; let partition p = G.partition (p <.> to_edge);; let size_edges = G.size_edges;; let size_nodes = G.size_nodes;; let transitive_closure g = G.transitive_closure g;; let floyd_warshall g = let floyd_warshall n m = for k = 0 to n - 1 do for i = 0 to n - 1 do for j = 0 to n - 1 do m.(i).(j) <- match (m.(i).(j),m.(i).(k),m.(k).(j)) with | (Some ij,Some ik,Some kj) -> let ikj = ik + kj in if ij < ikj then Some ij else Some ikj | (None,Some ik,Some kj) -> Some(ik + kj) | (Some ij,_,_) -> Some ij | _ -> None done done done in let (ns,n) = foldi_nodes (fun i n (xs,_) -> ((n,i)::xs,i+1)) g ([],0) in let n = size_nodes g in let path = Array.make_matrix n n None in iter_edges (fun (x,y) -> path.(List.assoc x ns).(List.assoc y ns) <- Some 1) g; floyd_warshall n path; (ns,path) ;; let is_acyclic g = let (_,path) = floyd_warshall g in List.exists (fun i -> path.(i).(i) <> None) (Listx.range 0 (Array.length path)) ;; let compare = G.compare;; let equal = G.equal;; let fprintf = G.fprintf;; let to_string = G.to_string;; end
27d9869ca6cf71be3a414eae897241a1b822410271fe440bbc31fe9859c02c27
kappelmann/eidi2_repetitorium_tum
ha6_angabe.ml
type avl_tree = Node of avl_tree_node | Leaf and avl_tree_node = { key : int; balance : int; left : avl_tree; right : avl_tree; } [@@deriving show] let singleton key = Node { key = key; balance = 0; left = Leaf; right = Leaf; } let signum x = if x > 0 then 1 else if x < 0 then -1 else 0 type direction = Left | Right [@@deriving show]
null
https://raw.githubusercontent.com/kappelmann/eidi2_repetitorium_tum/1d16bbc498487a85960e0d83152249eb13944611/additional_exercises/2016_17/Blatt%206%20L%C3%B6sungen/ocaml/ha6_angabe.ml
ocaml
type avl_tree = Node of avl_tree_node | Leaf and avl_tree_node = { key : int; balance : int; left : avl_tree; right : avl_tree; } [@@deriving show] let singleton key = Node { key = key; balance = 0; left = Leaf; right = Leaf; } let signum x = if x > 0 then 1 else if x < 0 then -1 else 0 type direction = Left | Right [@@deriving show]
968c9b7b994e9aada426b01ef3a377408120b7bc5b1044e47380ad59ebb76645
wdebeaum/DeepSemLex
triangle.lisp
;;;; ;;;; W::triangle ;;;; (define-words :pos W::n :templ COUNT-PRED-TEMPL :words ( (W::triangle (SENSES ((meta-data :origin fruit-carts :entry-date 20041103 :change-date nil :wn ("triangle%1:25:00") :comments nil) (example "take the triangle with the heart on the side") (LF-PARENT ONT::SHAPE-OBJECT) ) ) ) ))
null
https://raw.githubusercontent.com/wdebeaum/DeepSemLex/ce0e7523dd2b1ebd42b9e88ffbcfdb0fd339aaee/trips/src/LexiconManager/Data/new/triangle.lisp
lisp
W::triangle
(define-words :pos W::n :templ COUNT-PRED-TEMPL :words ( (W::triangle (SENSES ((meta-data :origin fruit-carts :entry-date 20041103 :change-date nil :wn ("triangle%1:25:00") :comments nil) (example "take the triangle with the heart on the side") (LF-PARENT ONT::SHAPE-OBJECT) ) ) ) ))
bc2c0be5f5cd6c619b46d3c8e9fcfe6434812f5e459850ab085d3eae0e2ef0d6
rtoy/cmucl
dlisp.lisp
-*-Mode : LISP ; Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*- ;;; ;;; ************************************************************************* Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . ;;; All rights reserved. ;;; ;;; Use and copying of this software and preparation of derivative works ;;; based upon this software are permitted. Any distribution of this software or derivative works must comply with all applicable United ;;; States export control laws. ;;; This software is made available AS IS , and Xerox Corporation makes no ;;; warranty about the software, its performance or its conformity to any ;;; specification. ;;; ;;; Any person obtaining a copy of this software is requested to send their ;;; name and post office or electronic mail address to: CommonLoops Coordinator Xerox PARC 3333 Coyote Hill Rd . Palo Alto , CA 94304 ( or send Arpanet mail to ) ;;; ;;; Suggestions, comments and requests for improvements are also welcome. ;;; ************************************************************************* (file-comment "$Header: src/pcl/dlisp.lisp $") ;;; (in-package :pcl) (intl:textdomain "cmucl") ;;; This file is (almost) functionally equivalent to dlap.lisp, ;;; but easier to read. ;;; Might generate faster code, too, depending on the compiler and ;;; whether an implementation-specific lap assembler was used. (defun emit-one-class-reader (class-slot-p) (emit-reader/writer :reader 1 class-slot-p)) (defun emit-one-class-boundp (class-slot-p) (emit-reader/writer :boundp 1 class-slot-p)) (defun emit-one-class-writer (class-slot-p) (emit-reader/writer :writer 1 class-slot-p)) (defun emit-two-class-reader (class-slot-p) (emit-reader/writer :reader 2 class-slot-p)) (defun emit-two-class-boundp (class-slot-p) (emit-reader/writer :boundp 2 class-slot-p)) (defun emit-two-class-writer (class-slot-p) (emit-reader/writer :writer 2 class-slot-p)) ;;; -------------------------------- (defun emit-one-index-readers (class-slot-p) (emit-one-or-n-index-reader/writer :reader nil class-slot-p)) (defun emit-one-index-boundps (class-slot-p) (emit-one-or-n-index-reader/writer :boundp nil class-slot-p)) (defun emit-one-index-writers (class-slot-p) (emit-one-or-n-index-reader/writer :writer nil class-slot-p)) (defun emit-n-n-readers () (emit-one-or-n-index-reader/writer :reader t nil)) (defun emit-n-n-boundps () (emit-one-or-n-index-reader/writer :boundp t nil)) (defun emit-n-n-writers () (emit-one-or-n-index-reader/writer :writer t nil)) ;;; -------------------------------- (defun emit-checking (metatypes applyp) (emit-checking-or-caching nil nil metatypes applyp)) (defun emit-caching (metatypes applyp) (emit-checking-or-caching t nil metatypes applyp)) (defun emit-in-checking-cache-p (metatypes) (emit-checking-or-caching nil t metatypes nil)) (defun emit-constant-value (metatypes) (emit-checking-or-caching t t metatypes nil)) ;;; -------------------------------- (defvar *precompiling-lap* nil) (defvar *emit-function-p* t) (defvar *optimize-cache-functions-p* t) (defun emit-default-only (metatypes applyp) (unless *optimize-cache-functions-p* (when (and (null *precompiling-lap*) *emit-function-p*) (return-from emit-default-only (emit-default-only-function metatypes applyp)))) (let* ((dlap-lambda-list (make-dlap-lambda-list metatypes applyp)) (args (remove '&rest dlap-lambda-list)) (restl (when applyp '(.lap-rest-arg.)))) (generating-lisp '(emf) dlap-lambda-list `(invoke-effective-method-function emf ,applyp ,@args ,@restl)))) ;;; -------------------------------- (defun generating-lisp (closure-variables args form) (let* ((rest (memq '&rest args)) (ldiff (and rest (ldiff args rest))) (args (if rest (append ldiff '(&rest .lap-rest-arg.)) args)) (lambda `(lambda ,closure-variables ,@(when (member 'miss-fn closure-variables) `((declare (type function miss-fn)))) #'(kernel:instance-lambda ,args ;; ;; Don't ask me why LOCALLY is necessary here. ;; Fact is that without it the resulting code is up ta 25 % slower . --gerd 2002 - 10 - 26 . (locally (declare #.*optimize-speed*) ,form))))) (values (if *precompiling-lap* `#',lambda (compile-lambda lambda)) nil))) ;;; ;;; cmu17 note: since std-instance-p is weakened, that branch may run ;;; on non-pcl instances (structures). The result will be the ;;; non-wrapper layout for the structure, which will cause a miss. The " slots " will be whatever the first slot is , but will be ignored . Similarly , fsc - instance - p returns true on funcallable structures as well as PCL fins . ;;; (defun emit-reader/writer (reader/writer 1-or-2-class class-slot-p) (unless *optimize-cache-functions-p* (when (and (null *precompiling-lap*) *emit-function-p*) (return-from emit-reader/writer (emit-reader/writer-function reader/writer 1-or-2-class class-slot-p)))) (let* ((instance (ecase reader/writer ((:reader :boundp) (dfun-arg-symbol 0)) (:writer (dfun-arg-symbol 1)))) (arglist (ecase reader/writer ((:reader :boundp) (list instance)) (:writer (list (dfun-arg-symbol 0) instance)))) (closure-variables (ecase 1-or-2-class (1 '(wrapper-0 index miss-fn)) (2 '(wrapper-0 wrapper-1 index miss-fn)))) (read-form (emit-slot-read-form class-slot-p 'index 'slots))) (generating-lisp closure-variables arglist `(let* (,@(unless class-slot-p `((slots nil))) (wrapper (cond ((std-instance-p ,instance) ,@(unless class-slot-p `((setq slots (std-instance-slots ,instance)))) (std-instance-wrapper ,instance)) ((fsc-instance-p ,instance) ,@(unless class-slot-p `((setq slots (fsc-instance-slots ,instance)))) (fsc-instance-wrapper ,instance))))) (block access (when (and wrapper (not (zerop (kernel:layout-hash wrapper 0))) ,@(if (eql 1 1-or-2-class) `((eq wrapper wrapper-0)) `((or (eq wrapper wrapper-0) (eq wrapper wrapper-1))))) ,@(ecase reader/writer (:reader `((let ((value ,read-form)) (unless (eq value +slot-unbound+) (return-from access value))))) (:boundp `((let ((value ,read-form)) (return-from access (not (eq value +slot-unbound+)))))) (:writer `((return-from access (setf ,read-form ,(car arglist))))))) (funcall miss-fn ,@arglist)))))) (defun emit-slot-read-form (class-slot-p index slots) (if class-slot-p `(cdr ,index) `(%slot-ref ,slots ,index))) (defun emit-boundp-check (value-form miss-fn arglist) `(let ((value ,value-form)) (if (eq value +slot-unbound+) (funcall ,miss-fn ,@arglist) value))) (defun emit-slot-access (reader/writer class-slot-p slots index miss-fn arglist) (let ((read-form (emit-slot-read-form class-slot-p index slots))) (ecase reader/writer (:reader (emit-boundp-check read-form miss-fn arglist)) (:boundp `(not (eq +slot-unbound+ ,read-form))) (:writer `(setf ,read-form ,(car arglist)))))) (defmacro emit-reader/writer-macro (reader/writer 1-or-2-class class-slot-p) (let ((*emit-function-p* nil) (*precompiling-lap* t)) (values (emit-reader/writer reader/writer 1-or-2-class class-slot-p)))) (defun emit-one-or-n-index-reader/writer (reader/writer cached-index-p class-slot-p) (unless *optimize-cache-functions-p* (when (and (null *precompiling-lap*) *emit-function-p*) (return-from emit-one-or-n-index-reader/writer (emit-one-or-n-index-reader/writer-function reader/writer cached-index-p class-slot-p)))) (multiple-value-bind (arglist metatypes) (ecase reader/writer ((:reader :boundp) (values (list (dfun-arg-symbol 0)) '(standard-instance))) (:writer (values (list (dfun-arg-symbol 0) (dfun-arg-symbol 1)) '(t standard-instance)))) (generating-lisp `(cache ,@(unless cached-index-p '(index)) miss-fn) arglist `(let (,@(unless class-slot-p '(slots)) ,@(when cached-index-p '(index))) ,(emit-dlap arglist metatypes (emit-slot-access reader/writer class-slot-p 'slots 'index 'miss-fn arglist) `(funcall miss-fn ,@arglist) (when cached-index-p 'index) (unless class-slot-p '(slots))))))) (defmacro emit-one-or-n-index-reader/writer-macro (reader/writer cached-index-p class-slot-p) (let ((*emit-function-p* nil) (*precompiling-lap* t)) (values (emit-one-or-n-index-reader/writer reader/writer cached-index-p class-slot-p)))) (defun emit-miss (miss-fn args &optional applyp) (let ((restl (when applyp '(.lap-rest-arg.)))) (if restl `(apply ,miss-fn ,@args ,@restl) `(funcall ,miss-fn ,@args ,@restl)))) (defun emit-checking-or-caching (cached-emf-p return-value-p metatypes applyp) (unless *optimize-cache-functions-p* (when (and (null *precompiling-lap*) *emit-function-p*) (return-from emit-checking-or-caching (emit-checking-or-caching-function cached-emf-p return-value-p metatypes applyp)))) (let* ((dlap-lambda-list (make-dlap-lambda-list metatypes applyp)) (args (remove '&rest dlap-lambda-list)) (restl (when applyp '(.lap-rest-arg.)))) (generating-lisp `(cache ,@(unless cached-emf-p '(emf)) miss-fn) dlap-lambda-list `(let (,@(when cached-emf-p '(emf))) ,(emit-dlap args metatypes (if return-value-p (if cached-emf-p 'emf t) `(invoke-effective-method-function emf ,applyp ,@args ,@restl)) (emit-miss 'miss-fn args applyp) (when cached-emf-p 'emf)))))) (defun emit-dlap (args metatypes hit miss value-reg &optional slot-regs) (let* ((index -1) (wrapper-bindings (mapcan (lambda (arg mt) (unless (eq mt t) (incf index) `((,(intern (format nil "WRAPPER-~D" index) *the-pcl-package*) ,(emit-fetch-wrapper mt arg 'miss (pop slot-regs)))))) args metatypes)) (wrappers (mapcar #'car wrapper-bindings))) (declare (fixnum index)) (assert (not (null wrappers)) () _"Every metatype is T.") `(block dfun (tagbody (let ((field (cache-field cache)) (cache-vector (cache-vector cache)) (mask (cache-mask cache)) (size (cache-size cache)) (overflow (cache-overflow cache)) ,@wrapper-bindings) (declare (fixnum size field mask)) ,(cond ((cdr wrappers) (emit-greater-than-1-dlap wrappers 'miss value-reg)) (value-reg (emit-1-t-dlap (car wrappers) 'miss value-reg)) (t (emit-1-nil-dlap (car wrappers) 'miss))) (return-from dfun ,hit)) miss (return-from dfun ,miss))))) (defun emit-1-nil-dlap (wrapper miss-label) `(let* ((primary ,(emit-1-wrapper-compute-primary-cache-location wrapper miss-label)) (location primary)) (declare (fixnum primary location)) (block search (loop (when (eq ,wrapper (cache-vector-ref cache-vector location)) (return-from search nil)) (setq location (the fixnum (+ location 1))) (when (= location size) (setq location 0)) (when (= location primary) (dolist (entry overflow) (when (eq (car entry) ,wrapper) (return-from search nil))) (go ,miss-label)))))) (defmacro get-cache-vector-lock-count (cache-vector) `(let ((lock-count (cache-vector-lock-count ,cache-vector))) (the fixnum lock-count))) (defun emit-1-t-dlap (wrapper miss-label value) `(let ((primary ,(emit-1-wrapper-compute-primary-cache-location wrapper miss-label)) (initial-lock-count (get-cache-vector-lock-count cache-vector))) (declare (fixnum primary initial-lock-count)) (let ((location primary)) (declare (fixnum location)) (block search (loop (when (eq ,wrapper (cache-vector-ref cache-vector location)) (setq ,value (cache-vector-ref cache-vector (1+ location))) (return-from search nil)) (setq location (the fixnum (+ location 2))) (when (= location size) (setq location 0)) (when (= location primary) (dolist (entry overflow) (when (eq (car entry) ,wrapper) (setq ,value (cdr entry)) (return-from search nil))) (go ,miss-label)))) (unless (= initial-lock-count (get-cache-vector-lock-count cache-vector)) (go ,miss-label))))) (defun emit-greater-than-1-dlap (wrappers miss-label value) (declare (type list wrappers)) (let ((cache-line-size (compute-line-size (+ (length wrappers) (if value 1 0))))) `(let ((primary 0) (size-1 (the fixnum (- size 1)))) (declare (fixnum primary size-1)) ,(emit-n-wrapper-compute-primary-cache-location wrappers miss-label) (let ((initial-lock-count (get-cache-vector-lock-count cache-vector))) (declare (fixnum initial-lock-count)) (let ((location primary)) (declare (fixnum location)) (block search (loop (let ((next-location (the fixnum (+ location ,cache-line-size)))) (declare #.*optimize-speed*) (declare (fixnum next-location)) (when (and ,@(mapcar (lambda (wrapper) `(eq ,wrapper (%svref cache-vector (setq location (the fixnum (1+ location)))))) wrappers)) ,@(when value `((setq location (the fixnum (1+ location))) (setq ,value (%svref cache-vector location)))) (return-from search nil)) (setq location next-location) (when (= location size-1) (setq location 0)) (when (= location primary) (loop for (ws . v) in overflow when (and ,@(mapcar (lambda (w) `(eq ,w (pop ws))) wrappers)) do ,@(when value `((setq ,value v))) (return-from search nil)) (go ,miss-label))))) (unless (= initial-lock-count (get-cache-vector-lock-count cache-vector)) (go ,miss-label))))))) (defun emit-1-wrapper-compute-primary-cache-location (wrapper miss-label) `(let ((wrapper-cache-no (kernel:layout-hash ,wrapper field))) (declare (fixnum wrapper-cache-no)) (when (zerop wrapper-cache-no) (go ,miss-label)) ,(let ((form `(logand mask wrapper-cache-no))) `(the fixnum ,form)))) #-pcl-xorhash (defun emit-n-wrapper-compute-primary-cache-location (wrappers miss-label) (declare (type list wrappers)) this returns 1 less that the actual location `(progn ,@(let ((adds 0) (len (length wrappers))) (declare (fixnum adds len)) (mapcar (lambda (wrapper) `(let ((wrapper-cache-no (kernel:layout-hash ,wrapper field))) (declare (fixnum wrapper-cache-no)) (when (zerop wrapper-cache-no) (go ,miss-label)) (setq primary (the fixnum (+ primary wrapper-cache-no))) ,@(progn (incf adds) (when (or (zerop (mod adds +max-hash-code-additions+)) (eql adds len)) `((setq primary ,(let ((form `(logand primary mask))) `(the fixnum ,form)))))))) wrappers)))) #+pcl-xorhash (defun emit-n-wrapper-compute-primary-cache-location (wrappers miss-label) (declare (type list wrappers)) this returns 1 less that the actual location `(progn ,@(let ((adds 0) (len (length wrappers))) (declare (fixnum adds len)) (mapcar (lambda (wrapper) `(let ((hash (kernel:layout-hash ,wrapper field))) (declare (fixnum hash)) (when (zerop hash) (go ,miss-label)) (setq primary (logxor primary hash)) ,@(progn (incf adds) (when (eql adds len) `((setq primary ,(let ((form `(logand primary mask))) `(the fixnum ,form)))))))) wrappers)))) ;;; ;;; cmu17 note: since std-instance-p is weakened, that branch may run ;;; on non-pcl instances (structures). The result will be the ;;; non-wrapper layout for the structure, which will cause a miss. The "slots" will be whatever the first slot is , but will be ignored . Similarly , fsc - instance - p returns true on funcallable structures as well as PCL fins . ;;; (defun emit-fetch-wrapper (metatype argument miss-label &optional slot) (ecase metatype ((standard-instance) `(cond ((std-instance-p ,argument) ,@(when slot `((setq ,slot (std-instance-slots ,argument)))) (std-instance-wrapper ,argument)) ((fsc-instance-p ,argument) ,@(when slot `((setq ,slot (fsc-instance-slots ,argument)))) (fsc-instance-wrapper ,argument)) (t (go ,miss-label)))) (class (assert (null slot) () _"Can't do a slot reg for this metatype.") `(wrapper-of-macro ,argument)) ((built-in-instance structure-instance) (assert (null slot) () _"Can't do a slot reg for this metatype.") `(built-in-or-structure-wrapper ,argument))))
null
https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/pcl/dlisp.lisp
lisp
Package:(PCL LISP 1000 ) ; ; Syntax : Common - lisp -*- ************************************************************************* All rights reserved. Use and copying of this software and preparation of derivative works based upon this software are permitted. Any distribution of this States export control laws. warranty about the software, its performance or its conformity to any specification. Any person obtaining a copy of this software is requested to send their name and post office or electronic mail address to: Suggestions, comments and requests for improvements are also welcome. ************************************************************************* This file is (almost) functionally equivalent to dlap.lisp, but easier to read. Might generate faster code, too, depending on the compiler and whether an implementation-specific lap assembler was used. -------------------------------- -------------------------------- -------------------------------- -------------------------------- Don't ask me why LOCALLY is necessary here. Fact is that without it the resulting code is cmu17 note: since std-instance-p is weakened, that branch may run on non-pcl instances (structures). The result will be the non-wrapper layout for the structure, which will cause a miss. cmu17 note: since std-instance-p is weakened, that branch may run on non-pcl instances (structures). The result will be the non-wrapper layout for the structure, which will cause a miss. The "slots"
Copyright ( c ) 1985 , 1986 , 1987 , 1988 , 1989 , 1990 Xerox Corporation . software or derivative works must comply with all applicable United This software is made available AS IS , and Xerox Corporation makes no CommonLoops Coordinator Xerox PARC 3333 Coyote Hill Rd . Palo Alto , CA 94304 ( or send Arpanet mail to ) (file-comment "$Header: src/pcl/dlisp.lisp $") (in-package :pcl) (intl:textdomain "cmucl") (defun emit-one-class-reader (class-slot-p) (emit-reader/writer :reader 1 class-slot-p)) (defun emit-one-class-boundp (class-slot-p) (emit-reader/writer :boundp 1 class-slot-p)) (defun emit-one-class-writer (class-slot-p) (emit-reader/writer :writer 1 class-slot-p)) (defun emit-two-class-reader (class-slot-p) (emit-reader/writer :reader 2 class-slot-p)) (defun emit-two-class-boundp (class-slot-p) (emit-reader/writer :boundp 2 class-slot-p)) (defun emit-two-class-writer (class-slot-p) (emit-reader/writer :writer 2 class-slot-p)) (defun emit-one-index-readers (class-slot-p) (emit-one-or-n-index-reader/writer :reader nil class-slot-p)) (defun emit-one-index-boundps (class-slot-p) (emit-one-or-n-index-reader/writer :boundp nil class-slot-p)) (defun emit-one-index-writers (class-slot-p) (emit-one-or-n-index-reader/writer :writer nil class-slot-p)) (defun emit-n-n-readers () (emit-one-or-n-index-reader/writer :reader t nil)) (defun emit-n-n-boundps () (emit-one-or-n-index-reader/writer :boundp t nil)) (defun emit-n-n-writers () (emit-one-or-n-index-reader/writer :writer t nil)) (defun emit-checking (metatypes applyp) (emit-checking-or-caching nil nil metatypes applyp)) (defun emit-caching (metatypes applyp) (emit-checking-or-caching t nil metatypes applyp)) (defun emit-in-checking-cache-p (metatypes) (emit-checking-or-caching nil t metatypes nil)) (defun emit-constant-value (metatypes) (emit-checking-or-caching t t metatypes nil)) (defvar *precompiling-lap* nil) (defvar *emit-function-p* t) (defvar *optimize-cache-functions-p* t) (defun emit-default-only (metatypes applyp) (unless *optimize-cache-functions-p* (when (and (null *precompiling-lap*) *emit-function-p*) (return-from emit-default-only (emit-default-only-function metatypes applyp)))) (let* ((dlap-lambda-list (make-dlap-lambda-list metatypes applyp)) (args (remove '&rest dlap-lambda-list)) (restl (when applyp '(.lap-rest-arg.)))) (generating-lisp '(emf) dlap-lambda-list `(invoke-effective-method-function emf ,applyp ,@args ,@restl)))) (defun generating-lisp (closure-variables args form) (let* ((rest (memq '&rest args)) (ldiff (and rest (ldiff args rest))) (args (if rest (append ldiff '(&rest .lap-rest-arg.)) args)) (lambda `(lambda ,closure-variables ,@(when (member 'miss-fn closure-variables) `((declare (type function miss-fn)))) #'(kernel:instance-lambda ,args up ta 25 % slower . --gerd 2002 - 10 - 26 . (locally (declare #.*optimize-speed*) ,form))))) (values (if *precompiling-lap* `#',lambda (compile-lambda lambda)) nil))) The " slots " will be whatever the first slot is , but will be ignored . Similarly , fsc - instance - p returns true on funcallable structures as well as PCL fins . (defun emit-reader/writer (reader/writer 1-or-2-class class-slot-p) (unless *optimize-cache-functions-p* (when (and (null *precompiling-lap*) *emit-function-p*) (return-from emit-reader/writer (emit-reader/writer-function reader/writer 1-or-2-class class-slot-p)))) (let* ((instance (ecase reader/writer ((:reader :boundp) (dfun-arg-symbol 0)) (:writer (dfun-arg-symbol 1)))) (arglist (ecase reader/writer ((:reader :boundp) (list instance)) (:writer (list (dfun-arg-symbol 0) instance)))) (closure-variables (ecase 1-or-2-class (1 '(wrapper-0 index miss-fn)) (2 '(wrapper-0 wrapper-1 index miss-fn)))) (read-form (emit-slot-read-form class-slot-p 'index 'slots))) (generating-lisp closure-variables arglist `(let* (,@(unless class-slot-p `((slots nil))) (wrapper (cond ((std-instance-p ,instance) ,@(unless class-slot-p `((setq slots (std-instance-slots ,instance)))) (std-instance-wrapper ,instance)) ((fsc-instance-p ,instance) ,@(unless class-slot-p `((setq slots (fsc-instance-slots ,instance)))) (fsc-instance-wrapper ,instance))))) (block access (when (and wrapper (not (zerop (kernel:layout-hash wrapper 0))) ,@(if (eql 1 1-or-2-class) `((eq wrapper wrapper-0)) `((or (eq wrapper wrapper-0) (eq wrapper wrapper-1))))) ,@(ecase reader/writer (:reader `((let ((value ,read-form)) (unless (eq value +slot-unbound+) (return-from access value))))) (:boundp `((let ((value ,read-form)) (return-from access (not (eq value +slot-unbound+)))))) (:writer `((return-from access (setf ,read-form ,(car arglist))))))) (funcall miss-fn ,@arglist)))))) (defun emit-slot-read-form (class-slot-p index slots) (if class-slot-p `(cdr ,index) `(%slot-ref ,slots ,index))) (defun emit-boundp-check (value-form miss-fn arglist) `(let ((value ,value-form)) (if (eq value +slot-unbound+) (funcall ,miss-fn ,@arglist) value))) (defun emit-slot-access (reader/writer class-slot-p slots index miss-fn arglist) (let ((read-form (emit-slot-read-form class-slot-p index slots))) (ecase reader/writer (:reader (emit-boundp-check read-form miss-fn arglist)) (:boundp `(not (eq +slot-unbound+ ,read-form))) (:writer `(setf ,read-form ,(car arglist)))))) (defmacro emit-reader/writer-macro (reader/writer 1-or-2-class class-slot-p) (let ((*emit-function-p* nil) (*precompiling-lap* t)) (values (emit-reader/writer reader/writer 1-or-2-class class-slot-p)))) (defun emit-one-or-n-index-reader/writer (reader/writer cached-index-p class-slot-p) (unless *optimize-cache-functions-p* (when (and (null *precompiling-lap*) *emit-function-p*) (return-from emit-one-or-n-index-reader/writer (emit-one-or-n-index-reader/writer-function reader/writer cached-index-p class-slot-p)))) (multiple-value-bind (arglist metatypes) (ecase reader/writer ((:reader :boundp) (values (list (dfun-arg-symbol 0)) '(standard-instance))) (:writer (values (list (dfun-arg-symbol 0) (dfun-arg-symbol 1)) '(t standard-instance)))) (generating-lisp `(cache ,@(unless cached-index-p '(index)) miss-fn) arglist `(let (,@(unless class-slot-p '(slots)) ,@(when cached-index-p '(index))) ,(emit-dlap arglist metatypes (emit-slot-access reader/writer class-slot-p 'slots 'index 'miss-fn arglist) `(funcall miss-fn ,@arglist) (when cached-index-p 'index) (unless class-slot-p '(slots))))))) (defmacro emit-one-or-n-index-reader/writer-macro (reader/writer cached-index-p class-slot-p) (let ((*emit-function-p* nil) (*precompiling-lap* t)) (values (emit-one-or-n-index-reader/writer reader/writer cached-index-p class-slot-p)))) (defun emit-miss (miss-fn args &optional applyp) (let ((restl (when applyp '(.lap-rest-arg.)))) (if restl `(apply ,miss-fn ,@args ,@restl) `(funcall ,miss-fn ,@args ,@restl)))) (defun emit-checking-or-caching (cached-emf-p return-value-p metatypes applyp) (unless *optimize-cache-functions-p* (when (and (null *precompiling-lap*) *emit-function-p*) (return-from emit-checking-or-caching (emit-checking-or-caching-function cached-emf-p return-value-p metatypes applyp)))) (let* ((dlap-lambda-list (make-dlap-lambda-list metatypes applyp)) (args (remove '&rest dlap-lambda-list)) (restl (when applyp '(.lap-rest-arg.)))) (generating-lisp `(cache ,@(unless cached-emf-p '(emf)) miss-fn) dlap-lambda-list `(let (,@(when cached-emf-p '(emf))) ,(emit-dlap args metatypes (if return-value-p (if cached-emf-p 'emf t) `(invoke-effective-method-function emf ,applyp ,@args ,@restl)) (emit-miss 'miss-fn args applyp) (when cached-emf-p 'emf)))))) (defun emit-dlap (args metatypes hit miss value-reg &optional slot-regs) (let* ((index -1) (wrapper-bindings (mapcan (lambda (arg mt) (unless (eq mt t) (incf index) `((,(intern (format nil "WRAPPER-~D" index) *the-pcl-package*) ,(emit-fetch-wrapper mt arg 'miss (pop slot-regs)))))) args metatypes)) (wrappers (mapcar #'car wrapper-bindings))) (declare (fixnum index)) (assert (not (null wrappers)) () _"Every metatype is T.") `(block dfun (tagbody (let ((field (cache-field cache)) (cache-vector (cache-vector cache)) (mask (cache-mask cache)) (size (cache-size cache)) (overflow (cache-overflow cache)) ,@wrapper-bindings) (declare (fixnum size field mask)) ,(cond ((cdr wrappers) (emit-greater-than-1-dlap wrappers 'miss value-reg)) (value-reg (emit-1-t-dlap (car wrappers) 'miss value-reg)) (t (emit-1-nil-dlap (car wrappers) 'miss))) (return-from dfun ,hit)) miss (return-from dfun ,miss))))) (defun emit-1-nil-dlap (wrapper miss-label) `(let* ((primary ,(emit-1-wrapper-compute-primary-cache-location wrapper miss-label)) (location primary)) (declare (fixnum primary location)) (block search (loop (when (eq ,wrapper (cache-vector-ref cache-vector location)) (return-from search nil)) (setq location (the fixnum (+ location 1))) (when (= location size) (setq location 0)) (when (= location primary) (dolist (entry overflow) (when (eq (car entry) ,wrapper) (return-from search nil))) (go ,miss-label)))))) (defmacro get-cache-vector-lock-count (cache-vector) `(let ((lock-count (cache-vector-lock-count ,cache-vector))) (the fixnum lock-count))) (defun emit-1-t-dlap (wrapper miss-label value) `(let ((primary ,(emit-1-wrapper-compute-primary-cache-location wrapper miss-label)) (initial-lock-count (get-cache-vector-lock-count cache-vector))) (declare (fixnum primary initial-lock-count)) (let ((location primary)) (declare (fixnum location)) (block search (loop (when (eq ,wrapper (cache-vector-ref cache-vector location)) (setq ,value (cache-vector-ref cache-vector (1+ location))) (return-from search nil)) (setq location (the fixnum (+ location 2))) (when (= location size) (setq location 0)) (when (= location primary) (dolist (entry overflow) (when (eq (car entry) ,wrapper) (setq ,value (cdr entry)) (return-from search nil))) (go ,miss-label)))) (unless (= initial-lock-count (get-cache-vector-lock-count cache-vector)) (go ,miss-label))))) (defun emit-greater-than-1-dlap (wrappers miss-label value) (declare (type list wrappers)) (let ((cache-line-size (compute-line-size (+ (length wrappers) (if value 1 0))))) `(let ((primary 0) (size-1 (the fixnum (- size 1)))) (declare (fixnum primary size-1)) ,(emit-n-wrapper-compute-primary-cache-location wrappers miss-label) (let ((initial-lock-count (get-cache-vector-lock-count cache-vector))) (declare (fixnum initial-lock-count)) (let ((location primary)) (declare (fixnum location)) (block search (loop (let ((next-location (the fixnum (+ location ,cache-line-size)))) (declare #.*optimize-speed*) (declare (fixnum next-location)) (when (and ,@(mapcar (lambda (wrapper) `(eq ,wrapper (%svref cache-vector (setq location (the fixnum (1+ location)))))) wrappers)) ,@(when value `((setq location (the fixnum (1+ location))) (setq ,value (%svref cache-vector location)))) (return-from search nil)) (setq location next-location) (when (= location size-1) (setq location 0)) (when (= location primary) (loop for (ws . v) in overflow when (and ,@(mapcar (lambda (w) `(eq ,w (pop ws))) wrappers)) do ,@(when value `((setq ,value v))) (return-from search nil)) (go ,miss-label))))) (unless (= initial-lock-count (get-cache-vector-lock-count cache-vector)) (go ,miss-label))))))) (defun emit-1-wrapper-compute-primary-cache-location (wrapper miss-label) `(let ((wrapper-cache-no (kernel:layout-hash ,wrapper field))) (declare (fixnum wrapper-cache-no)) (when (zerop wrapper-cache-no) (go ,miss-label)) ,(let ((form `(logand mask wrapper-cache-no))) `(the fixnum ,form)))) #-pcl-xorhash (defun emit-n-wrapper-compute-primary-cache-location (wrappers miss-label) (declare (type list wrappers)) this returns 1 less that the actual location `(progn ,@(let ((adds 0) (len (length wrappers))) (declare (fixnum adds len)) (mapcar (lambda (wrapper) `(let ((wrapper-cache-no (kernel:layout-hash ,wrapper field))) (declare (fixnum wrapper-cache-no)) (when (zerop wrapper-cache-no) (go ,miss-label)) (setq primary (the fixnum (+ primary wrapper-cache-no))) ,@(progn (incf adds) (when (or (zerop (mod adds +max-hash-code-additions+)) (eql adds len)) `((setq primary ,(let ((form `(logand primary mask))) `(the fixnum ,form)))))))) wrappers)))) #+pcl-xorhash (defun emit-n-wrapper-compute-primary-cache-location (wrappers miss-label) (declare (type list wrappers)) this returns 1 less that the actual location `(progn ,@(let ((adds 0) (len (length wrappers))) (declare (fixnum adds len)) (mapcar (lambda (wrapper) `(let ((hash (kernel:layout-hash ,wrapper field))) (declare (fixnum hash)) (when (zerop hash) (go ,miss-label)) (setq primary (logxor primary hash)) ,@(progn (incf adds) (when (eql adds len) `((setq primary ,(let ((form `(logand primary mask))) `(the fixnum ,form)))))))) wrappers)))) will be whatever the first slot is , but will be ignored . Similarly , fsc - instance - p returns true on funcallable structures as well as PCL fins . (defun emit-fetch-wrapper (metatype argument miss-label &optional slot) (ecase metatype ((standard-instance) `(cond ((std-instance-p ,argument) ,@(when slot `((setq ,slot (std-instance-slots ,argument)))) (std-instance-wrapper ,argument)) ((fsc-instance-p ,argument) ,@(when slot `((setq ,slot (fsc-instance-slots ,argument)))) (fsc-instance-wrapper ,argument)) (t (go ,miss-label)))) (class (assert (null slot) () _"Can't do a slot reg for this metatype.") `(wrapper-of-macro ,argument)) ((built-in-instance structure-instance) (assert (null slot) () _"Can't do a slot reg for this metatype.") `(built-in-or-structure-wrapper ,argument))))
9776739220760bb480cd1c4691c1114cec3f11fc0632bda3ed8e42af4878aefa
emqx/esockd
esockd_proxy_protocol.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. %%-------------------------------------------------------------------- %% @doc [Proxy Protocol](-protocol.txt) -module(esockd_proxy_protocol). -include("esockd.hrl"). -export([recv/3]). -ifdef(TEST). -export([parse_v1/2, parse_v2/4, parse_pp2_tlv/2, parse_pp2_ssl/1]). -endif. %% Protocol Command -define(LOCAL, 16#0). -define(PROXY, 16#1). %% Address families -define(UNSPEC, 16#0). -define(INET, 16#1). -define(INET6, 16#2). -define(UNIX, 16#3). -define(STREAM, 16#1). -define(DGRAM, 16#2). -define(SPACE, 16#20). -define(TIMEOUT, 5000). %% Proxy Protocol Additional Fields -define(PP2_TYPE_ALPN, 16#01). -define(PP2_TYPE_AUTHORITY, 16#02). -define(PP2_TYPE_CRC32C, 16#03). -define(PP2_TYPE_NOOP, 16#04). -define(PP2_TYPE_SSL, 16#20). -define(PP2_SUBTYPE_SSL_VERSION, 16#21). -define(PP2_SUBTYPE_SSL_CN, 16#22). -define(PP2_SUBTYPE_SSL_CIPHER, 16#23). -define(PP2_SUBTYPE_SSL_SIG_ALG, 16#24). -define(PP2_SUBTYPE_SSL_KEY_ALG, 16#25). -define(PP2_TYPE_NETNS, 16#30). Protocol signature : %% 16#0D,16#0A,16#00,16#0D,16#0A,16#51,16#55,16#49,16#54,16#0A -define(SIG, "\r\n\0\r\nQUIT\n"). -spec(recv(module(), inet:socket() | #ssl_socket{}, timeout()) -> {ok, #proxy_socket{}} | {error, term()}). recv(Transport, Sock, Timeout) -> {ok, OriginOpts} = Transport:getopts(Sock, [mode, active, packet]), ok = Transport:setopts(Sock, [binary, {active, once}, {packet, line}]), receive V1 TCP {_, _Sock, <<"PROXY TCP", Proto, ?SPACE, ProxyInfo/binary>>} -> Transport:setopts(Sock, OriginOpts), parse_v1(ProxyInfo, #proxy_socket{inet = inet_family(Proto), socket = Sock}); %% V1 Unknown {_, _Sock, <<"PROXY UNKNOWN", _ProxyInfo/binary>>} -> Transport:setopts(Sock, OriginOpts), {ok, Sock}; V2 TCP {_, _Sock, <<"\r\n">>} -> Transport:setopts(Sock, [{active, false}, {packet, raw}]), {ok, Header} = Transport:recv(Sock, 14, 1000), <<?SIG, 2:4, Cmd:4, AF:4, Trans:4, Len:16>> = Header, case Transport:recv(Sock, Len, 1000) of {ok, ProxyInfo} -> Transport:setopts(Sock, OriginOpts), parse_v2(Cmd, Trans, ProxyInfo, #proxy_socket{inet = inet_family(AF), socket = Sock}); {error, Reason} -> {error, {recv_proxy_info_error, Reason}} end; {tcp_error, _Sock, Reason} -> {error, {recv_proxy_info_error, Reason}}; {tcp_closed, _Sock} -> {error, {recv_proxy_info_error, tcp_closed}}; {_, _Sock, ProxyInfo} -> {error, {invalid_proxy_info, ProxyInfo}} after Timeout -> {error, proxy_proto_timeout} end. parse_v1(ProxyInfo, ProxySock) -> [SrcAddrBin, DstAddrBin, SrcPortBin, DstPortBin] = binary:split(ProxyInfo, [<<" ">>, <<"\r\n">>], [global, trim]), {ok, SrcAddr} = inet:parse_address(binary_to_list(SrcAddrBin)), {ok, DstAddr} = inet:parse_address(binary_to_list(DstAddrBin)), SrcPort = list_to_integer(binary_to_list(SrcPortBin)), DstPort = list_to_integer(binary_to_list(DstPortBin)), {ok, ProxySock#proxy_socket{src_addr = SrcAddr, dst_addr = DstAddr, src_port = SrcPort, dst_port = DstPort}}. parse_v2(?LOCAL, _Trans, _ProxyInfo, #proxy_socket{socket = Sock}) -> {ok, Sock}; parse_v2(?PROXY, ?STREAM, ProxyInfo, ProxySock = #proxy_socket{inet = inet4}) -> <<A:8, B:8, C:8, D:8, W:8, X:8, Y:8, Z:8, SrcPort:16, DstPort:16, AdditionalBytes/binary>> = ProxyInfo, parse_pp2_additional(AdditionalBytes, ProxySock#proxy_socket{ src_addr = {A, B, C, D}, src_port = SrcPort, dst_addr = {W, X, Y, Z}, dst_port = DstPort}); parse_v2(?PROXY, ?STREAM, ProxyInfo, ProxySock = #proxy_socket{inet = inet6}) -> <<A:16, B:16, C:16, D:16, E:16, F:16, G:16, H:16, R:16, S:16, T:16, U:16, V:16, W:16, X:16, Y:16, SrcPort:16, DstPort:16, AdditionalBytes/binary>> = ProxyInfo, parse_pp2_additional(AdditionalBytes, ProxySock#proxy_socket{ src_addr = {A, B, C, D, E, F, G, H}, src_port = SrcPort, dst_addr = {R, S, T, U, V, W, X, Y}, dst_port = DstPort}); parse_v2(_, _, _, #proxy_socket{socket = _Sock}) -> {error, unsupported_proto_v2}. parse_pp2_additional(<<>>, ProxySock) -> {ok, ProxySock}; parse_pp2_additional(Bytes, ProxySock) when is_binary(Bytes) -> IgnoreGuard = fun(?PP2_TYPE_NOOP) -> false; (_Type) -> true end, AdditionalInfo = parse_pp2_tlv(fun pp2_additional_field/1, Bytes, IgnoreGuard), {ok, ProxySock#proxy_socket{pp2_additional_info = AdditionalInfo}}. parse_pp2_tlv(Fun, Bytes) -> parse_pp2_tlv(Fun, Bytes, fun(_Any) -> true end). parse_pp2_tlv(Fun, Bytes, Guard) -> [Fun({Type, Val}) || <<Type:8, Len:16, Val:Len/binary>> <= Bytes, Guard(Type)]. pp2_additional_field({?PP2_TYPE_ALPN, PP2_ALPN}) -> {pp2_alpn, PP2_ALPN}; pp2_additional_field({?PP2_TYPE_AUTHORITY, PP2_AUTHORITY}) -> {pp2_authority, PP2_AUTHORITY}; pp2_additional_field({?PP2_TYPE_CRC32C, PP2_CRC32C}) -> {pp2_crc32c, PP2_CRC32C}; pp2_additional_field({?PP2_TYPE_NETNS, PP2_NETNS}) -> {pp2_netns, PP2_NETNS}; pp2_additional_field({?PP2_TYPE_SSL, PP2_SSL}) -> {pp2_ssl, parse_pp2_ssl(PP2_SSL)}; pp2_additional_field({Field, Value}) -> {{pp2_raw, Field}, Value}. parse_pp2_ssl(<<_Unused:5, PP2_CLIENT_CERT_SESS:1, PP2_CLIENT_CERT_CONN:1, PP2_CLIENT_SSL:1, PP2_SSL_VERIFY:32, SubFields/bitstring>>) -> [ %% The PP2_CLIENT_SSL flag indicates that the client connected over SSL/TLS. When this field is present , the US - ASCII string representation of the TLS version is appended at the end of the field in the TLV format using the type PP2_SUBTYPE_SSL_VERSION . {pp2_ssl_client, bool(PP2_CLIENT_SSL)}, %% PP2_CLIENT_CERT_CONN indicates that the client provided a certificate over the %% current connection. {pp2_ssl_client_cert_conn, bool(PP2_CLIENT_CERT_CONN)}, %% PP2_CLIENT_CERT_SESS indicates that the client provided a certificate at least once over the TLS session this connection belongs to . {pp2_ssl_client_cert_sess, bool(PP2_CLIENT_CERT_SESS)}, The < verify > field will be zero if the client presented a certificate and it was successfully verified , and non - zero otherwise . {pp2_ssl_verify, ssl_certificate_verified(PP2_SSL_VERIFY)} | parse_pp2_tlv(fun pp2_additional_ssl_field/1, SubFields) ]. pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_VERSION, PP2_SSL_VERSION}) -> {pp2_ssl_version, PP2_SSL_VERSION}; %% In all cases, the string representation (in UTF8) of the Common Name field ( OID : 2.5.4.3 ) of the client certificate 's Distinguished Name , is appended using the TLV format and the type PP2_SUBTYPE_SSL_CN . E.g. " example.com " . pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_CN, PP2_SSL_CN}) -> {pp2_ssl_cn, PP2_SSL_CN}; pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_CIPHER, PP2_SSL_CIPHER}) -> {pp2_ssl_cipher, PP2_SSL_CIPHER}; pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_SIG_ALG, PP2_SSL_SIG_ALG}) -> {pp2_ssl_sig_alg, PP2_SSL_SIG_ALG}; pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_KEY_ALG, PP2_SSL_KEY_ALG}) -> {pp2_ssl_key_alg, PP2_SSL_KEY_ALG}; pp2_additional_ssl_field({Field, Val}) -> {{pp2_ssl_raw, Field}, Val}. ssl_certificate_verified(0) -> success; ssl_certificate_verified(_) -> failed. V1 inet_family($4) -> inet4; inet_family($6) -> inet6; V2 inet_family(?UNSPEC) -> unspec; inet_family(?INET) -> inet4; inet_family(?INET6) -> inet6; inet_family(?UNIX) -> unix. bool(1) -> true; bool(_) -> false.
null
https://raw.githubusercontent.com/emqx/esockd/9b959fc11a1c398a589892f335235be6c5b4a454/src/esockd_proxy_protocol.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. -------------------------------------------------------------------- @doc [Proxy Protocol](-protocol.txt) Protocol Command Address families Proxy Protocol Additional Fields 16#0D,16#0A,16#00,16#0D,16#0A,16#51,16#55,16#49,16#54,16#0A V1 Unknown The PP2_CLIENT_SSL flag indicates that the client connected over SSL/TLS. When PP2_CLIENT_CERT_CONN indicates that the client provided a certificate over the current connection. PP2_CLIENT_CERT_SESS indicates that the client provided a In all cases, the string representation (in UTF8) of the Common Name field
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(esockd_proxy_protocol). -include("esockd.hrl"). -export([recv/3]). -ifdef(TEST). -export([parse_v1/2, parse_v2/4, parse_pp2_tlv/2, parse_pp2_ssl/1]). -endif. -define(LOCAL, 16#0). -define(PROXY, 16#1). -define(UNSPEC, 16#0). -define(INET, 16#1). -define(INET6, 16#2). -define(UNIX, 16#3). -define(STREAM, 16#1). -define(DGRAM, 16#2). -define(SPACE, 16#20). -define(TIMEOUT, 5000). -define(PP2_TYPE_ALPN, 16#01). -define(PP2_TYPE_AUTHORITY, 16#02). -define(PP2_TYPE_CRC32C, 16#03). -define(PP2_TYPE_NOOP, 16#04). -define(PP2_TYPE_SSL, 16#20). -define(PP2_SUBTYPE_SSL_VERSION, 16#21). -define(PP2_SUBTYPE_SSL_CN, 16#22). -define(PP2_SUBTYPE_SSL_CIPHER, 16#23). -define(PP2_SUBTYPE_SSL_SIG_ALG, 16#24). -define(PP2_SUBTYPE_SSL_KEY_ALG, 16#25). -define(PP2_TYPE_NETNS, 16#30). Protocol signature : -define(SIG, "\r\n\0\r\nQUIT\n"). -spec(recv(module(), inet:socket() | #ssl_socket{}, timeout()) -> {ok, #proxy_socket{}} | {error, term()}). recv(Transport, Sock, Timeout) -> {ok, OriginOpts} = Transport:getopts(Sock, [mode, active, packet]), ok = Transport:setopts(Sock, [binary, {active, once}, {packet, line}]), receive V1 TCP {_, _Sock, <<"PROXY TCP", Proto, ?SPACE, ProxyInfo/binary>>} -> Transport:setopts(Sock, OriginOpts), parse_v1(ProxyInfo, #proxy_socket{inet = inet_family(Proto), socket = Sock}); {_, _Sock, <<"PROXY UNKNOWN", _ProxyInfo/binary>>} -> Transport:setopts(Sock, OriginOpts), {ok, Sock}; V2 TCP {_, _Sock, <<"\r\n">>} -> Transport:setopts(Sock, [{active, false}, {packet, raw}]), {ok, Header} = Transport:recv(Sock, 14, 1000), <<?SIG, 2:4, Cmd:4, AF:4, Trans:4, Len:16>> = Header, case Transport:recv(Sock, Len, 1000) of {ok, ProxyInfo} -> Transport:setopts(Sock, OriginOpts), parse_v2(Cmd, Trans, ProxyInfo, #proxy_socket{inet = inet_family(AF), socket = Sock}); {error, Reason} -> {error, {recv_proxy_info_error, Reason}} end; {tcp_error, _Sock, Reason} -> {error, {recv_proxy_info_error, Reason}}; {tcp_closed, _Sock} -> {error, {recv_proxy_info_error, tcp_closed}}; {_, _Sock, ProxyInfo} -> {error, {invalid_proxy_info, ProxyInfo}} after Timeout -> {error, proxy_proto_timeout} end. parse_v1(ProxyInfo, ProxySock) -> [SrcAddrBin, DstAddrBin, SrcPortBin, DstPortBin] = binary:split(ProxyInfo, [<<" ">>, <<"\r\n">>], [global, trim]), {ok, SrcAddr} = inet:parse_address(binary_to_list(SrcAddrBin)), {ok, DstAddr} = inet:parse_address(binary_to_list(DstAddrBin)), SrcPort = list_to_integer(binary_to_list(SrcPortBin)), DstPort = list_to_integer(binary_to_list(DstPortBin)), {ok, ProxySock#proxy_socket{src_addr = SrcAddr, dst_addr = DstAddr, src_port = SrcPort, dst_port = DstPort}}. parse_v2(?LOCAL, _Trans, _ProxyInfo, #proxy_socket{socket = Sock}) -> {ok, Sock}; parse_v2(?PROXY, ?STREAM, ProxyInfo, ProxySock = #proxy_socket{inet = inet4}) -> <<A:8, B:8, C:8, D:8, W:8, X:8, Y:8, Z:8, SrcPort:16, DstPort:16, AdditionalBytes/binary>> = ProxyInfo, parse_pp2_additional(AdditionalBytes, ProxySock#proxy_socket{ src_addr = {A, B, C, D}, src_port = SrcPort, dst_addr = {W, X, Y, Z}, dst_port = DstPort}); parse_v2(?PROXY, ?STREAM, ProxyInfo, ProxySock = #proxy_socket{inet = inet6}) -> <<A:16, B:16, C:16, D:16, E:16, F:16, G:16, H:16, R:16, S:16, T:16, U:16, V:16, W:16, X:16, Y:16, SrcPort:16, DstPort:16, AdditionalBytes/binary>> = ProxyInfo, parse_pp2_additional(AdditionalBytes, ProxySock#proxy_socket{ src_addr = {A, B, C, D, E, F, G, H}, src_port = SrcPort, dst_addr = {R, S, T, U, V, W, X, Y}, dst_port = DstPort}); parse_v2(_, _, _, #proxy_socket{socket = _Sock}) -> {error, unsupported_proto_v2}. parse_pp2_additional(<<>>, ProxySock) -> {ok, ProxySock}; parse_pp2_additional(Bytes, ProxySock) when is_binary(Bytes) -> IgnoreGuard = fun(?PP2_TYPE_NOOP) -> false; (_Type) -> true end, AdditionalInfo = parse_pp2_tlv(fun pp2_additional_field/1, Bytes, IgnoreGuard), {ok, ProxySock#proxy_socket{pp2_additional_info = AdditionalInfo}}. parse_pp2_tlv(Fun, Bytes) -> parse_pp2_tlv(Fun, Bytes, fun(_Any) -> true end). parse_pp2_tlv(Fun, Bytes, Guard) -> [Fun({Type, Val}) || <<Type:8, Len:16, Val:Len/binary>> <= Bytes, Guard(Type)]. pp2_additional_field({?PP2_TYPE_ALPN, PP2_ALPN}) -> {pp2_alpn, PP2_ALPN}; pp2_additional_field({?PP2_TYPE_AUTHORITY, PP2_AUTHORITY}) -> {pp2_authority, PP2_AUTHORITY}; pp2_additional_field({?PP2_TYPE_CRC32C, PP2_CRC32C}) -> {pp2_crc32c, PP2_CRC32C}; pp2_additional_field({?PP2_TYPE_NETNS, PP2_NETNS}) -> {pp2_netns, PP2_NETNS}; pp2_additional_field({?PP2_TYPE_SSL, PP2_SSL}) -> {pp2_ssl, parse_pp2_ssl(PP2_SSL)}; pp2_additional_field({Field, Value}) -> {{pp2_raw, Field}, Value}. parse_pp2_ssl(<<_Unused:5, PP2_CLIENT_CERT_SESS:1, PP2_CLIENT_CERT_CONN:1, PP2_CLIENT_SSL:1, PP2_SSL_VERIFY:32, SubFields/bitstring>>) -> [ this field is present , the US - ASCII string representation of the TLS version is appended at the end of the field in the TLV format using the type PP2_SUBTYPE_SSL_VERSION . {pp2_ssl_client, bool(PP2_CLIENT_SSL)}, {pp2_ssl_client_cert_conn, bool(PP2_CLIENT_CERT_CONN)}, certificate at least once over the TLS session this connection belongs to . {pp2_ssl_client_cert_sess, bool(PP2_CLIENT_CERT_SESS)}, The < verify > field will be zero if the client presented a certificate and it was successfully verified , and non - zero otherwise . {pp2_ssl_verify, ssl_certificate_verified(PP2_SSL_VERIFY)} | parse_pp2_tlv(fun pp2_additional_ssl_field/1, SubFields) ]. pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_VERSION, PP2_SSL_VERSION}) -> {pp2_ssl_version, PP2_SSL_VERSION}; ( OID : 2.5.4.3 ) of the client certificate 's Distinguished Name , is appended using the TLV format and the type PP2_SUBTYPE_SSL_CN . E.g. " example.com " . pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_CN, PP2_SSL_CN}) -> {pp2_ssl_cn, PP2_SSL_CN}; pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_CIPHER, PP2_SSL_CIPHER}) -> {pp2_ssl_cipher, PP2_SSL_CIPHER}; pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_SIG_ALG, PP2_SSL_SIG_ALG}) -> {pp2_ssl_sig_alg, PP2_SSL_SIG_ALG}; pp2_additional_ssl_field({?PP2_SUBTYPE_SSL_KEY_ALG, PP2_SSL_KEY_ALG}) -> {pp2_ssl_key_alg, PP2_SSL_KEY_ALG}; pp2_additional_ssl_field({Field, Val}) -> {{pp2_ssl_raw, Field}, Val}. ssl_certificate_verified(0) -> success; ssl_certificate_verified(_) -> failed. V1 inet_family($4) -> inet4; inet_family($6) -> inet6; V2 inet_family(?UNSPEC) -> unspec; inet_family(?INET) -> inet4; inet_family(?INET6) -> inet6; inet_family(?UNIX) -> unix. bool(1) -> true; bool(_) -> false.
617e7486060eb46fa21f8f5955aaeb8ca6801a13aae2927afc129e096bc4dab7
nominolo/lambdachine
SumFromTo.hs
# LANGUAGE NoImplicitPrelude , MagicHash , BangPatterns # -- RUN: %bc_vm -- Fails with: No instance for ( GHC.Num . ) -- arising from the literal `1234567890' Possible fix : add an instance declaration for ( GHC.Num . ) In the first argument of ` sum ' , namely ` 1234567890 ' In the expression : ( sum 1234567890 ( upto ( I # 1 # ) ( I # 15 # ) ) ) -- In an equation for `test': test = ( sum 1234567890 ( upto ( I # 1 # ) ( I # 15 # ) ) ) -- XFAIL: * module Bc.SumFromTo where import Prelude ( Int , print ) import ( plusInt , gtInt ) import GHC.Prim import GHC.Bool import GHC.Integer.GMP.Internals (Integer(..)) import Prelude data Int = I# Int# data Integer = S # Int # smallInteger :: Int# -> Integer smallInteger x = S# x # INLINE smallInteger # fromInteger :: Integer -> Int fromInteger (S# n) = I# n # INLINE fromInteger # The NOINLINE stuff is to simulate these things coming from another -- module (or package even). plusInt :: Int -> Int -> Int plusInt (I# m) (I# n) = I# (m +# n) # NOINLINE plusInt # minusInt :: Int -> Int -> Int minusInt (I# m) (I# n) = I# (m -# n) # NOINLINE minusInt # gtInt :: Int -> Int -> Bool gtInt (I# m) (I# n) = m ># n # NOINLINE gtInt # eqInt :: Int -> Int -> Bool eqInt (I# m) (I# n) = m ==# n data List a = Nil | Cons a (List a) upto :: Int -> Int -> List Int upto from to = if from `gtInt` to then Nil else Cons from (upto (from `plusInt` I# 1#) to) sum :: Int -> List Int -> Int sum acc Nil = acc sum acc (Cons x xs) = let acc' = (acc `plusInt` x) in acc' `seq` sum acc' xs {- replicate :: Int -> a -> List a replicate n x = case n of I# 0# -> Nil _ -> Cons x (replicate (n `minusInt` I# 1#) x) -} {- replicate' n x | I# 0# `gtInt` n = Nil | True = Cons x (replicate' (n `minusInt` I# 1#) x) -} append : : List a - > List a - > List a append append ( Cons y ys ) xs = Cons y ( append ys xs ) foldr : : ( a - > r - > r ) - > r - > List a - > r foldr c n Nil = n foldr c n ( Cons a r ) = c a ( foldr c n r ) concat : : List ( List a ) - > List a concat xs = foldr append append :: List a -> List a -> List a append Nil xs = xs append (Cons y ys) xs = Cons y (append ys xs) foldr :: (a -> r -> r) -> r -> List a -> r foldr c n Nil = n foldr c n (Cons a r) = c a (foldr c n r) concat :: List (List a) -> List a concat xs = foldr append Nil xs -} --concatMap :: (a -> List b) -> List a -> List a --concatMap f xs = foldr zero :: Int zero = I# 0# one :: Int one = I# 1# test :: Int test = (sum 1234567890 (upto (I# 1#) (I# 15#))) --test = sum' (I# 4#) test1 :: Int test1 = sum zero (decr (I# 15#) Nil) --test = f (I# 5#) A0 --data A = A1 A | A2 A -- data B = B1 A f : : Int - > A - > A f x a = if x ` gtInt ` zero then let a ' = A1 x a x ' = x ` minusInt ` one in x ' ` seq ` f x ' a ' else a --lenA : : A - > Int - > Int --lenA f : : Int - > A - > A - > A f ! x ! a ! b = if x ` gtInt ` zero then g ( x ` minusInt ` one ) ( A1 b ) ( A2 a ) else a g : : Int - > A - > A - > A g ! x ! a ! b = if x ` gtInt ` zero then g ( x ` minusInt ` one ) ( A1 b ) ( A2 a ) else b f :: Int -> A -> A f x a = if x `gtInt` zero then let a' = A1 x a x' = x `minusInt` one in x' `seq` f x' a' else a --lenA :: A -> Int -> Int --lenA f :: Int -> A -> A -> A f !x !a !b = if x `gtInt` zero then g (x `minusInt` one) (A1 b) (A2 a) else a g :: Int -> A -> A -> A g !x !a !b = if x `gtInt` zero then g (x `minusInt` one) (A1 b) (A2 a) else b -} sum' :: Int -> Int sum' i = go i (I# 0#) where go :: Int -> Int -> Int go !y !res = if y `gtInt` zero then go (y `minusInt` one) ((res `plusInt` y) `minusInt` I# 100#) else res sum'' :: Int -> Int sum'' (I# y) = go3 y 0# go3 :: Int# -> Int# -> Int go3 y res = case y ># 0# of False -> I# y True -> go3 (y -# 1#) ((res +# y) -# 100#) go1 y res = if y ` gtInt ` zero then -- go (y `minusInt` one) ((res `plusInt` y) `minusInt` I# 100#) -- else -- res decr :: Int -> List Int -> List Int decr n l = if n `gtInt` zero then let l' = Cons n l n' = n `minusInt` one in n' `seq` decr n' l' else l foldl :: (a -> b -> a) -> a -> List b -> a foldl f z Nil = z foldl f z (Cons x xs) = foldl f (z `f` x) xs test2 a b = let x = Cons a y y = Cons b x in x
null
https://raw.githubusercontent.com/nominolo/lambdachine/49d97cf7a367a650ab421f7aa19feb90bfe14731/tests/Bc/SumFromTo.hs
haskell
RUN: %bc_vm Fails with: arising from the literal `1234567890' In an equation for `test': XFAIL: * module (or package even). replicate :: Int -> a -> List a replicate n x = case n of I# 0# -> Nil _ -> Cons x (replicate (n `minusInt` I# 1#) x) replicate' n x | I# 0# `gtInt` n = Nil | True = Cons x (replicate' (n `minusInt` I# 1#) x) concatMap :: (a -> List b) -> List a -> List a concatMap f xs = foldr test = sum' (I# 4#) test = f (I# 5#) A0 data A = A1 A | A2 A data B = B1 A lenA : : A - > Int - > Int lenA lenA :: A -> Int -> Int lenA go (y `minusInt` one) ((res `plusInt` y) `minusInt` I# 100#) else res
# LANGUAGE NoImplicitPrelude , MagicHash , BangPatterns # No instance for ( GHC.Num . ) Possible fix : add an instance declaration for ( GHC.Num . ) In the first argument of ` sum ' , namely ` 1234567890 ' In the expression : ( sum 1234567890 ( upto ( I # 1 # ) ( I # 15 # ) ) ) test = ( sum 1234567890 ( upto ( I # 1 # ) ( I # 15 # ) ) ) module Bc.SumFromTo where import Prelude ( Int , print ) import ( plusInt , gtInt ) import GHC.Prim import GHC.Bool import GHC.Integer.GMP.Internals (Integer(..)) import Prelude data Int = I# Int# data Integer = S # Int # smallInteger :: Int# -> Integer smallInteger x = S# x # INLINE smallInteger # fromInteger :: Integer -> Int fromInteger (S# n) = I# n # INLINE fromInteger # The NOINLINE stuff is to simulate these things coming from another plusInt :: Int -> Int -> Int plusInt (I# m) (I# n) = I# (m +# n) # NOINLINE plusInt # minusInt :: Int -> Int -> Int minusInt (I# m) (I# n) = I# (m -# n) # NOINLINE minusInt # gtInt :: Int -> Int -> Bool gtInt (I# m) (I# n) = m ># n # NOINLINE gtInt # eqInt :: Int -> Int -> Bool eqInt (I# m) (I# n) = m ==# n data List a = Nil | Cons a (List a) upto :: Int -> Int -> List Int upto from to = if from `gtInt` to then Nil else Cons from (upto (from `plusInt` I# 1#) to) sum :: Int -> List Int -> Int sum acc Nil = acc sum acc (Cons x xs) = let acc' = (acc `plusInt` x) in acc' `seq` sum acc' xs append : : List a - > List a - > List a append append ( Cons y ys ) xs = Cons y ( append ys xs ) foldr : : ( a - > r - > r ) - > r - > List a - > r foldr c n Nil = n foldr c n ( Cons a r ) = c a ( foldr c n r ) concat : : List ( List a ) - > List a concat xs = foldr append append :: List a -> List a -> List a append Nil xs = xs append (Cons y ys) xs = Cons y (append ys xs) foldr :: (a -> r -> r) -> r -> List a -> r foldr c n Nil = n foldr c n (Cons a r) = c a (foldr c n r) concat :: List (List a) -> List a concat xs = foldr append Nil xs -} zero :: Int zero = I# 0# one :: Int one = I# 1# test :: Int test = (sum 1234567890 (upto (I# 1#) (I# 15#))) test1 :: Int test1 = sum zero (decr (I# 15#) Nil) f : : Int - > A - > A f x a = if x ` gtInt ` zero then let a ' = A1 x a x ' = x ` minusInt ` one in x ' ` seq ` f x ' a ' else a f : : Int - > A - > A - > A f ! x ! a ! b = if x ` gtInt ` zero then g ( x ` minusInt ` one ) ( A1 b ) ( A2 a ) else a g : : Int - > A - > A - > A g ! x ! a ! b = if x ` gtInt ` zero then g ( x ` minusInt ` one ) ( A1 b ) ( A2 a ) else b f :: Int -> A -> A f x a = if x `gtInt` zero then let a' = A1 x a x' = x `minusInt` one in x' `seq` f x' a' else a f :: Int -> A -> A -> A f !x !a !b = if x `gtInt` zero then g (x `minusInt` one) (A1 b) (A2 a) else a g :: Int -> A -> A -> A g !x !a !b = if x `gtInt` zero then g (x `minusInt` one) (A1 b) (A2 a) else b -} sum' :: Int -> Int sum' i = go i (I# 0#) where go :: Int -> Int -> Int go !y !res = if y `gtInt` zero then go (y `minusInt` one) ((res `plusInt` y) `minusInt` I# 100#) else res sum'' :: Int -> Int sum'' (I# y) = go3 y 0# go3 :: Int# -> Int# -> Int go3 y res = case y ># 0# of False -> I# y True -> go3 (y -# 1#) ((res +# y) -# 100#) go1 y res = if y ` gtInt ` zero then decr :: Int -> List Int -> List Int decr n l = if n `gtInt` zero then let l' = Cons n l n' = n `minusInt` one in n' `seq` decr n' l' else l foldl :: (a -> b -> a) -> a -> List b -> a foldl f z Nil = z foldl f z (Cons x xs) = foldl f (z `f` x) xs test2 a b = let x = Cons a y y = Cons b x in x
307a4355939ce9ce6c3e615014c38ad2b6e661b674762454021c0af813a4502f
fragnix/fragnix
GHC.Constants.hs
{-# LINE 1 "GHC.Constants.hs" #-} # LANGUAGE Trustworthy # # LANGUAGE NoImplicitPrelude # module GHC.Constants where TODO : This used to include HaskellConstants.hs , but that has now gone . We probably want to include the constants in somehow -- instead. import GHC.Base () -- dummy dependency
null
https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/builtins/base/GHC.Constants.hs
haskell
# LINE 1 "GHC.Constants.hs" # instead. dummy dependency
# LANGUAGE Trustworthy # # LANGUAGE NoImplicitPrelude # module GHC.Constants where TODO : This used to include HaskellConstants.hs , but that has now gone . We probably want to include the constants in somehow
a8978ba5c504970bc30bf619608c917e689bd58d52a59d62db649d57f595daa4
fogfish/pts
pts_entity_sup.erl
%% Copyright ( c ) 2012 - 2013 , %% All Rights Reserved. %% %% This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License , version 3.0 as published by the Free Software Foundation ( the " License " ) . %% 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. %% You should have received a copy of the GNU Lesser General Public %% License along with this library; if not, write to the Free Software Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA or retrieve online -3.0.html %% %% @description %% entity supervisor -module(pts_entity_sup). -behaviour(supervisor). -author('Dmitry Kolesnikov <>'). -export([ start_link/3, init/1 ]). %% -define(CHILD(T, R, M), {M, {M, start_link, []}, R, 30000, T, dynamic}). -define(CHILD(T, R, M, A), {M, {M, start_link, A}, R, 30000, T, dynamic}). -define(CHILD(T, R, M, F, A), {M, {M, F, A}, R, 30000, T, dynamic}). start_link(Type, Recovery, Spec) -> supervisor:start_link(?MODULE, [Type, Recovery, Spec]). init([Type, Recovery, Spec]) -> {ok, { {simple_one_for_one, 10, 60}, child(Type, Recovery, Spec) } }. %%----------------------------------------------------------------------------- %% %% private %% %%----------------------------------------------------------------------------- child(Type, Recovery, Mod) when is_atom(Mod) -> [?CHILD(Type, Recovery, Mod)]; child(Type, Recovery, {Mod, Args}) when is_atom(Mod) -> [?CHILD(Type, Recovery, Mod, Args)]; child(Type, Recovery, {M, F, A}) -> [?CHILD(Type, Recovery, M, F, A)].
null
https://raw.githubusercontent.com/fogfish/pts/f98c594f1e596f81b5e54c9791bf69568327fba2/src/pts_entity_sup.erl
erlang
All Rights Reserved. This library is free software; you can redistribute it and/or modify basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the specific language governing rights and limitations under the License. License along with this library; if not, write to the Free Software @description entity supervisor ----------------------------------------------------------------------------- private -----------------------------------------------------------------------------
Copyright ( c ) 2012 - 2013 , it under the terms of the GNU Lesser General Public License , version 3.0 as published by the Free Software Foundation ( the " License " ) . Software distributed under the License is distributed on an " AS IS " You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA 02111 - 1307 USA or retrieve online -3.0.html -module(pts_entity_sup). -behaviour(supervisor). -author('Dmitry Kolesnikov <>'). -export([ start_link/3, init/1 ]). -define(CHILD(T, R, M), {M, {M, start_link, []}, R, 30000, T, dynamic}). -define(CHILD(T, R, M, A), {M, {M, start_link, A}, R, 30000, T, dynamic}). -define(CHILD(T, R, M, F, A), {M, {M, F, A}, R, 30000, T, dynamic}). start_link(Type, Recovery, Spec) -> supervisor:start_link(?MODULE, [Type, Recovery, Spec]). init([Type, Recovery, Spec]) -> {ok, { {simple_one_for_one, 10, 60}, child(Type, Recovery, Spec) } }. child(Type, Recovery, Mod) when is_atom(Mod) -> [?CHILD(Type, Recovery, Mod)]; child(Type, Recovery, {Mod, Args}) when is_atom(Mod) -> [?CHILD(Type, Recovery, Mod, Args)]; child(Type, Recovery, {M, F, A}) -> [?CHILD(Type, Recovery, M, F, A)].
b272739c7092d4f77afd30d3788cca3a70f4040e1d0eff51d04f429566ee0dc4
cmsc430/www
id-def-call.rkt
#lang racket (define (f x) x) (f 5)
null
https://raw.githubusercontent.com/cmsc430/www/23cf4e30e4bac377f656dc21fc7f2aea3005068a/langs/test-programs/iniquity/id-def-call.rkt
racket
#lang racket (define (f x) x) (f 5)
d640c64915fd53996d96201e4fc04559491405d9be987f20a6c59b26c25a5725
GlideAngle/flare-timing
PointDiff.hs
module Serve.PointDiff (DiffWay(..), getTaskPointsDiffStats) where import Control.Monad.Reader (MonadReader(), asks) import qualified Data.Map.Strict as Map import qualified Statistics.Sample as Stats (meanVariance) import qualified Data.Vector as V (fromList) import Data.Vector (Vector) import Servant (throwError) import qualified Flight.Track.Point as Alt (AlternativePointing(..), AltBreakdown(..), AirScoreBreakdown(..)) import Flight.Track.Point (CompPointing(..), Breakdown(..)) import "flight-gap-math" Flight.Score (TaskPoints(..)) import Flight.Comp (Pilot(..)) import Serve.Config (AppT(..), Config(pointing, altFsScore, altAsScore)) import Serve.Error (errTaskPoints, errAltPoints) data DiffWay = DiffWayFtFs | DiffWayFtAs | DiffWayAsFs getFt :: MonadReader (Config k) m => () -> m (Maybe [[(Pilot, TaskPoints)]]) getFt () = do fmap (\CompPointing{score} -> (fmap . fmap . fmap) (\Breakdown{total} -> total) score) <$> asks pointing getFs :: MonadReader (Config k) m => () -> m (Maybe [[(Pilot, TaskPoints)]]) getFs () = do fmap (\Alt.AlternativePointing{score} -> (fmap . fmap . fmap) (\Alt.AltBreakdown{total} -> total) score) <$> asks altFsScore getAs :: MonadReader (Config k) m => () -> m (Maybe [[(Pilot, TaskPoints)]]) getAs () = do fmap (\Alt.AlternativePointing{score} -> (fmap . fmap . fmap) (\Alt.AirScoreBreakdown{total} -> total) score) <$> asks altAsScore getTaskPointsDiffStats :: DiffWay -> AppT k IO [Maybe (Double, Double)] getTaskPointsDiffStats DiffWayFtFs = do ys <- getFt () xs <- getFs () getDiffStats ys xs getTaskPointsDiffStats DiffWayFtAs = do ys <- getFt () xs <- getAs () getDiffStats ys xs getTaskPointsDiffStats DiffWayAsFs = do ys <- getAs () xs <- getFs () getDiffStats ys xs getDiffStats :: Maybe [[(Pilot, TaskPoints)]] -> Maybe [[(Pilot, TaskPoints)]] -> AppT k IO [Maybe (Double, Double)] getDiffStats ys xs = do case (ys, xs) of (Just ys', Just xs') -> do let taskDiffs = [ let xsMap = Map.fromList xsTask in [(Map.lookup pilot xsMap, p') | (pilot, p') <- ysTask] | ysTask <- ys' | xsTask <- xs' ] return $ (uncurry diffStats . unzip) <$> taskDiffs (Nothing, _) -> throwError errTaskPoints (_, Nothing) -> throwError errAltPoints diffStats :: [Maybe TaskPoints] -> [TaskPoints] -> Maybe (Double, Double) diffStats xs ys = -- NOTE: For some pilots, airScore is giving a null score. To do the stats, substitute zero for those scores . let xs' :: Maybe [TaskPoints] xs' = Just $ maybe (TaskPoints 0) id <$> xs in do xs'' <- xs' let diffs = zipWith (\(TaskPoints y) (TaskPoints x) -> y - x) ys xs'' (mean, variance) <- maybeMeanVariance $ V.fromList diffs return (mean, sqrt variance) maybeMeanVariance :: Vector Double -> Maybe (Double, Double) maybeMeanVariance xs = if null xs then Nothing else Just $ Stats.meanVariance xs
null
https://raw.githubusercontent.com/GlideAngle/flare-timing/27bd34c1943496987382091441a1c2516c169263/lang-haskell/app-serve/src/Serve/PointDiff.hs
haskell
NOTE: For some pilots, airScore is giving a null score. To do the stats,
module Serve.PointDiff (DiffWay(..), getTaskPointsDiffStats) where import Control.Monad.Reader (MonadReader(), asks) import qualified Data.Map.Strict as Map import qualified Statistics.Sample as Stats (meanVariance) import qualified Data.Vector as V (fromList) import Data.Vector (Vector) import Servant (throwError) import qualified Flight.Track.Point as Alt (AlternativePointing(..), AltBreakdown(..), AirScoreBreakdown(..)) import Flight.Track.Point (CompPointing(..), Breakdown(..)) import "flight-gap-math" Flight.Score (TaskPoints(..)) import Flight.Comp (Pilot(..)) import Serve.Config (AppT(..), Config(pointing, altFsScore, altAsScore)) import Serve.Error (errTaskPoints, errAltPoints) data DiffWay = DiffWayFtFs | DiffWayFtAs | DiffWayAsFs getFt :: MonadReader (Config k) m => () -> m (Maybe [[(Pilot, TaskPoints)]]) getFt () = do fmap (\CompPointing{score} -> (fmap . fmap . fmap) (\Breakdown{total} -> total) score) <$> asks pointing getFs :: MonadReader (Config k) m => () -> m (Maybe [[(Pilot, TaskPoints)]]) getFs () = do fmap (\Alt.AlternativePointing{score} -> (fmap . fmap . fmap) (\Alt.AltBreakdown{total} -> total) score) <$> asks altFsScore getAs :: MonadReader (Config k) m => () -> m (Maybe [[(Pilot, TaskPoints)]]) getAs () = do fmap (\Alt.AlternativePointing{score} -> (fmap . fmap . fmap) (\Alt.AirScoreBreakdown{total} -> total) score) <$> asks altAsScore getTaskPointsDiffStats :: DiffWay -> AppT k IO [Maybe (Double, Double)] getTaskPointsDiffStats DiffWayFtFs = do ys <- getFt () xs <- getFs () getDiffStats ys xs getTaskPointsDiffStats DiffWayFtAs = do ys <- getFt () xs <- getAs () getDiffStats ys xs getTaskPointsDiffStats DiffWayAsFs = do ys <- getAs () xs <- getFs () getDiffStats ys xs getDiffStats :: Maybe [[(Pilot, TaskPoints)]] -> Maybe [[(Pilot, TaskPoints)]] -> AppT k IO [Maybe (Double, Double)] getDiffStats ys xs = do case (ys, xs) of (Just ys', Just xs') -> do let taskDiffs = [ let xsMap = Map.fromList xsTask in [(Map.lookup pilot xsMap, p') | (pilot, p') <- ysTask] | ysTask <- ys' | xsTask <- xs' ] return $ (uncurry diffStats . unzip) <$> taskDiffs (Nothing, _) -> throwError errTaskPoints (_, Nothing) -> throwError errAltPoints diffStats :: [Maybe TaskPoints] -> [TaskPoints] -> Maybe (Double, Double) diffStats xs ys = substitute zero for those scores . let xs' :: Maybe [TaskPoints] xs' = Just $ maybe (TaskPoints 0) id <$> xs in do xs'' <- xs' let diffs = zipWith (\(TaskPoints y) (TaskPoints x) -> y - x) ys xs'' (mean, variance) <- maybeMeanVariance $ V.fromList diffs return (mean, sqrt variance) maybeMeanVariance :: Vector Double -> Maybe (Double, Double) maybeMeanVariance xs = if null xs then Nothing else Just $ Stats.meanVariance xs
ecfdd5eab1a84e26528021fbe7a11e2292110653a6cc5025b07f2ae0d94adb75
stumpwm/stumpwm-contrib
test.lisp
(require :desktop-entry) (require :fiveam) (in-package #:desktop-entry) (defconstant *desktop-entry-pathnames* '(#P"google-chrome.desktop" #P"emacs.desktop" #P"xterm.desktop" #P"i3.desktop" #P"libfm-pref-apps.desktop" #P"firefox.desktop")) (defconstant *true-value-plist* '((:name "Google Chrome" :entry-type "Application" :exec "/usr/bin/google-chrome-stable %U" :path nil :categories ("Network" "WebBrowser") :no-display nil :only-show-in nil :terminal nil) (:name "GNU Emacs" :entry-type "Application" :exec "/usr/bin/emacs %F" :path nil :categories ("Development" "TextEditor") :no-display nil :only-show-in nil :terminal nil) (:name "XTerm" :entry-type "Application" :exec "xterm" :path "/usr/local/bin" :categories ("System" "TerminalEmulator") :no-display nil :only-show-in nil :terminal t) (:name "i3" :entry-type "Application" :exec "i3" :path nil :categories nil :no-display t :only-show-in nil :terminal nil) (:name "Preferred Applications" :entry-type "Application" :exec "libfm-pref-apps" :path nil :categories ("Settings" "DesktopSettings" "X-LXDE-Settings" "GTK") :no-display nil :only-show-in ("LXDE") :terminal nil) (:name "Mozilla Firefox" :entry-type "Application" :exec "firefox %u" :path nil :categories ("Network" "WebBrowser") :no-display nil :only-show-in nil :terminal nil))) (defconstant *true-value-entry* (loop for item in *true-value-plist* collect (make-desktop-entry item))) (block test-desktop-entry (fiveam:def-suite test-desktop-entry-suite) (fiveam:in-suite test-desktop-entry-suite) (fiveam:test init-desktop-entry (fiveam:is (equalp (load-desktop-file "google-chrome.desktop") (first *true-value-plist*))) (loop for index from 0 below (length *desktop-entry-pathnames*) do (fiveam:is (equalp (load-desktop-file (nth index *desktop-entry-pathnames*)) (nth index *true-value-plist*)))) (loop for index from 0 below (length *desktop-entry-pathnames*) do (fiveam:is (desktop-entry-equal (make-desktop-entry (nth index *desktop-entry-pathnames*)) (nth index *true-value-entry*))))) (fiveam:test test-add-to-entry-list-1 (let* ((entry-list nil) (entry-list (add-to-entry-list entry-list (make-desktop-entry #P"google-chrome.desktop"))) (entry-list-2 (add-to-entry-list entry-list (make-desktop-entry #P"emacs.desktop"))) (entry-list-3 (add-to-entry-list entry-list-2 (make-desktop-entry #P"google-chrome.desktop")))) (fiveam:is (and (= 1 (length entry-list)) (eq 'desktop-entry (type-of (first entry-list))) (desktop-entry-equal (first *true-value-entry*) (first entry-list)))) (fiveam:is (and (= 2 (length entry-list-2)) (desktop-entry-equal (second *true-value-entry*) (second entry-list-2)))) (fiveam:is (= 2 (length entry-list-3))))) (fiveam:test test-add-to-entry-list-2 (let ((entry-list nil)) (loop for index from 0 below (length *desktop-entry-pathnames*) do (setf entry-list (add-to-entry-list entry-list (nth index *desktop-entry-pathnames*))) (fiveam:is (= (+ index 1) (length entry-list))) (fiveam:is (desktop-entry-equal (nth index entry-list) (nth index *true-value-entry*))) do (setf entry-list (add-to-entry-list entry-list (make-desktop-entry (nth index *desktop-entry-pathnames*)))) (fiveam:is (= (+ index 1) (length entry-list))) (fiveam:is (desktop-entry-equal (nth index entry-list) (nth index *true-value-entry*)))))) (fiveam:test test-add-category (let ((entry (make-desktop-entry (first *desktop-entry-pathnames*)))) (fiveam:is (equal '("Network" "WebBrowser") (categories entry))) (add-category entry "Test") (fiveam:is (equal '("Network" "WebBrowser" "Test") (categories entry))) (add-category entry "Test") (fiveam:is (equal '("Network" "WebBrowser" "Test") (categories entry))) (add-category entry "Network") (fiveam:is (equal '("Network" "WebBrowser" "Test") (categories entry))))) (fiveam:def-suite test-entry-list-suite) (fiveam:in-suite test-entry-list-suite) (fiveam:test test-find-categories (fiveam:is (equal '("Network" "WebBrowser" "Development" "TextEditor" "System" "TerminalEmulator" "Settings" "DesktopSettings" "X-LXDE-Settings" "GTK") (find-categories *true-value-entry*))) (fiveam:is (equal '("Network" "WebBrowser" "Development" "TextEditor" "System" "TerminalEmulator") (find-categories *true-value-entry* :modify #'(lambda (entry) (if (only-show-in entry) nil (categories entry))))))) (fiveam:test test-entry-in-categories-p (let ((entry-1 (first *true-value-entry*)) (entry-2 (fifth *true-value-entry*))) (fiveam:is (entry-in-categories-p entry-1 '("Network"))) (fiveam:is (not (entry-in-categories-p entry-1 '("Test")))) (fiveam:is (not (entry-in-categories-p entry-1 '("Network" "Test")))) (fiveam:is (entry-in-categories-p entry-1 '("Network" "WebBrowser"))) (fiveam:is (entry-in-categories-p entry-2 '("Settings" "DesktopSettings" "GTK"))) (fiveam:is (not (entry-in-categories-p entry-2 '("Settings" "DesktopSettings" "GTK" "Test")))))) (fiveam:test test-find-entries (fiveam:is (not (find-entries *true-value-entry*))) (fiveam:is (= 2 (length (find-entries *true-value-entry* :test #'(lambda (entry) (entry-in-categories-p entry '("Network"))))))) (fiveam:is (every #'(lambda (a b) (desktop-entry-equal a b)) (find-entries *true-value-entry* :test #'(lambda (entry) (entry-in-categories-p entry '("Network")))) (list (first *true-value-entry*) (nth 5 *true-value-entry*))))) (fiveam:test test-group-entries (flet ((compare-groups (a b) (fiveam:is (= (length a) (length b))) (every #'(lambda (group1 group2) (fiveam:is (string= (car group1) (car group2))) (fiveam:is (= (length (cdr group1)) (length (cdr group2)))) (every #'(lambda (x y) (fiveam:is (desktop-entry-equal x y))) (cdr group1) (cdr group2))) a b))) (compare-groups (list (list "Network" (first *true-value-entry*))) (list (list "Network" (first *true-value-entry*)))) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) (cons nil (loop for index in '(1 2 3 4) collect (nth index *true-value-entry*)))) (group-entries *true-value-entry* :categories '("Network" "WebBrowser"))) (compare-groups (list (list "DesktopSettings" (fifth *true-value-entry*)) (list "Development" (second *true-value-entry*)) (cons nil (loop for index in '(0 2 3 5) collect (nth index *true-value-entry*)))) (group-entries *true-value-entry* :categories '("DesktopSettings" nil "Development"))) (compare-groups (list (list nil (first *true-value-entry*) (nth 5 *true-value-entry*))) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)))) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) nil) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count nil)) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) nil) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count 0)) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) nil) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count -1)) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) nil) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count 1)) (compare-groups (list (list nil (first *true-value-entry*) (nth 5 *true-value-entry*))) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count 3)))) (fiveam:run! 'test-desktop-entry-suite) (fiveam:run! 'test-entry-list-suite) ;; (init-entry-list) ( format t " menu ~S~% " ( build - menu ' ( " AudioVideo " ) : min - entry - in - category 3 ) ) ( format t " menu ~S~% " ( build - menu ' ( " Office " ) : min - entry - in - category 5 ) ) (return-from test-desktop-entry) )
null
https://raw.githubusercontent.com/stumpwm/stumpwm-contrib/a7dc1c663d04e6c73a4772c8a6ad56a34381096a/util/desktop-entry/test/test.lisp
lisp
(init-entry-list)
(require :desktop-entry) (require :fiveam) (in-package #:desktop-entry) (defconstant *desktop-entry-pathnames* '(#P"google-chrome.desktop" #P"emacs.desktop" #P"xterm.desktop" #P"i3.desktop" #P"libfm-pref-apps.desktop" #P"firefox.desktop")) (defconstant *true-value-plist* '((:name "Google Chrome" :entry-type "Application" :exec "/usr/bin/google-chrome-stable %U" :path nil :categories ("Network" "WebBrowser") :no-display nil :only-show-in nil :terminal nil) (:name "GNU Emacs" :entry-type "Application" :exec "/usr/bin/emacs %F" :path nil :categories ("Development" "TextEditor") :no-display nil :only-show-in nil :terminal nil) (:name "XTerm" :entry-type "Application" :exec "xterm" :path "/usr/local/bin" :categories ("System" "TerminalEmulator") :no-display nil :only-show-in nil :terminal t) (:name "i3" :entry-type "Application" :exec "i3" :path nil :categories nil :no-display t :only-show-in nil :terminal nil) (:name "Preferred Applications" :entry-type "Application" :exec "libfm-pref-apps" :path nil :categories ("Settings" "DesktopSettings" "X-LXDE-Settings" "GTK") :no-display nil :only-show-in ("LXDE") :terminal nil) (:name "Mozilla Firefox" :entry-type "Application" :exec "firefox %u" :path nil :categories ("Network" "WebBrowser") :no-display nil :only-show-in nil :terminal nil))) (defconstant *true-value-entry* (loop for item in *true-value-plist* collect (make-desktop-entry item))) (block test-desktop-entry (fiveam:def-suite test-desktop-entry-suite) (fiveam:in-suite test-desktop-entry-suite) (fiveam:test init-desktop-entry (fiveam:is (equalp (load-desktop-file "google-chrome.desktop") (first *true-value-plist*))) (loop for index from 0 below (length *desktop-entry-pathnames*) do (fiveam:is (equalp (load-desktop-file (nth index *desktop-entry-pathnames*)) (nth index *true-value-plist*)))) (loop for index from 0 below (length *desktop-entry-pathnames*) do (fiveam:is (desktop-entry-equal (make-desktop-entry (nth index *desktop-entry-pathnames*)) (nth index *true-value-entry*))))) (fiveam:test test-add-to-entry-list-1 (let* ((entry-list nil) (entry-list (add-to-entry-list entry-list (make-desktop-entry #P"google-chrome.desktop"))) (entry-list-2 (add-to-entry-list entry-list (make-desktop-entry #P"emacs.desktop"))) (entry-list-3 (add-to-entry-list entry-list-2 (make-desktop-entry #P"google-chrome.desktop")))) (fiveam:is (and (= 1 (length entry-list)) (eq 'desktop-entry (type-of (first entry-list))) (desktop-entry-equal (first *true-value-entry*) (first entry-list)))) (fiveam:is (and (= 2 (length entry-list-2)) (desktop-entry-equal (second *true-value-entry*) (second entry-list-2)))) (fiveam:is (= 2 (length entry-list-3))))) (fiveam:test test-add-to-entry-list-2 (let ((entry-list nil)) (loop for index from 0 below (length *desktop-entry-pathnames*) do (setf entry-list (add-to-entry-list entry-list (nth index *desktop-entry-pathnames*))) (fiveam:is (= (+ index 1) (length entry-list))) (fiveam:is (desktop-entry-equal (nth index entry-list) (nth index *true-value-entry*))) do (setf entry-list (add-to-entry-list entry-list (make-desktop-entry (nth index *desktop-entry-pathnames*)))) (fiveam:is (= (+ index 1) (length entry-list))) (fiveam:is (desktop-entry-equal (nth index entry-list) (nth index *true-value-entry*)))))) (fiveam:test test-add-category (let ((entry (make-desktop-entry (first *desktop-entry-pathnames*)))) (fiveam:is (equal '("Network" "WebBrowser") (categories entry))) (add-category entry "Test") (fiveam:is (equal '("Network" "WebBrowser" "Test") (categories entry))) (add-category entry "Test") (fiveam:is (equal '("Network" "WebBrowser" "Test") (categories entry))) (add-category entry "Network") (fiveam:is (equal '("Network" "WebBrowser" "Test") (categories entry))))) (fiveam:def-suite test-entry-list-suite) (fiveam:in-suite test-entry-list-suite) (fiveam:test test-find-categories (fiveam:is (equal '("Network" "WebBrowser" "Development" "TextEditor" "System" "TerminalEmulator" "Settings" "DesktopSettings" "X-LXDE-Settings" "GTK") (find-categories *true-value-entry*))) (fiveam:is (equal '("Network" "WebBrowser" "Development" "TextEditor" "System" "TerminalEmulator") (find-categories *true-value-entry* :modify #'(lambda (entry) (if (only-show-in entry) nil (categories entry))))))) (fiveam:test test-entry-in-categories-p (let ((entry-1 (first *true-value-entry*)) (entry-2 (fifth *true-value-entry*))) (fiveam:is (entry-in-categories-p entry-1 '("Network"))) (fiveam:is (not (entry-in-categories-p entry-1 '("Test")))) (fiveam:is (not (entry-in-categories-p entry-1 '("Network" "Test")))) (fiveam:is (entry-in-categories-p entry-1 '("Network" "WebBrowser"))) (fiveam:is (entry-in-categories-p entry-2 '("Settings" "DesktopSettings" "GTK"))) (fiveam:is (not (entry-in-categories-p entry-2 '("Settings" "DesktopSettings" "GTK" "Test")))))) (fiveam:test test-find-entries (fiveam:is (not (find-entries *true-value-entry*))) (fiveam:is (= 2 (length (find-entries *true-value-entry* :test #'(lambda (entry) (entry-in-categories-p entry '("Network"))))))) (fiveam:is (every #'(lambda (a b) (desktop-entry-equal a b)) (find-entries *true-value-entry* :test #'(lambda (entry) (entry-in-categories-p entry '("Network")))) (list (first *true-value-entry*) (nth 5 *true-value-entry*))))) (fiveam:test test-group-entries (flet ((compare-groups (a b) (fiveam:is (= (length a) (length b))) (every #'(lambda (group1 group2) (fiveam:is (string= (car group1) (car group2))) (fiveam:is (= (length (cdr group1)) (length (cdr group2)))) (every #'(lambda (x y) (fiveam:is (desktop-entry-equal x y))) (cdr group1) (cdr group2))) a b))) (compare-groups (list (list "Network" (first *true-value-entry*))) (list (list "Network" (first *true-value-entry*)))) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) (cons nil (loop for index in '(1 2 3 4) collect (nth index *true-value-entry*)))) (group-entries *true-value-entry* :categories '("Network" "WebBrowser"))) (compare-groups (list (list "DesktopSettings" (fifth *true-value-entry*)) (list "Development" (second *true-value-entry*)) (cons nil (loop for index in '(0 2 3 5) collect (nth index *true-value-entry*)))) (group-entries *true-value-entry* :categories '("DesktopSettings" nil "Development"))) (compare-groups (list (list nil (first *true-value-entry*) (nth 5 *true-value-entry*))) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)))) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) nil) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count nil)) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) nil) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count 0)) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) nil) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count -1)) (compare-groups (list (list "Network" (first *true-value-entry*) (nth 5 *true-value-entry*)) (list "WebBrowser" (first *true-value-entry*) (nth 5 *true-value-entry*)) nil) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count 1)) (compare-groups (list (list nil (first *true-value-entry*) (nth 5 *true-value-entry*))) (group-entries (list (first *true-value-entry*) (nth 5 *true-value-entry*)) :categories '("Network" "WebBrowser") :min-count 3)))) (fiveam:run! 'test-desktop-entry-suite) (fiveam:run! 'test-entry-list-suite) ( format t " menu ~S~% " ( build - menu ' ( " AudioVideo " ) : min - entry - in - category 3 ) ) ( format t " menu ~S~% " ( build - menu ' ( " Office " ) : min - entry - in - category 5 ) ) (return-from test-desktop-entry) )
3e32cdfb14cd8f31681adb667ef30db0710da1e931a56189cc2a9a096864debf
eamsden/pushbasedFRP
SignalVectors.hs
# LANGUAGE KindSignatures , EmptyDataDecls , GADTs , TypeFamilies # -- | This module defines /signal vectors/, a type-level representation -- of the input and output structure of signal functions, and value -- representations typed with signal vectors for use in implementing -- signal functions. module FRP.TimeFlies.SignalVectors ( -- * Type Representation of Signal Vectors -- | A signal vector is a type which describes -- the structure of the input or output of a signal -- function. Signal vectors do not have value members, -- but by representing signal functions and other implementation types using GADTs , we can include signal vectors in the types -- of signal functions and their implementations. SVEmpty(), SVSignal(), SVEvent(), SVAppend(), -- * Representations of Signal Vectors -- | Signal vectors abstract away from the representation, -- permitting different structures to be used to reify -- the vector depending on the need. -- ** Event Representation -- | This type and associated functions represent occurrences of events in -- a signal vector, and allow these representations to be constructed, -- deconstructed, and queried SVOccurrence(), occurrence, occLeft, occRight, splitOccurrences, occurrenceListToMaybe, fromOccurrence, chooseOccurrence, -- ** Signal Representations -- | These types give full and partial representations of the signals in a vector . " is intended for initializing -- signal functions, and storing signal state where necessary. An " SVDelta " is used to pass changes in a signal between signal functions . SVSample(), sample, sampleEvt, sampleNothing, combineSamples, splitSample, sampleValue, sampleDelta, SVDelta(), updateSample, delta, deltaNothing, combineDeltas, splitDelta, deltaValue, -- ** Handler vectors | An " SVHandler " is a collection of functions from the leaf types -- of a signal vector to a type specified in the handler. This is used -- for specifying output handlers in evaluation SVHandler(), emptyHandler, eventHandler, signalHandler, combineHandlers, applyHandlerOccurrence, applyHandlerDelta, -- * Types for describing evaluation inputs -- | These types are used to describe the inputs to a signal function -- within the evaluation interface. SVRoutable(..), SVEventInput(), svOcc, inputToOccurrence, SVSignalUpdate(), svSig, updateDelta ) where -- | Empty signal vector type data SVEmpty -- | Singleton signal signal vector type data SVSignal a -- | Singleton event signal vector type data SVEvent a | Combine two signal vector types data SVAppend svLeft svRight -- | Event representation data SVOccurrence sv where SVOccurrence :: a -> SVOccurrence (SVEvent a) SVOccLeft :: SVOccurrence svLeft -> SVOccurrence (SVAppend svLeft svRight) SVOccRight :: SVOccurrence svRight -> SVOccurrence (SVAppend svLeft svRight) -- | Construct an occurrence occurrence :: a -> SVOccurrence (SVEvent a) occurrence = SVOccurrence -- | Send an occurrence left occLeft :: SVOccurrence svLeft -> SVOccurrence (SVAppend svLeft svRight) occLeft = SVOccLeft -- | Send an occurrence right occRight :: SVOccurrence svRight -> SVOccurrence (SVAppend svLeft svRight) occRight = SVOccRight -- | Split a list of occurrences into lists of left and right splitOccurrences :: [SVOccurrence (SVAppend svLeft svRight)] -> ([SVOccurrence svLeft], [SVOccurrence svRight]) splitOccurrences = foldl (\(leftList, rightList) occurrence -> case occurrence of SVOccLeft occurrence' -> (occurrence':leftList, rightList) SVOccRight occurrence' -> (leftList, occurrence':rightList)) ([], []) | Give back the value of the first occurrence , or nothing if the occurrence list is empty occurrenceListToMaybe :: [SVOccurrence (SVEvent a)] -> Maybe a occurrenceListToMaybe ((SVOccurrence x):_) = Just x occurrenceListToMaybe _ = Nothing -- | The value of the occurrence fromOccurrence :: SVOccurrence (SVEvent a) -> a fromOccurrence (SVOccurrence x) = x -- | Allow case matching on an occurrence chooseOccurrence :: SVOccurrence (SVAppend svLeft svRight) -> Either (SVOccurrence svLeft) (SVOccurrence svRight) chooseOccurrence (SVOccLeft occLeft) = Left occLeft chooseOccurrence (SVOccRight occRight) = Right occRight -- | Full signal sample representation data SVSample sv where SVSample :: a -> SVSample (SVSignal a) SVSampleEvent :: SVSample (SVEvent a) SVSampleEmpty :: SVSample SVEmpty SVSampleBoth :: SVSample svLeft -> SVSample svRight -> SVSample (SVAppend svLeft svRight) -- | Construct a signal sample sample :: a -> SVSample (SVSignal a) sample = SVSample -- | An event placeholder in a sample sampleEvt :: SVSample (SVEvent a) sampleEvt = SVSampleEvent -- | An empty placeholder in a sample sampleNothing :: SVSample SVEmpty sampleNothing = SVSampleEmpty -- | Combine samples combineSamples :: SVSample svLeft -> SVSample svRight -> SVSample (SVAppend svLeft svRight) combineSamples = SVSampleBoth -- | Split a sample splitSample :: SVSample (SVAppend svLeft svRight) -> (SVSample svLeft, SVSample svRight) splitSample (SVSampleBoth sampleLeft sampleRight) = (sampleLeft, sampleRight) -- | The value of a sample sampleValue :: SVSample (SVSignal a) -> a sampleValue (SVSample x) = x -- | Create a delta from a sample sampleDelta :: SVSample sv -> SVDelta sv sampleDelta SVSampleEmpty = SVDeltaNothing sampleDelta SVSampleEvent = SVDeltaNothing sampleDelta (SVSample x) = SVDeltaSignal x sampleDelta (SVSampleBoth sampleLeft sampleRight) = combineDeltas (sampleDelta sampleLeft) (sampleDelta sampleRight) -- | Signal delta representation data SVDelta sv where SVDeltaSignal :: a -> SVDelta (SVSignal a) SVDeltaNothing :: SVDelta sv SVDeltaBoth :: SVDelta svLeft -> SVDelta svRight -> SVDelta (SVAppend svLeft svRight) -- | Use a signal delta to update a signal sample updateSample :: SVSample sv -> SVDelta sv -> SVSample sv updateSample sample SVDeltaNothing = sample updateSample (SVSampleBoth sampleLeft sampleRight) (SVDeltaBoth deltaLeft deltaRight) = SVSampleBoth (updateSample sampleLeft deltaLeft) (updateSample sampleRight deltaRight) updateSample _ (SVDeltaSignal x) = SVSample x -- | An empty signal delta deltaNothing :: SVDelta sv deltaNothing = SVDeltaNothing -- | A signal delta delta :: a -> SVDelta (SVSignal a) delta = SVDeltaSignal -- | Combine signal deltas combineDeltas :: SVDelta svLeft -> SVDelta svRight -> SVDelta (SVAppend svLeft svRight) combineDeltas SVDeltaNothing SVDeltaNothing = SVDeltaNothing combineDeltas deltaLeft deltaRight = SVDeltaBoth deltaLeft deltaRight -- | Split a signal delta splitDelta :: SVDelta (SVAppend svLeft svRight) -> (SVDelta svLeft, SVDelta svRight) splitDelta SVDeltaNothing = (SVDeltaNothing, SVDeltaNothing) splitDelta (SVDeltaBoth deltaLeft deltaRight) = (deltaLeft, deltaRight) -- | The value of a signal delta deltaValue :: SVDelta (SVSignal a) -> Maybe a deltaValue SVDeltaNothing = Nothing deltaValue (SVDeltaSignal x) = Just x -- | A vector of handlers data SVHandler out sv where SVHandlerEmpty :: SVHandler out SVEmpty SVHandlerSignal :: (a -> out) -> SVHandler out (SVSignal a) SVHandlerEvent :: (a -> out) -> SVHandler out (SVEvent a) SVHandlerBoth :: SVHandler out svLeft -> SVHandler out svRight -> SVHandler out (SVAppend svLeft svRight) -- | A handler for an empty vector emptyHandler :: SVHandler out SVEmpty emptyHandler = SVHandlerEmpty -- | A handler for a signal sample signalHandler :: (a -> out) -> SVHandler out (SVSignal a) signalHandler = SVHandlerSignal -- | A handler for event occurrences eventHandler :: (a -> out) -> SVHandler out (SVEvent a) eventHandler = SVHandlerEvent -- | Combine handlers combineHandlers :: SVHandler out svLeft -> SVHandler out svRight -> SVHandler out (SVAppend svLeft svRight) combineHandlers = SVHandlerBoth -- | Apply a handler to an event occurrence applyHandlerOccurrence :: SVHandler out sv -> SVOccurrence sv -> out applyHandlerOccurrence (SVHandlerEvent f) (SVOccurrence x) = f x applyHandlerOccurrence (SVHandlerBoth handlerLeft _) (SVOccLeft occLeft) = applyHandlerOccurrence handlerLeft occLeft applyHandlerOccurrence (SVHandlerBoth _ handlerRight) (SVOccRight occRight) = applyHandlerOccurrence handlerRight occRight -- | Apply a handler to a signal delta applyHandlerDelta :: SVHandler out sv -> SVDelta sv -> [out] applyHandlerDelta _ SVDeltaNothing = [] applyHandlerDelta (SVHandlerSignal f) (SVDeltaSignal x) = [f x] applyHandlerDelta (SVHandlerBoth handlerLeft handlerRight) (SVDeltaBoth signalLeft signalRight) = applyHandlerDelta handlerLeft signalLeft ++ applyHandlerDelta handlerRight signalRight -- | Inputs which may be sent left or right class SVRoutable (r :: * -> *) where svLeft :: r svLeft -> r (SVAppend svLeft svRight) svRight :: r svRight -> r (SVAppend svLeft svRight) -- | An event input data SVEventInput sv where SVEOcc :: a -> SVEventInput (SVEvent a) SVELeft :: SVEventInput svLeft -> SVEventInput (SVAppend svLeft svRight) SVERight :: SVEventInput svRight -> SVEventInput (SVAppend svLeft svRight) instance SVRoutable SVEventInput where svLeft = SVELeft svRight = SVERight -- | Construct an event input svOcc :: a -> SVEventInput (SVEvent a) svOcc = SVEOcc -- | Convert an event input to an event occurrence inputToOccurrence :: SVEventInput sv -> SVOccurrence sv inputToOccurrence (SVEOcc x) = SVOccurrence x inputToOccurrence (SVELeft inp) = SVOccLeft (inputToOccurrence inp) inputToOccurrence (SVERight inp) = SVOccRight (inputToOccurrence inp) -- | A signal update data SVSignalUpdate sv where SVUSig :: a -> SVSignalUpdate (SVSignal a) SVULeft :: SVSignalUpdate svLeft -> SVSignalUpdate (SVAppend svLeft svRight) SVURight :: SVSignalUpdate svRight -> SVSignalUpdate (SVAppend svLeft svRight) instance SVRoutable SVSignalUpdate where svLeft = SVULeft svRight = SVURight -- | Construct a signal update svSig :: a -> SVSignalUpdate (SVSignal a) svSig = SVUSig -- Update a signal delta with a signal update updateDelta :: SVDelta sv -> SVSignalUpdate sv -> SVDelta sv updateDelta _ (SVUSig x) = SVDeltaSignal x updateDelta (SVDeltaBoth deltaLeft deltaRight) (SVULeft update) = SVDeltaBoth (updateDelta deltaLeft update) deltaRight updateDelta (SVDeltaBoth deltaLeft deltaRight) (SVURight update) = SVDeltaBoth deltaLeft (updateDelta deltaRight update) updateDelta SVDeltaNothing (SVULeft update) = SVDeltaBoth (updateDelta SVDeltaNothing update) SVDeltaNothing updateDelta SVDeltaNothing (SVURight update) = SVDeltaBoth SVDeltaNothing (updateDelta SVDeltaNothing update)
null
https://raw.githubusercontent.com/eamsden/pushbasedFRP/1d6afd7aa2e45f44b9daa4a2265338747a6aa443/Code/time-flies/src/FRP/TimeFlies/SignalVectors.hs
haskell
| This module defines /signal vectors/, a type-level representation of the input and output structure of signal functions, and value representations typed with signal vectors for use in implementing signal functions. * Type Representation of Signal Vectors | A signal vector is a type which describes the structure of the input or output of a signal function. Signal vectors do not have value members, but by representing signal functions and other implementation of signal functions and their implementations. * Representations of Signal Vectors | Signal vectors abstract away from the representation, permitting different structures to be used to reify the vector depending on the need. ** Event Representation | This type and associated functions represent occurrences of events in a signal vector, and allow these representations to be constructed, deconstructed, and queried ** Signal Representations | These types give full and partial representations of the signal functions, and storing signal state where necessary. ** Handler vectors of a signal vector to a type specified in the handler. This is used for specifying output handlers in evaluation * Types for describing evaluation inputs | These types are used to describe the inputs to a signal function within the evaluation interface. | Empty signal vector type | Singleton signal signal vector type | Singleton event signal vector type | Event representation | Construct an occurrence | Send an occurrence left | Send an occurrence right | Split a list of occurrences into lists of left and right | The value of the occurrence | Allow case matching on an occurrence | Full signal sample representation | Construct a signal sample | An event placeholder in a sample | An empty placeholder in a sample | Combine samples | Split a sample | The value of a sample | Create a delta from a sample | Signal delta representation | Use a signal delta to update a signal sample | An empty signal delta | A signal delta | Combine signal deltas | Split a signal delta | The value of a signal delta | A vector of handlers | A handler for an empty vector | A handler for a signal sample | A handler for event occurrences | Combine handlers | Apply a handler to an event occurrence | Apply a handler to a signal delta | Inputs which may be sent left or right | An event input | Construct an event input | Convert an event input to an event occurrence | A signal update | Construct a signal update Update a signal delta with a signal update
# LANGUAGE KindSignatures , EmptyDataDecls , GADTs , TypeFamilies # module FRP.TimeFlies.SignalVectors ( types using GADTs , we can include signal vectors in the types SVEmpty(), SVSignal(), SVEvent(), SVAppend(), SVOccurrence(), occurrence, occLeft, occRight, splitOccurrences, occurrenceListToMaybe, fromOccurrence, chooseOccurrence, signals in a vector . " is intended for initializing An " SVDelta " is used to pass changes in a signal between signal functions . SVSample(), sample, sampleEvt, sampleNothing, combineSamples, splitSample, sampleValue, sampleDelta, SVDelta(), updateSample, delta, deltaNothing, combineDeltas, splitDelta, deltaValue, | An " SVHandler " is a collection of functions from the leaf types SVHandler(), emptyHandler, eventHandler, signalHandler, combineHandlers, applyHandlerOccurrence, applyHandlerDelta, SVRoutable(..), SVEventInput(), svOcc, inputToOccurrence, SVSignalUpdate(), svSig, updateDelta ) where data SVEmpty data SVSignal a data SVEvent a | Combine two signal vector types data SVAppend svLeft svRight data SVOccurrence sv where SVOccurrence :: a -> SVOccurrence (SVEvent a) SVOccLeft :: SVOccurrence svLeft -> SVOccurrence (SVAppend svLeft svRight) SVOccRight :: SVOccurrence svRight -> SVOccurrence (SVAppend svLeft svRight) occurrence :: a -> SVOccurrence (SVEvent a) occurrence = SVOccurrence occLeft :: SVOccurrence svLeft -> SVOccurrence (SVAppend svLeft svRight) occLeft = SVOccLeft occRight :: SVOccurrence svRight -> SVOccurrence (SVAppend svLeft svRight) occRight = SVOccRight splitOccurrences :: [SVOccurrence (SVAppend svLeft svRight)] -> ([SVOccurrence svLeft], [SVOccurrence svRight]) splitOccurrences = foldl (\(leftList, rightList) occurrence -> case occurrence of SVOccLeft occurrence' -> (occurrence':leftList, rightList) SVOccRight occurrence' -> (leftList, occurrence':rightList)) ([], []) | Give back the value of the first occurrence , or nothing if the occurrence list is empty occurrenceListToMaybe :: [SVOccurrence (SVEvent a)] -> Maybe a occurrenceListToMaybe ((SVOccurrence x):_) = Just x occurrenceListToMaybe _ = Nothing fromOccurrence :: SVOccurrence (SVEvent a) -> a fromOccurrence (SVOccurrence x) = x chooseOccurrence :: SVOccurrence (SVAppend svLeft svRight) -> Either (SVOccurrence svLeft) (SVOccurrence svRight) chooseOccurrence (SVOccLeft occLeft) = Left occLeft chooseOccurrence (SVOccRight occRight) = Right occRight data SVSample sv where SVSample :: a -> SVSample (SVSignal a) SVSampleEvent :: SVSample (SVEvent a) SVSampleEmpty :: SVSample SVEmpty SVSampleBoth :: SVSample svLeft -> SVSample svRight -> SVSample (SVAppend svLeft svRight) sample :: a -> SVSample (SVSignal a) sample = SVSample sampleEvt :: SVSample (SVEvent a) sampleEvt = SVSampleEvent sampleNothing :: SVSample SVEmpty sampleNothing = SVSampleEmpty combineSamples :: SVSample svLeft -> SVSample svRight -> SVSample (SVAppend svLeft svRight) combineSamples = SVSampleBoth splitSample :: SVSample (SVAppend svLeft svRight) -> (SVSample svLeft, SVSample svRight) splitSample (SVSampleBoth sampleLeft sampleRight) = (sampleLeft, sampleRight) sampleValue :: SVSample (SVSignal a) -> a sampleValue (SVSample x) = x sampleDelta :: SVSample sv -> SVDelta sv sampleDelta SVSampleEmpty = SVDeltaNothing sampleDelta SVSampleEvent = SVDeltaNothing sampleDelta (SVSample x) = SVDeltaSignal x sampleDelta (SVSampleBoth sampleLeft sampleRight) = combineDeltas (sampleDelta sampleLeft) (sampleDelta sampleRight) data SVDelta sv where SVDeltaSignal :: a -> SVDelta (SVSignal a) SVDeltaNothing :: SVDelta sv SVDeltaBoth :: SVDelta svLeft -> SVDelta svRight -> SVDelta (SVAppend svLeft svRight) updateSample :: SVSample sv -> SVDelta sv -> SVSample sv updateSample sample SVDeltaNothing = sample updateSample (SVSampleBoth sampleLeft sampleRight) (SVDeltaBoth deltaLeft deltaRight) = SVSampleBoth (updateSample sampleLeft deltaLeft) (updateSample sampleRight deltaRight) updateSample _ (SVDeltaSignal x) = SVSample x deltaNothing :: SVDelta sv deltaNothing = SVDeltaNothing delta :: a -> SVDelta (SVSignal a) delta = SVDeltaSignal combineDeltas :: SVDelta svLeft -> SVDelta svRight -> SVDelta (SVAppend svLeft svRight) combineDeltas SVDeltaNothing SVDeltaNothing = SVDeltaNothing combineDeltas deltaLeft deltaRight = SVDeltaBoth deltaLeft deltaRight splitDelta :: SVDelta (SVAppend svLeft svRight) -> (SVDelta svLeft, SVDelta svRight) splitDelta SVDeltaNothing = (SVDeltaNothing, SVDeltaNothing) splitDelta (SVDeltaBoth deltaLeft deltaRight) = (deltaLeft, deltaRight) deltaValue :: SVDelta (SVSignal a) -> Maybe a deltaValue SVDeltaNothing = Nothing deltaValue (SVDeltaSignal x) = Just x data SVHandler out sv where SVHandlerEmpty :: SVHandler out SVEmpty SVHandlerSignal :: (a -> out) -> SVHandler out (SVSignal a) SVHandlerEvent :: (a -> out) -> SVHandler out (SVEvent a) SVHandlerBoth :: SVHandler out svLeft -> SVHandler out svRight -> SVHandler out (SVAppend svLeft svRight) emptyHandler :: SVHandler out SVEmpty emptyHandler = SVHandlerEmpty signalHandler :: (a -> out) -> SVHandler out (SVSignal a) signalHandler = SVHandlerSignal eventHandler :: (a -> out) -> SVHandler out (SVEvent a) eventHandler = SVHandlerEvent combineHandlers :: SVHandler out svLeft -> SVHandler out svRight -> SVHandler out (SVAppend svLeft svRight) combineHandlers = SVHandlerBoth applyHandlerOccurrence :: SVHandler out sv -> SVOccurrence sv -> out applyHandlerOccurrence (SVHandlerEvent f) (SVOccurrence x) = f x applyHandlerOccurrence (SVHandlerBoth handlerLeft _) (SVOccLeft occLeft) = applyHandlerOccurrence handlerLeft occLeft applyHandlerOccurrence (SVHandlerBoth _ handlerRight) (SVOccRight occRight) = applyHandlerOccurrence handlerRight occRight applyHandlerDelta :: SVHandler out sv -> SVDelta sv -> [out] applyHandlerDelta _ SVDeltaNothing = [] applyHandlerDelta (SVHandlerSignal f) (SVDeltaSignal x) = [f x] applyHandlerDelta (SVHandlerBoth handlerLeft handlerRight) (SVDeltaBoth signalLeft signalRight) = applyHandlerDelta handlerLeft signalLeft ++ applyHandlerDelta handlerRight signalRight class SVRoutable (r :: * -> *) where svLeft :: r svLeft -> r (SVAppend svLeft svRight) svRight :: r svRight -> r (SVAppend svLeft svRight) data SVEventInput sv where SVEOcc :: a -> SVEventInput (SVEvent a) SVELeft :: SVEventInput svLeft -> SVEventInput (SVAppend svLeft svRight) SVERight :: SVEventInput svRight -> SVEventInput (SVAppend svLeft svRight) instance SVRoutable SVEventInput where svLeft = SVELeft svRight = SVERight svOcc :: a -> SVEventInput (SVEvent a) svOcc = SVEOcc inputToOccurrence :: SVEventInput sv -> SVOccurrence sv inputToOccurrence (SVEOcc x) = SVOccurrence x inputToOccurrence (SVELeft inp) = SVOccLeft (inputToOccurrence inp) inputToOccurrence (SVERight inp) = SVOccRight (inputToOccurrence inp) data SVSignalUpdate sv where SVUSig :: a -> SVSignalUpdate (SVSignal a) SVULeft :: SVSignalUpdate svLeft -> SVSignalUpdate (SVAppend svLeft svRight) SVURight :: SVSignalUpdate svRight -> SVSignalUpdate (SVAppend svLeft svRight) instance SVRoutable SVSignalUpdate where svLeft = SVULeft svRight = SVURight svSig :: a -> SVSignalUpdate (SVSignal a) svSig = SVUSig updateDelta :: SVDelta sv -> SVSignalUpdate sv -> SVDelta sv updateDelta _ (SVUSig x) = SVDeltaSignal x updateDelta (SVDeltaBoth deltaLeft deltaRight) (SVULeft update) = SVDeltaBoth (updateDelta deltaLeft update) deltaRight updateDelta (SVDeltaBoth deltaLeft deltaRight) (SVURight update) = SVDeltaBoth deltaLeft (updateDelta deltaRight update) updateDelta SVDeltaNothing (SVULeft update) = SVDeltaBoth (updateDelta SVDeltaNothing update) SVDeltaNothing updateDelta SVDeltaNothing (SVURight update) = SVDeltaBoth SVDeltaNothing (updateDelta SVDeltaNothing update)
98df866868d4024a5235c13f588b3ba2eef9f252268bc06eae38c47a81b371ba
input-output-hk/qeditas
blocktree.ml
Copyright ( c ) 2015 - 2016 The Qeditas developers Distributed under the MIT software license , see the accompanying file COPYING or -license.php . file COPYING or -license.php. *) open Big_int open Utils open Ser open Hashaux open Sha256 open Hash open Net open Db open Assets open Signat open Tx open Ctre open Block let checkpointsprivkeyk = ref None let checkpointspubkeyx = big_int_of_string "63717203732691002966627493523478395510925637964138185199101530429614494608215" let checkpointspubkeyy = big_int_of_string "14551538993109352432558649646564074001010059416911525032428212764782058901234" let checkpoints : (hashval,int64 * signat) Hashtbl.t = Hashtbl.create 1000;; let stxpool : (hashval,stx) Hashtbl.t = Hashtbl.create 1000;; let published_stx : (hashval,unit) Hashtbl.t = Hashtbl.create 1000;; let thytree : (hashval,Mathdata.ttree) Hashtbl.t = Hashtbl.create 1000;; let sigtree : (hashval,Mathdata.stree) Hashtbl.t = Hashtbl.create 1000;; * * It is n't clear if there are any circumstances when it is safe to say the header is not the header for a valid block . may be unused . * * type blocktree = BlocktreeNode of blocktree option * hashval list ref * hashval option * hashval option * hashval option * hashval * targetinfo * int64 * big_int * int64 * validationstatus ref * bool ref * (hashval * blocktree) list ref let genesisblocktreenode = ref (BlocktreeNode(None,ref [],None,None,None,!genesisledgerroot,(!genesiscurrentstakemod,!genesisfuturestakemod,!genesistarget),!Config.genesistimestamp,zero_big_int,1L,ref ValidBlock,ref false,ref []));; let lastcheckpointnode = ref !genesisblocktreenode;; let bestnode = ref !genesisblocktreenode;; let node_recent_stakers n = let BlocktreeNode(_,rs,_,_,_,_,_,_,_,_,_,_,_) = n in !rs let node_prevblockhash n = let BlocktreeNode(_,_,pbh,_,_,_,_,_,_,_,_,_,_) = n in pbh let node_theoryroot n = let BlocktreeNode(_,_,_,tr,_,_,_,_,_,_,_,_,_) = n in tr let node_signaroot n = let BlocktreeNode(_,_,_,_,sr,_,_,_,_,_,_,_,_) = n in sr let node_ledgerroot n = let BlocktreeNode(_,_,_,_,_,lr,_,_,_,_,_,_,_) = n in lr let node_targetinfo n = let BlocktreeNode(_,_,_,_,_,_,ti,_,_,_,_,_,_) = n in ti let node_timestamp n = let BlocktreeNode(_,_,_,_,_,_,_,tm,_,_,_,_,_) = n in tm let node_cumulstk n = let BlocktreeNode(_,_,_,_,_,_,_,_,cs,_,_,_,_) = n in cs let node_blockheight n = let BlocktreeNode(_,_,_,_,_,_,_,_,_,blkh,_,_,_) = n in blkh let node_validationstatus n = let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,vs,_,_) = n in !vs let node_children_ref n = let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,_,_,chr) = n in chr let print_best_node () = let BlocktreeNode(_,_,pbh,_,_,_,_,_,_,_,_,_,_) = !bestnode in match pbh with | Some(h) -> Printf.fprintf !log "bestnode pbh %s\n" (hashval_hexstring h); flush !log | None -> Printf.fprintf !log "bestnode pbh (genesis)\n"; flush !log let eq_node n1 n2 = node_prevblockhash n1 = node_prevblockhash n2 let blkheaders : (hashval,unit) Hashtbl.t = Hashtbl.create 1000;; let blkheadernode : (hashval option,blocktree) Hashtbl.t = Hashtbl.create 1000;; let orphanblkheaders : (hashval option,hashval * blockheader) Hashtbl.t = Hashtbl.create 1000;; let earlyblocktreenodes : (int64 * blocktree) list ref = ref [];; let tovalidate : (hashval,unit) Hashtbl.t = Hashtbl.create 100;; let known_thytree_p thyroot = match thyroot with | None -> true | Some(r) -> Hashtbl.mem thytree r let known_sigtree_p sigroot = match sigroot with | None -> true | Some(r) -> Hashtbl.mem sigtree r let lookup_thytree thyroot = match thyroot with | None -> None | Some(r) -> Some(Hashtbl.find thytree r) let lookup_sigtree sigroot = match sigroot with | None -> None | Some(r) -> Some(Hashtbl.find sigtree r) let add_thytree thyroot otht = match thyroot,otht with | Some(r),Some(tht) -> if not (Hashtbl.mem thytree r) then Hashtbl.add thytree r tht | _,_ -> () let add_sigtree sigroot osigt = match sigroot,osigt with | Some(r),Some(sigt) -> if not (Hashtbl.mem sigtree r) then Hashtbl.add sigtree r sigt | _,_ -> () let rec collect_inv m cnt tosend n txinv = if !cnt < m then if !cnt mod 5 = 0 && not (txinv = []) then begin match txinv with | (txid::txinvr) -> tosend := (int_of_msgtype STx,0L,txid)::!tosend; incr cnt; collect_inv m cnt tosend n txinvr | [] -> incr cnt; collect_inv m cnt tosend n [] (*** can never happen ***) end else let BlocktreeNode(par,_,pbh,_,_,_,_,_,_,blkh,_,_,_) = n in match pbh with | None -> () | Some(pbh) -> if DbBlockHeader.dbexists pbh then begin tosend := (int_of_msgtype Headers,Int64.sub blkh 1L,pbh)::!tosend; incr cnt; if DbBlockDelta.dbexists pbh then (tosend := (int_of_msgtype Blockdelta,blkh,pbh)::!tosend; incr cnt) end; match par with | None -> () | Some(p) -> collect_inv m cnt tosend p txinv let send_inv m sout cs = let cnt = ref 0 in let tosend = ref [] in let txinv = ref [] in Hashtbl.iter (fun k _ -> txinv := k::!txinv) stxpool; collect_inv m cnt tosend !bestnode !txinv; let invmsg = Buffer.create 10000 in let c = ref (seo_int32 seosb (Int32.of_int !cnt) (invmsg,None)) in List.iter (fun (i,blkh,h) -> let cn = seo_prod3 seo_int8 seo_int64 seo_hashval seosb (i,blkh,h) !c in c := cn) !tosend; ignore (queue_msg cs Inv (Buffer.contents invmsg));; send_inv_fn := send_inv;; let rec insertnewdelayed (tm,n) btnl = match btnl with | [] -> [(tm,n)] | (tm2,n2)::btnr when tm < tm2 -> (tm,n)::btnl | (tm2,n2)::btnr -> (tm2,n2)::insertnewdelayed (tm,n) btnr let process_new_tx h hh = try let tx1 = DbTx.dbget h in let txid = hashtx tx1 in if not (txid = h) then (*** wrong hash, remove it but don't blacklist the (wrong) hashval ***) begin Printf.fprintf !log "WARNING: Received tx with different hash as advertised, removing %s\nThis may be due to a bug or due to a misbehaving peer.\n" hh; flush !log; DbTx.dbdelete h; DbTxSignatures.dbdelete h; end else if tx_valid tx1 then begin (*** checking the validity of signatures and support depend on the current ledger; delay this here in favor of checking them before including them in a block we're actively trying to stake; note that the relevant properties are checked when they are included in a block as part of checking a block is valid ***) let txsigs1 = DbTxSignatures.dbget h in Hashtbl.add stxpool txid (tx1,txsigs1); end else (*** in this case, reject the tx since it's definitely not valid ***) begin DbBlacklist.dbput h true; DbTx.dbdelete h; DbTxSignatures.dbdelete h; end * * in some cases , failure should lead to blacklist and removal of the tx , but it 's not clear which cases ; if it 's in a block we might need to distinguish between definitely incorrect vs. possibly incorrect * * | Not_found -> Printf.fprintf !log "Problem with tx, deleting it\n"; flush !log; DbTx.dbdelete h; DbTxSignatures.dbdelete h; | e -> Printf.fprintf !log "exception %s\n" (Printexc.to_string e); flush !log; () let rec prev_nth_node i n = if i <= 0 then Some(n) else let BlocktreeNode(par,_,_,_,_,_,_,_,_,_,_,_,_) = n in match par with | None -> None | Some(p) -> prev_nth_node (i-1) p let update_bestnode n = Printf.fprintf !log "New best blockheader %s\n" (match node_prevblockhash n with Some(h) -> hashval_hexstring h | None -> "(genesis)"); flush !log; bestnode := n; netblkh := node_blockheight n; match !checkpointsprivkeyk with | None -> () | Some(k) -> match prev_nth_node 36 n with | None -> () ; (** no block is deep enough to be a checkpoint **) | Some(p) -> match node_prevblockhash p with | None -> () (** genesis block is the default checkpoint; ignore **) | Some(h) -> Printf.fprintf !log "Creating new checkpoint %Ld %s\n" (node_blockheight p) (hashval_hexstring h); lastcheckpointnode := p; let pblkh = node_blockheight p in let r = rand_256() in let sg : signat = signat_hashval h k r in Hashtbl.add checkpoints h (pblkh,sg); broadcast_inv [(int_of_msgtype Checkpoint,pblkh,h)] let rec processdelayednodes tm btnl = match btnl with | (tm2,n2)::btnr when tm2 <= tm -> let BlocktreeNode(_,_,_,_,_,_,_,_,bestcumulstk,_,_,_,_) = !bestnode in let BlocktreeNode(_,_,pbh,_,_,_,_,_,newcumulstk,_,_,_,_) = n2 in if gt_big_int newcumulstk bestcumulstk then update_bestnode n2; processdelayednodes tm btnr | _ -> btnl let rec processblockvalidation vl = match vl with | [] -> [] | (v,f)::vr -> let vr2 = processblockvalidation vr in f(); match !v with | Waiting(_,_) -> (v,f)::vr2 | _ -> vr2 let rec is_recent_staker stkaddr n i = if i > 0 then begin let BlocktreeNode(par,stakers,_,_,_,_,_,_,_,_,_,_,_) = n in if List.mem stkaddr !stakers then true else match par with | Some(p) -> is_recent_staker stkaddr p (i-1) | _ -> false end else false let rec record_recent_staker stkaddr n i = if i > 0 then begin let BlocktreeNode(par,stakers,_,_,_,_,_,_,_,_,_,_,_) = n in stakers := stkaddr::!stakers; match par with | Some(p) -> record_recent_staker stkaddr p (i-1) | None -> () end let equ_tinfo (x,(y3,y2,y1,y0),z) (u,(v3,v2,v1,v0),w) = x = u && y3 = v3 && y2 = v2 && y1 = v1 && Int64.logand y0 (Int64.lognot 1L) = Int64.logand v0 (Int64.lognot 1L) && eq_big_int z w let rec validate_block_of_node newnode thyroot sigroot tinf blkhght h blkdel cs = let (blkhd,_) as blkh = DbBlockHeader.dbget h in let blk = (blkh,blkdel) in if known_thytree_p thyroot && known_sigtree_p sigroot then (*** these should both be known if the parent block has been validated ***) let BlocktreeNode(_,_,_,tr2,sr2,_,tinf2,_,newcumulstake,blkhght2,vs,_,chlr) = newnode in Printf.fprintf !log "About to check if block %s at height %Ld is valid\n" (hashval_hexstring h) blkhght; begin match valid_block (lookup_thytree thyroot) (lookup_sigtree sigroot) blkhght tinf blk with | Some(tht2,sigt2) -> vs := ValidBlock; Hashtbl.remove tovalidate h; DbBlockDelta.dbput h blkdel; let BlocktreeNode(_,_,_,_,_,_,_,_,bestcumulstk,_,_,_,_) = !bestnode in if gt_big_int newcumulstake bestcumulstk then update_bestnode newnode; add_thytree blkhd.newtheoryroot tht2; add_sigtree blkhd.newsignaroot sigt2; broadcast_inv [(int_of_msgtype Blockdelta,blkhght,h)]; (*** construct a transformed tree consisting of elements ***) begin let prevc = load_expanded_ctree (ctree_of_block blk) in * * is performed last , i.e. , after the txs in the block . * * match tx_octree_trans blkhght cstk (txl_octree_trans blkhght txl (Some(prevc))) with | Some(newc) -> ignore (save_ctree_elements newc) | None -> raise (Failure("transformed tree was empty, although block seemed to be valid")) end; List.iter (fun (h,n) -> let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,vs,_,_) = n in match !vs with | Waiting(_,Some(blkdel,cs)) -> validate_block_of_node n tr2 sr2 tinf2 blkhght2 h blkdel cs | _ -> ()) !chlr | None -> (*** We can't mark it as invalid because the peer may be misbehaving and sending a blockdelta that does not correspond to the header. In this case, ban the peer, drop the connection, and request it from someone else. ***) Printf.fprintf !log "Block delta for %s was not valid.\n" (hashval_hexstring h); let tm = Unix.time() in cs.banned <- true; Hashtbl.add bannedpeers cs.addrfrom (); vs := Waiting(tm,None) end else raise (Failure("parent was validated but thyroot and/or sigroot is not known"));; let rec process_new_header_a h hh blkh1 blkhd1 initialization knownvalid = try process_new_header_aa h hh blkh1 blkhd1 (blockheader_stakeasset blkhd1) initialization knownvalid with | HeaderStakedAssetNotMin -> Printf.fprintf !log "Header %s has extra information beyong supporting staked asset; should have been caught before process_new_header_a\n" hh; raise (Failure "header does not only support staked asset") | HeaderNoStakedAsset -> Printf.fprintf !log "Header %s does not support staked asset; should have been caught before process_new_header_a\n" hh; raise (Failure "header does not support staked asset") and process_new_header_aa h hh blkh1 blkhd1 a initialization knownvalid = if valid_blockheader_signat blkh1 a then process_new_header_ab h hh blkh1 blkhd1 a initialization knownvalid else begin Printf.fprintf !log "Header %s has an invalid siagnure; should have been caught before process_new_header_aa\n" hh; raise (Failure "header has invalid signature") end and process_new_header_ab h hh blkh1 blkhd1 a initialization knownvalid = let prevblkh = blkhd1.prevblockhash in begin try let prevnode = Hashtbl.find blkheadernode prevblkh in begin try let BlocktreeNode(_,_,_,thyroot,sigroot,ledgerroot,currtinfo,tmstamp,prevcumulstk,blkhght,validated,blacklisted,succl) = prevnode in if !blacklisted then (*** child of a blacklisted node, drop and blacklist it ***) begin Printf.fprintf !log "Header %s is child of blacklisted node; deleting and blacklisting it.\n" hh; DbBlacklist.dbput h true; DbBlockHeader.dbdelete h; end else if valid_blockheader blkhght currtinfo blkh1 && blockheader_succ_a ledgerroot tmstamp currtinfo blkh1 then begin Printf.fprintf !log "bhsa %s %Ld %s %b\n" (hashval_hexstring ledgerroot) tmstamp (targetinfo_string currtinfo) (blockheader_succ_a ledgerroot tmstamp currtinfo blkh1); if not (DbBlockHeader.dbexists h) then DbBlockHeader.dbput h blkh1; Hashtbl.add blkheaders h (); broadcast_inv [(int_of_msgtype Headers,blkhght,h)]; let (csm1,fsm1,tar1) = currtinfo in let newcumulstake = cumul_stake prevcumulstk tar1 blkhd1.deltatime in let validated = ref (if knownvalid then ValidBlock else Waiting(Unix.time(),None)) in let newnode = BlocktreeNode(Some(prevnode),ref [blkhd1.stakeaddr],Some(h),blkhd1.newtheoryroot,blkhd1.newsignaroot,blkhd1.newledgerroot,blkhd1.tinfo,blkhd1.timestamp,newcumulstake,Int64.add blkhght 1L,validated,ref false,ref []) in (*** add it as a leaf, indicate that we want the block delta to validate it, and check if it's the best ***) Hashtbl.add blkheadernode (Some(h)) newnode; succl := (h,newnode)::!succl; record_recent_staker blkhd1.stakeaddr prevnode 6; begin try let blkdel = DbBlockDelta.dbget h in let blk = (blkh1,blkdel) in if known_thytree_p thyroot && known_sigtree_p sigroot then (*** these should both be known if the parent block has been validated ***) begin match valid_block (lookup_thytree thyroot) (lookup_sigtree sigroot) blkhght currtinfo blk with | Some(_,_) -> validated := ValidBlock | None -> (*** should not have happened, delete it from the database and request it again. ***) DbBlockDelta.dbdelete h; Hashtbl.add tovalidate h (); try find_and_send_requestdata GetBlockdelta h with Not_found -> Printf.fprintf !log "No source for block delta of %s; must wait until it is explicitly requested\n" hh end else raise (Failure "unknown thyroot or sigroot while trying to validate block") with Not_found -> Hashtbl.add tovalidate h (); try find_and_send_requestdata GetBlockdelta h with Not_found -> Printf.fprintf !log "No source for block delta of %s\n" hh end; if Int64.of_float (Unix.time()) < tmstamp then (*** delay it ***) earlyblocktreenodes := insertnewdelayed (tmstamp,newnode) !earlyblocktreenodes else let BlocktreeNode(_,_,_,_,_,_,_,_,bestcumulstk,_,_,_,_) = !bestnode in if gt_big_int newcumulstake bestcumulstk then update_bestnode newnode; List.iter (fun (h,blkh1) -> let (blkhd1,_) = blkh1 in process_new_header_a h (hashval_hexstring h) blkh1 blkhd1 initialization knownvalid) (Hashtbl.find_all orphanblkheaders (Some(h))); Hashtbl.remove orphanblkheaders (Some(h)) end else begin (*** if it's wrong, delete it and blacklist it so it won't look new in the future [note: signature is assumed to have been checked to be valid by now] ***) Printf.fprintf !log "Header %s was invalid, deleting and blacklisting it.\n" hh; Printf.fprintf !log "vbh %Ld %s %b\n" blkhght (targetinfo_string currtinfo) (valid_blockheader blkhght currtinfo blkh1); Printf.fprintf !log "bhsa %s %Ld %s %b\n" (hashval_hexstring ledgerroot) tmstamp (targetinfo_string currtinfo) (blockheader_succ_a ledgerroot tmstamp currtinfo blkh1); let newnode = BlocktreeNode(Some(prevnode),ref [],Some(h),blkhd1.newtheoryroot,blkhd1.newsignaroot,blkhd1.newledgerroot,blkhd1.tinfo,blkhd1.timestamp,zero_big_int,Int64.add blkhght 1L,ref InvalidBlock,ref true,ref []) in (*** dummy node just to remember it is blacklisted ***) Hashtbl.add blkheadernode (Some(h)) newnode; DbBlacklist.dbput h true; DbBlockHeader.dbdelete h; end with Not_found -> Printf.fprintf !log "unexpected Not_found in process_new_header_a %s\n" hh; raise (Failure "unexpected Not_found in process_new_header_a") end with Not_found -> (*** orphan block header, put it on the relevant hash table and request parent ***) Hashtbl.add orphanblkheaders prevblkh (h,blkh1); try find_and_send_requestdata GetHeader h with Not_found -> Printf.fprintf !log "no peer has parent header %s\n" hh end and process_new_header_b h hh initialization knownvalid = Printf.fprintf !log "Processing new header %s\n" hh; flush !log; try let blkh1 = DbBlockHeader.dbget h in let (blkhd1,blkhs1) = blkh1 in if not (hash_blockheaderdata blkhd1 = h) then (*** wrong hash, remove it but don't blacklist the (wrong) hashval ***) begin Printf.fprintf !log "WARNING: Block header in database has different hash than key, removing %s\nThis must be due to a bug.\n" hh; flush !log; DbBlockHeader.dbdelete h end else process_new_header_a h hh blkh1 blkhd1 initialization knownvalid with (*** in some cases, failure should lead to blacklist and removal of the header, but it's not clear which cases; if it's in a block we might need to distinguish between definitely incorrect vs. possibly incorrect ***) | Not_found -> Printf.fprintf !log "Problem with blockheader %s, deleting it\n" hh; flush !log; DbBlockHeader.dbdelete h | e -> Printf.fprintf !log "exception %s\n" (Printexc.to_string e); flush !log; () and process_new_header h hh initialization knownvalid = if not (Hashtbl.mem blkheaders h) then process_new_header_b h hh initialization knownvalid let init_headers () = DbBlockHeader.dbkeyiter (fun h -> let hs = hashval_hexstring h in Printf.printf "processing header %s\n" hs; flush stdout; process_new_header h hs true false) let initblocktree () = genesisblocktreenode := BlocktreeNode(None,ref [],None,None,None,!genesisledgerroot,(!genesiscurrentstakemod,!genesisfuturestakemod,!genesistarget),!Config.genesistimestamp,zero_big_int,1L,ref ValidBlock,ref false,ref []); lastcheckpointnode := !genesisblocktreenode; update_bestnode !genesisblocktreenode; Hashtbl.add blkheadernode None !genesisblocktreenode; init_headers() let rec find_best_validated_block_from fromnode bestn bestcumulstk = let BlocktreeNode(_,_,_,_,_,_,_,_,cumulstk,_,validatedp,blklistp,succl) = fromnode in if not !blklistp && !validatedp = ValidBlock then begin let newbestn = ref (if gt_big_int cumulstk bestcumulstk then fromnode else bestn) in let newbestcumulstk = ref (node_cumulstk !newbestn) in List.iter (fun (_,childnode) -> let (bn,bcs) = find_best_validated_block_from childnode !newbestn !newbestcumulstk in newbestn := bn; newbestcumulstk := bcs) !succl; (!newbestn,!newbestcumulstk) end else (bestn,bestcumulstk) let find_best_validated_block () = let (bn,bcs) = find_best_validated_block_from !lastcheckpointnode !lastcheckpointnode (node_cumulstk !lastcheckpointnode) in update_bestnode bn let rec blacklist_from h n = let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,_,blklstd,chl) = n in blklstd := true; DbBlacklist.dbput h true; DbBlockHeader.dbdelete h; List.iter (fun (k,c) -> blacklist_from k c) !chl let publish_stx txh stx1 = let (tx1,txsigs1) = stx1 in if not (Hashtbl.mem stxpool txh) then Hashtbl.add stxpool txh stx1; DbTx.dbput txh tx1; DbTxSignatures.dbput txh txsigs1; Hashtbl.add published_stx txh (); broadcast_inv [(int_of_msgtype STx,0L,txh)] let publish_block blkh bhh (bh,bd) = Printf.fprintf !log "publishing block %s\n" (hashval_hexstring bhh); flush !log; DbBlockHeader.dbput bhh bh; DbBlockDelta.dbput bhh bd; broadcast_inv [(int_of_msgtype Headers,blkh,bhh);(int_of_msgtype Blockdelta,blkh,bhh)];; Hashtbl.add msgtype_handler GetHeader (fun (sin,sout,cs,ms) -> let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetHeader in if not (List.mem (i,h) cs.sentinv) then (*** don't resend ***) try let bh = DbBlockHeader.dbget h in let s = Buffer.create 1000 in seosbf (seo_blockheader seosb bh (seo_hashval seosb h (seo_int8 seosb 1 (s,None)))); cs.sentinv <- (i,h)::cs.sentinv; let ss = Buffer.contents s in ignore (queue_msg cs Headers ss) with Not_found -> (*** don't have it to send, ignore ***) ());; Hashtbl.add msgtype_handler GetHeaders (fun (sin,sout,cs,ms) -> let c = ref (ms,String.length ms,None,0,0) in let m = ref 0 in let bhl = ref [] in * * peers can request at most 255 headers at a time * c := cn; let i = int_of_msgtype GetHeader in for j = 1 to n do let (h,cn) = sei_hashval seis !c in c := cn; if not (List.mem (i,h) cs.sentinv) then (*** don't resend ***) try let bh = DbBlockHeader.dbget h in incr m; bhl := (h,bh)::!bhl; cs.sentinv <- (i,h)::cs.sentinv with Not_found -> (*** don't have it to send, ignore ***) () done; let s = Buffer.create 10000 in let co = ref (seo_int8 seosb !m (s,None)) in List.iter (fun (h,bh) -> co := seo_blockheader seosb bh (seo_hashval seosb h !co)) !bhl; seosbf !co; let ss = Buffer.contents s in ignore (queue_msg cs Headers ss) );; Hashtbl.add msgtype_handler Headers (fun (sin,sout,cs,ms) -> let c = ref (ms,String.length ms,None,0,0) in * * peers can request at most 255 headers at a time * c := cn; let i = int_of_msgtype GetHeader in for j = 1 to n do let (h,cn) = sei_hashval seis !c in let (bh,cn) = sei_blockheader seis cn in (*** deserialize if only to get to the next one ***) c := cn; begin (*** excessive logging while testing ***) let s = Buffer.create 10000 in seosbf (seo_blockheader seosb bh (s,None)); Printf.fprintf !log "got blockheader %s:\n%s\n" (hashval_hexstring h) (Hashaux.string_hexstring (Buffer.contents s)); end; if not (DbBlockHeader.dbexists h) && List.mem (i,h) cs.invreq then let (bhd,bhs) = bh in if not (hash_blockheaderdata bhd = h) then begin (*** this may be the result of a misbehaving peer ***) Printf.fprintf !log "got a header with the wrong hash, dropping it and banning node\n"; flush !log; cs.banned <- true end else begin try let a = blockheader_stakeasset bhd in if not (valid_blockheader_signat (bhd,bhs) a) then begin (*** this may simply be the result of a misbehaving peer mangling the signature of an otherwise valid header ***) Printf.fprintf !log "got a header with an invalid signature, dropping it and banning node\n"; flush !log; cs.banned <- true end else process_new_header_ab h (hashval_hexstring h) bh bhd a false false with | HeaderStakedAssetNotMin -> (*** here it is safe to blacklist the header's hash since no valid header can have this hash ***) begin Printf.fprintf !log "header does not only have the staked asset; blacklisting it and banning node\n"; flush !log; cs.banned <- true end | HeaderNoStakedAsset -> (*** here it is safe to blacklist the header's hash since no valid header can have this hash ***) begin Printf.fprintf !log "header does not have the staked asset; blacklisting it and banning node\n"; flush !log; cs.banned <- true end end done);; let req_headers sout cs m nw = if m > 0 then begin let s = Buffer.create 1000 in let co = ref (seo_int8 seosb m (s,None)) in List.iter (fun h -> co := seo_hashval seosb h !co) nw; seosbf !co; Printf.fprintf !log "req_headers requesting:"; List.iter (fun h -> Printf.fprintf !log " %s" (hashval_hexstring h)) nw; Printf.fprintf !log "\n"; ignore (queue_msg cs GetHeaders (Buffer.contents s)) end;; let rec req_header_batches sout cs m hl nw = Printf.fprintf !log "rhb %d\n" m; if m = 255 then (req_headers sout cs m nw; req_header_batches sout cs 0 hl []) else match hl with | (_,h)::hr -> let i = int_of_msgtype GetHeader in cs.invreq <- (i,h)::cs.invreq; req_header_batches sout cs (m+1) hr (h::nw) | [] -> req_headers sout cs m nw;; Hashtbl.add msgtype_handler Inv (fun (sin,sout,cs,ms) -> let c = ref (ms,String.length ms,None,0,0) in let hl = ref [] in let (n,cn) = sei_int32 seis !c in Printf.fprintf !log "Inv %ld\n" n; c := cn; for j = 1 to Int32.to_int n do let ((i,blkh,h),cn) = sei_prod3 sei_int8 sei_int64 sei_hashval seis !c in Printf.fprintf !log "%d %Ld %s\n" i blkh (hashval_hexstring h); c := cn; cs.rinv <- (i,h)::cs.rinv; if i = int_of_msgtype Headers then Printf.fprintf !log "Headers, dbexists %b, archived %b\n" (DbBlockHeader.dbexists h) (DbArchived.dbexists h); if i = int_of_msgtype Headers && not (DbArchived.dbexists h) then begin try let bh = DbBlockHeader.dbget h in if not (Hashtbl.mem blkheadernode (Some(h))) then let (bhd,_) = bh in process_new_header_a h (hashval_hexstring h) bh bhd false false with Not_found -> hl := List.merge (fun (blkh1,_) (blkh2,_) -> compare blkh2 blkh1) !hl [(blkh,h)]; (*** reverse order because they will be reversed again when requested ***) Printf.fprintf !log "i %d blkh %Ld h %s hl:\n" i blkh (hashval_hexstring h); List.iter (fun (blkh1,h1) -> Printf.fprintf !log "%Ld %s\n" blkh1 (hashval_hexstring h)) !hl end else if i = int_of_msgtype Blockdelta && not (DbBlockDelta.dbexists h) && not (DbArchived.dbexists h) && Hashtbl.mem tovalidate h then begin try cs.invreq <- (int_of_msgtype GetBlockdelta,h)::cs.invreq; let s = Buffer.create 1000 in seosbf (seo_hashval seosb h (s,None)); Printf.fprintf !log "Immediately requesting blockdelta %s\n" (hashval_hexstring h); ignore (queue_msg cs GetBlockdelta (Buffer.contents s)) with exn -> Printf.fprintf !log "inv blockdelta %s\n" (Printexc.to_string exn) end else if i = int_of_msgtype STx && not (DbArchived.dbexists h) then begin if DbTx.dbexists h then if not (DbTxSignatures.dbexists h) then begin cs.invreq <- (int_of_msgtype GetTxSignatures,h)::cs.invreq; let s = Buffer.create 1000 in seosbf (seo_hashval seosb h (s,None)); ignore (queue_msg cs GetTxSignatures (Buffer.contents s)) end else () else begin cs.invreq <- (int_of_msgtype GetTx,h)::cs.invreq; let s = Buffer.create 1000 in seosbf (seo_hashval seosb h (s,None)); ignore (queue_msg cs GetTx (Buffer.contents s)) end end else if i = int_of_msgtype Checkpoint then begin (*** only request if we need it ***) try let lcp = !lastcheckpointnode in let BlocktreeNode(par,_,_,_,_,_,_,_,_,lcpblkh,_,_,_) = lcp in if lcpblkh < blkh then raise Exit else let lcpp = prev_nth_node (Int64.to_int (Int64.sub lcpblkh blkh)) lcp in match lcpp with | None -> raise Exit | Some(lcppn) -> match node_prevblockhash lcppn with | None -> raise Exit | Some(lcppnh) -> if not (lcppnh = h) then raise Exit * * if Exit was raised , then we need the checkpoint * * cs.invreq <- (int_of_msgtype GetCheckpoint,h)::cs.invreq; let s = Buffer.create 1000 in seosbf (seo_hashval seosb h (s,None)); ignore (queue_msg cs GetCheckpoint (Buffer.contents s)) end done; req_header_batches sout cs 0 !hl []);; Hashtbl.add msgtype_handler GetBlockdelta (fun (sin,sout,cs,ms) -> Printf.fprintf !log "Processing GetBlockdelta\n"; let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in Printf.fprintf !log "Processing GetBlockdelta %s\n" (hashval_hexstring h); let i = int_of_msgtype GetBlockdelta in if not (List.mem (i,h) cs.sentinv) then (*** don't resend ***) try let blkdel = DbBlockDelta.dbget h in let bdsb = Buffer.create 100 in seosbf (seo_blockdelta seosb blkdel (seo_hashval seosb h (bdsb,None))); let bdser = Buffer.contents bdsb in Printf.fprintf !log "Sending Block Delta (from db) %s\n" (hashval_hexstring h); ignore (queue_msg cs Blockdelta bdser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> Printf.fprintf !log "Unknown Block Delta %s (Bad Peer or Did I Advertize False Inventory?)\n" (hashval_hexstring h); ());; Hashtbl.add msgtype_handler Blockdelta (fun (sin,sout,cs,ms) -> let (h,r) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetBlockdelta in if not (DbBlockDelta.dbexists h) then (*** if we already have it, abort ***) begin try cs.invreq <- List.filter (fun (j,k) -> not (i = j && h = k)) cs.invreq; let BlocktreeNode(par,_,_,_,_,_,_,_,_,_,vs,_,chlr) as newnode = Hashtbl.find blkheadernode (Some(h)) in match !vs with | Waiting(tm,None) -> begin match par with | None -> (*** genesis node, parent implicitly valid ***) let (blkdel,_) = sei_blockdelta seis r in begin (*** excessive logging while testing ***) let s = Buffer.create 10000 in seosbf (seo_blockdelta seosb blkdel (s,None)); Printf.fprintf !log "got blockdelta %s:\n%s\n" (hashval_hexstring h) (Hashaux.string_hexstring (Buffer.contents s)); end; validate_block_of_node newnode None None (!genesiscurrentstakemod,!genesisfuturestakemod,!genesistarget) 1L h blkdel cs | Some(BlocktreeNode(_,_,_,thyroot,sigroot,_,tinf,_,_,blkhght,vsp,_,_)) -> match !vsp with | InvalidBlock -> raise Not_found (*** questionable if this can happen ***) | Waiting(_,_) -> let (blkdel,_) = sei_blockdelta seis r in begin (*** excessive logging while testing ***) let s = Buffer.create 10000 in seosbf (seo_blockdelta seosb blkdel (s,None)); Printf.fprintf !log "got blockdelta %s, waiting for parent block to be validated:\n%s\n" (hashval_hexstring h) (Hashaux.string_hexstring (Buffer.contents s)); end; vs := Waiting(tm,Some(blkdel,cs)) (*** wait for the parent to be validated; remember the connstate in case we decide to ban it for giving a bad block delta ***) | ValidBlock -> (*** validate now, and if valid check if children nodes are waiting to be validated ***) begin let (blkdel,_) = sei_blockdelta seis r in begin (*** excessive logging while testing ***) let s = Buffer.create 10000 in seosbf (seo_blockdelta seosb blkdel (s,None)); Printf.fprintf !log "got blockdelta %s:\n%s\n" (hashval_hexstring h) (Hashaux.string_hexstring (Buffer.contents s)); end; validate_block_of_node newnode thyroot sigroot tinf blkhght h blkdel cs end end | _ -> () with Not_found -> () end);; Hashtbl.add msgtype_handler GetTx (fun (sin,sout,cs,ms) -> Printf.fprintf !log "Processing GetTx\n"; let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in Printf.fprintf !log "Processing GetTx %s\n" (hashval_hexstring h); let i = int_of_msgtype GetTx in if not (List.mem (i,h) cs.sentinv) then (*** don't resend ***) try let (tau,_) = Hashtbl.find stxpool h in let tausb = Buffer.create 100 in seosbf (seo_tx seosb tau (seo_hashval seosb h (tausb,None))); let tauser = Buffer.contents tausb in Printf.fprintf !log "Sending Tx (from pool) %s\n" (hashval_hexstring h); ignore (queue_msg cs Tx tauser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> try let tau = DbTx.dbget h in let tausb = Buffer.create 100 in seosbf (seo_tx seosb tau (seo_hashval seosb h (tausb,None))); let tauser = Buffer.contents tausb in Printf.fprintf !log "Sending Tx (from db) %s\n" (hashval_hexstring h); ignore (queue_msg cs Tx tauser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> Printf.fprintf !log "Unknown Tx %s\n" (hashval_hexstring h); ());; Hashtbl.add msgtype_handler Tx (fun (sin,sout,cs,ms) -> let (h,r) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetTx in if not (DbTx.dbexists h) then (*** if we already have it, abort ***) if List.mem (i,h) cs.invreq then (*** only continue if it was requested ***) let (tau,_) = sei_tx seis r in if hashtx tau = h then begin DbTx.dbput h tau; cs.invreq <- List.filter (fun (j,k) -> not (i = j && h = k)) cs.invreq end else (*** otherwise, it seems to be a misbehaving peer -- ignore for now ***) (Printf.fprintf !Utils.log "misbehaving peer? [malformed Tx]\n"; flush !Utils.log) else (*** if something unrequested was sent, then seems to be a misbehaving peer ***) (Printf.fprintf !Utils.log "misbehaving peer? [unrequested Tx]\n"; flush !Utils.log));; Hashtbl.add msgtype_handler GetTxSignatures (fun (sin,sout,cs,ms) -> let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in Printf.fprintf !log "Processing GetTxSignatures %s\n" (hashval_hexstring h); let i = int_of_msgtype GetTxSignatures in if not (List.mem (i,h) cs.sentinv) then (*** don't resend ***) try let (_,s) = Hashtbl.find stxpool h in let ssb = Buffer.create 100 in seosbf (seo_txsigs seosb s (seo_hashval seosb h (ssb,None))); let sser = Buffer.contents ssb in Printf.fprintf !log "Sending TxSignatures (from pool) %s\n" (hashval_hexstring h); ignore (queue_msg cs TxSignatures sser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> try let s = DbTxSignatures.dbget h in let ssb = Buffer.create 100 in seosbf (seo_txsigs seosb s (seo_hashval seosb h (ssb,None))); let sser = Buffer.contents ssb in Printf.fprintf !log "Sending TxSignatures (from db) %s\n" (hashval_hexstring h); ignore (queue_msg cs TxSignatures sser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> Printf.fprintf !log "Unknown TxSignatures %s\n" (hashval_hexstring h); ());; Hashtbl.add msgtype_handler TxSignatures (fun (sin,sout,cs,ms) -> let (h,r) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetTxSignatures in if not (DbTxSignatures.dbexists h) then (*** if we already have it, abort ***) try let ((tauin,_) as tau) = DbTx.dbget h in if List.mem (i,h) cs.invreq then (*** only continue if it was requested ***) let (s,_) = sei_txsigs seis r in try let al = List.map (fun (_,aid) -> DbAsset.dbget aid) tauin in ignore (tx_signatures_valid_asof_blkh al (tau,s)); (*** signatures valid at some block height ***) Hashtbl.add stxpool h (tau,s); DbTxSignatures.dbput h s; cs.invreq <- List.filter (fun (j,k) -> not (i = j && h = k)) cs.invreq with | BadOrMissingSignature -> (*** otherwise, it seems to be a misbehaving peer -- ignore for now ***) (Printf.fprintf !Utils.log "misbehaving peer? [malformed TxSignatures]\n"; flush !Utils.log) | Not_found -> (*** in this case, we don't have all the spent assets in the database, which means we shouldn't have requested the signatures, ignore ***) () else (*** if something unrequested was sent, then seems to be a misbehaving peer ***) (Printf.fprintf !Utils.log "misbehaving peer? [unrequested TxSignatures]\n"; flush !Utils.log) * * do not know the tx , so drop the sig * * ());; let dumpblocktreestate sa = Printf.fprintf sa "=========\nstxpool:\n"; Hashtbl.iter (fun h ((tauin,tauout) as tau,tausg) -> Printf.fprintf sa "- tx %s\n" (hashval_hexstring (hashtx tau)); Printf.fprintf sa "inputs %d\n" (List.length tauin); let c = ref 0 in List.iter (fun (alpha,aid) -> Printf.fprintf sa "%d. %s %s\n" !c (Cryptocurr.addr_qedaddrstr alpha) (hashval_hexstring aid); incr c) tauin; Printf.fprintf sa "outputs %d\n" (List.length tauin); c := 0; List.iter (fun (alpha,(obl,u)) -> Printf.fprintf sa "%d. %s %s %s\n" !c (Cryptocurr.addr_qedaddrstr alpha) (obligation_string obl) (preasset_string u); incr c) tauout; let sb = Buffer.create 100 in seosbf (seo_stx seosb (tau,tausg) (sb,None)); Printf.fprintf sa "%s\n" (string_hexstring (Buffer.contents sb)) ) stxpool; Printf.fprintf sa "=========\npublished_stx:\n"; Hashtbl.iter (fun h () -> Printf.fprintf sa "- tx %s\n" (hashval_hexstring h)) published_stx; Printf.fprintf sa "=========\nthytree:\n"; Hashtbl.iter (fun h _ -> Printf.fprintf sa "- thytree root %s\n" (hashval_hexstring h)) thytree; Printf.fprintf sa "=========\nsigtree:\n"; Hashtbl.iter (fun h _ -> Printf.fprintf sa "- sigtree root %s\n" (hashval_hexstring h)) sigtree; Printf.fprintf sa "=========\nblkheaders:\n"; Hashtbl.iter (fun h _ -> Printf.fprintf sa "- blk %s\n" (hashval_hexstring h)) blkheaders; Printf.fprintf sa "=========\nblkheadernode:\n"; Hashtbl.iter (fun h (BlocktreeNode(_,rs,pbh,tr,sr,lr,((csm3,csm2,csm1,csm0),(fsm3,fsm2,fsm1,fsm0),tar),tm,cs,blkh,vs,bl,chr)) -> Printf.fprintf sa "- blk %s node:\n" (match h with Some(h) -> hashval_hexstring h | None -> "[genesis]"); Printf.fprintf sa "recentstakers:\n"; List.iter (fun k -> Printf.fprintf sa "%s\n" (hashval_hexstring k)) !rs; Printf.fprintf sa "prevblockhash: %s\n" (match pbh with Some(h) -> hashval_hexstring h | None -> "[genesis]"); Printf.fprintf sa "theory tree root: %s\n" (match tr with Some(h) -> hashval_hexstring h | None -> "[empty]"); Printf.fprintf sa "sig tree root: %s\n" (match sr with Some(h) -> hashval_hexstring h | None -> "[empty]"); Printf.fprintf sa "ledger tree root: %s\n" (hashval_hexstring lr); Printf.fprintf sa "targetinfo:\ncsm %Lx %Lx %Lx %Lx\nfsm %Lx %Lx %Lx %Lx\ntar %s\n" csm3 csm2 csm1 csm0 fsm3 fsm2 fsm1 fsm0 (string_of_big_int tar); Printf.fprintf sa "timestamp: %Ld\n" tm; Printf.fprintf sa "cumulative stake: %s\n" (string_of_big_int cs); Printf.fprintf sa "block height: %Ld\n" blkh; Printf.fprintf sa "validation status: %s\n" (match !vs with Waiting(tm,None) -> "Waiting " ^ string_of_float tm | Waiting(tm,Some(_)) -> "Waiting for parent " ^ string_of_float tm | ValidBlock -> "Valid" | InvalidBlock -> "Invalid"); if !bl then Printf.fprintf sa "*blacklisted*\n"; Printf.fprintf sa "children nodes: %d\n" (List.length !chr); List.iter (fun (h,_) -> Printf.fprintf sa "%s\n" (hashval_hexstring h)) !chr) blkheadernode; Printf.fprintf sa "=========\norphanblkheaders:\n"; Hashtbl.iter (fun h (k,bh) -> Printf.fprintf sa "- orphan blk %s waiting for %s\n" (hashval_hexstring k) (match h with Some(h) -> hashval_hexstring h | None -> "[genesis?]"); let sb = Buffer.create 100 in seosbf (seo_blockheader seosb bh (sb,None)); Printf.fprintf sa "%s\n" (string_hexstring (Buffer.contents sb))) orphanblkheaders; Printf.fprintf sa "=========\nearlyblocktreenodes:\n"; List.iter (fun (futuretm,BlocktreeNode(_,rs,pbh,tr,sr,lr,((csm3,csm2,csm1,csm0),(fsm3,fsm2,fsm1,fsm0),tar),tm,cs,blkh,vs,bl,chr)) -> Printf.fprintf sa "future timestamp: %Ld\n" futuretm; Printf.fprintf sa "recentstakers:\n"; List.iter (fun k -> Printf.fprintf sa "%s\n" (hashval_hexstring k)) !rs; Printf.fprintf sa "prevblockhash: %s\n" (match pbh with Some(h) -> hashval_hexstring h | None -> "[genesis]"); Printf.fprintf sa "theory tree root: %s\n" (match tr with Some(h) -> hashval_hexstring h | None -> "[empty]"); Printf.fprintf sa "sig tree root: %s\n" (match sr with Some(h) -> hashval_hexstring h | None -> "[empty]"); Printf.fprintf sa "ledger tree root: %s\n" (hashval_hexstring lr); Printf.fprintf sa "targetinfo:\ncsm %Lx %Lx %Lx %Lx\nfsm %Lx %Lx %Lx %Lx\ntar %s\n" csm3 csm2 csm1 csm0 fsm3 fsm2 fsm1 fsm0 (string_of_big_int tar); Printf.fprintf sa "timestamp: %Ld\n" tm; Printf.fprintf sa "cumulative stake: %s\n" (string_of_big_int cs); Printf.fprintf sa "block height: %Ld\n" blkh; Printf.fprintf sa "validation status: %s\n" (match !vs with Waiting(tm,None) -> "Waiting " ^ string_of_float tm | Waiting(tm,Some(_)) -> "Waiting for parent " ^ string_of_float tm | ValidBlock -> "Valid" | InvalidBlock -> "Invalid"); if !bl then Printf.fprintf sa "*blacklisted*\n"; Printf.fprintf sa "children nodes: %d\n" (List.length !chr); List.iter (fun (h,_) -> Printf.fprintf sa "%s\n" (hashval_hexstring h)) !chr) !earlyblocktreenodes; Printf.fprintf sa "=========\ntovalidate:\n"; Hashtbl.iter (fun h () -> Printf.fprintf sa "%s\n" (hashval_hexstring h)) tovalidate;; Hashtbl.add msgtype_handler GetCheckpoint (fun (sin,sout,cs,ms) -> let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetCheckpoint in if not (List.mem (i,h) cs.sentinv) then (*** don't resend ***) try let (chblkh,chsg) = Hashtbl.find checkpoints h in let sb = Buffer.create 100 in seosbf (seo_signat seosb chsg (seo_int64 seosb chblkh (seo_hashval seosb h (sb,None)))); let ser = Buffer.contents sb in Printf.fprintf !log "Sending Checkpoint %s\n" (hashval_hexstring h); ignore (queue_msg cs Checkpoint ser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> Printf.fprintf !log "Unknown Checkpoint %s (Bad Peer or Did I Advertize False Inventory?)\n" (hashval_hexstring h); ());; Hashtbl.add msgtype_handler Checkpoint (fun (sin,sout,cs,ms) -> Printf.fprintf !log "Processing Checkpoint\n"; let (h,r) = sei_hashval seis (ms,String.length ms,None,0,0) in let (blkh,r) = sei_int64 seis r in Printf.fprintf !log "Processing Checkpoint %Ld %s\n" blkh (hashval_hexstring h); let (sg,_) = sei_signat seis r in if Signat.verify_signed_hashval h (Some(checkpointspubkeyx,checkpointspubkeyy)) sg then begin Hashtbl.add checkpoints h (blkh,sg); if DbBlacklist.dbexists h then begin Printf.fprintf !log "Checkpoint %s was blacklisted; removing the blacklist.\n" (hashval_hexstring h); DbBlacklist.dbdelete h end; try let n = Hashtbl.find blkheadernode (Some(h)) in let BlocktreeNode(par,_,_,_,_,_,_,_,_,_,vs,blklstd,_) = n in begin match par with | None -> () | Some(p) -> let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,_,_,chl) = p in List.iter (fun (k,c) -> if not (k = h) then blacklist_from k c ) !chl end; if !blklstd then blklstd := false; if not (!vs = ValidBlock) then vs := ValidBlock; lastcheckpointnode := n; find_best_validated_block(); broadcast_inv [(int_of_msgtype Checkpoint,node_blockheight n,h)] with Not_found -> try let bh = DbBlockHeader.dbget h in let (bhd,bhs) = bh in * * just drop the cumul stake back to zero because I do n't know it here * * Hashtbl.add blkheadernode (Some(h)) fnode; Hashtbl.remove orphanblkheaders (Some(h)); lastcheckpointnode := fnode; update_bestnode fnode with Not_found -> Printf.fprintf !log "Unknown header %s, trying to request it.\n" (hashval_hexstring h); try find_and_send_requestdata Headers h with Not_found -> Printf.fprintf !log "No peer willing to send header was found %s\n" (hashval_hexstring h) end else Printf.fprintf !log "Bad signature on checkpoint\n%s\n" (string_hexstring ms));;
null
https://raw.githubusercontent.com/input-output-hk/qeditas/f4871bd20833cd08a215f9d5fc9df2d362cba410/src/blocktree.ml
ocaml
** can never happen ** ** wrong hash, remove it but don't blacklist the (wrong) hashval ** ** checking the validity of signatures and support depend on the current ledger; delay this here in favor of checking them before including them in a block we're actively trying to stake; note that the relevant properties are checked when they are included in a block as part of checking a block is valid ** ** in this case, reject the tx since it's definitely not valid ** * no block is deep enough to be a checkpoint * * genesis block is the default checkpoint; ignore * ** these should both be known if the parent block has been validated ** ** construct a transformed tree consisting of elements ** ** We can't mark it as invalid because the peer may be misbehaving and sending a blockdelta that does not correspond to the header. In this case, ban the peer, drop the connection, and request it from someone else. ** ** child of a blacklisted node, drop and blacklist it ** ** add it as a leaf, indicate that we want the block delta to validate it, and check if it's the best ** ** these should both be known if the parent block has been validated ** ** should not have happened, delete it from the database and request it again. ** ** delay it ** ** if it's wrong, delete it and blacklist it so it won't look new in the future [note: signature is assumed to have been checked to be valid by now] ** ** dummy node just to remember it is blacklisted ** ** orphan block header, put it on the relevant hash table and request parent ** ** wrong hash, remove it but don't blacklist the (wrong) hashval ** ** in some cases, failure should lead to blacklist and removal of the header, but it's not clear which cases; if it's in a block we might need to distinguish between definitely incorrect vs. possibly incorrect ** ** don't resend ** ** don't have it to send, ignore ** ** don't resend ** ** don't have it to send, ignore ** ** deserialize if only to get to the next one ** ** excessive logging while testing ** ** this may be the result of a misbehaving peer ** ** this may simply be the result of a misbehaving peer mangling the signature of an otherwise valid header ** ** here it is safe to blacklist the header's hash since no valid header can have this hash ** ** here it is safe to blacklist the header's hash since no valid header can have this hash ** ** reverse order because they will be reversed again when requested ** ** only request if we need it ** ** don't resend ** ** if we already have it, abort ** ** genesis node, parent implicitly valid ** ** excessive logging while testing ** ** questionable if this can happen ** ** excessive logging while testing ** ** wait for the parent to be validated; remember the connstate in case we decide to ban it for giving a bad block delta ** ** validate now, and if valid check if children nodes are waiting to be validated ** ** excessive logging while testing ** ** don't resend ** ** if we already have it, abort ** ** only continue if it was requested ** ** otherwise, it seems to be a misbehaving peer -- ignore for now ** ** if something unrequested was sent, then seems to be a misbehaving peer ** ** don't resend ** ** if we already have it, abort ** ** only continue if it was requested ** ** signatures valid at some block height ** ** otherwise, it seems to be a misbehaving peer -- ignore for now ** ** in this case, we don't have all the spent assets in the database, which means we shouldn't have requested the signatures, ignore ** ** if something unrequested was sent, then seems to be a misbehaving peer ** ** don't resend **
Copyright ( c ) 2015 - 2016 The Qeditas developers Distributed under the MIT software license , see the accompanying file COPYING or -license.php . file COPYING or -license.php. *) open Big_int open Utils open Ser open Hashaux open Sha256 open Hash open Net open Db open Assets open Signat open Tx open Ctre open Block let checkpointsprivkeyk = ref None let checkpointspubkeyx = big_int_of_string "63717203732691002966627493523478395510925637964138185199101530429614494608215" let checkpointspubkeyy = big_int_of_string "14551538993109352432558649646564074001010059416911525032428212764782058901234" let checkpoints : (hashval,int64 * signat) Hashtbl.t = Hashtbl.create 1000;; let stxpool : (hashval,stx) Hashtbl.t = Hashtbl.create 1000;; let published_stx : (hashval,unit) Hashtbl.t = Hashtbl.create 1000;; let thytree : (hashval,Mathdata.ttree) Hashtbl.t = Hashtbl.create 1000;; let sigtree : (hashval,Mathdata.stree) Hashtbl.t = Hashtbl.create 1000;; * * It is n't clear if there are any circumstances when it is safe to say the header is not the header for a valid block . may be unused . * * type blocktree = BlocktreeNode of blocktree option * hashval list ref * hashval option * hashval option * hashval option * hashval * targetinfo * int64 * big_int * int64 * validationstatus ref * bool ref * (hashval * blocktree) list ref let genesisblocktreenode = ref (BlocktreeNode(None,ref [],None,None,None,!genesisledgerroot,(!genesiscurrentstakemod,!genesisfuturestakemod,!genesistarget),!Config.genesistimestamp,zero_big_int,1L,ref ValidBlock,ref false,ref []));; let lastcheckpointnode = ref !genesisblocktreenode;; let bestnode = ref !genesisblocktreenode;; let node_recent_stakers n = let BlocktreeNode(_,rs,_,_,_,_,_,_,_,_,_,_,_) = n in !rs let node_prevblockhash n = let BlocktreeNode(_,_,pbh,_,_,_,_,_,_,_,_,_,_) = n in pbh let node_theoryroot n = let BlocktreeNode(_,_,_,tr,_,_,_,_,_,_,_,_,_) = n in tr let node_signaroot n = let BlocktreeNode(_,_,_,_,sr,_,_,_,_,_,_,_,_) = n in sr let node_ledgerroot n = let BlocktreeNode(_,_,_,_,_,lr,_,_,_,_,_,_,_) = n in lr let node_targetinfo n = let BlocktreeNode(_,_,_,_,_,_,ti,_,_,_,_,_,_) = n in ti let node_timestamp n = let BlocktreeNode(_,_,_,_,_,_,_,tm,_,_,_,_,_) = n in tm let node_cumulstk n = let BlocktreeNode(_,_,_,_,_,_,_,_,cs,_,_,_,_) = n in cs let node_blockheight n = let BlocktreeNode(_,_,_,_,_,_,_,_,_,blkh,_,_,_) = n in blkh let node_validationstatus n = let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,vs,_,_) = n in !vs let node_children_ref n = let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,_,_,chr) = n in chr let print_best_node () = let BlocktreeNode(_,_,pbh,_,_,_,_,_,_,_,_,_,_) = !bestnode in match pbh with | Some(h) -> Printf.fprintf !log "bestnode pbh %s\n" (hashval_hexstring h); flush !log | None -> Printf.fprintf !log "bestnode pbh (genesis)\n"; flush !log let eq_node n1 n2 = node_prevblockhash n1 = node_prevblockhash n2 let blkheaders : (hashval,unit) Hashtbl.t = Hashtbl.create 1000;; let blkheadernode : (hashval option,blocktree) Hashtbl.t = Hashtbl.create 1000;; let orphanblkheaders : (hashval option,hashval * blockheader) Hashtbl.t = Hashtbl.create 1000;; let earlyblocktreenodes : (int64 * blocktree) list ref = ref [];; let tovalidate : (hashval,unit) Hashtbl.t = Hashtbl.create 100;; let known_thytree_p thyroot = match thyroot with | None -> true | Some(r) -> Hashtbl.mem thytree r let known_sigtree_p sigroot = match sigroot with | None -> true | Some(r) -> Hashtbl.mem sigtree r let lookup_thytree thyroot = match thyroot with | None -> None | Some(r) -> Some(Hashtbl.find thytree r) let lookup_sigtree sigroot = match sigroot with | None -> None | Some(r) -> Some(Hashtbl.find sigtree r) let add_thytree thyroot otht = match thyroot,otht with | Some(r),Some(tht) -> if not (Hashtbl.mem thytree r) then Hashtbl.add thytree r tht | _,_ -> () let add_sigtree sigroot osigt = match sigroot,osigt with | Some(r),Some(sigt) -> if not (Hashtbl.mem sigtree r) then Hashtbl.add sigtree r sigt | _,_ -> () let rec collect_inv m cnt tosend n txinv = if !cnt < m then if !cnt mod 5 = 0 && not (txinv = []) then begin match txinv with | (txid::txinvr) -> tosend := (int_of_msgtype STx,0L,txid)::!tosend; incr cnt; collect_inv m cnt tosend n txinvr end else let BlocktreeNode(par,_,pbh,_,_,_,_,_,_,blkh,_,_,_) = n in match pbh with | None -> () | Some(pbh) -> if DbBlockHeader.dbexists pbh then begin tosend := (int_of_msgtype Headers,Int64.sub blkh 1L,pbh)::!tosend; incr cnt; if DbBlockDelta.dbexists pbh then (tosend := (int_of_msgtype Blockdelta,blkh,pbh)::!tosend; incr cnt) end; match par with | None -> () | Some(p) -> collect_inv m cnt tosend p txinv let send_inv m sout cs = let cnt = ref 0 in let tosend = ref [] in let txinv = ref [] in Hashtbl.iter (fun k _ -> txinv := k::!txinv) stxpool; collect_inv m cnt tosend !bestnode !txinv; let invmsg = Buffer.create 10000 in let c = ref (seo_int32 seosb (Int32.of_int !cnt) (invmsg,None)) in List.iter (fun (i,blkh,h) -> let cn = seo_prod3 seo_int8 seo_int64 seo_hashval seosb (i,blkh,h) !c in c := cn) !tosend; ignore (queue_msg cs Inv (Buffer.contents invmsg));; send_inv_fn := send_inv;; let rec insertnewdelayed (tm,n) btnl = match btnl with | [] -> [(tm,n)] | (tm2,n2)::btnr when tm < tm2 -> (tm,n)::btnl | (tm2,n2)::btnr -> (tm2,n2)::insertnewdelayed (tm,n) btnr let process_new_tx h hh = try let tx1 = DbTx.dbget h in let txid = hashtx tx1 in begin Printf.fprintf !log "WARNING: Received tx with different hash as advertised, removing %s\nThis may be due to a bug or due to a misbehaving peer.\n" hh; flush !log; DbTx.dbdelete h; DbTxSignatures.dbdelete h; end else if tx_valid tx1 then let txsigs1 = DbTxSignatures.dbget h in Hashtbl.add stxpool txid (tx1,txsigs1); end else begin DbBlacklist.dbput h true; DbTx.dbdelete h; DbTxSignatures.dbdelete h; end * * in some cases , failure should lead to blacklist and removal of the tx , but it 's not clear which cases ; if it 's in a block we might need to distinguish between definitely incorrect vs. possibly incorrect * * | Not_found -> Printf.fprintf !log "Problem with tx, deleting it\n"; flush !log; DbTx.dbdelete h; DbTxSignatures.dbdelete h; | e -> Printf.fprintf !log "exception %s\n" (Printexc.to_string e); flush !log; () let rec prev_nth_node i n = if i <= 0 then Some(n) else let BlocktreeNode(par,_,_,_,_,_,_,_,_,_,_,_,_) = n in match par with | None -> None | Some(p) -> prev_nth_node (i-1) p let update_bestnode n = Printf.fprintf !log "New best blockheader %s\n" (match node_prevblockhash n with Some(h) -> hashval_hexstring h | None -> "(genesis)"); flush !log; bestnode := n; netblkh := node_blockheight n; match !checkpointsprivkeyk with | None -> () | Some(k) -> match prev_nth_node 36 n with | Some(p) -> match node_prevblockhash p with | Some(h) -> Printf.fprintf !log "Creating new checkpoint %Ld %s\n" (node_blockheight p) (hashval_hexstring h); lastcheckpointnode := p; let pblkh = node_blockheight p in let r = rand_256() in let sg : signat = signat_hashval h k r in Hashtbl.add checkpoints h (pblkh,sg); broadcast_inv [(int_of_msgtype Checkpoint,pblkh,h)] let rec processdelayednodes tm btnl = match btnl with | (tm2,n2)::btnr when tm2 <= tm -> let BlocktreeNode(_,_,_,_,_,_,_,_,bestcumulstk,_,_,_,_) = !bestnode in let BlocktreeNode(_,_,pbh,_,_,_,_,_,newcumulstk,_,_,_,_) = n2 in if gt_big_int newcumulstk bestcumulstk then update_bestnode n2; processdelayednodes tm btnr | _ -> btnl let rec processblockvalidation vl = match vl with | [] -> [] | (v,f)::vr -> let vr2 = processblockvalidation vr in f(); match !v with | Waiting(_,_) -> (v,f)::vr2 | _ -> vr2 let rec is_recent_staker stkaddr n i = if i > 0 then begin let BlocktreeNode(par,stakers,_,_,_,_,_,_,_,_,_,_,_) = n in if List.mem stkaddr !stakers then true else match par with | Some(p) -> is_recent_staker stkaddr p (i-1) | _ -> false end else false let rec record_recent_staker stkaddr n i = if i > 0 then begin let BlocktreeNode(par,stakers,_,_,_,_,_,_,_,_,_,_,_) = n in stakers := stkaddr::!stakers; match par with | Some(p) -> record_recent_staker stkaddr p (i-1) | None -> () end let equ_tinfo (x,(y3,y2,y1,y0),z) (u,(v3,v2,v1,v0),w) = x = u && y3 = v3 && y2 = v2 && y1 = v1 && Int64.logand y0 (Int64.lognot 1L) = Int64.logand v0 (Int64.lognot 1L) && eq_big_int z w let rec validate_block_of_node newnode thyroot sigroot tinf blkhght h blkdel cs = let (blkhd,_) as blkh = DbBlockHeader.dbget h in let blk = (blkh,blkdel) in let BlocktreeNode(_,_,_,tr2,sr2,_,tinf2,_,newcumulstake,blkhght2,vs,_,chlr) = newnode in Printf.fprintf !log "About to check if block %s at height %Ld is valid\n" (hashval_hexstring h) blkhght; begin match valid_block (lookup_thytree thyroot) (lookup_sigtree sigroot) blkhght tinf blk with | Some(tht2,sigt2) -> vs := ValidBlock; Hashtbl.remove tovalidate h; DbBlockDelta.dbput h blkdel; let BlocktreeNode(_,_,_,_,_,_,_,_,bestcumulstk,_,_,_,_) = !bestnode in if gt_big_int newcumulstake bestcumulstk then update_bestnode newnode; add_thytree blkhd.newtheoryroot tht2; add_sigtree blkhd.newsignaroot sigt2; broadcast_inv [(int_of_msgtype Blockdelta,blkhght,h)]; begin let prevc = load_expanded_ctree (ctree_of_block blk) in * * is performed last , i.e. , after the txs in the block . * * match tx_octree_trans blkhght cstk (txl_octree_trans blkhght txl (Some(prevc))) with | Some(newc) -> ignore (save_ctree_elements newc) | None -> raise (Failure("transformed tree was empty, although block seemed to be valid")) end; List.iter (fun (h,n) -> let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,vs,_,_) = n in match !vs with | Waiting(_,Some(blkdel,cs)) -> validate_block_of_node n tr2 sr2 tinf2 blkhght2 h blkdel cs | _ -> ()) !chlr Printf.fprintf !log "Block delta for %s was not valid.\n" (hashval_hexstring h); let tm = Unix.time() in cs.banned <- true; Hashtbl.add bannedpeers cs.addrfrom (); vs := Waiting(tm,None) end else raise (Failure("parent was validated but thyroot and/or sigroot is not known"));; let rec process_new_header_a h hh blkh1 blkhd1 initialization knownvalid = try process_new_header_aa h hh blkh1 blkhd1 (blockheader_stakeasset blkhd1) initialization knownvalid with | HeaderStakedAssetNotMin -> Printf.fprintf !log "Header %s has extra information beyong supporting staked asset; should have been caught before process_new_header_a\n" hh; raise (Failure "header does not only support staked asset") | HeaderNoStakedAsset -> Printf.fprintf !log "Header %s does not support staked asset; should have been caught before process_new_header_a\n" hh; raise (Failure "header does not support staked asset") and process_new_header_aa h hh blkh1 blkhd1 a initialization knownvalid = if valid_blockheader_signat blkh1 a then process_new_header_ab h hh blkh1 blkhd1 a initialization knownvalid else begin Printf.fprintf !log "Header %s has an invalid siagnure; should have been caught before process_new_header_aa\n" hh; raise (Failure "header has invalid signature") end and process_new_header_ab h hh blkh1 blkhd1 a initialization knownvalid = let prevblkh = blkhd1.prevblockhash in begin try let prevnode = Hashtbl.find blkheadernode prevblkh in begin try let BlocktreeNode(_,_,_,thyroot,sigroot,ledgerroot,currtinfo,tmstamp,prevcumulstk,blkhght,validated,blacklisted,succl) = prevnode in begin Printf.fprintf !log "Header %s is child of blacklisted node; deleting and blacklisting it.\n" hh; DbBlacklist.dbput h true; DbBlockHeader.dbdelete h; end else if valid_blockheader blkhght currtinfo blkh1 && blockheader_succ_a ledgerroot tmstamp currtinfo blkh1 then begin Printf.fprintf !log "bhsa %s %Ld %s %b\n" (hashval_hexstring ledgerroot) tmstamp (targetinfo_string currtinfo) (blockheader_succ_a ledgerroot tmstamp currtinfo blkh1); if not (DbBlockHeader.dbexists h) then DbBlockHeader.dbput h blkh1; Hashtbl.add blkheaders h (); broadcast_inv [(int_of_msgtype Headers,blkhght,h)]; let (csm1,fsm1,tar1) = currtinfo in let newcumulstake = cumul_stake prevcumulstk tar1 blkhd1.deltatime in let validated = ref (if knownvalid then ValidBlock else Waiting(Unix.time(),None)) in let newnode = BlocktreeNode(Some(prevnode),ref [blkhd1.stakeaddr],Some(h),blkhd1.newtheoryroot,blkhd1.newsignaroot,blkhd1.newledgerroot,blkhd1.tinfo,blkhd1.timestamp,newcumulstake,Int64.add blkhght 1L,validated,ref false,ref []) in Hashtbl.add blkheadernode (Some(h)) newnode; succl := (h,newnode)::!succl; record_recent_staker blkhd1.stakeaddr prevnode 6; begin try let blkdel = DbBlockDelta.dbget h in let blk = (blkh1,blkdel) in begin match valid_block (lookup_thytree thyroot) (lookup_sigtree sigroot) blkhght currtinfo blk with | Some(_,_) -> validated := ValidBlock DbBlockDelta.dbdelete h; Hashtbl.add tovalidate h (); try find_and_send_requestdata GetBlockdelta h with Not_found -> Printf.fprintf !log "No source for block delta of %s; must wait until it is explicitly requested\n" hh end else raise (Failure "unknown thyroot or sigroot while trying to validate block") with Not_found -> Hashtbl.add tovalidate h (); try find_and_send_requestdata GetBlockdelta h with Not_found -> Printf.fprintf !log "No source for block delta of %s\n" hh end; earlyblocktreenodes := insertnewdelayed (tmstamp,newnode) !earlyblocktreenodes else let BlocktreeNode(_,_,_,_,_,_,_,_,bestcumulstk,_,_,_,_) = !bestnode in if gt_big_int newcumulstake bestcumulstk then update_bestnode newnode; List.iter (fun (h,blkh1) -> let (blkhd1,_) = blkh1 in process_new_header_a h (hashval_hexstring h) blkh1 blkhd1 initialization knownvalid) (Hashtbl.find_all orphanblkheaders (Some(h))); Hashtbl.remove orphanblkheaders (Some(h)) end else Printf.fprintf !log "Header %s was invalid, deleting and blacklisting it.\n" hh; Printf.fprintf !log "vbh %Ld %s %b\n" blkhght (targetinfo_string currtinfo) (valid_blockheader blkhght currtinfo blkh1); Printf.fprintf !log "bhsa %s %Ld %s %b\n" (hashval_hexstring ledgerroot) tmstamp (targetinfo_string currtinfo) (blockheader_succ_a ledgerroot tmstamp currtinfo blkh1); Hashtbl.add blkheadernode (Some(h)) newnode; DbBlacklist.dbput h true; DbBlockHeader.dbdelete h; end with Not_found -> Printf.fprintf !log "unexpected Not_found in process_new_header_a %s\n" hh; raise (Failure "unexpected Not_found in process_new_header_a") end Hashtbl.add orphanblkheaders prevblkh (h,blkh1); try find_and_send_requestdata GetHeader h with Not_found -> Printf.fprintf !log "no peer has parent header %s\n" hh end and process_new_header_b h hh initialization knownvalid = Printf.fprintf !log "Processing new header %s\n" hh; flush !log; try let blkh1 = DbBlockHeader.dbget h in let (blkhd1,blkhs1) = blkh1 in begin Printf.fprintf !log "WARNING: Block header in database has different hash than key, removing %s\nThis must be due to a bug.\n" hh; flush !log; DbBlockHeader.dbdelete h end else process_new_header_a h hh blkh1 blkhd1 initialization knownvalid | Not_found -> Printf.fprintf !log "Problem with blockheader %s, deleting it\n" hh; flush !log; DbBlockHeader.dbdelete h | e -> Printf.fprintf !log "exception %s\n" (Printexc.to_string e); flush !log; () and process_new_header h hh initialization knownvalid = if not (Hashtbl.mem blkheaders h) then process_new_header_b h hh initialization knownvalid let init_headers () = DbBlockHeader.dbkeyiter (fun h -> let hs = hashval_hexstring h in Printf.printf "processing header %s\n" hs; flush stdout; process_new_header h hs true false) let initblocktree () = genesisblocktreenode := BlocktreeNode(None,ref [],None,None,None,!genesisledgerroot,(!genesiscurrentstakemod,!genesisfuturestakemod,!genesistarget),!Config.genesistimestamp,zero_big_int,1L,ref ValidBlock,ref false,ref []); lastcheckpointnode := !genesisblocktreenode; update_bestnode !genesisblocktreenode; Hashtbl.add blkheadernode None !genesisblocktreenode; init_headers() let rec find_best_validated_block_from fromnode bestn bestcumulstk = let BlocktreeNode(_,_,_,_,_,_,_,_,cumulstk,_,validatedp,blklistp,succl) = fromnode in if not !blklistp && !validatedp = ValidBlock then begin let newbestn = ref (if gt_big_int cumulstk bestcumulstk then fromnode else bestn) in let newbestcumulstk = ref (node_cumulstk !newbestn) in List.iter (fun (_,childnode) -> let (bn,bcs) = find_best_validated_block_from childnode !newbestn !newbestcumulstk in newbestn := bn; newbestcumulstk := bcs) !succl; (!newbestn,!newbestcumulstk) end else (bestn,bestcumulstk) let find_best_validated_block () = let (bn,bcs) = find_best_validated_block_from !lastcheckpointnode !lastcheckpointnode (node_cumulstk !lastcheckpointnode) in update_bestnode bn let rec blacklist_from h n = let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,_,blklstd,chl) = n in blklstd := true; DbBlacklist.dbput h true; DbBlockHeader.dbdelete h; List.iter (fun (k,c) -> blacklist_from k c) !chl let publish_stx txh stx1 = let (tx1,txsigs1) = stx1 in if not (Hashtbl.mem stxpool txh) then Hashtbl.add stxpool txh stx1; DbTx.dbput txh tx1; DbTxSignatures.dbput txh txsigs1; Hashtbl.add published_stx txh (); broadcast_inv [(int_of_msgtype STx,0L,txh)] let publish_block blkh bhh (bh,bd) = Printf.fprintf !log "publishing block %s\n" (hashval_hexstring bhh); flush !log; DbBlockHeader.dbput bhh bh; DbBlockDelta.dbput bhh bd; broadcast_inv [(int_of_msgtype Headers,blkh,bhh);(int_of_msgtype Blockdelta,blkh,bhh)];; Hashtbl.add msgtype_handler GetHeader (fun (sin,sout,cs,ms) -> let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetHeader in try let bh = DbBlockHeader.dbget h in let s = Buffer.create 1000 in seosbf (seo_blockheader seosb bh (seo_hashval seosb h (seo_int8 seosb 1 (s,None)))); cs.sentinv <- (i,h)::cs.sentinv; let ss = Buffer.contents s in ignore (queue_msg cs Headers ss) with Not_found -> ());; Hashtbl.add msgtype_handler GetHeaders (fun (sin,sout,cs,ms) -> let c = ref (ms,String.length ms,None,0,0) in let m = ref 0 in let bhl = ref [] in * * peers can request at most 255 headers at a time * c := cn; let i = int_of_msgtype GetHeader in for j = 1 to n do let (h,cn) = sei_hashval seis !c in c := cn; try let bh = DbBlockHeader.dbget h in incr m; bhl := (h,bh)::!bhl; cs.sentinv <- (i,h)::cs.sentinv with Not_found -> () done; let s = Buffer.create 10000 in let co = ref (seo_int8 seosb !m (s,None)) in List.iter (fun (h,bh) -> co := seo_blockheader seosb bh (seo_hashval seosb h !co)) !bhl; seosbf !co; let ss = Buffer.contents s in ignore (queue_msg cs Headers ss) );; Hashtbl.add msgtype_handler Headers (fun (sin,sout,cs,ms) -> let c = ref (ms,String.length ms,None,0,0) in * * peers can request at most 255 headers at a time * c := cn; let i = int_of_msgtype GetHeader in for j = 1 to n do let (h,cn) = sei_hashval seis !c in c := cn; let s = Buffer.create 10000 in seosbf (seo_blockheader seosb bh (s,None)); Printf.fprintf !log "got blockheader %s:\n%s\n" (hashval_hexstring h) (Hashaux.string_hexstring (Buffer.contents s)); end; if not (DbBlockHeader.dbexists h) && List.mem (i,h) cs.invreq then let (bhd,bhs) = bh in if not (hash_blockheaderdata bhd = h) then Printf.fprintf !log "got a header with the wrong hash, dropping it and banning node\n"; flush !log; cs.banned <- true end else begin try let a = blockheader_stakeasset bhd in if not (valid_blockheader_signat (bhd,bhs) a) then Printf.fprintf !log "got a header with an invalid signature, dropping it and banning node\n"; flush !log; cs.banned <- true end else process_new_header_ab h (hashval_hexstring h) bh bhd a false false with begin Printf.fprintf !log "header does not only have the staked asset; blacklisting it and banning node\n"; flush !log; cs.banned <- true end begin Printf.fprintf !log "header does not have the staked asset; blacklisting it and banning node\n"; flush !log; cs.banned <- true end end done);; let req_headers sout cs m nw = if m > 0 then begin let s = Buffer.create 1000 in let co = ref (seo_int8 seosb m (s,None)) in List.iter (fun h -> co := seo_hashval seosb h !co) nw; seosbf !co; Printf.fprintf !log "req_headers requesting:"; List.iter (fun h -> Printf.fprintf !log " %s" (hashval_hexstring h)) nw; Printf.fprintf !log "\n"; ignore (queue_msg cs GetHeaders (Buffer.contents s)) end;; let rec req_header_batches sout cs m hl nw = Printf.fprintf !log "rhb %d\n" m; if m = 255 then (req_headers sout cs m nw; req_header_batches sout cs 0 hl []) else match hl with | (_,h)::hr -> let i = int_of_msgtype GetHeader in cs.invreq <- (i,h)::cs.invreq; req_header_batches sout cs (m+1) hr (h::nw) | [] -> req_headers sout cs m nw;; Hashtbl.add msgtype_handler Inv (fun (sin,sout,cs,ms) -> let c = ref (ms,String.length ms,None,0,0) in let hl = ref [] in let (n,cn) = sei_int32 seis !c in Printf.fprintf !log "Inv %ld\n" n; c := cn; for j = 1 to Int32.to_int n do let ((i,blkh,h),cn) = sei_prod3 sei_int8 sei_int64 sei_hashval seis !c in Printf.fprintf !log "%d %Ld %s\n" i blkh (hashval_hexstring h); c := cn; cs.rinv <- (i,h)::cs.rinv; if i = int_of_msgtype Headers then Printf.fprintf !log "Headers, dbexists %b, archived %b\n" (DbBlockHeader.dbexists h) (DbArchived.dbexists h); if i = int_of_msgtype Headers && not (DbArchived.dbexists h) then begin try let bh = DbBlockHeader.dbget h in if not (Hashtbl.mem blkheadernode (Some(h))) then let (bhd,_) = bh in process_new_header_a h (hashval_hexstring h) bh bhd false false with Not_found -> Printf.fprintf !log "i %d blkh %Ld h %s hl:\n" i blkh (hashval_hexstring h); List.iter (fun (blkh1,h1) -> Printf.fprintf !log "%Ld %s\n" blkh1 (hashval_hexstring h)) !hl end else if i = int_of_msgtype Blockdelta && not (DbBlockDelta.dbexists h) && not (DbArchived.dbexists h) && Hashtbl.mem tovalidate h then begin try cs.invreq <- (int_of_msgtype GetBlockdelta,h)::cs.invreq; let s = Buffer.create 1000 in seosbf (seo_hashval seosb h (s,None)); Printf.fprintf !log "Immediately requesting blockdelta %s\n" (hashval_hexstring h); ignore (queue_msg cs GetBlockdelta (Buffer.contents s)) with exn -> Printf.fprintf !log "inv blockdelta %s\n" (Printexc.to_string exn) end else if i = int_of_msgtype STx && not (DbArchived.dbexists h) then begin if DbTx.dbexists h then if not (DbTxSignatures.dbexists h) then begin cs.invreq <- (int_of_msgtype GetTxSignatures,h)::cs.invreq; let s = Buffer.create 1000 in seosbf (seo_hashval seosb h (s,None)); ignore (queue_msg cs GetTxSignatures (Buffer.contents s)) end else () else begin cs.invreq <- (int_of_msgtype GetTx,h)::cs.invreq; let s = Buffer.create 1000 in seosbf (seo_hashval seosb h (s,None)); ignore (queue_msg cs GetTx (Buffer.contents s)) end end else if i = int_of_msgtype Checkpoint then try let lcp = !lastcheckpointnode in let BlocktreeNode(par,_,_,_,_,_,_,_,_,lcpblkh,_,_,_) = lcp in if lcpblkh < blkh then raise Exit else let lcpp = prev_nth_node (Int64.to_int (Int64.sub lcpblkh blkh)) lcp in match lcpp with | None -> raise Exit | Some(lcppn) -> match node_prevblockhash lcppn with | None -> raise Exit | Some(lcppnh) -> if not (lcppnh = h) then raise Exit * * if Exit was raised , then we need the checkpoint * * cs.invreq <- (int_of_msgtype GetCheckpoint,h)::cs.invreq; let s = Buffer.create 1000 in seosbf (seo_hashval seosb h (s,None)); ignore (queue_msg cs GetCheckpoint (Buffer.contents s)) end done; req_header_batches sout cs 0 !hl []);; Hashtbl.add msgtype_handler GetBlockdelta (fun (sin,sout,cs,ms) -> Printf.fprintf !log "Processing GetBlockdelta\n"; let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in Printf.fprintf !log "Processing GetBlockdelta %s\n" (hashval_hexstring h); let i = int_of_msgtype GetBlockdelta in try let blkdel = DbBlockDelta.dbget h in let bdsb = Buffer.create 100 in seosbf (seo_blockdelta seosb blkdel (seo_hashval seosb h (bdsb,None))); let bdser = Buffer.contents bdsb in Printf.fprintf !log "Sending Block Delta (from db) %s\n" (hashval_hexstring h); ignore (queue_msg cs Blockdelta bdser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> Printf.fprintf !log "Unknown Block Delta %s (Bad Peer or Did I Advertize False Inventory?)\n" (hashval_hexstring h); ());; Hashtbl.add msgtype_handler Blockdelta (fun (sin,sout,cs,ms) -> let (h,r) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetBlockdelta in begin try cs.invreq <- List.filter (fun (j,k) -> not (i = j && h = k)) cs.invreq; let BlocktreeNode(par,_,_,_,_,_,_,_,_,_,vs,_,chlr) as newnode = Hashtbl.find blkheadernode (Some(h)) in match !vs with | Waiting(tm,None) -> begin match par with let (blkdel,_) = sei_blockdelta seis r in let s = Buffer.create 10000 in seosbf (seo_blockdelta seosb blkdel (s,None)); Printf.fprintf !log "got blockdelta %s:\n%s\n" (hashval_hexstring h) (Hashaux.string_hexstring (Buffer.contents s)); end; validate_block_of_node newnode None None (!genesiscurrentstakemod,!genesisfuturestakemod,!genesistarget) 1L h blkdel cs | Some(BlocktreeNode(_,_,_,thyroot,sigroot,_,tinf,_,_,blkhght,vsp,_,_)) -> match !vsp with | Waiting(_,_) -> let (blkdel,_) = sei_blockdelta seis r in let s = Buffer.create 10000 in seosbf (seo_blockdelta seosb blkdel (s,None)); Printf.fprintf !log "got blockdelta %s, waiting for parent block to be validated:\n%s\n" (hashval_hexstring h) (Hashaux.string_hexstring (Buffer.contents s)); end; begin let (blkdel,_) = sei_blockdelta seis r in let s = Buffer.create 10000 in seosbf (seo_blockdelta seosb blkdel (s,None)); Printf.fprintf !log "got blockdelta %s:\n%s\n" (hashval_hexstring h) (Hashaux.string_hexstring (Buffer.contents s)); end; validate_block_of_node newnode thyroot sigroot tinf blkhght h blkdel cs end end | _ -> () with Not_found -> () end);; Hashtbl.add msgtype_handler GetTx (fun (sin,sout,cs,ms) -> Printf.fprintf !log "Processing GetTx\n"; let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in Printf.fprintf !log "Processing GetTx %s\n" (hashval_hexstring h); let i = int_of_msgtype GetTx in try let (tau,_) = Hashtbl.find stxpool h in let tausb = Buffer.create 100 in seosbf (seo_tx seosb tau (seo_hashval seosb h (tausb,None))); let tauser = Buffer.contents tausb in Printf.fprintf !log "Sending Tx (from pool) %s\n" (hashval_hexstring h); ignore (queue_msg cs Tx tauser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> try let tau = DbTx.dbget h in let tausb = Buffer.create 100 in seosbf (seo_tx seosb tau (seo_hashval seosb h (tausb,None))); let tauser = Buffer.contents tausb in Printf.fprintf !log "Sending Tx (from db) %s\n" (hashval_hexstring h); ignore (queue_msg cs Tx tauser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> Printf.fprintf !log "Unknown Tx %s\n" (hashval_hexstring h); ());; Hashtbl.add msgtype_handler Tx (fun (sin,sout,cs,ms) -> let (h,r) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetTx in let (tau,_) = sei_tx seis r in if hashtx tau = h then begin DbTx.dbput h tau; cs.invreq <- List.filter (fun (j,k) -> not (i = j && h = k)) cs.invreq end (Printf.fprintf !Utils.log "misbehaving peer? [malformed Tx]\n"; flush !Utils.log) (Printf.fprintf !Utils.log "misbehaving peer? [unrequested Tx]\n"; flush !Utils.log));; Hashtbl.add msgtype_handler GetTxSignatures (fun (sin,sout,cs,ms) -> let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in Printf.fprintf !log "Processing GetTxSignatures %s\n" (hashval_hexstring h); let i = int_of_msgtype GetTxSignatures in try let (_,s) = Hashtbl.find stxpool h in let ssb = Buffer.create 100 in seosbf (seo_txsigs seosb s (seo_hashval seosb h (ssb,None))); let sser = Buffer.contents ssb in Printf.fprintf !log "Sending TxSignatures (from pool) %s\n" (hashval_hexstring h); ignore (queue_msg cs TxSignatures sser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> try let s = DbTxSignatures.dbget h in let ssb = Buffer.create 100 in seosbf (seo_txsigs seosb s (seo_hashval seosb h (ssb,None))); let sser = Buffer.contents ssb in Printf.fprintf !log "Sending TxSignatures (from db) %s\n" (hashval_hexstring h); ignore (queue_msg cs TxSignatures sser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> Printf.fprintf !log "Unknown TxSignatures %s\n" (hashval_hexstring h); ());; Hashtbl.add msgtype_handler TxSignatures (fun (sin,sout,cs,ms) -> let (h,r) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetTxSignatures in try let ((tauin,_) as tau) = DbTx.dbget h in let (s,_) = sei_txsigs seis r in try let al = List.map (fun (_,aid) -> DbAsset.dbget aid) tauin in Hashtbl.add stxpool h (tau,s); DbTxSignatures.dbput h s; cs.invreq <- List.filter (fun (j,k) -> not (i = j && h = k)) cs.invreq with (Printf.fprintf !Utils.log "misbehaving peer? [malformed TxSignatures]\n"; flush !Utils.log) () (Printf.fprintf !Utils.log "misbehaving peer? [unrequested TxSignatures]\n"; flush !Utils.log) * * do not know the tx , so drop the sig * * ());; let dumpblocktreestate sa = Printf.fprintf sa "=========\nstxpool:\n"; Hashtbl.iter (fun h ((tauin,tauout) as tau,tausg) -> Printf.fprintf sa "- tx %s\n" (hashval_hexstring (hashtx tau)); Printf.fprintf sa "inputs %d\n" (List.length tauin); let c = ref 0 in List.iter (fun (alpha,aid) -> Printf.fprintf sa "%d. %s %s\n" !c (Cryptocurr.addr_qedaddrstr alpha) (hashval_hexstring aid); incr c) tauin; Printf.fprintf sa "outputs %d\n" (List.length tauin); c := 0; List.iter (fun (alpha,(obl,u)) -> Printf.fprintf sa "%d. %s %s %s\n" !c (Cryptocurr.addr_qedaddrstr alpha) (obligation_string obl) (preasset_string u); incr c) tauout; let sb = Buffer.create 100 in seosbf (seo_stx seosb (tau,tausg) (sb,None)); Printf.fprintf sa "%s\n" (string_hexstring (Buffer.contents sb)) ) stxpool; Printf.fprintf sa "=========\npublished_stx:\n"; Hashtbl.iter (fun h () -> Printf.fprintf sa "- tx %s\n" (hashval_hexstring h)) published_stx; Printf.fprintf sa "=========\nthytree:\n"; Hashtbl.iter (fun h _ -> Printf.fprintf sa "- thytree root %s\n" (hashval_hexstring h)) thytree; Printf.fprintf sa "=========\nsigtree:\n"; Hashtbl.iter (fun h _ -> Printf.fprintf sa "- sigtree root %s\n" (hashval_hexstring h)) sigtree; Printf.fprintf sa "=========\nblkheaders:\n"; Hashtbl.iter (fun h _ -> Printf.fprintf sa "- blk %s\n" (hashval_hexstring h)) blkheaders; Printf.fprintf sa "=========\nblkheadernode:\n"; Hashtbl.iter (fun h (BlocktreeNode(_,rs,pbh,tr,sr,lr,((csm3,csm2,csm1,csm0),(fsm3,fsm2,fsm1,fsm0),tar),tm,cs,blkh,vs,bl,chr)) -> Printf.fprintf sa "- blk %s node:\n" (match h with Some(h) -> hashval_hexstring h | None -> "[genesis]"); Printf.fprintf sa "recentstakers:\n"; List.iter (fun k -> Printf.fprintf sa "%s\n" (hashval_hexstring k)) !rs; Printf.fprintf sa "prevblockhash: %s\n" (match pbh with Some(h) -> hashval_hexstring h | None -> "[genesis]"); Printf.fprintf sa "theory tree root: %s\n" (match tr with Some(h) -> hashval_hexstring h | None -> "[empty]"); Printf.fprintf sa "sig tree root: %s\n" (match sr with Some(h) -> hashval_hexstring h | None -> "[empty]"); Printf.fprintf sa "ledger tree root: %s\n" (hashval_hexstring lr); Printf.fprintf sa "targetinfo:\ncsm %Lx %Lx %Lx %Lx\nfsm %Lx %Lx %Lx %Lx\ntar %s\n" csm3 csm2 csm1 csm0 fsm3 fsm2 fsm1 fsm0 (string_of_big_int tar); Printf.fprintf sa "timestamp: %Ld\n" tm; Printf.fprintf sa "cumulative stake: %s\n" (string_of_big_int cs); Printf.fprintf sa "block height: %Ld\n" blkh; Printf.fprintf sa "validation status: %s\n" (match !vs with Waiting(tm,None) -> "Waiting " ^ string_of_float tm | Waiting(tm,Some(_)) -> "Waiting for parent " ^ string_of_float tm | ValidBlock -> "Valid" | InvalidBlock -> "Invalid"); if !bl then Printf.fprintf sa "*blacklisted*\n"; Printf.fprintf sa "children nodes: %d\n" (List.length !chr); List.iter (fun (h,_) -> Printf.fprintf sa "%s\n" (hashval_hexstring h)) !chr) blkheadernode; Printf.fprintf sa "=========\norphanblkheaders:\n"; Hashtbl.iter (fun h (k,bh) -> Printf.fprintf sa "- orphan blk %s waiting for %s\n" (hashval_hexstring k) (match h with Some(h) -> hashval_hexstring h | None -> "[genesis?]"); let sb = Buffer.create 100 in seosbf (seo_blockheader seosb bh (sb,None)); Printf.fprintf sa "%s\n" (string_hexstring (Buffer.contents sb))) orphanblkheaders; Printf.fprintf sa "=========\nearlyblocktreenodes:\n"; List.iter (fun (futuretm,BlocktreeNode(_,rs,pbh,tr,sr,lr,((csm3,csm2,csm1,csm0),(fsm3,fsm2,fsm1,fsm0),tar),tm,cs,blkh,vs,bl,chr)) -> Printf.fprintf sa "future timestamp: %Ld\n" futuretm; Printf.fprintf sa "recentstakers:\n"; List.iter (fun k -> Printf.fprintf sa "%s\n" (hashval_hexstring k)) !rs; Printf.fprintf sa "prevblockhash: %s\n" (match pbh with Some(h) -> hashval_hexstring h | None -> "[genesis]"); Printf.fprintf sa "theory tree root: %s\n" (match tr with Some(h) -> hashval_hexstring h | None -> "[empty]"); Printf.fprintf sa "sig tree root: %s\n" (match sr with Some(h) -> hashval_hexstring h | None -> "[empty]"); Printf.fprintf sa "ledger tree root: %s\n" (hashval_hexstring lr); Printf.fprintf sa "targetinfo:\ncsm %Lx %Lx %Lx %Lx\nfsm %Lx %Lx %Lx %Lx\ntar %s\n" csm3 csm2 csm1 csm0 fsm3 fsm2 fsm1 fsm0 (string_of_big_int tar); Printf.fprintf sa "timestamp: %Ld\n" tm; Printf.fprintf sa "cumulative stake: %s\n" (string_of_big_int cs); Printf.fprintf sa "block height: %Ld\n" blkh; Printf.fprintf sa "validation status: %s\n" (match !vs with Waiting(tm,None) -> "Waiting " ^ string_of_float tm | Waiting(tm,Some(_)) -> "Waiting for parent " ^ string_of_float tm | ValidBlock -> "Valid" | InvalidBlock -> "Invalid"); if !bl then Printf.fprintf sa "*blacklisted*\n"; Printf.fprintf sa "children nodes: %d\n" (List.length !chr); List.iter (fun (h,_) -> Printf.fprintf sa "%s\n" (hashval_hexstring h)) !chr) !earlyblocktreenodes; Printf.fprintf sa "=========\ntovalidate:\n"; Hashtbl.iter (fun h () -> Printf.fprintf sa "%s\n" (hashval_hexstring h)) tovalidate;; Hashtbl.add msgtype_handler GetCheckpoint (fun (sin,sout,cs,ms) -> let (h,_) = sei_hashval seis (ms,String.length ms,None,0,0) in let i = int_of_msgtype GetCheckpoint in try let (chblkh,chsg) = Hashtbl.find checkpoints h in let sb = Buffer.create 100 in seosbf (seo_signat seosb chsg (seo_int64 seosb chblkh (seo_hashval seosb h (sb,None)))); let ser = Buffer.contents sb in Printf.fprintf !log "Sending Checkpoint %s\n" (hashval_hexstring h); ignore (queue_msg cs Checkpoint ser); cs.sentinv <- (i,h)::cs.sentinv with Not_found -> Printf.fprintf !log "Unknown Checkpoint %s (Bad Peer or Did I Advertize False Inventory?)\n" (hashval_hexstring h); ());; Hashtbl.add msgtype_handler Checkpoint (fun (sin,sout,cs,ms) -> Printf.fprintf !log "Processing Checkpoint\n"; let (h,r) = sei_hashval seis (ms,String.length ms,None,0,0) in let (blkh,r) = sei_int64 seis r in Printf.fprintf !log "Processing Checkpoint %Ld %s\n" blkh (hashval_hexstring h); let (sg,_) = sei_signat seis r in if Signat.verify_signed_hashval h (Some(checkpointspubkeyx,checkpointspubkeyy)) sg then begin Hashtbl.add checkpoints h (blkh,sg); if DbBlacklist.dbexists h then begin Printf.fprintf !log "Checkpoint %s was blacklisted; removing the blacklist.\n" (hashval_hexstring h); DbBlacklist.dbdelete h end; try let n = Hashtbl.find blkheadernode (Some(h)) in let BlocktreeNode(par,_,_,_,_,_,_,_,_,_,vs,blklstd,_) = n in begin match par with | None -> () | Some(p) -> let BlocktreeNode(_,_,_,_,_,_,_,_,_,_,_,_,chl) = p in List.iter (fun (k,c) -> if not (k = h) then blacklist_from k c ) !chl end; if !blklstd then blklstd := false; if not (!vs = ValidBlock) then vs := ValidBlock; lastcheckpointnode := n; find_best_validated_block(); broadcast_inv [(int_of_msgtype Checkpoint,node_blockheight n,h)] with Not_found -> try let bh = DbBlockHeader.dbget h in let (bhd,bhs) = bh in * * just drop the cumul stake back to zero because I do n't know it here * * Hashtbl.add blkheadernode (Some(h)) fnode; Hashtbl.remove orphanblkheaders (Some(h)); lastcheckpointnode := fnode; update_bestnode fnode with Not_found -> Printf.fprintf !log "Unknown header %s, trying to request it.\n" (hashval_hexstring h); try find_and_send_requestdata Headers h with Not_found -> Printf.fprintf !log "No peer willing to send header was found %s\n" (hashval_hexstring h) end else Printf.fprintf !log "Bad signature on checkpoint\n%s\n" (string_hexstring ms));;
d61ca3902159134f81c6b1411fc777801a3d0d2e29dabbd442f566c979dfcf0c
renatoalencar/ocaml-socks-client
test_socks4.ml
open Socks let test_socks4_connect_ip_address () = let request = Socks4.Request.connect (`IPv4 (Ipaddr.V4.of_string_exn "192.168.0.1")) 80 in let buf = Socks4.Request.to_string request in Alcotest.(check string) "Request should match" buf "\004\001\000\080\192\168\000\001\000" let test_socks4_bind_ip_address () = let request = Socks4.Request.bind (`IPv4 (Ipaddr.V4.of_string_exn "192.168.0.1")) 80 in let buf = Socks4.Request.to_string request in Alcotest.(check string) "Request should match" buf "\004\002\000\080\192\168\000\001\000" let test_socks4a_connect_domain_name () = let request = Socks4.Request.connect (`Domain "ocaml.org") 80 in let buf = Socks4.Request.to_string request in Alcotest.(check string) "Request should match" buf "\004\001\000\080\000\000\000\001\000ocaml.org\000" let test_socks4a_bind_domain_name () = let request = Socks4.Request.bind (`Domain "ocaml.org") 80 in let buf = Socks4.Request.to_string request in Alcotest.(check string) "Request should match" buf "\004\002\000\080\000\000\000\001\000ocaml.org\000" let code = let format_code = function | `RequestGranted -> "RequestGranted" | `RequestFailed -> "RequestFailed" | `RequestRejectedIdentd -> "RequestRejectedIdentd" | `UserIdNotMatching -> "UserIdNotMatching" in let compare a b = match a, b with | (`RequestGranted, `RequestGranted) | (`RequestFailed, `RequestFailed) | (`RequestRejectedIdentd, `RequestRejectedIdentd) | (`UserIdNotMatching, `UserIdNotMatching) -> true | _ -> false in let pp_code ppf x = Fmt.pf ppf "%s" (format_code x) in Alcotest.testable pp_code compare let test_socks4_response_success () = let response = Socks4.Response.of_string "\000\090\000\080\192\168\000\001" in Alcotest.(check string) "Parse IP address" (Ipaddr.V4.to_string response.ip) "192.168.0.1"; Alcotest.(check int) "Parse port" response.port 80; Alcotest.(check code) "Parse code" response.code `RequestGranted let test_socks4_response_failed () = let response = Cstruct.of_string "\000\091\000\080\192\168\000\001" in let response = Socks4.Response.of_cstruct response in Alcotest.(check string) "Parse IP address" (Ipaddr.V4.to_string response.ip) "192.168.0.1"; Alcotest.(check int) "Parse port" response.port 80; Alcotest.(check code) "Parse code" response.code `RequestFailed let test_socks4_response_identd () = let response = Cstruct.of_string "\000\092\000\080\192\168\000\001" in let response = Socks4.Response.of_cstruct response in Alcotest.(check string) "Parse IP address" (Ipaddr.V4.to_string response.ip) "192.168.0.1"; Alcotest.(check int) "Parse port" response.port 80; Alcotest.(check code) "Parse code" response.code `RequestRejectedIdentd let test_socks4_response_userid () = let response = Cstruct.of_string "\000\093\000\080\192\168\000\001" in let response = Socks4.Response.of_cstruct response in Alcotest.(check string) "Parse IP address" (Ipaddr.V4.to_string response.ip) "192.168.0.1"; Alcotest.(check int) "Parse port" response.port 80; Alcotest.(check code) "Parse code" response.code `UserIdNotMatching let () = let open Alcotest in run "Socks4" [ "Request", [ test_case "SOCKS4 connect request" `Quick test_socks4_connect_ip_address ; test_case "SOCKS4 bind request" `Quick test_socks4_bind_ip_address ; test_case "SOCKS4a connect with domain name" `Quick test_socks4a_connect_domain_name ; test_case "SOCKS4a bind request with domain name" `Quick test_socks4a_bind_domain_name ]; "Response", [ test_case "Request granted" `Quick test_socks4_response_success ; test_case "Request rejected" `Quick test_socks4_response_failed ; test_case "Request rejected identd" `Quick test_socks4_response_identd ; test_case "User ID not matching" `Quick test_socks4_response_userid ] ]
null
https://raw.githubusercontent.com/renatoalencar/ocaml-socks-client/1acef3e07123483f6ea571387029930684120be1/tests/test_socks4.ml
ocaml
open Socks let test_socks4_connect_ip_address () = let request = Socks4.Request.connect (`IPv4 (Ipaddr.V4.of_string_exn "192.168.0.1")) 80 in let buf = Socks4.Request.to_string request in Alcotest.(check string) "Request should match" buf "\004\001\000\080\192\168\000\001\000" let test_socks4_bind_ip_address () = let request = Socks4.Request.bind (`IPv4 (Ipaddr.V4.of_string_exn "192.168.0.1")) 80 in let buf = Socks4.Request.to_string request in Alcotest.(check string) "Request should match" buf "\004\002\000\080\192\168\000\001\000" let test_socks4a_connect_domain_name () = let request = Socks4.Request.connect (`Domain "ocaml.org") 80 in let buf = Socks4.Request.to_string request in Alcotest.(check string) "Request should match" buf "\004\001\000\080\000\000\000\001\000ocaml.org\000" let test_socks4a_bind_domain_name () = let request = Socks4.Request.bind (`Domain "ocaml.org") 80 in let buf = Socks4.Request.to_string request in Alcotest.(check string) "Request should match" buf "\004\002\000\080\000\000\000\001\000ocaml.org\000" let code = let format_code = function | `RequestGranted -> "RequestGranted" | `RequestFailed -> "RequestFailed" | `RequestRejectedIdentd -> "RequestRejectedIdentd" | `UserIdNotMatching -> "UserIdNotMatching" in let compare a b = match a, b with | (`RequestGranted, `RequestGranted) | (`RequestFailed, `RequestFailed) | (`RequestRejectedIdentd, `RequestRejectedIdentd) | (`UserIdNotMatching, `UserIdNotMatching) -> true | _ -> false in let pp_code ppf x = Fmt.pf ppf "%s" (format_code x) in Alcotest.testable pp_code compare let test_socks4_response_success () = let response = Socks4.Response.of_string "\000\090\000\080\192\168\000\001" in Alcotest.(check string) "Parse IP address" (Ipaddr.V4.to_string response.ip) "192.168.0.1"; Alcotest.(check int) "Parse port" response.port 80; Alcotest.(check code) "Parse code" response.code `RequestGranted let test_socks4_response_failed () = let response = Cstruct.of_string "\000\091\000\080\192\168\000\001" in let response = Socks4.Response.of_cstruct response in Alcotest.(check string) "Parse IP address" (Ipaddr.V4.to_string response.ip) "192.168.0.1"; Alcotest.(check int) "Parse port" response.port 80; Alcotest.(check code) "Parse code" response.code `RequestFailed let test_socks4_response_identd () = let response = Cstruct.of_string "\000\092\000\080\192\168\000\001" in let response = Socks4.Response.of_cstruct response in Alcotest.(check string) "Parse IP address" (Ipaddr.V4.to_string response.ip) "192.168.0.1"; Alcotest.(check int) "Parse port" response.port 80; Alcotest.(check code) "Parse code" response.code `RequestRejectedIdentd let test_socks4_response_userid () = let response = Cstruct.of_string "\000\093\000\080\192\168\000\001" in let response = Socks4.Response.of_cstruct response in Alcotest.(check string) "Parse IP address" (Ipaddr.V4.to_string response.ip) "192.168.0.1"; Alcotest.(check int) "Parse port" response.port 80; Alcotest.(check code) "Parse code" response.code `UserIdNotMatching let () = let open Alcotest in run "Socks4" [ "Request", [ test_case "SOCKS4 connect request" `Quick test_socks4_connect_ip_address ; test_case "SOCKS4 bind request" `Quick test_socks4_bind_ip_address ; test_case "SOCKS4a connect with domain name" `Quick test_socks4a_connect_domain_name ; test_case "SOCKS4a bind request with domain name" `Quick test_socks4a_bind_domain_name ]; "Response", [ test_case "Request granted" `Quick test_socks4_response_success ; test_case "Request rejected" `Quick test_socks4_response_failed ; test_case "Request rejected identd" `Quick test_socks4_response_identd ; test_case "User ID not matching" `Quick test_socks4_response_userid ] ]
0355bb91ad71f18f08ba5b0c32b9629daecd78cd60ac289477527036d1d24988
coq/coq
pltac.mli
(************************************************************************) (* * The Coq Proof Assistant / The Coq Development Team *) v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \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) *) (************************************************************************) (** Ltac parsing entries *) open Pcoq open Libnames open Constrexpr open Tacexpr open Genredexpr open Tactypes val open_constr : constr_expr Entry.t val constr_with_bindings : constr_expr with_bindings Entry.t val bindings : constr_expr bindings Entry.t val hypident : (Names.lident * Locus.hyp_location_flag) Entry.t val constr_may_eval : (constr_expr,qualid or_by_notation,constr_expr) may_eval Entry.t val constr_eval : (constr_expr,qualid or_by_notation,constr_expr) may_eval Entry.t val uconstr : constr_expr Entry.t val quantified_hypothesis : quantified_hypothesis Entry.t val destruction_arg : constr_expr with_bindings Tactics.destruction_arg Entry.t val int_or_var : int Locus.or_var Entry.t val nat_or_var : int Locus.or_var Entry.t val simple_tactic : raw_tactic_expr Entry.t val simple_intropattern : constr_expr intro_pattern_expr CAst.t Entry.t val in_clause : Names.lident Locus.clause_expr Entry.t val clause_dft_concl : Names.lident Locus.clause_expr Entry.t val tactic_value : raw_tactic_arg Entry.t val ltac_expr : raw_tactic_expr Entry.t val binder_tactic : raw_tactic_expr Entry.t val tactic : raw_tactic_expr Entry.t val tactic_eoi : raw_tactic_expr Entry.t
null
https://raw.githubusercontent.com/coq/coq/c6ab5496cb6694e9e5b33183a9645e14083b90f7/plugins/ltac/pltac.mli
ocaml
********************************************************************** * The Coq Proof Assistant / The Coq Development Team // * This file is distributed under the terms of the * (see LICENSE file for the text of the license) ********************************************************************** * Ltac parsing entries
v * Copyright INRIA , CNRS and contributors < O _ _ _ , , * ( see version control and CREDITS file for authors & dates ) \VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * GNU Lesser General Public License Version 2.1 open Pcoq open Libnames open Constrexpr open Tacexpr open Genredexpr open Tactypes val open_constr : constr_expr Entry.t val constr_with_bindings : constr_expr with_bindings Entry.t val bindings : constr_expr bindings Entry.t val hypident : (Names.lident * Locus.hyp_location_flag) Entry.t val constr_may_eval : (constr_expr,qualid or_by_notation,constr_expr) may_eval Entry.t val constr_eval : (constr_expr,qualid or_by_notation,constr_expr) may_eval Entry.t val uconstr : constr_expr Entry.t val quantified_hypothesis : quantified_hypothesis Entry.t val destruction_arg : constr_expr with_bindings Tactics.destruction_arg Entry.t val int_or_var : int Locus.or_var Entry.t val nat_or_var : int Locus.or_var Entry.t val simple_tactic : raw_tactic_expr Entry.t val simple_intropattern : constr_expr intro_pattern_expr CAst.t Entry.t val in_clause : Names.lident Locus.clause_expr Entry.t val clause_dft_concl : Names.lident Locus.clause_expr Entry.t val tactic_value : raw_tactic_arg Entry.t val ltac_expr : raw_tactic_expr Entry.t val binder_tactic : raw_tactic_expr Entry.t val tactic : raw_tactic_expr Entry.t val tactic_eoi : raw_tactic_expr Entry.t
a2eb242e3e1cd140d48ed9b594df96c1288e00f3f7b91b7f493350b94e61bf0c
gas2serra/mcclim-desktop
application-mixins.lisp
(in-package :desktop-internals) ;;;; ;;;; Application Mixin ;;;; ;;; ;;; Simple Application Mixin ;;; (defclass simple-application-mixin () ((entry-fn :initarg :entry-fn :accessor application-entry-fn :initform nil))) (defmethod run-application ((application simple-application-mixin) &rest args) (with-slots (entry-fn name) application (if entry-fn (apply entry-fn application args) (progn (log-error (format nil "Entry function for ~A undefined" name)) (error "Entry function for ~A undefined" name))))) ;;; ;;; Simple CL Appplication Mixin ;;; (defclass simple-cl-application-mixin (simple-application-mixin) ()) (defmethod load-application ((application simple-cl-application-mixin) &optional force-p) (declare (ignore force-p)) (with-slots (name system-name debug-system-p) application (if system-name (if debug-system-p (asdf:operate 'asdf:load-source-op system-name :force-not t) (asdf:require-system system-name)) (log-warn (format nil "System name for ~A undefined" name))))) (defmethod install-application ((application simple-cl-application-mixin) &optional force-p) (declare (ignore force-p)) (with-slots (name system-name git-repo) application (if system-name (handler-case (ql:quickload system-name) (ql:system-not-found () (log-warn (format nil "System ~A non found in quicklisp" name)) (if git-repo (let ((cur-dir (uiop/os:getcwd))) (uiop/os:chdir (first ql:*local-project-directories*)) (uiop/run-program:run-program (list "git" "clone" git-repo) :force-shell t :output t :error-output t) (uiop/os:chdir cur-dir) (ql:quickload system-name)) (log-warn (format nil "Git repository for ~A undefined" name))))) (log-warn (format nil "System name for ~A undefined" name))))) ;;; ;;; Simple Shell Mixin ;;; (defclass simple-shell-application-mixin (simple-application-mixin) ((make-command-fn :initarg :make-command-fn :accessor application-make-command-fn :initform nil)) (:default-initargs :entry-fn #'(lambda (application &rest args) (with-slots (make-command-fn name) application (if make-command-fn (uiop:run-program (apply make-command-fn args)) (progn (log-error (format nil "Make command function for ~A undefined" name)) (error "Make command function for ~A undefined" name))))))) ;;;; Standard Application Mixin ;;;; (defclass standard-application-mixin () ()) ;;; protocols (defgeneric application-file (application &optional force-p force-user-p)) (defgeneric application-config-file (application &optional force-p force-user-p)) (defgeneric application-style-file (application &optional force-p force-user-p force-style)) (defgeneric load-application-config-file (application)) (defgeneric load-application-style-file (application &optional force-style)) ;;; protocol: application files (defmethod application-file ((application standard-application-mixin) &optional force-p force-user-p) (with-slots (name) application (find-application-file name force-p force-user-p))) (defmethod application-config-file ((application standard-application-mixin) &optional force-p force-user-p) (with-slots (name) application (find-config-file name nil force-p force-user-p))) (defmethod application-style-file ((application standard-application-mixin) &optional force-p force-user-p force-style) (with-slots (name) application (find-config-file name (or force-style nil) force-p force-user-p))) ;;; protocol: load files (defmethod load-application-config-file ((application standard-application-mixin)) (with-slots (name) application (let ((config-file (application-config-file application))) (if config-file (let ((*application* application)) (load config-file)) (log-warn (format nil "Config file (~A) for ~A not found" (config-file-relative-pathname name) name)))))) (defmethod load-application-style-file ((application standard-application-mixin) &optional force-style) (with-slots (name) application (let ((sty (or force-style))) (let ((style-file (application-style-file application nil nil sty))) (if style-file (let ((*application* application)) (load style-file)) (progn (log-warn (format nil "Style file (~A) for ~A not found" (config-file-relative-pathname name sty) name)) (unless (eq sty :default) (load-application-style-file application :default)))))))) ;;; protocol: configure (defmethod configure-application :before ((application standard-application-mixin) &optional force-p) (declare (ignore force-p)) (load-application-config-file application) (load-application-style-file application)) ;;; Standard CL Application Mixin ;;; (defclass standard-cl-application-mixin (standard-application-mixin) ()) ;;; ;;; Debugger Application ;;; (defclass simple-debugger-application-mixin () ((debugger-fn :initarg :debugger-fn :accessor application-debugger-fn :initform nil)))
null
https://raw.githubusercontent.com/gas2serra/mcclim-desktop/f85d19c57d76322ae3c05f98ae43bfc8c0d0a554/Core/src/application-mixins.lisp
lisp
Application Mixin Simple Application Mixin Simple CL Appplication Mixin Simple Shell Mixin protocols protocol: application files protocol: load files protocol: configure Debugger Application
(in-package :desktop-internals) (defclass simple-application-mixin () ((entry-fn :initarg :entry-fn :accessor application-entry-fn :initform nil))) (defmethod run-application ((application simple-application-mixin) &rest args) (with-slots (entry-fn name) application (if entry-fn (apply entry-fn application args) (progn (log-error (format nil "Entry function for ~A undefined" name)) (error "Entry function for ~A undefined" name))))) (defclass simple-cl-application-mixin (simple-application-mixin) ()) (defmethod load-application ((application simple-cl-application-mixin) &optional force-p) (declare (ignore force-p)) (with-slots (name system-name debug-system-p) application (if system-name (if debug-system-p (asdf:operate 'asdf:load-source-op system-name :force-not t) (asdf:require-system system-name)) (log-warn (format nil "System name for ~A undefined" name))))) (defmethod install-application ((application simple-cl-application-mixin) &optional force-p) (declare (ignore force-p)) (with-slots (name system-name git-repo) application (if system-name (handler-case (ql:quickload system-name) (ql:system-not-found () (log-warn (format nil "System ~A non found in quicklisp" name)) (if git-repo (let ((cur-dir (uiop/os:getcwd))) (uiop/os:chdir (first ql:*local-project-directories*)) (uiop/run-program:run-program (list "git" "clone" git-repo) :force-shell t :output t :error-output t) (uiop/os:chdir cur-dir) (ql:quickload system-name)) (log-warn (format nil "Git repository for ~A undefined" name))))) (log-warn (format nil "System name for ~A undefined" name))))) (defclass simple-shell-application-mixin (simple-application-mixin) ((make-command-fn :initarg :make-command-fn :accessor application-make-command-fn :initform nil)) (:default-initargs :entry-fn #'(lambda (application &rest args) (with-slots (make-command-fn name) application (if make-command-fn (uiop:run-program (apply make-command-fn args)) (progn (log-error (format nil "Make command function for ~A undefined" name)) (error "Make command function for ~A undefined" name))))))) Standard Application Mixin (defclass standard-application-mixin () ()) (defgeneric application-file (application &optional force-p force-user-p)) (defgeneric application-config-file (application &optional force-p force-user-p)) (defgeneric application-style-file (application &optional force-p force-user-p force-style)) (defgeneric load-application-config-file (application)) (defgeneric load-application-style-file (application &optional force-style)) (defmethod application-file ((application standard-application-mixin) &optional force-p force-user-p) (with-slots (name) application (find-application-file name force-p force-user-p))) (defmethod application-config-file ((application standard-application-mixin) &optional force-p force-user-p) (with-slots (name) application (find-config-file name nil force-p force-user-p))) (defmethod application-style-file ((application standard-application-mixin) &optional force-p force-user-p force-style) (with-slots (name) application (find-config-file name (or force-style nil) force-p force-user-p))) (defmethod load-application-config-file ((application standard-application-mixin)) (with-slots (name) application (let ((config-file (application-config-file application))) (if config-file (let ((*application* application)) (load config-file)) (log-warn (format nil "Config file (~A) for ~A not found" (config-file-relative-pathname name) name)))))) (defmethod load-application-style-file ((application standard-application-mixin) &optional force-style) (with-slots (name) application (let ((sty (or force-style))) (let ((style-file (application-style-file application nil nil sty))) (if style-file (let ((*application* application)) (load style-file)) (progn (log-warn (format nil "Style file (~A) for ~A not found" (config-file-relative-pathname name sty) name)) (unless (eq sty :default) (load-application-style-file application :default)))))))) (defmethod configure-application :before ((application standard-application-mixin) &optional force-p) (declare (ignore force-p)) (load-application-config-file application) (load-application-style-file application)) Standard CL Application Mixin (defclass standard-cl-application-mixin (standard-application-mixin) ()) (defclass simple-debugger-application-mixin () ((debugger-fn :initarg :debugger-fn :accessor application-debugger-fn :initform nil)))
94f4d391a334895af1c4e37ef09b9632d0cc725954feb13bb3411cbd2675cde7
moby/vpnkit
connect.mli
module Unix: sig include Sig.Connector val vsock_path: string ref end module Hvsock: sig include Sig.Connector val set_port_forward_addr: Hvsock.Af_hyperv.sockaddr -> unit end
null
https://raw.githubusercontent.com/moby/vpnkit/7bfcba6e59c1e5450b667a392bf56371faae58b2/src/bin/connect.mli
ocaml
module Unix: sig include Sig.Connector val vsock_path: string ref end module Hvsock: sig include Sig.Connector val set_port_forward_addr: Hvsock.Af_hyperv.sockaddr -> unit end
fdae13c8d1bbf663518a8f11c3dd09fab1ce01eb7e780fd4cc450700be5f5059
BinaryAnalysisPlatform/bap-plugins
memdep.mli
open Bap.Std type t (** [create ?memory arch sub] computes a memory model of a given subroutine [sub]. If static memory is provided, then it will be used to resolve memory accesses.*) val create : ?memory:value memmap -> arch -> sub term -> t (** [load model ~mem ~addr endian size] statically evaluates with respect to a computed memory [model].*) val load : t -> mem:exp -> addr:exp -> endian -> size -> exp option
null
https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap-plugins/2e9aa5c7c24ef494d0e7db1b43c5ceedcb4196a8/fold_consts/memdep.mli
ocaml
* [create ?memory arch sub] computes a memory model of a given subroutine [sub]. If static memory is provided, then it will be used to resolve memory accesses. * [load model ~mem ~addr endian size] statically evaluates with respect to a computed memory [model].
open Bap.Std type t val create : ?memory:value memmap -> arch -> sub term -> t val load : t -> mem:exp -> addr:exp -> endian -> size -> exp option
309e0729c25dbd68f5bd9f7ad2a7de2e843ff03d80870ab912a6e014ae4e3cc6
monadbobo/ocaml-core
core_array.ml
module Array = StdLabels.Array open Sexplib.Std open Bin_prot.Std let invalid_argf = Core_printf.invalid_argf type 'a t = 'a array with sexp, bin_io let max_length = Caml.Sys.max_array_length (* Standard functions *) let append = Array.append let blit = Array.blit let concat = Array.concat let copy = Array.copy let create_matrix = Array.create_matrix let fill = Array.fill let fold_right = Array.fold_right let init = Array.init let iteri = Array.iteri let make_matrix = Array.make_matrix let map = Array.map let mapi = Array.mapi let of_list = Array.of_list Note that 's stable_sort and are the same . Regular sort is unstable and slower , but uses constant heap space . slower, but uses constant heap space. *) let sort = Array.sort let stable_sort = Array.stable_sort let sub = Array.sub let to_list = Array.to_list external create : int -> 'a -> 'a array = "caml_make_vect" let create i x = try create i x with Invalid_argument _ -> invalid_argf "Array.create %d: invalid length" i () ;; external get : 'a array -> int -> 'a = "%array_safe_get" external set : 'a array -> int -> 'a -> unit = "%array_safe_set" external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get" external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set" external length : 'a array -> int = "%array_length" let max_length = Sys.max_array_length let to_array t = t let is_empty t = length t = 0 let is_sorted t ~cmp = let rec loop i = if i < 1 then true else cmp t.(i - 1) t.(i) <= 0 && loop (i - 1) in loop (length t - 1) TEST = is_sorted [||] ~cmp:compare TEST = is_sorted [|0|] ~cmp:compare TEST = is_sorted [|0;1;2;2;4|] ~cmp:compare TEST = not (is_sorted [|0;1;2;3;2|] ~cmp:compare) let fold t ~init ~f = Array.fold_left t ~init ~f let count t ~f = Container.fold_count fold t ~f let foldi t ~init ~f = let rec loop i ac = if i = length t then ac else loop (i + 1) (f i ac t.(i)) in loop 0 init ;; TEST = foldi [||] ~init:13 ~f:(fun _ _ _ -> failwith "bad") = 13 TEST = foldi [| 13 |] ~init:17 ~f:(fun i ac x -> ac + i + x) = 30 TEST = foldi [| 13; 17 |] ~init:19 ~f:(fun i ac x -> ac + i + x) = 50 let iter t ~f = Array.iter t ~f let concat_map t ~f = concat (to_list (map ~f t)) * [ normalize array index ] returns a new index into the array such that if index is less than zero , the returned index will " wrap around " -- i.e. array.(normalize array ( -1 ) ) returns the last element of the array . than zero, the returned index will "wrap around" -- i.e. array.(normalize array (-1)) returns the last element of the array. *) let normalize t i = Ordered_collection_common.normalize ~length_fun:length t i * [ slice array start stop ] returns a fresh array including elements [ array.(start ) ] through [ array.(stop-1 ) ] with the small tweak that the start and stop positions are normalized and a stop index of 0 means the same thing a stop index of [ Array.length array ] . In summary , it 's like the slicing in Python or Matlab . through [array.(stop-1)] with the small tweak that the start and stop positions are normalized and a stop index of 0 means the same thing a stop index of [Array.length array]. In summary, it's like the slicing in Python or Matlab. *) let slice t start stop = Ordered_collection_common.slice ~length_fun:length ~sub_fun:sub t start stop (** [nget array index] "normalizes" the index to {!Array.get} -- see normalize *) let nget t i = t.(normalize t i) (** [nset array index value] "normalizes" the index to {!Array.set} -- see normalize *) let nset t i v = t.(normalize t i) <- v let swap = Array_permute.swap;; (** reverses an array in place. *) let rev_inplace t = let i = ref 0 in let j = ref (length t - 1) in while !i < !j; do swap t !i !j; incr i; decr j; done ;; let of_list_rev l = let t = of_list l in rev_inplace t; t (* [list_length] and [of_list_rev_map] are based on functions from the OCaml distribution. *) Can not use here because the List module depends on Array . let rec list_length accu = function | [] -> accu | _h::t -> list_length (succ accu) t let of_list_map xs ~f = match xs with | [] -> [||] | hd::tl as l -> let a = create (list_length 0 l) (f hd) in let rec fill i = function | [] -> a | hd::tl -> unsafe_set a i (f hd); fill (i+1) tl in fill 1 tl let of_list_rev_map xs ~f = let t = of_list_map xs ~f in rev_inplace t; t (** [filter_opt array] returns a new array where [None] entries are omitted and [Some x] entries are replaced with [x]. Note that this changes the index at which elements will appear. *) let filter_opt t = let n = length t in let res_size = ref 0 in let first_some = ref None in for i = 0 to n - 1 do begin match t.(i) with | None -> () | Some _ as s -> if !res_size = 0 then first_some := s; incr res_size; end; done; match !first_some with | None -> [||] | Some el -> let result = create !res_size el in let pos = ref 0 in for i = 0 to n - 1 do begin match t.(i) with | None -> () | Some x -> result.(!pos) <- x; incr pos; end; done; result TEST = filter_opt [|Some 1; None; Some 2; None; Some 3|] = [|1; 2; 3|] TEST = filter_opt [|Some 1; None; Some 2|] = [|1; 2|] TEST = filter_opt [|Some 1|] = [|1|] TEST = filter_opt [|None|] = [||] TEST = filter_opt [||] = [||] (** [filter_map ~f array] maps [f] over [array] and filters [None] out of the results. *) let filter_map t ~f = filter_opt (map t ~f) (** Same as {!filter_map} but uses {!Array.mapi}. *) let filter_mapi t ~f = filter_opt (mapi t ~f) let iter2 t1 t2 ~f = if length t1 <> length t2 then invalid_arg "Array.iter2"; iteri t1 ~f:(fun i x1 -> f x1 t2.(i)) let map2 t1 t2 ~f = let len = length t1 in if length t2 <> len then invalid_arg "Array.map2"; init len ~f:(fun i -> f t1.(i) t2.(i)) let fold2_exn t1 t2 ~init ~f = if length t1 <> length t2 then invalid_arg "Array.fold2_exn"; foldi t1 ~init ~f:(fun i ac x -> f ac x t2.(i)) ;; TEST = fold2_exn [||] [||] ~init:13 ~f:(fun _ -> failwith "fail") = 13 TEST = fold2_exn [| 1 |] [| "1" |] ~init:[] ~f:(fun ac a b -> (a, b) :: ac) = [ 1, "1" ] (** [filter ~f array] removes the elements for which [f] returns false. *) let filter ~f = filter_map ~f:(fun x -> if f x then Some x else None) (** Like {!filter} except [f] also receives the index. *) let filteri ~f = filter_mapi ~f:(fun i x -> if f i x then Some x else None) let exists t ~f = let rec loop i = if i < 0 then false else if f t.(i) then true else loop (i - 1) in loop (length t - 1) let mem ?(equal = (=)) t a = exists t ~f:(equal a) let for_all t ~f = let rec loop i = if i < 0 then true else if f t.(i) then loop (i - 1) else false in loop (length t - 1) let for_all2 t1 t2 ~f = let len = length t1 in if length t2 <> len then invalid_arg "Array.for_all2"; let rec loop i = if i < 0 then true else if f t1.(i) t2.(i) then loop (i - 1) else false in loop (len - 1) let equal t1 t2 ~equal = length t1 = length t2 && for_all2 t1 t2 ~f:equal TEST = equal [||] [||] ~equal:(=) TEST = equal [| 1 |] [| 1 |] ~equal:(=) TEST = equal [| 1; 2 |] [| 1; 2 |] ~equal:(=) TEST = not (equal [||] [| 1 |] ~equal:(=)) TEST = not (equal [| 1 |] [||] ~equal:(=)) TEST = not (equal [| 1 |] [| 1; 2 |] ~equal:(=)) TEST = not (equal [| 1; 2 |] [| 1; 3 |] ~equal:(=)) let replace t i ~f = t.(i) <- f t.(i) (** modifies an array in place -- [t.(i)] will be set to [f(t.(i))] *) let replace_all t ~f = for i = 0 to length t - 1 do t.(i) <- f t.(i) done let findi t ~f = let length = length t in let rec loop i = if i >= length then None else if f i t.(i) then Some (i, t.(i)) else loop (i + 1) in loop 0 ;; let findi_exn t ~f = match findi t ~f with | None -> raise Not_found | Some x -> x ;; let find_exn t ~f = match findi t ~f:(fun _i x -> f x) with | None -> raise Not_found | Some (_i, x) -> x ;; let find t ~f = Option.map (findi t ~f:(fun _i x -> f x)) ~f:(fun (_i, x) -> x) let find_map t ~f = let length = length t in let rec loop i = if i >= length then None else match f t.(i) with | None -> loop (i + 1) | Some _ as res -> res in loop 0 ;; let reduce t ~f = if length t = 0 then None else begin let r = ref t.(0) in for i = 1 to length t - 1 do r := f !r t.(i) done; Some !r end let reduce_exn t ~f = match reduce t ~f with | None -> invalid_arg "Array.reduce_exn" | Some v -> v let permute = Array_permute.permute let combine t1 t2 = if length t1 <> length t2 then failwith "Array.combine" else map2 t1 t2 ~f:(fun x1 x2 -> x1, x2) let split t = let n = length t in if n = 0 then [||], [||] else let x, y = t.(0) in let res1 = create n x in let res2 = create n y in for i = 1 to n - 1 do let x, y = t.(i) in res1.(i) <- x; res2.(i) <- y; done; res1, res2 let sorted_copy t ~cmp = let t1 = copy t in sort t1 ~cmp; t1 let partitioni_tf t ~f = let (trues, falses) = mapi t ~f:(fun i x -> if f i x then (Some x, None) else (None, Some x)) |! split in (filter_opt trues, filter_opt falses) let partition_tf t ~f = partitioni_tf t ~f:(fun _i x -> f x) let last t = t.(length t - 1) module Infix = struct let ( <|> ) t (start,stop) = slice t start stop end (* We use [init 0] rather than [||] because all [||] are physically equal, and we want [empty] to create a new array. *) let empty () = init 0 ~f:(fun _ -> assert false) let cartesian_product t1 t2 = if is_empty t1 || is_empty t2 then empty () else let n1 = length t1 in let n2 = length t2 in let t = create (n1 * n2) (t1.(0), t2.(0)) in let r = ref 0 in for i1 = 0 to n1 - 1 do for i2 = 0 to n2 - 1 do t.(!r) <- (t1.(i1), t2.(i2)); incr r; done done; t ;;
null
https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib/core_array.ml
ocaml
Standard functions * [nget array index] "normalizes" the index to {!Array.get} -- see normalize * [nset array index value] "normalizes" the index to {!Array.set} -- see normalize * reverses an array in place. [list_length] and [of_list_rev_map] are based on functions from the OCaml distribution. * [filter_opt array] returns a new array where [None] entries are omitted and [Some x] entries are replaced with [x]. Note that this changes the index at which elements will appear. * [filter_map ~f array] maps [f] over [array] and filters [None] out of the results. * Same as {!filter_map} but uses {!Array.mapi}. * [filter ~f array] removes the elements for which [f] returns false. * Like {!filter} except [f] also receives the index. * modifies an array in place -- [t.(i)] will be set to [f(t.(i))] We use [init 0] rather than [||] because all [||] are physically equal, and we want [empty] to create a new array.
module Array = StdLabels.Array open Sexplib.Std open Bin_prot.Std let invalid_argf = Core_printf.invalid_argf type 'a t = 'a array with sexp, bin_io let max_length = Caml.Sys.max_array_length let append = Array.append let blit = Array.blit let concat = Array.concat let copy = Array.copy let create_matrix = Array.create_matrix let fill = Array.fill let fold_right = Array.fold_right let init = Array.init let iteri = Array.iteri let make_matrix = Array.make_matrix let map = Array.map let mapi = Array.mapi let of_list = Array.of_list Note that 's stable_sort and are the same . Regular sort is unstable and slower , but uses constant heap space . slower, but uses constant heap space. *) let sort = Array.sort let stable_sort = Array.stable_sort let sub = Array.sub let to_list = Array.to_list external create : int -> 'a -> 'a array = "caml_make_vect" let create i x = try create i x with Invalid_argument _ -> invalid_argf "Array.create %d: invalid length" i () ;; external get : 'a array -> int -> 'a = "%array_safe_get" external set : 'a array -> int -> 'a -> unit = "%array_safe_set" external unsafe_get : 'a array -> int -> 'a = "%array_unsafe_get" external unsafe_set : 'a array -> int -> 'a -> unit = "%array_unsafe_set" external length : 'a array -> int = "%array_length" let max_length = Sys.max_array_length let to_array t = t let is_empty t = length t = 0 let is_sorted t ~cmp = let rec loop i = if i < 1 then true else cmp t.(i - 1) t.(i) <= 0 && loop (i - 1) in loop (length t - 1) TEST = is_sorted [||] ~cmp:compare TEST = is_sorted [|0|] ~cmp:compare TEST = is_sorted [|0;1;2;2;4|] ~cmp:compare TEST = not (is_sorted [|0;1;2;3;2|] ~cmp:compare) let fold t ~init ~f = Array.fold_left t ~init ~f let count t ~f = Container.fold_count fold t ~f let foldi t ~init ~f = let rec loop i ac = if i = length t then ac else loop (i + 1) (f i ac t.(i)) in loop 0 init ;; TEST = foldi [||] ~init:13 ~f:(fun _ _ _ -> failwith "bad") = 13 TEST = foldi [| 13 |] ~init:17 ~f:(fun i ac x -> ac + i + x) = 30 TEST = foldi [| 13; 17 |] ~init:19 ~f:(fun i ac x -> ac + i + x) = 50 let iter t ~f = Array.iter t ~f let concat_map t ~f = concat (to_list (map ~f t)) * [ normalize array index ] returns a new index into the array such that if index is less than zero , the returned index will " wrap around " -- i.e. array.(normalize array ( -1 ) ) returns the last element of the array . than zero, the returned index will "wrap around" -- i.e. array.(normalize array (-1)) returns the last element of the array. *) let normalize t i = Ordered_collection_common.normalize ~length_fun:length t i * [ slice array start stop ] returns a fresh array including elements [ array.(start ) ] through [ array.(stop-1 ) ] with the small tweak that the start and stop positions are normalized and a stop index of 0 means the same thing a stop index of [ Array.length array ] . In summary , it 's like the slicing in Python or Matlab . through [array.(stop-1)] with the small tweak that the start and stop positions are normalized and a stop index of 0 means the same thing a stop index of [Array.length array]. In summary, it's like the slicing in Python or Matlab. *) let slice t start stop = Ordered_collection_common.slice ~length_fun:length ~sub_fun:sub t start stop let nget t i = t.(normalize t i) let nset t i v = t.(normalize t i) <- v let swap = Array_permute.swap;; let rev_inplace t = let i = ref 0 in let j = ref (length t - 1) in while !i < !j; do swap t !i !j; incr i; decr j; done ;; let of_list_rev l = let t = of_list l in rev_inplace t; t Can not use here because the List module depends on Array . let rec list_length accu = function | [] -> accu | _h::t -> list_length (succ accu) t let of_list_map xs ~f = match xs with | [] -> [||] | hd::tl as l -> let a = create (list_length 0 l) (f hd) in let rec fill i = function | [] -> a | hd::tl -> unsafe_set a i (f hd); fill (i+1) tl in fill 1 tl let of_list_rev_map xs ~f = let t = of_list_map xs ~f in rev_inplace t; t let filter_opt t = let n = length t in let res_size = ref 0 in let first_some = ref None in for i = 0 to n - 1 do begin match t.(i) with | None -> () | Some _ as s -> if !res_size = 0 then first_some := s; incr res_size; end; done; match !first_some with | None -> [||] | Some el -> let result = create !res_size el in let pos = ref 0 in for i = 0 to n - 1 do begin match t.(i) with | None -> () | Some x -> result.(!pos) <- x; incr pos; end; done; result TEST = filter_opt [|Some 1; None; Some 2; None; Some 3|] = [|1; 2; 3|] TEST = filter_opt [|Some 1; None; Some 2|] = [|1; 2|] TEST = filter_opt [|Some 1|] = [|1|] TEST = filter_opt [|None|] = [||] TEST = filter_opt [||] = [||] let filter_map t ~f = filter_opt (map t ~f) let filter_mapi t ~f = filter_opt (mapi t ~f) let iter2 t1 t2 ~f = if length t1 <> length t2 then invalid_arg "Array.iter2"; iteri t1 ~f:(fun i x1 -> f x1 t2.(i)) let map2 t1 t2 ~f = let len = length t1 in if length t2 <> len then invalid_arg "Array.map2"; init len ~f:(fun i -> f t1.(i) t2.(i)) let fold2_exn t1 t2 ~init ~f = if length t1 <> length t2 then invalid_arg "Array.fold2_exn"; foldi t1 ~init ~f:(fun i ac x -> f ac x t2.(i)) ;; TEST = fold2_exn [||] [||] ~init:13 ~f:(fun _ -> failwith "fail") = 13 TEST = fold2_exn [| 1 |] [| "1" |] ~init:[] ~f:(fun ac a b -> (a, b) :: ac) = [ 1, "1" ] let filter ~f = filter_map ~f:(fun x -> if f x then Some x else None) let filteri ~f = filter_mapi ~f:(fun i x -> if f i x then Some x else None) let exists t ~f = let rec loop i = if i < 0 then false else if f t.(i) then true else loop (i - 1) in loop (length t - 1) let mem ?(equal = (=)) t a = exists t ~f:(equal a) let for_all t ~f = let rec loop i = if i < 0 then true else if f t.(i) then loop (i - 1) else false in loop (length t - 1) let for_all2 t1 t2 ~f = let len = length t1 in if length t2 <> len then invalid_arg "Array.for_all2"; let rec loop i = if i < 0 then true else if f t1.(i) t2.(i) then loop (i - 1) else false in loop (len - 1) let equal t1 t2 ~equal = length t1 = length t2 && for_all2 t1 t2 ~f:equal TEST = equal [||] [||] ~equal:(=) TEST = equal [| 1 |] [| 1 |] ~equal:(=) TEST = equal [| 1; 2 |] [| 1; 2 |] ~equal:(=) TEST = not (equal [||] [| 1 |] ~equal:(=)) TEST = not (equal [| 1 |] [||] ~equal:(=)) TEST = not (equal [| 1 |] [| 1; 2 |] ~equal:(=)) TEST = not (equal [| 1; 2 |] [| 1; 3 |] ~equal:(=)) let replace t i ~f = t.(i) <- f t.(i) let replace_all t ~f = for i = 0 to length t - 1 do t.(i) <- f t.(i) done let findi t ~f = let length = length t in let rec loop i = if i >= length then None else if f i t.(i) then Some (i, t.(i)) else loop (i + 1) in loop 0 ;; let findi_exn t ~f = match findi t ~f with | None -> raise Not_found | Some x -> x ;; let find_exn t ~f = match findi t ~f:(fun _i x -> f x) with | None -> raise Not_found | Some (_i, x) -> x ;; let find t ~f = Option.map (findi t ~f:(fun _i x -> f x)) ~f:(fun (_i, x) -> x) let find_map t ~f = let length = length t in let rec loop i = if i >= length then None else match f t.(i) with | None -> loop (i + 1) | Some _ as res -> res in loop 0 ;; let reduce t ~f = if length t = 0 then None else begin let r = ref t.(0) in for i = 1 to length t - 1 do r := f !r t.(i) done; Some !r end let reduce_exn t ~f = match reduce t ~f with | None -> invalid_arg "Array.reduce_exn" | Some v -> v let permute = Array_permute.permute let combine t1 t2 = if length t1 <> length t2 then failwith "Array.combine" else map2 t1 t2 ~f:(fun x1 x2 -> x1, x2) let split t = let n = length t in if n = 0 then [||], [||] else let x, y = t.(0) in let res1 = create n x in let res2 = create n y in for i = 1 to n - 1 do let x, y = t.(i) in res1.(i) <- x; res2.(i) <- y; done; res1, res2 let sorted_copy t ~cmp = let t1 = copy t in sort t1 ~cmp; t1 let partitioni_tf t ~f = let (trues, falses) = mapi t ~f:(fun i x -> if f i x then (Some x, None) else (None, Some x)) |! split in (filter_opt trues, filter_opt falses) let partition_tf t ~f = partitioni_tf t ~f:(fun _i x -> f x) let last t = t.(length t - 1) module Infix = struct let ( <|> ) t (start,stop) = slice t start stop end let empty () = init 0 ~f:(fun _ -> assert false) let cartesian_product t1 t2 = if is_empty t1 || is_empty t2 then empty () else let n1 = length t1 in let n2 = length t2 in let t = create (n1 * n2) (t1.(0), t2.(0)) in let r = ref 0 in for i1 = 0 to n1 - 1 do for i2 = 0 to n2 - 1 do t.(!r) <- (t1.(i1), t2.(i2)); incr r; done done; t ;;
5f75c0a587d2a49e3719693c9fac0d1cb2baa3c674794f42aa1463cb38c22d95
lemmaandrew/CodingBatHaskell
hasOne.hs
From Given a positive int n , return true if it contains a 1 digit . Note : use % to get the rightmost digit , and / to discard the rightmost digit . Given a positive int n, return true if it contains a 1 digit. Note: use % to get the rightmost digit, and / to discard the rightmost digit. -} import Test.Hspec ( hspec, describe, it, shouldBe ) hasOne :: Int -> Bool hasOne n = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "True" $ hasOne 10 `shouldBe` True it "False" $ hasOne 22 `shouldBe` False it "False" $ hasOne 220 `shouldBe` False it "True" $ hasOne 212 `shouldBe` True it "True" $ hasOne 1 `shouldBe` True it "False" $ hasOne 9 `shouldBe` False it "True" $ hasOne 211112 `shouldBe` True it "True" $ hasOne 121121 `shouldBe` True it "False" $ hasOne 222222 `shouldBe` False it "True" $ hasOne 56156 `shouldBe` True it "False" $ hasOne 56556 `shouldBe` False
null
https://raw.githubusercontent.com/lemmaandrew/CodingBatHaskell/d839118be02e1867504206657a0664fd79d04736/CodingBat/AP-1/hasOne.hs
haskell
From Given a positive int n , return true if it contains a 1 digit . Note : use % to get the rightmost digit , and / to discard the rightmost digit . Given a positive int n, return true if it contains a 1 digit. Note: use % to get the rightmost digit, and / to discard the rightmost digit. -} import Test.Hspec ( hspec, describe, it, shouldBe ) hasOne :: Int -> Bool hasOne n = undefined main :: IO () main = hspec $ describe "Tests:" $ do it "True" $ hasOne 10 `shouldBe` True it "False" $ hasOne 22 `shouldBe` False it "False" $ hasOne 220 `shouldBe` False it "True" $ hasOne 212 `shouldBe` True it "True" $ hasOne 1 `shouldBe` True it "False" $ hasOne 9 `shouldBe` False it "True" $ hasOne 211112 `shouldBe` True it "True" $ hasOne 121121 `shouldBe` True it "False" $ hasOne 222222 `shouldBe` False it "True" $ hasOne 56156 `shouldBe` True it "False" $ hasOne 56556 `shouldBe` False
ec127dee5491a7c39fa1b1c4047b0b27ca9503e627d0aa186e2d068afbce0297
alephcloud/hs-aws-kinesis-client
CLI.hs
Copyright ( c ) 2013 - 2015 PivotCloud , Inc. -- . . Client . Consumer -- -- Please feel free to contact us at with any -- contributions, additions, or other feedback; we would love to hear from -- you. -- 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. {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE RecordWildCards # # LANGUAGE TupleSections # # LANGUAGE UndecidableInstances # # LANGUAGE UnicodeSyntax # -- | -- Module: Main Copyright : Copyright © 2013 - 2015 PivotCloud , Inc. -- License: Apache-2.0 Maintainer : < > -- Stability: experimental -- module Main ( main ) where import Aws import Aws.Kinesis hiding (Record) import Aws.Kinesis.Client.Common import Aws.Kinesis.Client.Consumer import CLI.Config import Configuration.Utils import Configuration.Utils.Aws.Credentials import Control.Concurrent.Lifted import Control.Concurrent.Async.Lifted import Control.Exception.Lifted import Control.Lens import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.Control import Control.Monad.Trans.Except import Control.Monad.Codensity import Control.Monad.Reader.Class import Control.Monad.Trans.Reader (ReaderT(..)) import Control.Monad.Unicode import qualified Data.Aeson as A import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy.Char8 as BL8 import Data.Conduit import qualified Data.Conduit.List as CL import Data.Monoid.Unicode import Data.Traversable import Data.Typeable import qualified Network.HTTP.Conduit as HC import Prelude.Unicode import System.Exit import System.IO.Error import PkgInfo_kinesis_cli data CLIError = MissingCredentials | NoInstanceMetadataCredentials deriving (Typeable, Show) instance Exception CLIError type MonadCLI m = ( MonadReader Config m , MonadIO m , MonadBaseControl IO m ) managedKinesisKit ∷ MonadCLI m ⇒ Codensity m KinesisKit managedKinesisKit = do Config{..} ← ask manager ← managedHttpManager credentials ← lift $ runExceptT (credentialsFromConfig _configCredentialConfig) ≫= either throwIO return return KinesisKit { _kkManager = manager , _kkConfiguration = Configuration { timeInfo = Timestamp , credentials = credentials , logger = defaultLog Warning } , _kkKinesisConfiguration = defaultKinesisConfiguration _configRegion } cliConsumerKit ∷ MonadCLI m ⇒ KinesisKit → m ConsumerKit cliConsumerKit kinesisKit = do Config{..} ← ask savedStreamState ← case _configStateIn of Just path → liftIO $ do code ← catch (Just <$> BL8.readFile path) $ \case exn | isDoesNotExistError exn → return Nothing | otherwise → throwIO exn traverse (either (fail ∘ ("Invalid saved state: " ⊕)) return) $ A.eitherDecode <$> code Nothing → return Nothing return $ makeConsumerKit kinesisKit _configStreamName & ckBatchSize .~ 100 & ckIteratorType .~ _configIteratorType & ckSavedStreamState .~ savedStreamState app ∷ MonadCLI m ⇒ Codensity m ExitCode app = do Config{..} ← ask consumer ← managedKinesisKit ≫= lift ∘ cliConsumerKit ≫= managedKinesisConsumer let source = consumerSource consumer step n r = succ n <$ liftIO (B8.putStrLn $ recordData r) countingSink = CL.foldM step (1 ∷ Int) sink = case _configLimit of Just limit → CL.isolate limit =$ countingSink Nothing → countingSink runConsumer = do n ← catch (source $$ sink) $ \SomeException{} → return 0 return $ maybe True (n ≥) _configLimit -- If a timeout is set, then we will race the timeout against the consumer. result ← lift $ case _configTimeout of Just seconds → race (threadDelay $ seconds * 1000000) runConsumer Nothing → Right <$> runConsumer let successful = case result of -- if we timed out: if there a requested limit, then we failed to get -- it (and this is a failure); if there was no requested limit, then we -- consider this a success. Left () → isn't _Just _configLimit -- if we did not timeout, then it is a success Right b → b lift ∘ when successful ∘ void ∘ for _configStateOut $ \outPath → do state ← consumerStreamState consumer liftIO ∘ BL8.writeFile outPath $ A.encode state return $ if successful then ExitSuccess else ExitFailure 1 mainInfo ∷ ProgramInfo Config mainInfo = programInfoValidate "Kinesis CLI" pConfig defaultConfig validateConfig main ∷ IO () main = do runWithPkgInfoConfiguration mainInfo pkgInfo $ runReaderT (lowerCodensity app) >=> exitWith managedHttpManager ∷ ( MonadIO m , MonadBaseControl IO m ) ⇒ Codensity m HC.Manager managedHttpManager = Codensity $ HC.withManager ∘ (lift ∘)
null
https://raw.githubusercontent.com/alephcloud/hs-aws-kinesis-client/8ef77b8b7d7e9a840b1c7bd39b44861957580a1c/cli/CLI.hs
haskell
Please feel free to contact us at with any contributions, additions, or other feedback; we would love to hear from you. 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 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. # LANGUAGE ConstraintKinds # # LANGUAGE DeriveDataTypeable # # LANGUAGE OverloadedStrings # | Module: Main License: Apache-2.0 Stability: experimental If a timeout is set, then we will race the timeout against the consumer. if we timed out: if there a requested limit, then we failed to get it (and this is a failure); if there was no requested limit, then we consider this a success. if we did not timeout, then it is a success
Copyright ( c ) 2013 - 2015 PivotCloud , Inc. . . Client . Consumer Licensed under the Apache License , Version 2.0 ( the " License " ) ; you may distributed under the License is distributed on an " AS IS " BASIS , WITHOUT # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE GeneralizedNewtypeDeriving # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE RecordWildCards # # LANGUAGE TupleSections # # LANGUAGE UndecidableInstances # # LANGUAGE UnicodeSyntax # Copyright : Copyright © 2013 - 2015 PivotCloud , Inc. Maintainer : < > module Main ( main ) where import Aws import Aws.Kinesis hiding (Record) import Aws.Kinesis.Client.Common import Aws.Kinesis.Client.Consumer import CLI.Config import Configuration.Utils import Configuration.Utils.Aws.Credentials import Control.Concurrent.Lifted import Control.Concurrent.Async.Lifted import Control.Exception.Lifted import Control.Lens import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.Control import Control.Monad.Trans.Except import Control.Monad.Codensity import Control.Monad.Reader.Class import Control.Monad.Trans.Reader (ReaderT(..)) import Control.Monad.Unicode import qualified Data.Aeson as A import qualified Data.ByteString.Char8 as B8 import qualified Data.ByteString.Lazy.Char8 as BL8 import Data.Conduit import qualified Data.Conduit.List as CL import Data.Monoid.Unicode import Data.Traversable import Data.Typeable import qualified Network.HTTP.Conduit as HC import Prelude.Unicode import System.Exit import System.IO.Error import PkgInfo_kinesis_cli data CLIError = MissingCredentials | NoInstanceMetadataCredentials deriving (Typeable, Show) instance Exception CLIError type MonadCLI m = ( MonadReader Config m , MonadIO m , MonadBaseControl IO m ) managedKinesisKit ∷ MonadCLI m ⇒ Codensity m KinesisKit managedKinesisKit = do Config{..} ← ask manager ← managedHttpManager credentials ← lift $ runExceptT (credentialsFromConfig _configCredentialConfig) ≫= either throwIO return return KinesisKit { _kkManager = manager , _kkConfiguration = Configuration { timeInfo = Timestamp , credentials = credentials , logger = defaultLog Warning } , _kkKinesisConfiguration = defaultKinesisConfiguration _configRegion } cliConsumerKit ∷ MonadCLI m ⇒ KinesisKit → m ConsumerKit cliConsumerKit kinesisKit = do Config{..} ← ask savedStreamState ← case _configStateIn of Just path → liftIO $ do code ← catch (Just <$> BL8.readFile path) $ \case exn | isDoesNotExistError exn → return Nothing | otherwise → throwIO exn traverse (either (fail ∘ ("Invalid saved state: " ⊕)) return) $ A.eitherDecode <$> code Nothing → return Nothing return $ makeConsumerKit kinesisKit _configStreamName & ckBatchSize .~ 100 & ckIteratorType .~ _configIteratorType & ckSavedStreamState .~ savedStreamState app ∷ MonadCLI m ⇒ Codensity m ExitCode app = do Config{..} ← ask consumer ← managedKinesisKit ≫= lift ∘ cliConsumerKit ≫= managedKinesisConsumer let source = consumerSource consumer step n r = succ n <$ liftIO (B8.putStrLn $ recordData r) countingSink = CL.foldM step (1 ∷ Int) sink = case _configLimit of Just limit → CL.isolate limit =$ countingSink Nothing → countingSink runConsumer = do n ← catch (source $$ sink) $ \SomeException{} → return 0 return $ maybe True (n ≥) _configLimit result ← lift $ case _configTimeout of Just seconds → race (threadDelay $ seconds * 1000000) runConsumer Nothing → Right <$> runConsumer let successful = case result of Left () → isn't _Just _configLimit Right b → b lift ∘ when successful ∘ void ∘ for _configStateOut $ \outPath → do state ← consumerStreamState consumer liftIO ∘ BL8.writeFile outPath $ A.encode state return $ if successful then ExitSuccess else ExitFailure 1 mainInfo ∷ ProgramInfo Config mainInfo = programInfoValidate "Kinesis CLI" pConfig defaultConfig validateConfig main ∷ IO () main = do runWithPkgInfoConfiguration mainInfo pkgInfo $ runReaderT (lowerCodensity app) >=> exitWith managedHttpManager ∷ ( MonadIO m , MonadBaseControl IO m ) ⇒ Codensity m HC.Manager managedHttpManager = Codensity $ HC.withManager ∘ (lift ∘)
f50bfb0050cae437b160ba6ecc0407dee5886216a60c50ae2d450039cf701891
iustin/corydalis
ImageSpec.hs
Copyright ( C ) 2013 This program is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with this program . If not , see < / > . Copyright (C) 2013 Iustin Pop This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see </>. -} # LANGUAGE NoImplicitPrelude # {-# LANGUAGE OverloadedStrings #-} module Handler.ImageSpec (spec) where import TestImport spec :: Spec spec = parallel $ withApp $ it "loads an image page and checks it looks right" $ do login checkNotFound $ ImageR "foo" "bar"
null
https://raw.githubusercontent.com/iustin/corydalis/43f8bf004904847fad43c428a9e1b20e67da964d/test/Handler/ImageSpec.hs
haskell
# LANGUAGE OverloadedStrings #
Copyright ( C ) 2013 This program is free software : you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation , either version 3 of the License , or ( at your option ) any later version . This program is distributed in the hope that it will be useful , but WITHOUT ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU Affero General Public License for more details . You should have received a copy of the GNU Affero General Public License along with this program . If not , see < / > . Copyright (C) 2013 Iustin Pop This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see </>. -} # LANGUAGE NoImplicitPrelude # module Handler.ImageSpec (spec) where import TestImport spec :: Spec spec = parallel $ withApp $ it "loads an image page and checks it looks right" $ do login checkNotFound $ ImageR "foo" "bar"
82a9405420096c26c366aaff3a2c6f8810db7eb33cae07798e1cb51b2e0a50ed
8c6794b6/guile-tjit
t-mod-03.scm
;;; Loop with modulo, with various sign combinations. (define (loop n x) (let lp ((n n) (acc '())) (if (= n 0) (reverse! acc) (lp (- n 1) (cons (list (modulo n x) (modulo (- n) x) (modulo n (- x)) (modulo (- n) (- x))) acc))))) (loop 100 17)
null
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/test-suite/tjit/t-mod-03.scm
scheme
Loop with modulo, with various sign combinations.
(define (loop n x) (let lp ((n n) (acc '())) (if (= n 0) (reverse! acc) (lp (- n 1) (cons (list (modulo n x) (modulo (- n) x) (modulo n (- x)) (modulo (- n) (- x))) acc))))) (loop 100 17)
7ff015797b9dc68dc65e17016bd64c1f4b789b6d60cc45432b0ab91d3289f7cc
janestreet/universe
import.ml
open! Core open Pam (* The service [other] comes with the recent [pam] package *) let default_service = "other" let default_user = "foo" let with_pam ?(user = default_user) ?(service = default_service) ~f () = let open Or_error.Let_syntax in let conv _ = Error Pam_conv.Result.PAM_CONV_ERR in let%bind t = pam_start ~service ~user ~conv in let value = f t in let%bind () = pam_end t in value ;; let with_pam_exn ?user ?service ~f () = with_pam ?user ?service ~f () |> ok_exn
null
https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/pam/test/import.ml
ocaml
The service [other] comes with the recent [pam] package
open! Core open Pam let default_service = "other" let default_user = "foo" let with_pam ?(user = default_user) ?(service = default_service) ~f () = let open Or_error.Let_syntax in let conv _ = Error Pam_conv.Result.PAM_CONV_ERR in let%bind t = pam_start ~service ~user ~conv in let value = f t in let%bind () = pam_end t in value ;; let with_pam_exn ?user ?service ~f () = with_pam ?user ?service ~f () |> ok_exn
697b580881e05c0561a693688adb6ea22d8deb110c9a9803e2208afaa6ec5155
jessealama/argo
main.rkt
#lang racket/base (provide adheres-to-schema? json-schema? check-json/schema json-pretty-print json-in-one-line parse-json) (require (only-in (file "./schema.rkt") json-schema?)) (require (only-in (file "./validate.rkt") adheres-to-schema? check-json/schema)) (require (only-in (file "./pp.rkt") json-pretty-print)) (require (only-in (file "./oneline.rkt") json-in-one-line)) (require (file "./parse.rkt")) ;; Checking at the command line (module+ main (require racket/cmdline (only-in (file "util.rkt") file-content/bytes bytes->string)) (define quiet-mode (make-parameter #f)) (define-values (schema-path instance-path) (command-line #:program "argo" #:once-each [("--quiet") "Write nothing to stdout." (quiet-mode #f)] #:args (schema-path instance-path) (values schema-path instance-path))) (unless (file-exists? schema-path) (displayln (format "Schema file \"~a\" does not exist." schema-path)) (exit 1)) (unless (file-exists? instance-path) (displayln (format "Instance file \"~a\" does not exist." instance-path)) (exit 1)) (define (parse-fail err) #f) (define schema/bytes (file-content/bytes schema-path)) (define instance/bytes (file-content/bytes instance-path)) (define schema/string (bytes->string schema/bytes)) (define instance/string (bytes->string instance/bytes)) (when (eq? schema/string #f) (displayln (format "Contents of schema at \"~a\" cannot be interpreted as a UTF-8 string." schema-path)) (exit 1)) (when (eq? instance/string #f) (displayln (format "Contents of instance at \"~a\" cannot be interpreted as a UTF-8 string." instance-path)) (exit 1)) (define-values (schema/jsexpr schema-well-formed?) (parse-json-string schema/string)) (define-values (instance/jsexpr instance-well-formed?) (parse-json-string instance/string)) (unless schema-well-formed? (displayln (format "Schema at \"~a\" is not well-formed JSON." schema-path)) (exit 1)) (unless instance-well-formed? (displayln (format "Instance at \"~a\" is not well-formed JSON." instance-path)) (exit 1)) (unless (json-schema? schema/jsexpr) (displayln (format "Schema at \"~a\" is not a JSON schema." schema-path)) (exit 1)) (define adheres? (adheres-to-schema? instance/jsexpr schema/jsexpr)) (exit (if adheres? 0 1)))
null
https://raw.githubusercontent.com/jessealama/argo/244234415715d2e9294d56f04f79e86f56bcb64f/main.rkt
racket
Checking at the command line
#lang racket/base (provide adheres-to-schema? json-schema? check-json/schema json-pretty-print json-in-one-line parse-json) (require (only-in (file "./schema.rkt") json-schema?)) (require (only-in (file "./validate.rkt") adheres-to-schema? check-json/schema)) (require (only-in (file "./pp.rkt") json-pretty-print)) (require (only-in (file "./oneline.rkt") json-in-one-line)) (require (file "./parse.rkt")) (module+ main (require racket/cmdline (only-in (file "util.rkt") file-content/bytes bytes->string)) (define quiet-mode (make-parameter #f)) (define-values (schema-path instance-path) (command-line #:program "argo" #:once-each [("--quiet") "Write nothing to stdout." (quiet-mode #f)] #:args (schema-path instance-path) (values schema-path instance-path))) (unless (file-exists? schema-path) (displayln (format "Schema file \"~a\" does not exist." schema-path)) (exit 1)) (unless (file-exists? instance-path) (displayln (format "Instance file \"~a\" does not exist." instance-path)) (exit 1)) (define (parse-fail err) #f) (define schema/bytes (file-content/bytes schema-path)) (define instance/bytes (file-content/bytes instance-path)) (define schema/string (bytes->string schema/bytes)) (define instance/string (bytes->string instance/bytes)) (when (eq? schema/string #f) (displayln (format "Contents of schema at \"~a\" cannot be interpreted as a UTF-8 string." schema-path)) (exit 1)) (when (eq? instance/string #f) (displayln (format "Contents of instance at \"~a\" cannot be interpreted as a UTF-8 string." instance-path)) (exit 1)) (define-values (schema/jsexpr schema-well-formed?) (parse-json-string schema/string)) (define-values (instance/jsexpr instance-well-formed?) (parse-json-string instance/string)) (unless schema-well-formed? (displayln (format "Schema at \"~a\" is not well-formed JSON." schema-path)) (exit 1)) (unless instance-well-formed? (displayln (format "Instance at \"~a\" is not well-formed JSON." instance-path)) (exit 1)) (unless (json-schema? schema/jsexpr) (displayln (format "Schema at \"~a\" is not a JSON schema." schema-path)) (exit 1)) (define adheres? (adheres-to-schema? instance/jsexpr schema/jsexpr)) (exit (if adheres? 0 1)))
b6f7ca0b44324ed8d396615a2908d2481a27448a8266f20b4f26ae4d1086736f
haskell-github/github
SearchIssues.hs
{-# LANGUAGE OverloadedStrings #-} module Main where import qualified GitHub import qualified Data.Text as T import Control.Monad (forM_) import Data.Monoid ((<>)) main :: IO () main = do let query = "build repo:haskell-github/github" result <- GitHub.github' GitHub.searchIssuesR query 1000 case result of Left e -> putStrLn $ "Error: " ++ show e Right r -> do forM_ (GitHub.searchResultResults r) $ \r -> do putStrLn $ formatIssue r putStrLn "" putStrLn $ "Count: " ++ show (GitHub.searchResultTotalCount r) ++ " matches for the query: \"" ++ T.unpack query ++ "\"" formatIssue :: GitHub.Issue -> String formatIssue issue = (show $ GitHub.issueUser issue) <> " opened this issue " <> (show $ GitHub.issueCreatedAt issue) <> "\n" <> (show $ GitHub.issueState issue) <> " with " <> (show $ GitHub.issueComments issue) <> " comments" <> "\n\n" <> (T.unpack $ GitHub.issueTitle issue)
null
https://raw.githubusercontent.com/haskell-github/github/83acdf8f4c7d525c896e9d12494be65a628007c3/samples/Search/SearchIssues.hs
haskell
# LANGUAGE OverloadedStrings #
module Main where import qualified GitHub import qualified Data.Text as T import Control.Monad (forM_) import Data.Monoid ((<>)) main :: IO () main = do let query = "build repo:haskell-github/github" result <- GitHub.github' GitHub.searchIssuesR query 1000 case result of Left e -> putStrLn $ "Error: " ++ show e Right r -> do forM_ (GitHub.searchResultResults r) $ \r -> do putStrLn $ formatIssue r putStrLn "" putStrLn $ "Count: " ++ show (GitHub.searchResultTotalCount r) ++ " matches for the query: \"" ++ T.unpack query ++ "\"" formatIssue :: GitHub.Issue -> String formatIssue issue = (show $ GitHub.issueUser issue) <> " opened this issue " <> (show $ GitHub.issueCreatedAt issue) <> "\n" <> (show $ GitHub.issueState issue) <> " with " <> (show $ GitHub.issueComments issue) <> " comments" <> "\n\n" <> (T.unpack $ GitHub.issueTitle issue)
d5ad7db608490d1cf287e14e77cdcec94bd8d19a12a123b2aa69093ebb6cccec
mstksg/advent-of-code-2017
Disjoints.hs
module AOC2017.Util.Disjoints ( Disjoints(..) , disjoint ) where import Data.List import qualified Data.IntSet as IS import qualified Data.Set as S -- | Monoid representing a collection of disjoint "connected sets" newtype Disjoints = D { getD :: S.Set IS.IntSet } instance Monoid Disjoints where mempty = D S.empty | mappend is much faster if the smaller set is second mappend xs ys = foldl' go ys (getD xs) where go (D zs) z = D (newGroup `S.insert` disjoints) where overlaps = S.filter (not . IS.null . (`IS.intersection` z)) zs disjoints = zs `S.difference` overlaps newGroup = IS.unions $ z : S.toList overlaps disjoint :: IS.IntSet -> Disjoints disjoint = D . S.singleton
null
https://raw.githubusercontent.com/mstksg/advent-of-code-2017/f9e97680726e87be175cf423241da3048ef6564d/src/AOC2017/Util/Disjoints.hs
haskell
| Monoid representing a collection of disjoint "connected sets"
module AOC2017.Util.Disjoints ( Disjoints(..) , disjoint ) where import Data.List import qualified Data.IntSet as IS import qualified Data.Set as S newtype Disjoints = D { getD :: S.Set IS.IntSet } instance Monoid Disjoints where mempty = D S.empty | mappend is much faster if the smaller set is second mappend xs ys = foldl' go ys (getD xs) where go (D zs) z = D (newGroup `S.insert` disjoints) where overlaps = S.filter (not . IS.null . (`IS.intersection` z)) zs disjoints = zs `S.difference` overlaps newGroup = IS.unions $ z : S.toList overlaps disjoint :: IS.IntSet -> Disjoints disjoint = D . S.singleton
279c53ab396c4e8e322b8ad51265211e36f825df097edef5ea6625a98296991f
grin-compiler/ghc-whole-program-compiler-project
Linker.hs
# LANGUAGE RecordWildCards # module Stg.Foreign.Linker where import Data.List import System.Directory import System.FilePath import System.Process import Text.Printf import Stg.Program import Stg.Syntax import Stg.Foreign.Stubs getExtStgWorkDirectory :: FilePath -> IO FilePath getExtStgWorkDirectory ghcstgappFname = do absFname <- makeAbsolute ghcstgappFname pure $ takeDirectory absFname </> ".ext-stg-work" </> takeBaseName ghcstgappFname linkForeignCbitsSharedLib :: FilePath -> IO () linkForeignCbitsSharedLib ghcstgappFname = do workDir <- getExtStgWorkDirectory ghcstgappFname createDirectoryIfMissing True workDir let stubFname = workDir </> "stub.c" genStubs ghcstgappFname >>= writeFile stubFname (StgAppLinkerInfo{..}, linkerInfoList') <- getAppLinkerInfo ghcstgappFname let linkerInfoList = filter (\StgLibLinkerInfo{..} -> stglibName /= "rts") linkerInfoList' cbitsOpts = [ unwords $ concat [ [ "-L" ++ dir | dir <- stglibExtraLibDirs] , stglibLdOptions , [ "-l" ++ lib | lib <- stglibExtraLibs] ] | StgLibLinkerInfo{..} <- linkerInfoList ] cbitsArs = concatMap stglibCbitsPaths linkerInfoList stubArs = concatMap stglibCapiStubsPaths linkerInfoList arList = case cbitsArs ++ stubArs of [] -> [] l -> case stgappPlatformOS of "darwin" -> ["-Wl,-all_load"] ++ l _ -> ["-Wl,--whole-archive"] ++ l ++ ["-Wl,--no-whole-archive"] stubOpts = [ "-fPIC" , "stub.c" ] appOpts = unwords $ concat [ [ "-L" ++ dir | dir <- stgappExtraLibDirs] , stgappLdOptions , [ "-l" ++ lib | lib <- stgappExtraLibs] ] linkScript = unlines [ "#!/usr/bin/env bash" , "set -e" , case stgappPlatformOS of "darwin" -> "gcc -o cbits.so -shared \\" _ -> "gcc -o cbits.so -shared -Wl,--no-as-needed \\" ] ++ intercalate " \\\n" (map (" " ++) . filter (/= "") $ arList ++ cbitsOpts ++ stgappCObjects ++ [appOpts] ++ stubOpts) ++ "\n" let scriptFname = workDir </> "cbits.so.sh" writeFile scriptFname linkScript callCommand $ printf "(cd %s; bash cbits.so.sh)" workDir
null
https://raw.githubusercontent.com/grin-compiler/ghc-whole-program-compiler-project/5c1121243e1a73dcf5882d8b6c4f6c5569234ea1/external-stg/lib/Stg/Foreign/Linker.hs
haskell
# LANGUAGE RecordWildCards # module Stg.Foreign.Linker where import Data.List import System.Directory import System.FilePath import System.Process import Text.Printf import Stg.Program import Stg.Syntax import Stg.Foreign.Stubs getExtStgWorkDirectory :: FilePath -> IO FilePath getExtStgWorkDirectory ghcstgappFname = do absFname <- makeAbsolute ghcstgappFname pure $ takeDirectory absFname </> ".ext-stg-work" </> takeBaseName ghcstgappFname linkForeignCbitsSharedLib :: FilePath -> IO () linkForeignCbitsSharedLib ghcstgappFname = do workDir <- getExtStgWorkDirectory ghcstgappFname createDirectoryIfMissing True workDir let stubFname = workDir </> "stub.c" genStubs ghcstgappFname >>= writeFile stubFname (StgAppLinkerInfo{..}, linkerInfoList') <- getAppLinkerInfo ghcstgappFname let linkerInfoList = filter (\StgLibLinkerInfo{..} -> stglibName /= "rts") linkerInfoList' cbitsOpts = [ unwords $ concat [ [ "-L" ++ dir | dir <- stglibExtraLibDirs] , stglibLdOptions , [ "-l" ++ lib | lib <- stglibExtraLibs] ] | StgLibLinkerInfo{..} <- linkerInfoList ] cbitsArs = concatMap stglibCbitsPaths linkerInfoList stubArs = concatMap stglibCapiStubsPaths linkerInfoList arList = case cbitsArs ++ stubArs of [] -> [] l -> case stgappPlatformOS of "darwin" -> ["-Wl,-all_load"] ++ l _ -> ["-Wl,--whole-archive"] ++ l ++ ["-Wl,--no-whole-archive"] stubOpts = [ "-fPIC" , "stub.c" ] appOpts = unwords $ concat [ [ "-L" ++ dir | dir <- stgappExtraLibDirs] , stgappLdOptions , [ "-l" ++ lib | lib <- stgappExtraLibs] ] linkScript = unlines [ "#!/usr/bin/env bash" , "set -e" , case stgappPlatformOS of "darwin" -> "gcc -o cbits.so -shared \\" _ -> "gcc -o cbits.so -shared -Wl,--no-as-needed \\" ] ++ intercalate " \\\n" (map (" " ++) . filter (/= "") $ arList ++ cbitsOpts ++ stgappCObjects ++ [appOpts] ++ stubOpts) ++ "\n" let scriptFname = workDir </> "cbits.so.sh" writeFile scriptFname linkScript callCommand $ printf "(cd %s; bash cbits.so.sh)" workDir
9a9a8e54cb9f992f509d8574a5b83f1391d4a3cf09a369dffdbaebca1be1e62a
yetanalytics/sse-fx
command.cljs
(ns com.yetanalytics.sse-fx.command "Easily send command events to a server. Posts, uses transit, and expects a 202" (:require [goog.net.XhrIo :as xhrio] [com.yetanalytics.sse-fx.codec :as codec] [re-frame.core :as re-frame])) (defn send-command! [{:keys [uri data encode-msg-fn handle-accepted handle-error headers] :or {encode-msg-fn codec/encode-string} :as arg-map}] (xhrio/send uri (fn [e] (let [xhr (.-target e) status (.getStatus xhr)] (if (= 202 status) (when handle-accepted (handle-accepted xhr arg-map)) (when handle-error (handle-error xhr arg-map))))) "POST" (cond-> data encode-msg-fn encode-msg-fn) (clj->js (merge {"Content-Type" "application/transit+json"} headers)))) (defn send-fx [{:keys [handle-accepted handle-error] :as arg-map}] (send-command! (cond-> arg-map handle-accepted (assoc :handle-accepted (fn [xhr argm] (re-frame/dispatch (conj handle-accepted xhr argm)))) handle-error (assoc :handle-error (fn [xhr argm] (re-frame/dispatch (conj handle-error xhr argm))))))) (defn register! "Register fx for commands" [] (do (re-frame/reg-fx ::send send-fx)))
null
https://raw.githubusercontent.com/yetanalytics/sse-fx/0d1cf6f271ea15d3d4a24d898caca6542d754b54/src/com/yetanalytics/sse_fx/command.cljs
clojure
(ns com.yetanalytics.sse-fx.command "Easily send command events to a server. Posts, uses transit, and expects a 202" (:require [goog.net.XhrIo :as xhrio] [com.yetanalytics.sse-fx.codec :as codec] [re-frame.core :as re-frame])) (defn send-command! [{:keys [uri data encode-msg-fn handle-accepted handle-error headers] :or {encode-msg-fn codec/encode-string} :as arg-map}] (xhrio/send uri (fn [e] (let [xhr (.-target e) status (.getStatus xhr)] (if (= 202 status) (when handle-accepted (handle-accepted xhr arg-map)) (when handle-error (handle-error xhr arg-map))))) "POST" (cond-> data encode-msg-fn encode-msg-fn) (clj->js (merge {"Content-Type" "application/transit+json"} headers)))) (defn send-fx [{:keys [handle-accepted handle-error] :as arg-map}] (send-command! (cond-> arg-map handle-accepted (assoc :handle-accepted (fn [xhr argm] (re-frame/dispatch (conj handle-accepted xhr argm)))) handle-error (assoc :handle-error (fn [xhr argm] (re-frame/dispatch (conj handle-error xhr argm))))))) (defn register! "Register fx for commands" [] (do (re-frame/reg-fx ::send send-fx)))
a1d6230565ceaf2e826cddf9f316cd1f4010157ca4567e2010613890ab45e9c6
CompSciCabal/SMRTYPRTY
nikolap.rkt
2.78 (define (type-tag datum) (cond ((number? datum) datum) ((pair? datum) (car datum)) (else (error "Bad tagged datum -- TYPE-TAG" datum)))) (define (contents datum) (cond ((number? datum) datum) ((pair? datum) (cadr datum)) (else (error "Bad tagged datum -- CONTENGS" datum)))) (define (attach-tag tag content) (cond ((number? content) content) ((pair? content) (cons tag content)))) 2.79 + 2.80 (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'make 'scheme-number (lambda (x) (tag x)) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (tag (= x y)))) (put '=zero? 'scheme-number (lambda (x) (= 0 x))) 'done)) (define (install-rational-package) ;; internal procedures (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (equ-rational? x y) (= (* (numer x) (denom y)) (* (numer y) (denom x)))) ;; interface to rest of the system (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) (put 'equ? '(rational rational) (lambda (x y) (tag (equ-rational? x y)))) (put '=zero? 'rational-number (lambda (x) (= 0 (numer x)))) 'done) (define (install-complex-package) ;; imported procedures from rectangular and polar packages (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) ;; internal procedures (define (add-complex z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) (define (div-complex z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) (define (equ-complex? z1 z2) (and (= (real-part z1) (real-part z2)) (= (imag-part z1) (imag-part z2)))) ;; interface to rest of the system (define (tag z) (attach-tag 'complex z)) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'equ? '(complex complex) (lambda (z1 z2) (tag (equ-complex? z1 z2)))) (put '=zero? 'complex-number (lambda (x) (= 0 (real-part x) (imag-part x)))) 'done) (define (equ? x y) (apply-generic 'equ? x y)) (define (=zero? x) (apply-generic '=zero? x)) 2.81 (define (apply-generic op . args) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (if (= (length args) 2) (let ((type1 (car type-tags)) (type2 (cadr type-tags)) (a1 (car args)) (a2 (cadr args))) (if (equal? type1 type2) (apply-generic op type1 type2) (let ((t1->t2 (get-coercion type1 type2)) (t2->t1 (get-coercion type2 type1))) (cond (t1->t2 (apply-generic op (t1->t2 a1) a2)) (t2->t1 (apply-generic op a1 (t2->t1 a2))) (else (error "No method for these types" (list op type-tags))))))) (error "No method for these types" (list op type-tags)))))))
null
https://raw.githubusercontent.com/CompSciCabal/SMRTYPRTY/4a5550789c997c20fb7256b81469de1f1fce3514/sicp/v3/2.5/nikolap.rkt
racket
internal procedures interface to rest of the system imported procedures from rectangular and polar packages internal procedures interface to rest of the system
2.78 (define (type-tag datum) (cond ((number? datum) datum) ((pair? datum) (car datum)) (else (error "Bad tagged datum -- TYPE-TAG" datum)))) (define (contents datum) (cond ((number? datum) datum) ((pair? datum) (cadr datum)) (else (error "Bad tagged datum -- CONTENGS" datum)))) (define (attach-tag tag content) (cond ((number? content) content) ((pair? content) (cons tag content)))) 2.79 + 2.80 (define (install-scheme-number-package) (define (tag x) (attach-tag 'scheme-number x)) (put 'add '(scheme-number scheme-number) (lambda (x y) (tag (+ x y)))) (put 'sub '(scheme-number scheme-number) (lambda (x y) (tag (- x y)))) (put 'mul '(scheme-number scheme-number) (lambda (x y) (tag (* x y)))) (put 'div '(scheme-number scheme-number) (lambda (x y) (tag (/ x y)))) (put 'make 'scheme-number (lambda (x) (tag x)) (put 'equ? '(scheme-number scheme-number) (lambda (x y) (tag (= x y)))) (put '=zero? 'scheme-number (lambda (x) (= 0 x))) 'done)) (define (install-rational-package) (define (numer x) (car x)) (define (denom x) (cdr x)) (define (make-rat n d) (let ((g (gcd n d))) (cons (/ n g) (/ d g)))) (define (add-rat x y) (make-rat (+ (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (sub-rat x y) (make-rat (- (* (numer x) (denom y)) (* (numer y) (denom x))) (* (denom x) (denom y)))) (define (mul-rat x y) (make-rat (* (numer x) (numer y)) (* (denom x) (denom y)))) (define (div-rat x y) (make-rat (* (numer x) (denom y)) (* (denom x) (numer y)))) (define (equ-rational? x y) (= (* (numer x) (denom y)) (* (numer y) (denom x)))) (define (tag x) (attach-tag 'rational x)) (put 'add '(rational rational) (lambda (x y) (tag (add-rat x y)))) (put 'sub '(rational rational) (lambda (x y) (tag (sub-rat x y)))) (put 'mul '(rational rational) (lambda (x y) (tag (mul-rat x y)))) (put 'div '(rational rational) (lambda (x y) (tag (div-rat x y)))) (put 'make 'rational (lambda (n d) (tag (make-rat n d)))) (put 'equ? '(rational rational) (lambda (x y) (tag (equ-rational? x y)))) (put '=zero? 'rational-number (lambda (x) (= 0 (numer x)))) 'done) (define (install-complex-package) (define (make-from-real-imag x y) ((get 'make-from-real-imag 'rectangular) x y)) (define (make-from-mag-ang r a) ((get 'make-from-mag-ang 'polar) r a)) (define (add-complex z1 z2) (make-from-real-imag (+ (real-part z1) (real-part z2)) (+ (imag-part z1) (imag-part z2)))) (define (sub-complex z1 z2) (make-from-real-imag (- (real-part z1) (real-part z2)) (- (imag-part z1) (imag-part z2)))) (define (mul-complex z1 z2) (make-from-mag-ang (* (magnitude z1) (magnitude z2)) (+ (angle z1) (angle z2)))) (define (div-complex z1 z2) (make-from-mag-ang (/ (magnitude z1) (magnitude z2)) (- (angle z1) (angle z2)))) (define (equ-complex? z1 z2) (and (= (real-part z1) (real-part z2)) (= (imag-part z1) (imag-part z2)))) (define (tag z) (attach-tag 'complex z)) (put 'add '(complex complex) (lambda (z1 z2) (tag (add-complex z1 z2)))) (put 'sub '(complex complex) (lambda (z1 z2) (tag (sub-complex z1 z2)))) (put 'mul '(complex complex) (lambda (z1 z2) (tag (mul-complex z1 z2)))) (put 'div '(complex complex) (lambda (z1 z2) (tag (div-complex z1 z2)))) (put 'make-from-real-imag 'complex (lambda (x y) (tag (make-from-real-imag x y)))) (put 'make-from-mag-ang 'complex (lambda (r a) (tag (make-from-mag-ang r a)))) (put 'equ? '(complex complex) (lambda (z1 z2) (tag (equ-complex? z1 z2)))) (put '=zero? 'complex-number (lambda (x) (= 0 (real-part x) (imag-part x)))) 'done) (define (equ? x y) (apply-generic 'equ? x y)) (define (=zero? x) (apply-generic '=zero? x)) 2.81 (define (apply-generic op . args) (let ((type-tags (map type-tag args))) (let ((proc (get op type-tags))) (if proc (apply proc (map contents args)) (if (= (length args) 2) (let ((type1 (car type-tags)) (type2 (cadr type-tags)) (a1 (car args)) (a2 (cadr args))) (if (equal? type1 type2) (apply-generic op type1 type2) (let ((t1->t2 (get-coercion type1 type2)) (t2->t1 (get-coercion type2 type1))) (cond (t1->t2 (apply-generic op (t1->t2 a1) a2)) (t2->t1 (apply-generic op a1 (t2->t1 a2))) (else (error "No method for these types" (list op type-tags))))))) (error "No method for these types" (list op type-tags)))))))
a2d0458490d84792bd369a46838748df46b781808344daa4717f8a208eb43bb4
elaforge/karya
Meter.hs
Copyright 2013 -- This program is distributed under the terms of the GNU General Public -- License 3.0, see COPYING or -3.0.txt # LANGUAGE CPP # -- | Support for rhythmic spelling in different meters. module Perform.Lilypond.Meter ( Meter, meter_nums, meter_denom , time_num , default_meter , measure_time , unparse_meter, parse_meter , is_binary -- * tie breaking , allowed_duration #ifdef TESTING , module Perform.Lilypond.Meter #endif ) where import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Text as Text import qualified Data.Vector.Unboxed as Vector import Data.Vector.Unboxed ((!)) import qualified Util.Num as Num import qualified Util.P as P import qualified Util.Parse as Parse import qualified Util.Seq as Seq import qualified Perform.Lilypond.Types as Types import Perform.Lilypond.Types (Duration(..), NoteDuration(..), Time) import qualified Ui.Meter.Make as Meter.Make import qualified Ui.Meter.Meter as Meter import Ui.Meter.Meter (AbstractMeter(..)) import Global data Meter = Meter { | NonEmpty list of numerators . E.g. [ 2 , 3 ] indicates 2 + 3 . meter_nums :: ![Int] , meter_denom :: !Duration , meter_ranks :: !Ranks } deriving (Eq, Show) | Meter rank , indexed by 128th note . type Ranks = Vector.Vector Rank type Rank = Int time_num :: Meter -> Int time_num = Num.sum . meter_nums rank_at :: Meter -> Time -> Int rank_at meter t = v ! (time_index t `mod` Vector.length v) where v = meter_ranks meter time_index :: Time -> Int time_index = fromIntegral index_time :: Int -> Time index_time = fromIntegral instance Pretty Meter where pretty = unparse_meter instance Types.ToLily Meter where to_lily (Meter nums denom _) = showt (Num.sum nums) <> "/" <> Types.to_lily denom is_binary :: Meter -> Bool is_binary meter = case meter_nums meter of [num] -> (==0) $ snd $ properFraction $ logBase 2 (fromIntegral num) _ -> False | Duration of a measure , in Time . measure_time :: Meter -> Time measure_time meter = fromIntegral (time_num meter) * Types.dur_to_time (meter_denom meter) unparse_meter :: Meter -> Text unparse_meter meter = Text.intercalate "+" (map showt (meter_nums meter)) <> "/" <> Types.to_lily (meter_denom meter) default_meter :: Meter Right default_meter = parse_meter "4/4" parse_meter :: Text -> Either Text Meter parse_meter text = do (nums, denom) <- first ("parsing meter: "<>) $ Parse.parse p_meter text denom <- tryJust ("denominator not a valid duration: " <> showt denom) $ Types.int_dur denom make_meter nums denom (abstract_meter nums denom) abstract_meter :: [Int] -> Duration -> [AbstractMeter] abstract_meter nums denom = case Map.lookup (nums, denom) default_meters of Just m -> [m] Nothing -> case default_divisions nums denom of [num] -> [D (replicate num T)] nums -> [D [D (replicate n T) | n <- nums]] where -- Certain simple duple meters get a simpler division. This has the effect of allowing notes to cross beat divisions , e.g. 4 2 4 in 4/4 . default_meters = Map.fromList [ (([1], D4), T) , (([2], D4), T) , (([4], D4), T) ] default_divisions :: [Int] -> Duration -> [Int] default_divisions [num] denom = Map.findWithDefault [num] (num, denom) defaults where defaults = Map.fromList [ ((5, D8), [3, 2]) , ((6, D8), [3, 3]) , ((7, D8), [3, 4]) , ((9, D8), [3, 3, 3]) , ((12, D8), [3, 3, 3, 3]) ] default_divisions nums _ = nums p_meter :: Parse.Parser ([Int], Int) p_meter = (,) <$> P.sepBy1 Parse.p_positive (P.char '+') <*> (P.char '/' *> Parse.p_positive) make_meter :: [Int] -> Duration -> [AbstractMeter] -> Either Text Meter make_meter nums denom meters = Meter nums denom <$> vector where vector | frac /= 0 = Left $ "can't fit " <> showt ranks <> " into " <> showt expected <> " by doubling" | otherwise = Right $ to_vector $ subdivides (replicate exp 2) meters (exp, frac) = properFraction $ logBase 2 (fromIntegral expected / fromIntegral ranks) expected = Num.sum nums * time_index (Types.dur_to_time denom) ranks = Num.sum $ map abstract_length meters to_vector = Vector.fromList . map (fromEnum . fst) . Meter.Make.to_rank_durations . map (1,) subdivides :: [Int] -> [AbstractMeter] -> [AbstractMeter] subdivides divs meter = foldr subdivide meter (reverse divs) subdivide :: Int -> [AbstractMeter] -> [AbstractMeter] subdivide n = map (Meter.subdivide n) abstract_length :: AbstractMeter -> Int abstract_length (D ds) = Num.sum $ map abstract_length ds abstract_length T = 1 -- * allowed time | Figure out how much time a note at the given position should be allowed before it must tie . The heuristic is : - A binary meter is one whose numerator is a power of 2 . - First , restrict the maximum ' allowed_time ' . For binary meters , this is up to the rank of the start point - 2 , which means that if you start on an 8th note , you can span until the next half note . Compound meters are different because the rank divisions do n't correspond to binary note divisions ( e.g. 3/4 goes dotted half , quarter , 8th , etc . , instead of 4/4 's whole , half , quarter , etc . ) . So they only go up to the rank-1 . This is winds up being too restrictive though , because it means that e.g. you could never span a quarter note if you start on an eighth , but 8 4 8 4 is a perfectly readable 3/4 bar . So the allowed duration is extended to twice the duration to the next rank-1 crossing , which allows 8 8~8 to become 8 4 . - Next , if the allowed duration corresponds exactly to possible note duration , take that . This expresses that it 's preferable to spell without a tie if you can . If it does n't correspond to a note duration , then it has to be tied , and break on the place where it crosses the lowest rank . - Complex meters like 2 + 3/4 are treated as binary if you are in the binary part . TODO not yet See NOTE [ tie - breaking heuristic ] before it must tie. The heuristic is: - A binary meter is one whose numerator is a power of 2. - First, restrict the maximum 'allowed_time'. For binary meters, this is up to the rank of the start point - 2, which means that if you start on an 8th note, you can span until the next half note. Compound meters are different because the rank divisions don't correspond to binary note divisions (e.g. 3/4 goes dotted half, quarter, 8th, etc., instead of 4/4's whole, half, quarter, etc.). So they only go up to the rank-1. This is winds up being too restrictive though, because it means that e.g. you could never span a quarter note if you start on an eighth, but 8 4 8 4 is a perfectly readable 3/4 bar. So the allowed duration is extended to twice the duration to the next rank-1 crossing, which allows 8 8~8 to become 8 4. - Next, if the allowed duration corresponds exactly to possible note duration, take that. This expresses that it's preferable to spell without a tie if you can. If it doesn't correspond to a note duration, then it has to be tied, and break on the place where it crosses the lowest rank. - Complex meters like 2+3/4 are treated as binary if you are in the binary part. TODO not yet See NOTE [tie-breaking heuristic] -} allowed_duration :: Bool -> Meter -> Time -> Time -> NoteDuration allowed_duration use_dot meter start_ dur = best_duration . min (start + dur) $ allowed_time meter start where best_duration end | Just ndur <- List.find ((== start+dur) . to_time) candidates = ndur | otherwise = fromMaybe (Types.NoteDuration Types.D128 False) $ Seq.minimum_on (rank_at meter . to_time) candidates where candidates = takeWhile ((<=end) . to_time) $ if use_dot then dotted_durs else durs durs = reverse $ map (flip NoteDuration False) [D1 .. D128] dotted_durs = reverse [NoteDuration d dot | d <- [D1 .. D64], dot <- [True, False]] start = start_ `mod` measure_time meter to_time dur = start + Types.note_dur_to_time dur -- | See 'allowed_duration'. allowed_time :: Meter -> Time -> Time allowed_time meter start = fromMaybe (measure_time meter) $ if is_binary meter -- TODO is_binary in this part of the meter then at_rank (start_rank - 2) else case at_rank (start_rank - 1) of Nothing -> Nothing Just end -> min (start + (end - start) * 2) <$> at_rank (start_rank - 2) where at_rank n = find_rank start n meter start_rank = rank_at meter start -- | Find the time of the rank <= the given one. Rank 0 can never be spanned, -- so always stop at a rank 0. find_rank :: Time -> Rank -> Meter -> Maybe Time find_rank start rank = fmap ((+ (start + 1)) . index_time) . Vector.findIndex (<= max 0 rank) . Vector.drop (time_index start + 1) . meter_ranks NOTE [ tie - breaking heuristic ] Because it 's 3/4 , h is not a valid rank , because it does n't divide at natural points . Actually ranks are not note durations , they are metric divisions . But this should be ok : 0 w | 3/4 1 q q q | 2 e e e e e e | 4 - ----->4 - ----->8 - ->| But if it 's longer than 4 , then switch to tieing on the low rank : 0 w | 3/4 1 q q q | 2 e e e e e e | 8 - - > | 4 - ----- > | 8 - ->4 - ----- > | 4 . , but 4 . is too complicated 8 - ->4.--------- > | 2 , seems like jumping 2 ranks , 8,4,2 . 8 - ->2 - ------------->| 0 w | 3/4 1 q q q | 2 e e e e e e | 3 s s s s s s s s s s s s | s > 8 - - > s>8 - - > s>8 - ->s > s>4 - ----- > s>4 - ----->s > s>8 - ->4 - ----- > So maybe what I want is not spanning ranks , but the duration spanning ranks . E.g. I started on an 8th note rank , so I can have up to 4 duration , but not beyond . Or maybe I could go up to rank-1 , but add a candidate at distance * 2 ? 0 w | 5/4 1 h h | 2 q q q q q | 3 e e e e e e e e e e | 4 s s s s s s s s s s s s s s s s s s s s | I think this is like 4/4 , if I do n't cross rank 1 I should be ok . Or treat it as one 2/4 , one 3/4 ? In that case , I should n't do complicated things in the second part . 0 w | 6/8 1 q q | 2 e e e e e e | 8 - - > 4 - ----- > 4 - ----->8 - - > 1 q q | 2 e e e e e e | 8 - ->8 - - > 0 w | 6/8 1 q q | 2 e e e e e e | 3 s s s s s s s s s s s s | s > 8 - - > s>8 - - > 0 w | 4/4 1 h h | 2 q q q q | 3 e e e e e e e e | 8 - - > 4 - ----- > 8 - ->8.-- > 4.--------- > 4.--------->8 - - > | could be 2 , but crosses h 4.--------->4 - ----- > | so 3 to 1 But 1 h h | 16 2 q q q q | 8 3 e e e e e e e e | 4 4 - ----->4 - ----->4 - ----- > 4 - ----->8 - ->8 - ->4 - ----- > 2 - ------------- > So for binary , go up to rank-2 . For compound , go up to rank-1 , but allow a complete note as long as its duration is rank-1 . Or maybe I could say I do n't like 8~8 2 q q q q | 8 3 e e e e e e e e | 4 4 s s s s s s s s s s s s s s s s | 2 s > 8 - - > > 8.--->s > 8.--->8 - - > 8.--->8.--- > 8.--->4 - ----- > 4/4 0 w | 32 1 h h | 16 2 q q q q | 8 3 e e e e e e e e | 4 4 s s s s s s s s s s s s s s s s | 2 5 33333333333333333333333333333333| 1 |------ > |-------------------------- > 3/4 0 w | 1 h h | 2 q q q | 3 e e e e e e | 4 s s s s s s s s s s s s | 5 333333333333333333333333| 2.--------------------- > 0->0 8- > 3->2 2 - -------------- > 2->0 8 - - > 3->2 4 - ------ > 2->0 8 - -- > 3->end NOTE [tie-breaking heuristic] Because it's 3/4, h is not a valid rank, because it doesn't divide at natural points. Actually ranks are not note durations, they are metric divisions. But this should be ok: 0 w | 3/4 1 q q q | 2 e e e e e e | 4------>4------>8-->| But if it's longer than 4, then switch to tieing on the low rank: 0 w | 3/4 1 q q q | 2 e e e e e e | 8--> | 4------> | 8-->4------> | 4., but 4. is too complicated 8-->4.---------> | 2, seems like jumping 2 ranks, 8,4,2. 8-->2-------------->| 0 w | 3/4 1 q q q | 2 e e e e e e | 3 s s s s s s s s s s s s | s> 8--> s>8--> s>8-->s> s>4------> s>4------>s> s>8-->4------> So maybe what I want is not spanning ranks, but the duration spanning ranks. E.g. I started on an 8th note rank, so I can have up to 4 duration, but not beyond. Or maybe I could go up to rank-1, but add a candidate at distance * 2? 0 w | 5/4 1 h h | 2 q q q q q | 3 e e e e e e e e e e | 4 s s s s s s s s s s s s s s s s s s s s | I think this is like 4/4, if I don't cross rank 1 I should be ok. Or treat it as one 2/4, one 3/4? In that case, I shouldn't do complicated things in the second part. 0 w | 6/8 1 q q | 2 e e e e e e | 8--> 4------> 4------>8--> 1 q q | 2 e e e e e e | 8-->8--> 0 w | 6/8 1 q q | 2 e e e e e e | 3 s s s s s s s s s s s s | s> 8--> s>8--> 0 w | 4/4 1 h h | 2 q q q q | 3 e e e e e e e e | 8--> 4------> 8-->8.--> 4.---------> 4.--------->8--> | could be 2, but crosses h 4.--------->4------> | so 3 to 1 But 1 h h | 16 2 q q q q | 8 3 e e e e e e e e | 4 4------>4------>4------> 4------>8-->8-->4------> 2--------------> So for binary, go up to rank-2. For compound, go up to rank-1, but allow a complete note as long as its duration is rank-1. Or maybe I could say I don't like 8~8 2 q q q q | 8 3 e e e e e e e e | 4 4 s s s s s s s s s s s s s s s s | 2 s> 8--> 8.---> 8.--->s> 8.--->8--> 8.--->8.---> 8.--->4------> 4/4 0 w | 32 1 h h | 16 2 q q q q | 8 3 e e e e e e e e | 4 4 s s s s s s s s s s s s s s s s | 2 5 33333333333333333333333333333333| 1 |------> |--------------------------> 3/4 0 w | 1 h h | 2 q q q | 3 e e e e e e | 4 s s s s s s s s s s s s | 5 333333333333333333333333| 2.---------------------> 0->0 8-> 3->2 2---------------> 2->0 8--> 3->2 4-------> 2->0 8---> 3->end -}
null
https://raw.githubusercontent.com/elaforge/karya/a6638f16da9f018686023977c1292d6ce5095e28/Perform/Lilypond/Meter.hs
haskell
This program is distributed under the terms of the GNU General Public License 3.0, see COPYING or -3.0.txt | Support for rhythmic spelling in different meters. * tie breaking Certain simple duple meters get a simpler division. This has the effect * allowed time | See 'allowed_duration'. TODO is_binary in this part of the meter | Find the time of the rank <= the given one. Rank 0 can never be spanned, so always stop at a rank 0. --->4 - ----->8 - ->| --- > | --- > | 4 . , but 4 . is too complicated ------- > | 2 , seems like jumping 2 ranks , 8,4,2 . ----------->| --- > --->s > --- > --- > --->8 - - > --- > > ------- > ------->8 - - > | could be 2 , but crosses h ------->4 - ----- > | so 3 to 1 --->4 - ----->4 - ----- > --->8 - ->8 - ->4 - ----- > ----------- > ->s > ->8 - - > ->8.--- > ->4 - ----- > ---- > ------------------------ > ------------------- > 0->0 ------------ > 2->0 ---- > 2->0 > 3->end ---->4------>8-->| > | ----> | >4------> | 4., but 4. is too complicated >4.---------> | 2, seems like jumping 2 ranks, 8,4,2. >2-------------->| > > >s> ----> ---->s> >4------> > ----> ---->8--> >8--> > > > ----> >8.--> -------> ------->8--> | could be 2, but crosses h ------->4------> | so 3 to 1 ---->4------>4------> ---->8-->8-->4------> ------------> > -> ->s> ->8--> ->8.---> ->4------> ----> ------------------------> -------------------> 0->0 -------------> 2->0 > 3->2 -----> 2->0 -> 3->end
Copyright 2013 # LANGUAGE CPP # module Perform.Lilypond.Meter ( Meter, meter_nums, meter_denom , time_num , default_meter , measure_time , unparse_meter, parse_meter , is_binary , allowed_duration #ifdef TESTING , module Perform.Lilypond.Meter #endif ) where import qualified Data.List as List import qualified Data.Map as Map import qualified Data.Text as Text import qualified Data.Vector.Unboxed as Vector import Data.Vector.Unboxed ((!)) import qualified Util.Num as Num import qualified Util.P as P import qualified Util.Parse as Parse import qualified Util.Seq as Seq import qualified Perform.Lilypond.Types as Types import Perform.Lilypond.Types (Duration(..), NoteDuration(..), Time) import qualified Ui.Meter.Make as Meter.Make import qualified Ui.Meter.Meter as Meter import Ui.Meter.Meter (AbstractMeter(..)) import Global data Meter = Meter { | NonEmpty list of numerators . E.g. [ 2 , 3 ] indicates 2 + 3 . meter_nums :: ![Int] , meter_denom :: !Duration , meter_ranks :: !Ranks } deriving (Eq, Show) | Meter rank , indexed by 128th note . type Ranks = Vector.Vector Rank type Rank = Int time_num :: Meter -> Int time_num = Num.sum . meter_nums rank_at :: Meter -> Time -> Int rank_at meter t = v ! (time_index t `mod` Vector.length v) where v = meter_ranks meter time_index :: Time -> Int time_index = fromIntegral index_time :: Int -> Time index_time = fromIntegral instance Pretty Meter where pretty = unparse_meter instance Types.ToLily Meter where to_lily (Meter nums denom _) = showt (Num.sum nums) <> "/" <> Types.to_lily denom is_binary :: Meter -> Bool is_binary meter = case meter_nums meter of [num] -> (==0) $ snd $ properFraction $ logBase 2 (fromIntegral num) _ -> False | Duration of a measure , in Time . measure_time :: Meter -> Time measure_time meter = fromIntegral (time_num meter) * Types.dur_to_time (meter_denom meter) unparse_meter :: Meter -> Text unparse_meter meter = Text.intercalate "+" (map showt (meter_nums meter)) <> "/" <> Types.to_lily (meter_denom meter) default_meter :: Meter Right default_meter = parse_meter "4/4" parse_meter :: Text -> Either Text Meter parse_meter text = do (nums, denom) <- first ("parsing meter: "<>) $ Parse.parse p_meter text denom <- tryJust ("denominator not a valid duration: " <> showt denom) $ Types.int_dur denom make_meter nums denom (abstract_meter nums denom) abstract_meter :: [Int] -> Duration -> [AbstractMeter] abstract_meter nums denom = case Map.lookup (nums, denom) default_meters of Just m -> [m] Nothing -> case default_divisions nums denom of [num] -> [D (replicate num T)] nums -> [D [D (replicate n T) | n <- nums]] where of allowing notes to cross beat divisions , e.g. 4 2 4 in 4/4 . default_meters = Map.fromList [ (([1], D4), T) , (([2], D4), T) , (([4], D4), T) ] default_divisions :: [Int] -> Duration -> [Int] default_divisions [num] denom = Map.findWithDefault [num] (num, denom) defaults where defaults = Map.fromList [ ((5, D8), [3, 2]) , ((6, D8), [3, 3]) , ((7, D8), [3, 4]) , ((9, D8), [3, 3, 3]) , ((12, D8), [3, 3, 3, 3]) ] default_divisions nums _ = nums p_meter :: Parse.Parser ([Int], Int) p_meter = (,) <$> P.sepBy1 Parse.p_positive (P.char '+') <*> (P.char '/' *> Parse.p_positive) make_meter :: [Int] -> Duration -> [AbstractMeter] -> Either Text Meter make_meter nums denom meters = Meter nums denom <$> vector where vector | frac /= 0 = Left $ "can't fit " <> showt ranks <> " into " <> showt expected <> " by doubling" | otherwise = Right $ to_vector $ subdivides (replicate exp 2) meters (exp, frac) = properFraction $ logBase 2 (fromIntegral expected / fromIntegral ranks) expected = Num.sum nums * time_index (Types.dur_to_time denom) ranks = Num.sum $ map abstract_length meters to_vector = Vector.fromList . map (fromEnum . fst) . Meter.Make.to_rank_durations . map (1,) subdivides :: [Int] -> [AbstractMeter] -> [AbstractMeter] subdivides divs meter = foldr subdivide meter (reverse divs) subdivide :: Int -> [AbstractMeter] -> [AbstractMeter] subdivide n = map (Meter.subdivide n) abstract_length :: AbstractMeter -> Int abstract_length (D ds) = Num.sum $ map abstract_length ds abstract_length T = 1 | Figure out how much time a note at the given position should be allowed before it must tie . The heuristic is : - A binary meter is one whose numerator is a power of 2 . - First , restrict the maximum ' allowed_time ' . For binary meters , this is up to the rank of the start point - 2 , which means that if you start on an 8th note , you can span until the next half note . Compound meters are different because the rank divisions do n't correspond to binary note divisions ( e.g. 3/4 goes dotted half , quarter , 8th , etc . , instead of 4/4 's whole , half , quarter , etc . ) . So they only go up to the rank-1 . This is winds up being too restrictive though , because it means that e.g. you could never span a quarter note if you start on an eighth , but 8 4 8 4 is a perfectly readable 3/4 bar . So the allowed duration is extended to twice the duration to the next rank-1 crossing , which allows 8 8~8 to become 8 4 . - Next , if the allowed duration corresponds exactly to possible note duration , take that . This expresses that it 's preferable to spell without a tie if you can . If it does n't correspond to a note duration , then it has to be tied , and break on the place where it crosses the lowest rank . - Complex meters like 2 + 3/4 are treated as binary if you are in the binary part . TODO not yet See NOTE [ tie - breaking heuristic ] before it must tie. The heuristic is: - A binary meter is one whose numerator is a power of 2. - First, restrict the maximum 'allowed_time'. For binary meters, this is up to the rank of the start point - 2, which means that if you start on an 8th note, you can span until the next half note. Compound meters are different because the rank divisions don't correspond to binary note divisions (e.g. 3/4 goes dotted half, quarter, 8th, etc., instead of 4/4's whole, half, quarter, etc.). So they only go up to the rank-1. This is winds up being too restrictive though, because it means that e.g. you could never span a quarter note if you start on an eighth, but 8 4 8 4 is a perfectly readable 3/4 bar. So the allowed duration is extended to twice the duration to the next rank-1 crossing, which allows 8 8~8 to become 8 4. - Next, if the allowed duration corresponds exactly to possible note duration, take that. This expresses that it's preferable to spell without a tie if you can. If it doesn't correspond to a note duration, then it has to be tied, and break on the place where it crosses the lowest rank. - Complex meters like 2+3/4 are treated as binary if you are in the binary part. TODO not yet See NOTE [tie-breaking heuristic] -} allowed_duration :: Bool -> Meter -> Time -> Time -> NoteDuration allowed_duration use_dot meter start_ dur = best_duration . min (start + dur) $ allowed_time meter start where best_duration end | Just ndur <- List.find ((== start+dur) . to_time) candidates = ndur | otherwise = fromMaybe (Types.NoteDuration Types.D128 False) $ Seq.minimum_on (rank_at meter . to_time) candidates where candidates = takeWhile ((<=end) . to_time) $ if use_dot then dotted_durs else durs durs = reverse $ map (flip NoteDuration False) [D1 .. D128] dotted_durs = reverse [NoteDuration d dot | d <- [D1 .. D64], dot <- [True, False]] start = start_ `mod` measure_time meter to_time dur = start + Types.note_dur_to_time dur allowed_time :: Meter -> Time -> Time allowed_time meter start = fromMaybe (measure_time meter) $ if is_binary meter then at_rank (start_rank - 2) else case at_rank (start_rank - 1) of Nothing -> Nothing Just end -> min (start + (end - start) * 2) <$> at_rank (start_rank - 2) where at_rank n = find_rank start n meter start_rank = rank_at meter start find_rank :: Time -> Rank -> Meter -> Maybe Time find_rank start rank = fmap ((+ (start + 1)) . index_time) . Vector.findIndex (<= max 0 rank) . Vector.drop (time_index start + 1) . meter_ranks NOTE [ tie - breaking heuristic ] Because it 's 3/4 , h is not a valid rank , because it does n't divide at natural points . Actually ranks are not note durations , they are metric divisions . But this should be ok : 0 w | 3/4 1 q q q | 2 e e e e e e | But if it 's longer than 4 , then switch to tieing on the low rank : 0 w | 3/4 1 q q q | 2 e e e e e e | 8 - - > | 0 w | 3/4 1 q q q | 2 e e e e e e | 3 s s s s s s s s s s s s | s > 8 - - > s>8 - - > s>8 - ->s > So maybe what I want is not spanning ranks , but the duration spanning ranks . E.g. I started on an 8th note rank , so I can have up to 4 duration , but not beyond . Or maybe I could go up to rank-1 , but add a candidate at distance * 2 ? 0 w | 5/4 1 h h | 2 q q q q q | 3 e e e e e e e e e e | 4 s s s s s s s s s s s s s s s s s s s s | I think this is like 4/4 , if I do n't cross rank 1 I should be ok . Or treat it as one 2/4 , one 3/4 ? In that case , I should n't do complicated things in the second part . 0 w | 6/8 1 q q | 2 e e e e e e | 8 - - > 1 q q | 2 e e e e e e | 8 - ->8 - - > 0 w | 6/8 1 q q | 2 e e e e e e | 3 s s s s s s s s s s s s | s > 8 - - > s>8 - - > 0 w | 4/4 1 h h | 2 q q q q | 3 e e e e e e e e | 8 - - > But 1 h h | 16 2 q q q q | 8 3 e e e e e e e e | 4 So for binary , go up to rank-2 . For compound , go up to rank-1 , but allow a complete note as long as its duration is rank-1 . Or maybe I could say I do n't like 8~8 2 q q q q | 8 3 e e e e e e e e | 4 4 s s s s s s s s s s s s s s s s | 2 s > 8 - - > > 4/4 0 w | 32 1 h h | 16 2 q q q q | 8 3 e e e e e e e e | 4 4 s s s s s s s s s s s s s s s s | 2 5 33333333333333333333333333333333| 1 3/4 0 w | 1 h h | 2 q q q | 3 e e e e e e | 4 s s s s s s s s s s s s | 5 333333333333333333333333| 8- > 3->2 8 - - > 3->2 NOTE [tie-breaking heuristic] Because it's 3/4, h is not a valid rank, because it doesn't divide at natural points. Actually ranks are not note durations, they are metric divisions. But this should be ok: 0 w | 3/4 1 q q q | 2 e e e e e e | But if it's longer than 4, then switch to tieing on the low rank: 0 w | 3/4 1 q q q | 2 e e e e e e | 0 w | 3/4 1 q q q | 2 e e e e e e | 3 s s s s s s s s s s s s | s> So maybe what I want is not spanning ranks, but the duration spanning ranks. E.g. I started on an 8th note rank, so I can have up to 4 duration, but not beyond. Or maybe I could go up to rank-1, but add a candidate at distance * 2? 0 w | 5/4 1 h h | 2 q q q q q | 3 e e e e e e e e e e | 4 s s s s s s s s s s s s s s s s s s s s | I think this is like 4/4, if I don't cross rank 1 I should be ok. Or treat it as one 2/4, one 3/4? In that case, I shouldn't do complicated things in the second part. 0 w | 6/8 1 q q | 2 e e e e e e | 1 q q | 2 e e e e e e | 0 w | 6/8 1 q q | 2 e e e e e e | 3 s s s s s s s s s s s s | s> 0 w | 4/4 1 h h | 2 q q q q | 3 e e e e e e e e | But 1 h h | 16 2 q q q q | 8 3 e e e e e e e e | 4 So for binary, go up to rank-2. For compound, go up to rank-1, but allow a complete note as long as its duration is rank-1. Or maybe I could say I don't like 8~8 2 q q q q | 8 3 e e e e e e e e | 4 4 s s s s s s s s s s s s s s s s | 2 s> 4/4 0 w | 32 1 h h | 16 2 q q q q | 8 3 e e e e e e e e | 4 4 s s s s s s s s s s s s s s s s | 2 5 33333333333333333333333333333333| 1 3/4 0 w | 1 h h | 2 q q q | 3 e e e e e e | 4 s s s s s s s s s s s s | 5 333333333333333333333333| 8-> 3->2 -}
dd9846fef6b5ee0ecf8043b53eca77e238b8aa89d1d4108fac9850f32215d59c
xclerc/ocamljava
sTM.mli
* This file is part of library . * Copyright ( C ) 2007 - 2015 . * * library is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation ; either version 3 of the License , or * ( at your option ) any later version . * * library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program . If not , see < / > . * This file is part of OCaml-Java library. * Copyright (C) 2007-2015 Xavier Clerc. * * OCaml-Java library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * OCaml-Java library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see </>. *) * Minimalistic implementation of a Software Transactional Memory . { b WARNING :} the current implementation has only been lightly tested . This module provides support for a { i partial } STM , that protects only values of type [ STM.ref ] . {b WARNING:} the current implementation has only been lightly tested. This module provides support for a {i partial} STM, that protects only values of type [STM.ref]. *) type 'a ref (** The type of values protected by transactions, should store only immutable values. *) val ref : 'a -> 'a ref (** Builds a value of type [ref], that can then only be accessed during a transaction. *) exception Retry (** The exception used to request the current transaction to restart. *) exception Abort (** The exception used to request the current transaction to be cancelled. Any exception can be used to abort a transaction, but this one makes programs more readable. *) exception Cancelled (** The exception used to indicate that the transaction is cancelled, because it has failed and retries have been exhausted. *) val run : ?retries:int -> (('a ref -> 'a) -> ('a ref -> 'a -> unit) -> 'b) -> 'b * [ run ~retries f ] executes the function [ f ] inside a newly - created transaction . Function [ f ] is passed two functions [ g ] and [ s ] that are to be used as respectively read and write accessors to [ ref ] values . The [ retries ] parameter ( defaulting to [ 64 ] ) indicates how many time a transaction should be retried . [ g ] and [ s ] will raise [ Failure ] is they are called from another thread , or outside the lifetime of the transaction . The [ Retry ] exception can be raised to requested the current transaction to be re - executed from the beginning , while any other exception will cause the transaction to be aborted . Raises the exception raised by the transaction , if different from [ Retry ] . @raise Cancelled if the transaction can not be committed , and retries have been exhausted transaction. Function [f] is passed two functions [g] and [s] that are to be used as respectively read and write accessors to [ref] values. The [retries] parameter (defaulting to [64]) indicates how many time a transaction should be retried. [g] and [s] will raise [Failure] is they are called from another thread, or outside the lifetime of the transaction. The [Retry] exception can be raised to requested the current transaction to be re-executed from the beginning, while any other exception will cause the transaction to be aborted. Raises the exception raised by the transaction, if different from [Retry]. @raise Cancelled if the transaction cannot be committed, and retries have been exhausted *) val run_read_only : ?retries:int -> (('a ref -> 'a) -> 'b) -> 'b (** Akin to {!run}, but with a smaller overhead due to the fact that the transaction is guaranteed to only read values. *)
null
https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/library/concurrent/src/stm/sTM.mli
ocaml
* The type of values protected by transactions, should store only immutable values. * Builds a value of type [ref], that can then only be accessed during a transaction. * The exception used to request the current transaction to restart. * The exception used to request the current transaction to be cancelled. Any exception can be used to abort a transaction, but this one makes programs more readable. * The exception used to indicate that the transaction is cancelled, because it has failed and retries have been exhausted. * Akin to {!run}, but with a smaller overhead due to the fact that the transaction is guaranteed to only read values.
* This file is part of library . * Copyright ( C ) 2007 - 2015 . * * library is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation ; either version 3 of the License , or * ( at your option ) any later version . * * library is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program . If not , see < / > . * This file is part of OCaml-Java library. * Copyright (C) 2007-2015 Xavier Clerc. * * OCaml-Java library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * OCaml-Java library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see </>. *) * Minimalistic implementation of a Software Transactional Memory . { b WARNING :} the current implementation has only been lightly tested . This module provides support for a { i partial } STM , that protects only values of type [ STM.ref ] . {b WARNING:} the current implementation has only been lightly tested. This module provides support for a {i partial} STM, that protects only values of type [STM.ref]. *) type 'a ref val ref : 'a -> 'a ref exception Retry exception Abort exception Cancelled val run : ?retries:int -> (('a ref -> 'a) -> ('a ref -> 'a -> unit) -> 'b) -> 'b * [ run ~retries f ] executes the function [ f ] inside a newly - created transaction . Function [ f ] is passed two functions [ g ] and [ s ] that are to be used as respectively read and write accessors to [ ref ] values . The [ retries ] parameter ( defaulting to [ 64 ] ) indicates how many time a transaction should be retried . [ g ] and [ s ] will raise [ Failure ] is they are called from another thread , or outside the lifetime of the transaction . The [ Retry ] exception can be raised to requested the current transaction to be re - executed from the beginning , while any other exception will cause the transaction to be aborted . Raises the exception raised by the transaction , if different from [ Retry ] . @raise Cancelled if the transaction can not be committed , and retries have been exhausted transaction. Function [f] is passed two functions [g] and [s] that are to be used as respectively read and write accessors to [ref] values. The [retries] parameter (defaulting to [64]) indicates how many time a transaction should be retried. [g] and [s] will raise [Failure] is they are called from another thread, or outside the lifetime of the transaction. The [Retry] exception can be raised to requested the current transaction to be re-executed from the beginning, while any other exception will cause the transaction to be aborted. Raises the exception raised by the transaction, if different from [Retry]. @raise Cancelled if the transaction cannot be committed, and retries have been exhausted *) val run_read_only : ?retries:int -> (('a ref -> 'a) -> 'b) -> 'b
aa81afd44b28a40788fbc44ec77634a40c2902c1bc61737a394293620d6e0b51
mirage/mirage
context.mli
* Copyright ( c ) 2013 - 2020 < > * Copyright ( c ) 2013 - 2020 Anil Madhavapeddy < > * Copyright ( c ) 2015 - 2020 < > * * 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-2020 Thomas Gazagnaire <> * Copyright (c) 2013-2020 Anil Madhavapeddy <> * Copyright (c) 2015-2020 Gabriel Radanne <> * * 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. *) (** Universal map of keys *) type 'a key (** The type for keys. *) val new_key : string -> 'a key (** [new_key n] is a new key with name [k]. *) type t (** The type for context maps. *) val empty : t (** [empty] is the empty context. *) val add : 'a key -> 'a -> t -> t (** [add k v t] is [t] augmented with the binding [(k, v)]. Any previous binding of [k] is removed. *) val mem : 'a key -> t -> bool (** [mem k t] is true iff [k] has been added to [t]. *) val find : 'a key -> t -> 'a option (** [find k t] is [v] is the binding [(k, v)] has been added to [t], otherwise it is [None]. *) val merge : default:t -> t -> t * [ merge ] merges [ t ] on top of [ default ] . If a key appears in both [ default ] and [ t ] , the value present in [ t ] is kept . [default] and [t], the value present in [t] is kept. *) val dump : t Fmt.t (** [dump] dumps the state of [t]. *)
null
https://raw.githubusercontent.com/mirage/mirage/7e36d793ad8bd34beb51bbba62a39aa035f7e297/lib/functoria/context.mli
ocaml
* Universal map of keys * The type for keys. * [new_key n] is a new key with name [k]. * The type for context maps. * [empty] is the empty context. * [add k v t] is [t] augmented with the binding [(k, v)]. Any previous binding of [k] is removed. * [mem k t] is true iff [k] has been added to [t]. * [find k t] is [v] is the binding [(k, v)] has been added to [t], otherwise it is [None]. * [dump] dumps the state of [t].
* Copyright ( c ) 2013 - 2020 < > * Copyright ( c ) 2013 - 2020 Anil Madhavapeddy < > * Copyright ( c ) 2015 - 2020 < > * * 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-2020 Thomas Gazagnaire <> * Copyright (c) 2013-2020 Anil Madhavapeddy <> * Copyright (c) 2015-2020 Gabriel Radanne <> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. *) type 'a key val new_key : string -> 'a key type t val empty : t val add : 'a key -> 'a -> t -> t val mem : 'a key -> t -> bool val find : 'a key -> t -> 'a option val merge : default:t -> t -> t * [ merge ] merges [ t ] on top of [ default ] . If a key appears in both [ default ] and [ t ] , the value present in [ t ] is kept . [default] and [t], the value present in [t] is kept. *) val dump : t Fmt.t
55c664e863b15d79ddf2dcae1041a9f5b514be5520e7668f909b90d10e09777c
adlai/cjhunt
util.lisp
(in-package :cl-user) (defpackage cjhunt.util (:use :cl :anaphora) (:export :remhash-if :getjso)) (in-package :cjhunt.util) (defun remhash-if (predicate old) "Copy `old', skipping all entries for which (funcall `predicate' key value)" (let ((save (loop for key being the hash-key in old using (hash-value data) unless (funcall predicate key data) collect (cons key data)))) (declare (dynamic-extent save)) (aprog1 (make-hash-table :rehash-size (hash-table-rehash-size old) :test (hash-table-test old) :size (length save) :rehash-threshold (hash-table-rehash-threshold old)) (loop for (key . data) in save do (setf (gethash key it) data))))) (defun getjso (key &optional map) (if map (cdr (assoc (intern (string key) :keyword) map :test #'string=)) (lambda (map) (getjso key map))))
null
https://raw.githubusercontent.com/adlai/cjhunt/fb89d8600e6b42c9d6b67dd3fded59907e91a3be/src/util.lisp
lisp
(in-package :cl-user) (defpackage cjhunt.util (:use :cl :anaphora) (:export :remhash-if :getjso)) (in-package :cjhunt.util) (defun remhash-if (predicate old) "Copy `old', skipping all entries for which (funcall `predicate' key value)" (let ((save (loop for key being the hash-key in old using (hash-value data) unless (funcall predicate key data) collect (cons key data)))) (declare (dynamic-extent save)) (aprog1 (make-hash-table :rehash-size (hash-table-rehash-size old) :test (hash-table-test old) :size (length save) :rehash-threshold (hash-table-rehash-threshold old)) (loop for (key . data) in save do (setf (gethash key it) data))))) (defun getjso (key &optional map) (if map (cdr (assoc (intern (string key) :keyword) map :test #'string=)) (lambda (map) (getjso key map))))
3f83035a695ff4d2241f161973bc0746d26780145e6cd301b36eafa0a1f30ee9
NorfairKing/smos
IssueSpec.hs
{-# LANGUAGE OverloadedStrings #-} module Smos.GitHub.IssueSpec (spec) where import GitHub import GitHub.Data.Name import Smos.GitHub.Issue import Smos.GitHub.Issue.Gen () import Test.Syd spec :: Spec spec = do describe "parseGitHubUrl" $ do it "works for this pull request example" $ parseGitHubUrl "" `shouldBe` Just ( PullRequestUrl (N "owner") (N "repo") (IssueNumber 167) ) it "works for this issue example" $ parseGitHubUrl "" `shouldBe` Just ( IssueUrl (N "owner") (N "repo") (IssueNumber 168) )
null
https://raw.githubusercontent.com/NorfairKing/smos/3b7021c22915ae16ae721c7da60d715e24f4e6bb/smos-github/test/Smos/GitHub/IssueSpec.hs
haskell
# LANGUAGE OverloadedStrings #
module Smos.GitHub.IssueSpec (spec) where import GitHub import GitHub.Data.Name import Smos.GitHub.Issue import Smos.GitHub.Issue.Gen () import Test.Syd spec :: Spec spec = do describe "parseGitHubUrl" $ do it "works for this pull request example" $ parseGitHubUrl "" `shouldBe` Just ( PullRequestUrl (N "owner") (N "repo") (IssueNumber 167) ) it "works for this issue example" $ parseGitHubUrl "" `shouldBe` Just ( IssueUrl (N "owner") (N "repo") (IssueNumber 168) )
dfbadea3d9d03b7c971b8bbdead854fb6617279078797f468abf669023b276cd
muyinliu/cl-graphicsmagick
types.lisp
(in-package :gm) ;;; Common types (define-foreign-type double-type () nil (:actual-type :double) (:simple-parser %double)) (defmethod translate-to-foreign (value (type double-type)) (coerce value 'double-float)) Enum definitions magick / colorspace.h (defcenum %ColorspaceType :%UndefinedColorspace Plain old RGB colorspace Plain old full - range grayscale :%TransparentColorspace ;; RGB but preserve matte channel during quantize :%OHTAColorspace CIE XYZ Kodak PhotoCD PhotoYCC :%YIQColorspace :%YPbPrColorspace :%YUVColorspace Cyan , magenta , yellow , black , alpha Kodak PhotoCD sRGB Hue , saturation , luminosity Hue , whiteness , blackness :%LABColorspace ;; LAB colorspace not supported yet other than via lcms RGB data with Cineon Log scaling , 2.048 density range Luma ( Y ) according to ITU - R 601 YCbCr according to ITU - R 601 Luma ( Y ) according to ITU - R 709 YCbCr according to ITU - R 709 ;; magick/compare.h (defcenum %MetricType :%UndefinedMetric :%MeanAbsoluteErrorMetric :%MeanSquaredErrorMetric :%PeakAbsoluteErrorMetric :%PeakSignalToNoiseRatioMetric :%RootMeanSquaredErrorMetric) magick / constitute.h (defcenum %StorageType :%CharPixel ;; Unsigned 8 bit 'unsigned char' :%ShortPixel ;; Unsigned 16 bit 'unsigned short int' :%IntegerPixel ;; Unsigned 32 bit 'unsigned int' Unsigned 32 or 64 bit ( CPU dependent ) ' unsigned long ' Floating point 32 - bit ' float ' Floating point 64 - bit ' double ' ;; magick/error.h (defcenum %ExceptionType (:%UndefinedException 0) (:%WarningException 300) ;; warning exceptions (:%ResourceLimitWarning 300) (:%TypeWarning 305) (:%OptionWarning 310) (:%DelegateWarning 315) (:%MissingDelegateWarning 320) (:%CorruptImageWarning 325) (:%FileOpenWarning 330) (:%BlobWarning 335) (:%StreamWarning 340) (:%CacheWarning 345) (:%CoderWarning 350) (:%ModuleWarning 355) (:%DrawWarning 360) (:%ImageWarning 365) (:%XServerWarning 380) (:%MonitorWarning 385) (:%RegistryWarning 390) (:%ConfigureWarning 395) (:%ErrorException 400) ;; error exceptions (:%ResourceLimitError 400) (:%TypeError 405) (:%OptionError 410) (:%DelegateError 415) (:%MissingDelegateError 420) (:%CorruptImageError 425) (:%FileOpenError 430) (:%BlobError 435) (:%StreamError 440) (:%CacheError 445) (:%CoderError 450) (:%ModuleError 455) (:%DrawError 460) (:%ImageError 465) (:%WandError 467) (:%XServerError 480) (:%MonitorError 485) (:%RegistryError 490) (:%ConfigureError 495) (:%FatalErrorException 700) ;; fatal error exceptions (:%ResourceLimitFatalError 700) (:%TypeFatalError 705) (:%OptionFatalError 710) (:%DelegateFatalError 715) (:%MissingDelegateFatalError 720) (:%CorruptImageFatalError 725) (:%FileOpenFatalError 730) (:%BlobFatalError 735) (:%StreamFatalError 740) (:%CacheFatalError 745) (:%CoderFatalError 750) (:%ModuleFatalError 755) (:%DrawFatalError 760) (:%ImageFatalError 765) (:%XServerFatalError 780) (:%MonitorFatalError 785) (:%RegistryFatalError 790) (:%ConfigureFatalError 795)) ;; magick/image.h (defcenum %AlphaType :%UnspecifiedAlpha :%AssociatedAlpha :%UnassociatedAlpha) (defcenum %ChannelType :%UndefinedChannel RGB Red channel CMYK Cyan channel RGB Green channel CMYK Magenta channel RGB Blue channel CMYK Yellow channel :%OpacityChannel ;; Opacity channel :%BlackChannel ;; CMYK Black (K) channel :%MatteChannel ;; Same as Opacity channel (deprecated) Color channels Color channels represent an intensity . (defcenum %ClassType :%UndefinedClass :%DirectClass :%PseudoClass) (defcenum %CompositeOperator (:%UndefinedCompositeOp 0) :%OverCompositeOp :%InCompositeOp :%OutCompositeOp :%AtopCompositeOp :%XorCompositeOp :%PlusCompositeOp :%MinusCompositeOp :%AddCompositeOp :%SubtractCompositeOp :%DifferenceCompositeOp :%MultiplyCompositeOp :%BumpmapCompositeOp :%CopyCompositeOp :%CopyRedCompositeOp :%CopyGreenCompositeOp :%CopyBlueCompositeOp :%CopyOpacityCompositeOp :%ClearCompositeOp :%DissolveCompositeOp :%DisplaceCompositeOp :%ModulateCompositeOp :%ThresholdCompositeOp :%NoCompositeOp :%DarkenCompositeOp :%LightenCompositeOp :%HueCompositeOp :%SaturateCompositeOp :%ColorizeCompositeOp :%LuminizeCompositeOp :%ScreenCompositeOp :%OverlayCompositeOp :%CopyCyanCompositeOp :%CopyMagentaCompositeOp :%CopyYellowCompositeOp :%CopyBlackCompositeOp :%DivideCompositeOp :%HardLightCompositeOp :%ExclusionCompositeOp :%ColorDodgeCompositeOp :%ColorBurnCompositeOp :%SoftLightCompositeOp :%LinearBurnCompositeOp :%LinearDodgeCompositeOp :%LinearLightCompositeOp :%VividLightCompositeOp :%PinLightCompositeOp :%HardMixCompositeOp) (defcenum %CompressionType :%UndefinedCompression :%NoCompression :%BZipCompression :%FaxCompression = :%Group4Compression :%JPEGCompression :%LosslessJPEGCompression :%LZWCompression :%RLECompression :%ZipCompression Lempel - Ziv - Markov chain algorithm ISO / IEC std 15444 - 1 ISO / IEC std 11544 / ITU - T rec T.82 ISO / IEC std 14492 / ITU - T rec T.88 (defcenum %DisposeType :%UndefinedDispose :%NoneDispose :%BackgroundDispose :%PreviousDispose) (defcenum %EndianType :%UndefinedEndian :%LSBEndian ;; "little" endian " big " endian native endian (defcenum %FilterTypes :%UndefinedFilter :%PointFilter :%BoxFilter :%TriangleFilter :%HermiteFilter :%HanningFilter :%HammingFilter :%BlackmanFilter :%GaussianFilter :%QuadraticFilter :%CubicFilter :%CatromFilter :%MitchellFilter :%LanczosFilter :%BesselFilter :%SincFilter) (defcenum %GeometryFlags (:%NoValue #x00000) (:%XValue #x00001) (:%YValue #x00002) (:%WidthValue #x00004) (:%HeightValue #x00008) (:%AllValues #x0000F) (:%XNegative #x00010) (:%YNegative #x00020) (:%PercentValue #x01000) ;; % (:%AspectValue #x02000) ;; ! (:%LessValue #x04000) ;; < (:%GreaterValue #x08000) ;; > (:%AreaValue #x10000) ;; @ (:%MinimumValue #x20000));; ^ (defcenum %GravityType :%ForgetGravity :%NorthWestGravity :%NorthGravity :%NorthEastGravity :%WestGravity :%CenterGravity :%EastGravity :%SouthWestGravity :%SouthGravity :%SouthEastGravity :%StaticGravity) (defcenum %ImageType :%UndefinedType :%BilevelType :%GrayscaleType :%GrayscaleMatteType :%PaletteType :%PaletteMatteType :%TrueColorType :%TrueColorMatteType :%ColorSeparationType :%ColorSeparationMatteType :%OptimizeType) (defcenum %InterlaceType :%UndefinedInterlace :%NoInterlace :%LineInterlace :%PlaneInterlace :%PartitionInterlace) (defcenum %MontageMode :%UndefinedMode :%FrameMode :%UnframeMode :%ConcatenateMode) (defcenum %NoiseType :%UniformNoise :%GaussianNoise :%MultiplicativeGaussianNoise :%ImpulseNoise :%LaplacianNoise :%PoissonNoise :%RandomNoise :%UndefinedNoise) Image orientation . Based on TIFF standard values ( also EXIF ) . (defcenum %OrientationType ;; Line direction | Frame Direction ;; ---------------|---------------- :%UndefinedOrientation ;; Unknown | Unknown :%TopLeftOrientation ;; Left to right | Top to bottom :%TopRightOrientation ;; Right to left | Top to bottom :%BottomRightOrientation ;; Right to left | Bottom to top :%BottomLeftOrientation ;; Left to right | Bottom to top :%LeftTopOrientation ;; Top to bottom | Left to right :%RightTopOrientation ;; Top to bottom | Right to left :%RightBottomOrientation ;; Bottom to top | Right to left :%LeftBottomOrientation) ;; Bottom to top | Left to right (defcenum %PreviewType :%UndefinedPreview :%RotatePreview :%ShearPreview :%RollPreview :%HuePreview :%SaturationPreview :%BrightnessPreview :%GammaPreview :%SpiffPreview :%DullPreview :%GrayscalePreview :%QuantizePreview :%DespecklePreview :%ReduceNoisePreview :%AddNoisePreview :%SharpenPreview :%BlurPreview :%ThresholdPreview :%EdgeDetectPreview :%SpreadPreview :%SolarizePreview :%ShadePreview :%RaisePreview :%SegmentPreview :%SwirlPreview :%ImplodePreview :%WavePreview :%OilPaintPreview :%CharcoalDrawingPreview :%JPEGPreview) (defcenum %RenderingIntent :%UndefinedIntent :%SaturationIntent :%PerceptualIntent :%AbsoluteIntent :%RelativeIntent) (defcenum %ResolutionType :%UndefinedResolution :%PixelsPerInchResolution :%PixelsPerCentimeterResolution) ;; magick/operator.h (defcenum %QuantumOperator :%UndefinedQuantumOp :%AddQuantumOp ;; Add value Bitwise AND value :%AssignQuantumOp ;; Direct value assignment :%DivideQuantumOp ;; Divide by value Bitwise left - shift value N bits :%MultiplyQuantumOp ;; Multiply by value Bitwise OR value Bitwise right shift value :%SubtractQuantumOp ;; Subtract value :%ThresholdQuantumOp ;; Above threshold white otherwise black :%ThresholdBlackQuantumOp ;; Below threshold is black :%ThresholdWhiteQuantumOp ;; Above threshold is white :%XorQuantumOp ;; Bitwise XOR value :%NoiseGaussianQuantumOp ;; Gaussian noise :%NoiseImpulseQuantumOp ;; Impulse noise :%NoiseLaplacianQuantumOp ;; Laplacian noise Multiplicative gaussian noise :%NoisePoissonQuantumOp ;; Poisson noise :%NoiseUniformQuantumOp ;; Uniform noise :%NegateQuantumOp ;; Negate (invert) channel ignore value :%GammaQuantumOp ;; Adjust image gamma :%DepthQuantumOp ;; Adjust image depth Below added on 2008 - 12 - 13 :%LogQuantumOp ;; log(quantum*value+1)/log(value+1) :%MaxQuantumOp ;; Assign value if > quantum :%MinQuantumOp ;; Assign value if < quantum Power function : pow(quantum , value ) Below added on 2012 - 03 - 17 :%NoiseRandomQuantumOp ;; Random noise Below added on 2014 - 05 - 17 :%ThresholdBlackNegateQuantumOp ;; Below threshold is set to white :%ThresholdWhiteNegateQuantumOp) ;; Above threshold is set to black ;; magick/pixel_cache.h (defcenum %VirtualPixelMethod :%UndefinedVirtualPixelMethod :%ConstantVirtualPixelMethod :%EdgeVirtualPixelMethod :%MirrorVirtualPixelMethod :%TileVirtualPixelMethod) ;; magick/render.h (defcenum %FillRule :%UndefinedRule :%EvenOddRule :%NonZeroRule) (defcenum %LineCap :%UndefinedCap :%ButtCap :%RoundCap :%SquareCap) (defcenum %LineJoin :%UndefinedJoin :%MiterJoin :%RoundJoin :%BevelJoin) (defcenum %ClipPathUnits :%UserSpace :%UserSpaceOnUse :%ObjectBoundingBox) (defcenum %PaintMethod (:%PointMethod 0) :%ReplaceMethod :%FloodfillMethod :%FillToBorderMethod :%ResetMethod) (defcenum %DecorationType :%NoDecoration :%UnderlineDecoration :%OverlineDecoration :%LineThroughDecoration) magick / resource.h (defcenum %ResourceType :%UndefinedResource=0 ;; Undefined value Pixel cache total disk space ( Gigabytes ) Pixel cache number of open files ( Files ) Pixel cache total file memory - mapping ( Megabytes ) :%MemoryResource ;; Maximum pixel cache heap memory allocations (Megabytes) Maximum number of pixels in single image ( Pixels ) :%ThreadsResource ;; Maximum number of worker threads Maximum pixel width of an image ( Pixels ) Maximum pixel height of an image ( Pixels ) ;; magick/type.h (defcenum %StretchType :%NormalStretch :%UltraCondensedStretch :%ExtraCondensedStretch :%CondensedStretch :%SemiCondensedStretch :%SemiExpandedStretch :%ExpandedStretch :%ExtraExpandedStretch :%UltraExpandedStretch :%AnyStretch) (defcenum %StyleType :%NormalStyle :%ItalicStyle :%ObliqueStyle :%AnyStyle) ;; wand/drawing_wand.c (defcenum %PathMode :%DefaultPathMode :%AbsolutePathMode :%RelativePathMode) magick / common.h ;; # define MagickPass 1 (defconstant +magick-pass+ 1) magick / common.h ;; ;; #define MagickPassFail unsigned int (defctype %MagickPassFail (:unsigned-int)) magick / common.h ;; # define MagickBool unsigned int (defctype %MagickBool (:unsigned-int)) ;;; Type definitions ;; magick/error.h ;; typedef struct _ ExceptionInfo ;; { ;; /* ;; Exception severity, reason, and description ;; */ ExceptionType ;; severity; ;; ;; char ;; *reason, ;; *description; ;; ;; /* ;; Value of errno (or equivalent) when exception was thrown. ;; */ ;; int ;; error_number; ;; ;; /* ;; Reporting source module, function (if available), and source ;; module line. ;; */ ;; char ;; *module, ;; *function; ;; ;; unsigned long ;; line; ;; ;; /* ;; Structure sanity check ;; */ ;; unsigned long ;; signature; } ExceptionInfo ; (defctype %ExceptionInfo (:pointer)) ;; magick/image.h (defctype %Image (:pointer)) ;; magick/image.h ;; typedef unsigned int Quantum ; (defctype %Quantum (:unsigned-int)) wand / ;; ;; #define MagickSizeType magick_int64_t typedef signed _ _ int64 magick_int64_t ; // -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807 (defctype %MagickSizeType (:long)) ;; wand/pixel_wand.h (defctype %PixelWand (:pointer)) ;; wand/magick_wand.c ;; struct _ MagickWand ;; { ;; char ;; id[MaxTextExtent]; ;; ExceptionInfo ;; exception; ;; ;; ImageInfo ;; *image_info; ;; ;; QuantizeInfo ;; *quantize_info; ;; ;; Image ;; *image, /* Current working image */ ;; *images; /* Whole image list */ ;; ;; unsigned int ;; iterator; ;; ;; unsigned long ;; signature; ;; }; typedef struct _ MagickWand MagickWand (defctype %MagickWand (:pointer)) ;; wand/drawing_wand.c ;; ;; struct _DrawingWand ;; { ;; /* Support structures */ ExceptionInfo ;; exception; ;; ;; Image ;; *image; ;; ;; MagickBool ;; own_image; /* If true, then we own the image. */ ;; ;; /* MVG output string and housekeeping */ ;; char ;; *mvg; /* MVG data */ ;; ;; size_t ;; mvg_alloc, /* total allocated memory */ mvg_length ; / * total MVG length * / ;; ;; unsigned int mvg_width ; / * current line length * / ;; ;; /* Pattern support */ ;; char ;; *pattern_id; ;; ;; RectangleInfo ;; pattern_bounds; ;; ;; size_t ;; pattern_offset; ;; ;; /* Graphic drawing_wand */ ;; int ;; index; /* array index */ ;; ;; **graphic_context; ;; ;; int ;; filter_off; /* true if not filtering attributes */ ;; ;; /* Pretty-printing depth */ ;; unsigned int ;; indent_depth; /* number of left-hand pad characters */ ;; ;; /* Path operation support */ PathOperation ;; path_operation; ;; ;; PathMode ;; path_mode; ;; ;; /* Structure unique signature */ ;; unsigned long ;; signature; ;; }; (defctype %DrawingWand (:pointer)) ;; magick/nt_base.h ;; # define MAGICK_POSIX_IO_SIZE_T unsigned int # define MAGICK_POSIX_IO_SIZE_T size_t (defctype %size_t (:unsigned-int)) ;; unsigned int ;; magick/nt_base.h ;; # if ! ) & & ! defined(__MINGW32 _ _ ) & & ! _ _ ) # if defined(WIN64 ) typedef _ _ int64 ssize_t ; ;; # else ;; typedef int ssize_t; ;; # endif # endif / * ! ) & & ! defined(__MINGW32 _ _ ) & & ! int / int64 stdio.h (defctype %FILE (:pointer)) ;; magick/image.h ;; typedef struct _ ;; { ;; #if defined(WORDS_BIGENDIAN) ;; /* RGBA */ # define MAGICK_PIXELS_RGBA 1 Quantum ;; red, ;; green, ;; blue, ;; opacity; ;; #else / * BGRA ( as used by Microsoft Windows DIB ) * / # define MAGICK_PIXELS_BGRA 1 Quantum ;; blue, ;; green, ;; red, ;; opacity; ;; #endif } ; (defctype %PixelPacket (:pointer)) ;; magick/image.h ;; ;; typedef struct _AffineMatrix ;; { ;; double ;; sx, ;; rx, ;; ry, ;; sy, tx , ;; ty; } AffineMatrix ; (defctype %AffineMatrix (:pointer)) ;; magick/render.h ;; typedef struct _ ;; { ;; char ;; *primitive, ;; *geometry; ;; AffineMatrix ;; affine; ;; GravityType ;; gravity; ;; ;; fill, ;; stroke; ;; ;; double ;; stroke_width; ;; ;; GradientInfo ;; gradient; ;; ;; Image ;; *fill_pattern, ;; *tile, ;; *stroke_pattern; ;; ;; unsigned int ;; stroke_antialias, ;; text_antialias; ;; ;; FillRule ;; fill_rule; ;; ;; linecap; ;; LineJoin linejoin ; ;; ;; unsigned long ;; miterlimit; ;; ;; double ;; dash_offset; ;; ;; decorate; ;; CompositeOperator ;; compose; ;; ;; char ;; *text, ;; *font, ;; *family; ;; StyleType ;; style; ;; StretchType ;; stretch; ;; ;; unsigned long ;; weight; ;; ;; char ;; *encoding; ;; ;; double ;; pointsize; ;; ;; char ;; *density; ;; AlignType ;; align; ;; ;; undercolor, ;; border_color; ;; ;; char ;; *server_name; ;; ;; double * dash_pattern ; / * Terminated by value 0.0 ( i.e. < MagickEpsilon)*/ ;; ;; char ;; *clip_path; ;; ;; bounds; ;; ;; ClipPathUnits ;; clip_units; ;; Quantum ;; opacity; ;; ;; unsigned int ;; render, ; / * Spare . Was long - deprecated ' debug ' * / ;; ;; ElementReference ;; element_reference; ;; ;; unsigned long ;; signature; } ; (defctype %DrawInfo (:pointer)) ;; magick/render.h ;; typedef struct _ PointInfo ;; { ;; double ;; x, ;; y; } PointInfo ; (defctype %PointInfo (:pointer))
null
https://raw.githubusercontent.com/muyinliu/cl-graphicsmagick/ffcf9ceb2d78b338776f6542f2f175c943186c79/src/cffi/types.lisp
lisp
Common types RGB but preserve matte channel during quantize LAB colorspace not supported yet other than via lcms magick/compare.h Unsigned 8 bit 'unsigned char' Unsigned 16 bit 'unsigned short int' Unsigned 32 bit 'unsigned int' magick/error.h warning exceptions error exceptions fatal error exceptions magick/image.h Opacity channel CMYK Black (K) channel Same as Opacity channel (deprecated) "little" endian % ! < > @ ^ Line direction | Frame Direction ---------------|---------------- Unknown | Unknown Left to right | Top to bottom Right to left | Top to bottom Right to left | Bottom to top Left to right | Bottom to top Top to bottom | Left to right Top to bottom | Right to left Bottom to top | Right to left Bottom to top | Left to right magick/operator.h Add value Direct value assignment Divide by value Multiply by value Subtract value Above threshold white otherwise black Below threshold is black Above threshold is white Bitwise XOR value Gaussian noise Impulse noise Laplacian noise Poisson noise Uniform noise Negate (invert) channel ignore value Adjust image gamma Adjust image depth log(quantum*value+1)/log(value+1) Assign value if > quantum Assign value if < quantum Random noise Below threshold is set to white Above threshold is set to black magick/pixel_cache.h magick/render.h Undefined value Maximum pixel cache heap memory allocations (Megabytes) Maximum number of worker threads magick/type.h wand/drawing_wand.c #define MagickPassFail unsigned int Type definitions magick/error.h { /* Exception severity, reason, and description */ severity; char *reason, *description; /* Value of errno (or equivalent) when exception was thrown. */ int error_number; /* Reporting source module, function (if available), and source module line. */ char *module, *function; unsigned long line; /* Structure sanity check */ unsigned long signature; magick/image.h magick/image.h #define MagickSizeType magick_int64_t wand/pixel_wand.h wand/magick_wand.c { char id[MaxTextExtent]; exception; ImageInfo *image_info; QuantizeInfo *quantize_info; Image *image, /* Current working image */ *images; /* Whole image list */ unsigned int iterator; unsigned long signature; }; wand/drawing_wand.c struct _DrawingWand { /* Support structures */ exception; Image *image; MagickBool own_image; /* If true, then we own the image. */ /* MVG output string and housekeeping */ char *mvg; /* MVG data */ size_t mvg_alloc, /* total allocated memory */ / * total MVG length * / unsigned int / * current line length * / /* Pattern support */ char *pattern_id; RectangleInfo pattern_bounds; size_t pattern_offset; /* Graphic drawing_wand */ int index; /* array index */ **graphic_context; int filter_off; /* true if not filtering attributes */ /* Pretty-printing depth */ unsigned int indent_depth; /* number of left-hand pad characters */ /* Path operation support */ path_operation; PathMode path_mode; /* Structure unique signature */ unsigned long signature; }; magick/nt_base.h unsigned int magick/nt_base.h # else typedef int ssize_t; # endif magick/image.h { #if defined(WORDS_BIGENDIAN) /* RGBA */ red, green, blue, opacity; #else blue, green, red, opacity; #endif magick/image.h typedef struct _AffineMatrix { double sx, rx, ry, sy, ty; magick/render.h { char *primitive, *geometry; affine; gravity; fill, stroke; double stroke_width; GradientInfo gradient; Image *fill_pattern, *tile, *stroke_pattern; unsigned int stroke_antialias, text_antialias; FillRule fill_rule; linecap; unsigned long miterlimit; double dash_offset; decorate; compose; char *text, *font, *family; style; stretch; unsigned long weight; char *encoding; double pointsize; char *density; align; undercolor, border_color; char *server_name; double / * Terminated by value 0.0 ( i.e. < MagickEpsilon)*/ char *clip_path; bounds; ClipPathUnits clip_units; opacity; unsigned int render, / * Spare . Was long - deprecated ' debug ' * / ElementReference element_reference; unsigned long signature; magick/render.h { double x, y;
(in-package :gm) (define-foreign-type double-type () nil (:actual-type :double) (:simple-parser %double)) (defmethod translate-to-foreign (value (type double-type)) (coerce value 'double-float)) Enum definitions magick / colorspace.h (defcenum %ColorspaceType :%UndefinedColorspace Plain old RGB colorspace Plain old full - range grayscale :%OHTAColorspace CIE XYZ Kodak PhotoCD PhotoYCC :%YIQColorspace :%YPbPrColorspace :%YUVColorspace Cyan , magenta , yellow , black , alpha Kodak PhotoCD sRGB Hue , saturation , luminosity Hue , whiteness , blackness RGB data with Cineon Log scaling , 2.048 density range Luma ( Y ) according to ITU - R 601 YCbCr according to ITU - R 601 Luma ( Y ) according to ITU - R 709 YCbCr according to ITU - R 709 (defcenum %MetricType :%UndefinedMetric :%MeanAbsoluteErrorMetric :%MeanSquaredErrorMetric :%PeakAbsoluteErrorMetric :%PeakSignalToNoiseRatioMetric :%RootMeanSquaredErrorMetric) magick / constitute.h (defcenum %StorageType Unsigned 32 or 64 bit ( CPU dependent ) ' unsigned long ' Floating point 32 - bit ' float ' Floating point 64 - bit ' double ' (defcenum %ExceptionType (:%UndefinedException 0) (:%ResourceLimitWarning 300) (:%TypeWarning 305) (:%OptionWarning 310) (:%DelegateWarning 315) (:%MissingDelegateWarning 320) (:%CorruptImageWarning 325) (:%FileOpenWarning 330) (:%BlobWarning 335) (:%StreamWarning 340) (:%CacheWarning 345) (:%CoderWarning 350) (:%ModuleWarning 355) (:%DrawWarning 360) (:%ImageWarning 365) (:%XServerWarning 380) (:%MonitorWarning 385) (:%RegistryWarning 390) (:%ConfigureWarning 395) (:%ResourceLimitError 400) (:%TypeError 405) (:%OptionError 410) (:%DelegateError 415) (:%MissingDelegateError 420) (:%CorruptImageError 425) (:%FileOpenError 430) (:%BlobError 435) (:%StreamError 440) (:%CacheError 445) (:%CoderError 450) (:%ModuleError 455) (:%DrawError 460) (:%ImageError 465) (:%WandError 467) (:%XServerError 480) (:%MonitorError 485) (:%RegistryError 490) (:%ConfigureError 495) (:%ResourceLimitFatalError 700) (:%TypeFatalError 705) (:%OptionFatalError 710) (:%DelegateFatalError 715) (:%MissingDelegateFatalError 720) (:%CorruptImageFatalError 725) (:%FileOpenFatalError 730) (:%BlobFatalError 735) (:%StreamFatalError 740) (:%CacheFatalError 745) (:%CoderFatalError 750) (:%ModuleFatalError 755) (:%DrawFatalError 760) (:%ImageFatalError 765) (:%XServerFatalError 780) (:%MonitorFatalError 785) (:%RegistryFatalError 790) (:%ConfigureFatalError 795)) (defcenum %AlphaType :%UnspecifiedAlpha :%AssociatedAlpha :%UnassociatedAlpha) (defcenum %ChannelType :%UndefinedChannel RGB Red channel CMYK Cyan channel RGB Green channel CMYK Magenta channel RGB Blue channel CMYK Yellow channel Color channels Color channels represent an intensity . (defcenum %ClassType :%UndefinedClass :%DirectClass :%PseudoClass) (defcenum %CompositeOperator (:%UndefinedCompositeOp 0) :%OverCompositeOp :%InCompositeOp :%OutCompositeOp :%AtopCompositeOp :%XorCompositeOp :%PlusCompositeOp :%MinusCompositeOp :%AddCompositeOp :%SubtractCompositeOp :%DifferenceCompositeOp :%MultiplyCompositeOp :%BumpmapCompositeOp :%CopyCompositeOp :%CopyRedCompositeOp :%CopyGreenCompositeOp :%CopyBlueCompositeOp :%CopyOpacityCompositeOp :%ClearCompositeOp :%DissolveCompositeOp :%DisplaceCompositeOp :%ModulateCompositeOp :%ThresholdCompositeOp :%NoCompositeOp :%DarkenCompositeOp :%LightenCompositeOp :%HueCompositeOp :%SaturateCompositeOp :%ColorizeCompositeOp :%LuminizeCompositeOp :%ScreenCompositeOp :%OverlayCompositeOp :%CopyCyanCompositeOp :%CopyMagentaCompositeOp :%CopyYellowCompositeOp :%CopyBlackCompositeOp :%DivideCompositeOp :%HardLightCompositeOp :%ExclusionCompositeOp :%ColorDodgeCompositeOp :%ColorBurnCompositeOp :%SoftLightCompositeOp :%LinearBurnCompositeOp :%LinearDodgeCompositeOp :%LinearLightCompositeOp :%VividLightCompositeOp :%PinLightCompositeOp :%HardMixCompositeOp) (defcenum %CompressionType :%UndefinedCompression :%NoCompression :%BZipCompression :%FaxCompression = :%Group4Compression :%JPEGCompression :%LosslessJPEGCompression :%LZWCompression :%RLECompression :%ZipCompression Lempel - Ziv - Markov chain algorithm ISO / IEC std 15444 - 1 ISO / IEC std 11544 / ITU - T rec T.82 ISO / IEC std 14492 / ITU - T rec T.88 (defcenum %DisposeType :%UndefinedDispose :%NoneDispose :%BackgroundDispose :%PreviousDispose) (defcenum %EndianType :%UndefinedEndian " big " endian native endian (defcenum %FilterTypes :%UndefinedFilter :%PointFilter :%BoxFilter :%TriangleFilter :%HermiteFilter :%HanningFilter :%HammingFilter :%BlackmanFilter :%GaussianFilter :%QuadraticFilter :%CubicFilter :%CatromFilter :%MitchellFilter :%LanczosFilter :%BesselFilter :%SincFilter) (defcenum %GeometryFlags (:%NoValue #x00000) (:%XValue #x00001) (:%YValue #x00002) (:%WidthValue #x00004) (:%HeightValue #x00008) (:%AllValues #x0000F) (:%XNegative #x00010) (:%YNegative #x00020) (defcenum %GravityType :%ForgetGravity :%NorthWestGravity :%NorthGravity :%NorthEastGravity :%WestGravity :%CenterGravity :%EastGravity :%SouthWestGravity :%SouthGravity :%SouthEastGravity :%StaticGravity) (defcenum %ImageType :%UndefinedType :%BilevelType :%GrayscaleType :%GrayscaleMatteType :%PaletteType :%PaletteMatteType :%TrueColorType :%TrueColorMatteType :%ColorSeparationType :%ColorSeparationMatteType :%OptimizeType) (defcenum %InterlaceType :%UndefinedInterlace :%NoInterlace :%LineInterlace :%PlaneInterlace :%PartitionInterlace) (defcenum %MontageMode :%UndefinedMode :%FrameMode :%UnframeMode :%ConcatenateMode) (defcenum %NoiseType :%UniformNoise :%GaussianNoise :%MultiplicativeGaussianNoise :%ImpulseNoise :%LaplacianNoise :%PoissonNoise :%RandomNoise :%UndefinedNoise) Image orientation . Based on TIFF standard values ( also EXIF ) . (defcenum %PreviewType :%UndefinedPreview :%RotatePreview :%ShearPreview :%RollPreview :%HuePreview :%SaturationPreview :%BrightnessPreview :%GammaPreview :%SpiffPreview :%DullPreview :%GrayscalePreview :%QuantizePreview :%DespecklePreview :%ReduceNoisePreview :%AddNoisePreview :%SharpenPreview :%BlurPreview :%ThresholdPreview :%EdgeDetectPreview :%SpreadPreview :%SolarizePreview :%ShadePreview :%RaisePreview :%SegmentPreview :%SwirlPreview :%ImplodePreview :%WavePreview :%OilPaintPreview :%CharcoalDrawingPreview :%JPEGPreview) (defcenum %RenderingIntent :%UndefinedIntent :%SaturationIntent :%PerceptualIntent :%AbsoluteIntent :%RelativeIntent) (defcenum %ResolutionType :%UndefinedResolution :%PixelsPerInchResolution :%PixelsPerCentimeterResolution) (defcenum %QuantumOperator :%UndefinedQuantumOp Bitwise AND value Bitwise left - shift value N bits Bitwise OR value Bitwise right shift value Multiplicative gaussian noise Below added on 2008 - 12 - 13 Power function : pow(quantum , value ) Below added on 2012 - 03 - 17 Below added on 2014 - 05 - 17 (defcenum %VirtualPixelMethod :%UndefinedVirtualPixelMethod :%ConstantVirtualPixelMethod :%EdgeVirtualPixelMethod :%MirrorVirtualPixelMethod :%TileVirtualPixelMethod) (defcenum %FillRule :%UndefinedRule :%EvenOddRule :%NonZeroRule) (defcenum %LineCap :%UndefinedCap :%ButtCap :%RoundCap :%SquareCap) (defcenum %LineJoin :%UndefinedJoin :%MiterJoin :%RoundJoin :%BevelJoin) (defcenum %ClipPathUnits :%UserSpace :%UserSpaceOnUse :%ObjectBoundingBox) (defcenum %PaintMethod (:%PointMethod 0) :%ReplaceMethod :%FloodfillMethod :%FillToBorderMethod :%ResetMethod) (defcenum %DecorationType :%NoDecoration :%UnderlineDecoration :%OverlineDecoration :%LineThroughDecoration) magick / resource.h (defcenum %ResourceType Pixel cache total disk space ( Gigabytes ) Pixel cache number of open files ( Files ) Pixel cache total file memory - mapping ( Megabytes ) Maximum number of pixels in single image ( Pixels ) Maximum pixel width of an image ( Pixels ) Maximum pixel height of an image ( Pixels ) (defcenum %StretchType :%NormalStretch :%UltraCondensedStretch :%ExtraCondensedStretch :%CondensedStretch :%SemiCondensedStretch :%SemiExpandedStretch :%ExpandedStretch :%ExtraExpandedStretch :%UltraExpandedStretch :%AnyStretch) (defcenum %StyleType :%NormalStyle :%ItalicStyle :%ObliqueStyle :%AnyStyle) (defcenum %PathMode :%DefaultPathMode :%AbsolutePathMode :%RelativePathMode) magick / common.h # define MagickPass 1 (defconstant +magick-pass+ 1) magick / common.h (defctype %MagickPassFail (:unsigned-int)) magick / common.h # define MagickBool unsigned int (defctype %MagickBool (:unsigned-int)) typedef struct _ ExceptionInfo ExceptionType (defctype %ExceptionInfo (:pointer)) (defctype %Image (:pointer)) (defctype %Quantum (:unsigned-int)) wand / // -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807 (defctype %MagickSizeType (:long)) (defctype %PixelWand (:pointer)) struct _ MagickWand ExceptionInfo typedef struct _ MagickWand MagickWand (defctype %MagickWand (:pointer)) ExceptionInfo PathOperation (defctype %DrawingWand (:pointer)) # define MAGICK_POSIX_IO_SIZE_T unsigned int # define MAGICK_POSIX_IO_SIZE_T size_t # if ! ) & & ! defined(__MINGW32 _ _ ) & & ! _ _ ) # if defined(WIN64 ) # endif / * ! ) & & ! defined(__MINGW32 _ _ ) & & ! int / int64 stdio.h (defctype %FILE (:pointer)) typedef struct _ # define MAGICK_PIXELS_RGBA 1 Quantum / * BGRA ( as used by Microsoft Windows DIB ) * / # define MAGICK_PIXELS_BGRA 1 Quantum (defctype %PixelPacket (:pointer)) tx , (defctype %AffineMatrix (:pointer)) typedef struct _ AffineMatrix GravityType LineJoin CompositeOperator StyleType StretchType AlignType Quantum (defctype %DrawInfo (:pointer)) typedef struct _ PointInfo (defctype %PointInfo (:pointer))
ba6fb8434d17a13d7183fbff9597e124db7dc245f7fd379e3335af17b16d3920
kmi/irs
wp-html-describe.lisp
(in-package wsmo-protocol) (defun ip::goal-details (ontology method html-stream &optional (lookup-function #'ocml::irs-lookup-current-word)) (ip::task-details ontology method html-stream lookup-function)) (defun ip::web-service-details (ontology method html-stream &optional (lookup-function #'ocml::irs-lookup-current-word)) (ip::task-details ontology method html-stream lookup-function)) (defun ip::mediator-details (ontology method html-stream &optional (lookup-function #'ocml::irs-lookup-current-word)) (ip::task-details ontology method html-stream lookup-function)) (defvar *standard-other-goal-slots* '(ocml::used-mediator ocml::has-effect ocml::has-post-condition)) (defun html-describe-class-slots-p (x) (and x (ocml::get-domain-class x) (ocml::domain-slots (ocml::get-domain-class x)))) defined for the delivery version of the IRS server ;;for some reason deleted classes get through (defun check-class-and-find-all-web-services-which-solve-goal (goal-name) (and (ocml::get-domain-class goal-name) (find-all-web-services-which-solve-goal goal-name))) (defun ocml::describe-goal-internals (goal-name class ontology stream &optional (lookup-function #'ocml::mnm-lookup-current-word)) (let ((associated-web-services (check-class-and-find-all-web-services-which-solve-goal goal-name)) (input-roles (input-roles goal-name)) (output-role (output-role goal-name)) (other-slots (intersection (ocml::domain-slots class) *standard-other-goal-slots*)) (non-functional-properties (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,goal-name ocml::has-non-functional-properties))))) (when associated-web-services (let ((associated-web-services-info (mapcar #'(lambda (x) (list (ocml::name x) (ocml::name (ocml::home-ontology x)))) associated-web-services))) (format stream "~A" (http::bold "Associated Web Services: ")) (format stream (http::internal-insert-ocml-links (format nil "~(~{~a (~a)~}~{~{; ~a (~a)~}~}~)" (car associated-web-services-info) (cdr associated-web-services-info)) lookup-function ontology)) (format stream "<br>"))) (when input-roles (format stream "~A" (http::bold "Input Roles:")) (loop for slot in input-roles do (describe-wsmo-slot slot class ontology stream lookup-function)) (format stream "<br>")) (when output-role (format stream "~A" (http::bold "Output Role:")) (describe-wsmo-slot output-role class ontology stream lookup-function) (format stream "<br>")) (when other-slots (format stream "~A" (http::bold "Other Slots:")) (loop for slot in other-slots do (describe-wsmo-slot slot class ontology stream lookup-function)) (format stream "<br>")) (when (html-describe-class-slots-p non-functional-properties) (format stream "~A" (http::bold "Non Functional Properties:")) (describe-wsmo-class-slots non-functional-properties ontology stream lookup-function #'(lambda (class slot) (ip::get-class-slot-value class slot)))))) (defun describe-wsmo-slot (slot class ontology stream &optional (lookup-function #'mnm-lookup-current-word)) (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b>~(~a~)</b>" (ocml::insert-spaces 4) (ocml::add-html-relation-colour slot)) lookup-function ontology)) (multiple-value-bind (values defaults) (ocml::get-slot-values-from-class-structure class slot ) (when values (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~)</i></b>~{~a~}" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour :value) (mapcar #'(lambda (x) (ocml::format-ocml-value x 1 nil)) values)) lookup-function ontology))) (when defaults (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~):</i></b>~{~a~}" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour :default-value) (mapcar #'(lambda (x) (ocml::format-ocml-value x 1 nil)) defaults)) lookup-function ontology))) (let ((type-info (remove-duplicates (ocml::find-option-value class slot :type)))) (when type-info (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~):</i></b>~{~a~}" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour :type) (mapcar #'(lambda (x) (ocml::format-ocml-value x 1 nil)) type-info)) lookup-function ontology)))) (loop for option in '(:min-cardinality :max-cardinality :inheritance) for value = (ocml::find-option-value class slot option) when value do (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~):</i></b> ~:(~a~)" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour option) value) lookup-function ontology))) (let ((doc (ocml::find-slot-documentation class slot))) (when doc (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~):</i></b> <i>~a</i>" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour :documentation) doc) lookup-function ontology)))))) (defun describe-wsmo-class-slots (class-name ontology stream lookup-function &optional slot-test) (let ((class (ocml::get-domain-class class-name))) (when class (dolist (slot (ocml::domain-slots class)) (when (or (null slot-test) (funcall slot-test class-name slot)) (describe-wsmo-slot slot class ontology stream lookup-function)))))) (defun ocml::describe-web-service-internals (web-service-name class ontology stream &optional (lookup-function #'ocml::mnm-lookup-current-word)) (let* ((input-roles (input-roles web-service-name)) (output-role (output-role web-service-name)) (host (web-onto::findany '?x `(ocml::wsmo-web-service-host ,web-service-name ?x))) (port (web-onto::findany '?x `(ocml::wsmo-web-service-port ,web-service-name ?x))) (location (web-onto::findany '?x `(ocml::wsmo-web-service-location ,web-service-name ?x))) (non-functional-properties (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,web-service-name ocml::has-non-functional-properties)))) (capability (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,web-service-name ocml::has-capability)))) (mediators (web-onto::findany '?x `(= ?x (ocml::all-class-slot-values ,web-service-name ocml::used-mediator)))) (interface (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,web-service-name ocml::has-interface)))) (orchestration (when (and interface (ocml::get-domain-class interface)) (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,interface ocml::has-orchestration))))) (choreography (when (and interface (ocml::get-domain-class interface)) (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,interface ocml::has-choreography))))) (interface-mediators (when (and interface (ocml::get-domain-class interface)) (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,interface ocml::used-mediator)))))) (when host (format stream "~A" (http::bold "Publisher URL:")) (cond ((and port location) (format stream " http://~a:~a~a" host port location)) (location (format stream " http://~a~a" host location)) (port (format stream " http://~a:~a" host port)) (t (format stream " http://~a" host))) (format stream "<br>")) (when input-roles (format stream "~A" (http::bold "Input Roles:")) (loop for slot in input-roles do (describe-wsmo-slot slot class ontology stream lookup-function)) (format stream "<br>")) (when output-role (format stream "~A" (http::bold "Output Role:")) (describe-wsmo-slot output-role class ontology stream lookup-function) (format stream "<br>")) (when mediators (format stream "~A" (http::bold "Mediators:")) (dolist (mediator mediators) (describe-wsmo-slot mediator class ontology stream lookup-function)) (format stream "<br>")) (when (html-describe-class-slots-p capability) (format stream "~A" (http::bold "Capability:")) (describe-wsmo-class-slots capability ontology stream lookup-function) (format stream "<br>")) (when (or (html-describe-class-slots-p orchestration) (html-describe-class-slots-p choreography) (html-describe-class-slots-p interface-mediators)) (format stream "~A" (http::bold "Interface Components:<br>")) (when (html-describe-class-slots-p orchestration) (format stream "~A" (http::bold (http::italic "Orchestration:"))) (describe-wsmo-class-slots orchestration ontology stream lookup-function) (format stream "<br>")) (when (html-describe-class-slots-p choreography) (format stream "~A" (http::bold (http::italic "Choreography:"))) (describe-wsmo-class-slots choreography ontology stream lookup-function) (format stream "<br>")) (when (html-describe-class-slots-p interface-mediators) (format stream "~A" (http::bold (http::italic "Interface Mediators:"))) (describe-wsmo-class-slots interface-mediators ontology stream lookup-function) (format stream "<br>"))) (when (html-describe-class-slots-p non-functional-properties) (format stream "~A" (http::bold (http::italic "Non Functional Properties:"))) (describe-wsmo-class-slots non-functional-properties ontology stream lookup-function #'(lambda (class slot) (ip::get-class-slot-value class slot)))))) (defun ocml::describe-mediator-internals (mediator-name class ontology stream &optional (lookup-function #'ocml::mnm-lookup-current-word)) (let* ((non-functional-properties (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,mediator-name ocml::has-non-functional-properties)))) (main-slots (remove 'ocml::has-non-functional-properties (ocml::domain-slots class)))) (when main-slots (format stream "~A" (http::bold "Main Slots:")) (loop for slot in main-slots do (describe-wsmo-slot slot class ontology stream lookup-function)) (format stream "<br>")) (when (html-describe-class-slots-p non-functional-properties) (format stream "~A" (http::bold "Non Functional Properties:")) (describe-wsmo-class-slots non-functional-properties ontology stream lookup-function #'(lambda (class slot) (ip::get-class-slot-value class slot))))))
null
https://raw.githubusercontent.com/kmi/irs/e1b8d696f61c6b6878c0e92d993ed549fee6e7dd/src/web/wp-html-describe.lisp
lisp
for some reason deleted classes get through
(in-package wsmo-protocol) (defun ip::goal-details (ontology method html-stream &optional (lookup-function #'ocml::irs-lookup-current-word)) (ip::task-details ontology method html-stream lookup-function)) (defun ip::web-service-details (ontology method html-stream &optional (lookup-function #'ocml::irs-lookup-current-word)) (ip::task-details ontology method html-stream lookup-function)) (defun ip::mediator-details (ontology method html-stream &optional (lookup-function #'ocml::irs-lookup-current-word)) (ip::task-details ontology method html-stream lookup-function)) (defvar *standard-other-goal-slots* '(ocml::used-mediator ocml::has-effect ocml::has-post-condition)) (defun html-describe-class-slots-p (x) (and x (ocml::get-domain-class x) (ocml::domain-slots (ocml::get-domain-class x)))) defined for the delivery version of the IRS server (defun check-class-and-find-all-web-services-which-solve-goal (goal-name) (and (ocml::get-domain-class goal-name) (find-all-web-services-which-solve-goal goal-name))) (defun ocml::describe-goal-internals (goal-name class ontology stream &optional (lookup-function #'ocml::mnm-lookup-current-word)) (let ((associated-web-services (check-class-and-find-all-web-services-which-solve-goal goal-name)) (input-roles (input-roles goal-name)) (output-role (output-role goal-name)) (other-slots (intersection (ocml::domain-slots class) *standard-other-goal-slots*)) (non-functional-properties (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,goal-name ocml::has-non-functional-properties))))) (when associated-web-services (let ((associated-web-services-info (mapcar #'(lambda (x) (list (ocml::name x) (ocml::name (ocml::home-ontology x)))) associated-web-services))) (format stream "~A" (http::bold "Associated Web Services: ")) (format stream (http::internal-insert-ocml-links (format nil "~(~{~a (~a)~}~{~{; ~a (~a)~}~}~)" (car associated-web-services-info) (cdr associated-web-services-info)) lookup-function ontology)) (format stream "<br>"))) (when input-roles (format stream "~A" (http::bold "Input Roles:")) (loop for slot in input-roles do (describe-wsmo-slot slot class ontology stream lookup-function)) (format stream "<br>")) (when output-role (format stream "~A" (http::bold "Output Role:")) (describe-wsmo-slot output-role class ontology stream lookup-function) (format stream "<br>")) (when other-slots (format stream "~A" (http::bold "Other Slots:")) (loop for slot in other-slots do (describe-wsmo-slot slot class ontology stream lookup-function)) (format stream "<br>")) (when (html-describe-class-slots-p non-functional-properties) (format stream "~A" (http::bold "Non Functional Properties:")) (describe-wsmo-class-slots non-functional-properties ontology stream lookup-function #'(lambda (class slot) (ip::get-class-slot-value class slot)))))) (defun describe-wsmo-slot (slot class ontology stream &optional (lookup-function #'mnm-lookup-current-word)) (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b>~(~a~)</b>" (ocml::insert-spaces 4) (ocml::add-html-relation-colour slot)) lookup-function ontology)) (multiple-value-bind (values defaults) (ocml::get-slot-values-from-class-structure class slot ) (when values (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~)</i></b>~{~a~}" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour :value) (mapcar #'(lambda (x) (ocml::format-ocml-value x 1 nil)) values)) lookup-function ontology))) (when defaults (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~):</i></b>~{~a~}" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour :default-value) (mapcar #'(lambda (x) (ocml::format-ocml-value x 1 nil)) defaults)) lookup-function ontology))) (let ((type-info (remove-duplicates (ocml::find-option-value class slot :type)))) (when type-info (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~):</i></b>~{~a~}" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour :type) (mapcar #'(lambda (x) (ocml::format-ocml-value x 1 nil)) type-info)) lookup-function ontology)))) (loop for option in '(:min-cardinality :max-cardinality :inheritance) for value = (ocml::find-option-value class slot option) when value do (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~):</i></b> ~:(~a~)" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour option) value) lookup-function ontology))) (let ((doc (ocml::find-slot-documentation class slot))) (when doc (format stream (http::internal-insert-ocml-links (format nil "<br>~a<b><i>~:(~a~):</i></b> <i>~a</i>" (ocml::insert-spaces 5) (ocml::add-html-slot-option-colour :documentation) doc) lookup-function ontology)))))) (defun describe-wsmo-class-slots (class-name ontology stream lookup-function &optional slot-test) (let ((class (ocml::get-domain-class class-name))) (when class (dolist (slot (ocml::domain-slots class)) (when (or (null slot-test) (funcall slot-test class-name slot)) (describe-wsmo-slot slot class ontology stream lookup-function)))))) (defun ocml::describe-web-service-internals (web-service-name class ontology stream &optional (lookup-function #'ocml::mnm-lookup-current-word)) (let* ((input-roles (input-roles web-service-name)) (output-role (output-role web-service-name)) (host (web-onto::findany '?x `(ocml::wsmo-web-service-host ,web-service-name ?x))) (port (web-onto::findany '?x `(ocml::wsmo-web-service-port ,web-service-name ?x))) (location (web-onto::findany '?x `(ocml::wsmo-web-service-location ,web-service-name ?x))) (non-functional-properties (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,web-service-name ocml::has-non-functional-properties)))) (capability (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,web-service-name ocml::has-capability)))) (mediators (web-onto::findany '?x `(= ?x (ocml::all-class-slot-values ,web-service-name ocml::used-mediator)))) (interface (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,web-service-name ocml::has-interface)))) (orchestration (when (and interface (ocml::get-domain-class interface)) (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,interface ocml::has-orchestration))))) (choreography (when (and interface (ocml::get-domain-class interface)) (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,interface ocml::has-choreography))))) (interface-mediators (when (and interface (ocml::get-domain-class interface)) (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,interface ocml::used-mediator)))))) (when host (format stream "~A" (http::bold "Publisher URL:")) (cond ((and port location) (format stream " http://~a:~a~a" host port location)) (location (format stream " http://~a~a" host location)) (port (format stream " http://~a:~a" host port)) (t (format stream " http://~a" host))) (format stream "<br>")) (when input-roles (format stream "~A" (http::bold "Input Roles:")) (loop for slot in input-roles do (describe-wsmo-slot slot class ontology stream lookup-function)) (format stream "<br>")) (when output-role (format stream "~A" (http::bold "Output Role:")) (describe-wsmo-slot output-role class ontology stream lookup-function) (format stream "<br>")) (when mediators (format stream "~A" (http::bold "Mediators:")) (dolist (mediator mediators) (describe-wsmo-slot mediator class ontology stream lookup-function)) (format stream "<br>")) (when (html-describe-class-slots-p capability) (format stream "~A" (http::bold "Capability:")) (describe-wsmo-class-slots capability ontology stream lookup-function) (format stream "<br>")) (when (or (html-describe-class-slots-p orchestration) (html-describe-class-slots-p choreography) (html-describe-class-slots-p interface-mediators)) (format stream "~A" (http::bold "Interface Components:<br>")) (when (html-describe-class-slots-p orchestration) (format stream "~A" (http::bold (http::italic "Orchestration:"))) (describe-wsmo-class-slots orchestration ontology stream lookup-function) (format stream "<br>")) (when (html-describe-class-slots-p choreography) (format stream "~A" (http::bold (http::italic "Choreography:"))) (describe-wsmo-class-slots choreography ontology stream lookup-function) (format stream "<br>")) (when (html-describe-class-slots-p interface-mediators) (format stream "~A" (http::bold (http::italic "Interface Mediators:"))) (describe-wsmo-class-slots interface-mediators ontology stream lookup-function) (format stream "<br>"))) (when (html-describe-class-slots-p non-functional-properties) (format stream "~A" (http::bold (http::italic "Non Functional Properties:"))) (describe-wsmo-class-slots non-functional-properties ontology stream lookup-function #'(lambda (class slot) (ip::get-class-slot-value class slot)))))) (defun ocml::describe-mediator-internals (mediator-name class ontology stream &optional (lookup-function #'ocml::mnm-lookup-current-word)) (let* ((non-functional-properties (web-onto::findany '?x `(= ?x (ocml::the-class-slot-value ,mediator-name ocml::has-non-functional-properties)))) (main-slots (remove 'ocml::has-non-functional-properties (ocml::domain-slots class)))) (when main-slots (format stream "~A" (http::bold "Main Slots:")) (loop for slot in main-slots do (describe-wsmo-slot slot class ontology stream lookup-function)) (format stream "<br>")) (when (html-describe-class-slots-p non-functional-properties) (format stream "~A" (http::bold "Non Functional Properties:")) (describe-wsmo-class-slots non-functional-properties ontology stream lookup-function #'(lambda (class slot) (ip::get-class-slot-value class slot))))))
e5382145b77bdba99cc9c9dc5d50d290b1535c7eb390bf90048737158c3a6c87
OCamlPro/ezjs_fetch
ezjs_fetch_lwt.ml
open Ezjs_min_lwt include Ezjs_fetch let (>>=?) x f = Lwt.bind x @@ function | Error _ as err -> Lwt.return err | Ok x -> f x let (>|=?) x f = Lwt.bind x @@ function | Error _ as err -> Lwt.return err | Ok x -> Lwt.return (Ok (f x)) let catch p = Lwt.bind (Promise.to_lwt p) @@ function | Error e -> Lwt.return_error e | Ok r -> match Opt.to_option r with | None -> Lwt.return_error (error_of_string "Cannot parse response body") | Some x -> Lwt.return_ok x type 'a body_translate = response_js t -> ('a, error t) result Lwt.t let to_array_buffer : Typed_array.arrayBuffer t body_translate = fun b -> catch b##arrayBuffer let to_blob : File.blob t body_translate = fun b -> catch b##blob let to_form_data : Js_of_ocaml.Form.formData t body_translate = fun b -> catch b##formData let to_js : 'a t body_translate = fun b -> catch b##json >|=? Unsafe.coerce let to_text : string body_translate = fun b -> catch b##text >|=? to_string let to_response (tr : 'a body_translate) (r :response_js t) = tr r >|=? fun body -> { headers = get_headers r##.headers; ok = to_bool r##.ok; redirected = to_bool r##.redirected; status = r##.status; status_text = to_string r##.statusText; typ = to_string r##.type_; url = to_string r##.url; body_used = to_bool r##.bodyUsed; body } let fetch ?cache ?credentials ?headers ?integrity ?meth ?mode ?redirect ?referrer ?body ?referrerPolicy ?keepalive url tr = Promise.to_lwt (fetch_base ?cache ?credentials ?headers ?integrity ?meth ?mode ?redirect ?referrer ?body ?referrerPolicy ?keepalive url) >>=? fun r -> to_response tr r let fetch_request r tr = Promise.to_lwt (fetch_request_base r) >>=? fun r -> to_response tr r
null
https://raw.githubusercontent.com/OCamlPro/ezjs_fetch/aabe9cb29dc257686fa15cd18ce436492b1480c3/src/ezjs_fetch_lwt.ml
ocaml
open Ezjs_min_lwt include Ezjs_fetch let (>>=?) x f = Lwt.bind x @@ function | Error _ as err -> Lwt.return err | Ok x -> f x let (>|=?) x f = Lwt.bind x @@ function | Error _ as err -> Lwt.return err | Ok x -> Lwt.return (Ok (f x)) let catch p = Lwt.bind (Promise.to_lwt p) @@ function | Error e -> Lwt.return_error e | Ok r -> match Opt.to_option r with | None -> Lwt.return_error (error_of_string "Cannot parse response body") | Some x -> Lwt.return_ok x type 'a body_translate = response_js t -> ('a, error t) result Lwt.t let to_array_buffer : Typed_array.arrayBuffer t body_translate = fun b -> catch b##arrayBuffer let to_blob : File.blob t body_translate = fun b -> catch b##blob let to_form_data : Js_of_ocaml.Form.formData t body_translate = fun b -> catch b##formData let to_js : 'a t body_translate = fun b -> catch b##json >|=? Unsafe.coerce let to_text : string body_translate = fun b -> catch b##text >|=? to_string let to_response (tr : 'a body_translate) (r :response_js t) = tr r >|=? fun body -> { headers = get_headers r##.headers; ok = to_bool r##.ok; redirected = to_bool r##.redirected; status = r##.status; status_text = to_string r##.statusText; typ = to_string r##.type_; url = to_string r##.url; body_used = to_bool r##.bodyUsed; body } let fetch ?cache ?credentials ?headers ?integrity ?meth ?mode ?redirect ?referrer ?body ?referrerPolicy ?keepalive url tr = Promise.to_lwt (fetch_base ?cache ?credentials ?headers ?integrity ?meth ?mode ?redirect ?referrer ?body ?referrerPolicy ?keepalive url) >>=? fun r -> to_response tr r let fetch_request r tr = Promise.to_lwt (fetch_request_base r) >>=? fun r -> to_response tr r
90a0d39b8526c8eb913aca1522df30d6eed416a71babec9af55c287f57d3aed3
erikd/haskell-big-integer-experiment
Loop.hs
# LANGUAGE BangPatterns , CPP , MagicHash # The ideas for these loop functions were stolen from loop package : The function intLoop is pretty much just like the upstream 's numLoop , with with more explicit types . The intLoopState adds a state value that is threaded through the computation . A more general version of this function was contributed back upstream : The ideas for these loop functions were stolen from Niklas Hambüchen's loop package: The function intLoop is pretty much just like the upstream's numLoop, with with more explicit types. The intLoopState adds a state value that is threaded through the computation. A more general version of this function was contributed back upstream: -} module Common.GHC.Integer.Loop ( intLoop , intLoopState ) where import Common.GHC.Integer.StrictPrim -- | @intLoop start end f@: Loops over a contiguous numerical range, including -- @end@. -- It uses @(+ 1)@ so for most integer types it has no bounds ( overflow ) check . # INLINE intLoop # intLoop :: Int -> Int -> (Int -> StrictPrim ()) -> StrictPrim () intLoop start end f = go start where go !x | x == end = f x | otherwise = do f x go (x + 1) -- | @intLoopState start end f@: Loops over a contiguous numerical range, from @start@ up to and including @end@ , threading a state value through the -- computation. # INLINE intLoopState # intLoopState :: Int -> Int -> b -> (Int -> b -> StrictPrim b) -> StrictPrim b intLoopState start end initState f = go start initState where go !x !s | x == end = f x s | otherwise = do !ns <- f x s go (x + 1) ns
null
https://raw.githubusercontent.com/erikd/haskell-big-integer-experiment/7841ec3fcc5be219fa16963849bd12137112f8a9/Common/GHC/Integer/Loop.hs
haskell
| @intLoop start end f@: Loops over a contiguous numerical range, including @end@. | @intLoopState start end f@: Loops over a contiguous numerical range, from computation.
# LANGUAGE BangPatterns , CPP , MagicHash # The ideas for these loop functions were stolen from loop package : The function intLoop is pretty much just like the upstream 's numLoop , with with more explicit types . The intLoopState adds a state value that is threaded through the computation . A more general version of this function was contributed back upstream : The ideas for these loop functions were stolen from Niklas Hambüchen's loop package: The function intLoop is pretty much just like the upstream's numLoop, with with more explicit types. The intLoopState adds a state value that is threaded through the computation. A more general version of this function was contributed back upstream: -} module Common.GHC.Integer.Loop ( intLoop , intLoopState ) where import Common.GHC.Integer.StrictPrim It uses @(+ 1)@ so for most integer types it has no bounds ( overflow ) check . # INLINE intLoop # intLoop :: Int -> Int -> (Int -> StrictPrim ()) -> StrictPrim () intLoop start end f = go start where go !x | x == end = f x | otherwise = do f x go (x + 1) @start@ up to and including @end@ , threading a state value through the # INLINE intLoopState # intLoopState :: Int -> Int -> b -> (Int -> b -> StrictPrim b) -> StrictPrim b intLoopState start end initState f = go start initState where go !x !s | x == end = f x s | otherwise = do !ns <- f x s go (x + 1) ns
253f54613326f72743b9584eeb551afa039fb954a33a17d7f5583cee0232ab35
Quid2/zm
K3878b3580fc5.hs
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} module Test.ZM.ADT.UnicodeLetter.K3878b3580fc5 (UnicodeLetter(..)) where import qualified Prelude(Eq,Ord,Show) import qualified GHC.Generics import qualified Flat import qualified Data.Model import qualified Test.ZM.ADT.Char.K066db52af145 newtype UnicodeLetter = UnicodeLetter Test.ZM.ADT.Char.K066db52af145.Char deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat) instance Data.Model.Model UnicodeLetter
null
https://raw.githubusercontent.com/Quid2/zm/02c0514777a75ac054bfd6251edd884372faddea/test/Test/ZM/ADT/UnicodeLetter/K3878b3580fc5.hs
haskell
# LANGUAGE DeriveAnyClass # # LANGUAGE DeriveGeneric #
module Test.ZM.ADT.UnicodeLetter.K3878b3580fc5 (UnicodeLetter(..)) where import qualified Prelude(Eq,Ord,Show) import qualified GHC.Generics import qualified Flat import qualified Data.Model import qualified Test.ZM.ADT.Char.K066db52af145 newtype UnicodeLetter = UnicodeLetter Test.ZM.ADT.Char.K066db52af145.Char deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat) instance Data.Model.Model UnicodeLetter
d7551c3745bddc9188a4ce768fc85cb26a6291064027b8b274e10eae16045c54
gregr/racket-misc
match.rkt
#lang racket/base (provide lambda/destruct define/destruct cata lambda/cata define/cata match/cata match-let1+values for/fold/match/derived for*/fold/match/derived for/fold/match for*/fold/match for/list/match for*/list/match ) (require (for-syntax racket/base) racket/function racket/match ) (module+ test (require racket/set rackunit )) (define-syntax (lambda/destruct stx) (syntax-case stx () ((_ (pattern ...) body ...) (with-syntax (((argname ...) (generate-temporaries #'(pattern ...)))) #`(lambda (argname ...) (match* (argname ...) ((pattern ...) body ...))))))) (define-syntax match-let1+values (syntax-rules (values) ((_ (values vals ...) val-expr body ...) (call-with-values (thunk val-expr) (lambda/destruct (vals ...) body ...))) ((_ pattern val-expr body ...) (match-let ((pattern val-expr)) body ...)))) (define-syntax define/destruct (syntax-rules () ((_ (name pattern ...) body ...) (define name (lambda/destruct (pattern ...) body ...))))) (module+ test (define/destruct (list-2nd-of-4 (list a b c d)) b) (check-equal? (list-2nd-of-4 '(a b c d)) 'b)) (define current-cata (make-parameter (lambda args (error "use of current-cata not in a catamorphism" args)))) (define-match-expander cata (lambda (stx) (syntax-case stx () ((_ pats ...) #'(app (current-cata) pats ...))))) (define-syntax (lambda/cata stx) (syntax-case stx () ((_ (pattern body ...) ...) (with-syntax (((cata-name) (generate-temporaries #'(cata-name)))) #'((thunk (define (cata-name value) (parameterize ((current-cata cata-name)) (match value (pattern body ...) ...))) cata-name)))))) (define-syntax define/cata (syntax-rules () ((_ name body ...) (define name (lambda/cata body ...))))) (define-syntax match/cata (syntax-rules () ((_ value body ...) ((lambda/cata body ...) value)))) (module+ test (check-equal? (match/cata (list 1 2 3 4) ('() '()) ((cons a (cata b)) (cons (+ a 1) b))) (list 2 3 4 5))) (define-syntax (for_/fold/match/derived-cont stx) (syntax-case stx (values) ((_ cont original acc for-clauses () (source ...) (pattern ...) body ...) #'(cont original acc for-clauses (match* (source ...) ((pattern ...) body ...)))) ((_ cont original acc (for-clause ...) (((values pats ...) seq) pat-for-clause ...) (source ...) (pattern ...) body ...) (with-syntax (((elems ...) (generate-temporaries #'(pats ...)))) #'(for_/fold/match/derived-cont cont original acc (for-clause ... ((elems ...) seq)) (pat-for-clause ...) (source ... elems ...) (pattern ... pats ...) body ...))) ((_ cont original acc (for-clause ...) ((pat seq) pat-for-clause ...) (source ...) (pattern ...) body ...) (with-syntax (((elem) (generate-temporaries #'(pat)))) #'(for_/fold/match/derived-cont cont original acc (for-clause ... (elem seq)) (pat-for-clause ...) (source ... elem) (pattern ... pat) body ...))) ((_ cont original acc (for-clause ...) (kw expr pat-for-clause ...) (source ...) (pattern ...) body ...) #'(for_/fold/match/derived-cont cont original acc (for-clause ... kw (match* (source ...) ((pattern ...) expr))) (pat-for-clause ...) (source ...) (pattern ...) body ...)))) (define-syntax (for_/fold/match/derived stx) (syntax-case stx () ((_ cont original ((acc-pattern acc-init) ...) (pat-for-clause ...) body ...) (with-syntax (((acc ...) (generate-temporaries #'((acc-pattern acc-init) ...)))) #'(for_/fold/match/derived-cont cont original ((acc acc-init) ...) () (pat-for-clause ...) (acc ...) (acc-pattern ...) body ...))))) (define-syntax for/fold/match/derived (syntax-rules () ((_ rest ...) (for_/fold/match/derived for/fold/derived rest ...)))) (define-syntax for*/fold/match/derived (syntax-rules () ((_ rest ...) (for_/fold/match/derived for*/fold/derived rest ...)))) (define-syntax (for/fold/match stx) (syntax-case stx () ((_ accs seqs body ...) #`(for/fold/match/derived #,stx accs seqs body ...)))) (define-syntax (for*/fold/match stx) (syntax-case stx () ((_ accs seqs body ...) #`(for*/fold/match/derived #,stx accs seqs body ...)))) (module+ test (check-equal? (for/fold/match (((cons sum _) (cons 0 'irrelevant))) (((cons a b) (list (cons 1 2) (cons 7 4)))) (cons (+ a b sum) 'something)) (cons 14 'something))) (module+ test (check-equal? (for/fold/match (((cons sum _) (cons 0 'irrelevant))) (((cons a b) (list (cons 1 2) (cons 7 4))) #:when #t (c (list 10 20)) ) (cons (+ a b c sum) 'something)) (cons (* 2 (+ 1 2 7 4 10 20)) 'something))) (module+ test (check-equal? (for/fold/match (((cons sum keys) (cons 0 (set)))) (((values key (list v0 v1)) (hash 'a (list 1 2) 'b (list 3 4) 'c (list 5 6)))) (cons (+ v0 v1 sum) (set-add keys key))) (cons (+ 1 2 3 4 5 6) (set 'a 'b 'c)))) (module+ test (check-equal? (for/fold/match (((list junk sum) (list '() 0))) ((x (list 1 2 3)) ((list y tag) '((4 i) (5 j) (6 k))) #:when (even? y) (z '(a b c)) ) (list (cons (list tag z) junk) (+ x y sum))) (list (reverse '((i a) (i b) (i c) (k a) (k b) (k c))) (* 3 (+ 1 3 4 6))))) (module+ test (check-equal? (for*/fold/match ((results '())) (((list x y) '((1 2) (3 4))) (sym '(a b))) (cons (list (+ x y) sym) results)) '((7 b) (7 a) (3 b) (3 a)) )) (define-syntax (for_/list/match stx) (syntax-case stx () ((_ cont seqs body ...) (with-syntax ((original stx) (list-acc (datum->syntax #'this 'list-acc))) #'(reverse (cont original ((list-acc '())) seqs (cons (begin body ...) list-acc))))))) (define-syntax for/list/match (syntax-rules () ((_ rest ...) (for_/list/match for/fold/match/derived rest ...)))) (define-syntax for*/list/match (syntax-rules () ((_ rest ...) (for_/list/match for*/fold/match/derived rest ...)))) (module+ test (check-equal? (for/list/match (((list a b) '((a b) (c d))) ((list c d) '((1 2) (3 4)))) (list a b c d)) '((a b 1 2) (c d 3 4)))) (module+ test (check-equal? (for/list/match ((x (list 1 2 3)) ((list y tag) '((4 i) (5 j) (6 k))) #:when (even? y) (z '(a b c)) ) (list tag z (+ x y))) '((i a 5) (i b 5) (i c 5) (k a 9) (k b 9) (k c 9)))) (module+ test (check-equal? (for*/list/match (((list a b) '((a b) (c d))) (c '(1 2))) (list a b c)) '((a b 1) (a b 2) (c d 1) (c d 2))))
null
https://raw.githubusercontent.com/gregr/racket-misc/0a5c9d4875288795e209d06982b82848c989d08b/match.rkt
racket
#lang racket/base (provide lambda/destruct define/destruct cata lambda/cata define/cata match/cata match-let1+values for/fold/match/derived for*/fold/match/derived for/fold/match for*/fold/match for/list/match for*/list/match ) (require (for-syntax racket/base) racket/function racket/match ) (module+ test (require racket/set rackunit )) (define-syntax (lambda/destruct stx) (syntax-case stx () ((_ (pattern ...) body ...) (with-syntax (((argname ...) (generate-temporaries #'(pattern ...)))) #`(lambda (argname ...) (match* (argname ...) ((pattern ...) body ...))))))) (define-syntax match-let1+values (syntax-rules (values) ((_ (values vals ...) val-expr body ...) (call-with-values (thunk val-expr) (lambda/destruct (vals ...) body ...))) ((_ pattern val-expr body ...) (match-let ((pattern val-expr)) body ...)))) (define-syntax define/destruct (syntax-rules () ((_ (name pattern ...) body ...) (define name (lambda/destruct (pattern ...) body ...))))) (module+ test (define/destruct (list-2nd-of-4 (list a b c d)) b) (check-equal? (list-2nd-of-4 '(a b c d)) 'b)) (define current-cata (make-parameter (lambda args (error "use of current-cata not in a catamorphism" args)))) (define-match-expander cata (lambda (stx) (syntax-case stx () ((_ pats ...) #'(app (current-cata) pats ...))))) (define-syntax (lambda/cata stx) (syntax-case stx () ((_ (pattern body ...) ...) (with-syntax (((cata-name) (generate-temporaries #'(cata-name)))) #'((thunk (define (cata-name value) (parameterize ((current-cata cata-name)) (match value (pattern body ...) ...))) cata-name)))))) (define-syntax define/cata (syntax-rules () ((_ name body ...) (define name (lambda/cata body ...))))) (define-syntax match/cata (syntax-rules () ((_ value body ...) ((lambda/cata body ...) value)))) (module+ test (check-equal? (match/cata (list 1 2 3 4) ('() '()) ((cons a (cata b)) (cons (+ a 1) b))) (list 2 3 4 5))) (define-syntax (for_/fold/match/derived-cont stx) (syntax-case stx (values) ((_ cont original acc for-clauses () (source ...) (pattern ...) body ...) #'(cont original acc for-clauses (match* (source ...) ((pattern ...) body ...)))) ((_ cont original acc (for-clause ...) (((values pats ...) seq) pat-for-clause ...) (source ...) (pattern ...) body ...) (with-syntax (((elems ...) (generate-temporaries #'(pats ...)))) #'(for_/fold/match/derived-cont cont original acc (for-clause ... ((elems ...) seq)) (pat-for-clause ...) (source ... elems ...) (pattern ... pats ...) body ...))) ((_ cont original acc (for-clause ...) ((pat seq) pat-for-clause ...) (source ...) (pattern ...) body ...) (with-syntax (((elem) (generate-temporaries #'(pat)))) #'(for_/fold/match/derived-cont cont original acc (for-clause ... (elem seq)) (pat-for-clause ...) (source ... elem) (pattern ... pat) body ...))) ((_ cont original acc (for-clause ...) (kw expr pat-for-clause ...) (source ...) (pattern ...) body ...) #'(for_/fold/match/derived-cont cont original acc (for-clause ... kw (match* (source ...) ((pattern ...) expr))) (pat-for-clause ...) (source ...) (pattern ...) body ...)))) (define-syntax (for_/fold/match/derived stx) (syntax-case stx () ((_ cont original ((acc-pattern acc-init) ...) (pat-for-clause ...) body ...) (with-syntax (((acc ...) (generate-temporaries #'((acc-pattern acc-init) ...)))) #'(for_/fold/match/derived-cont cont original ((acc acc-init) ...) () (pat-for-clause ...) (acc ...) (acc-pattern ...) body ...))))) (define-syntax for/fold/match/derived (syntax-rules () ((_ rest ...) (for_/fold/match/derived for/fold/derived rest ...)))) (define-syntax for*/fold/match/derived (syntax-rules () ((_ rest ...) (for_/fold/match/derived for*/fold/derived rest ...)))) (define-syntax (for/fold/match stx) (syntax-case stx () ((_ accs seqs body ...) #`(for/fold/match/derived #,stx accs seqs body ...)))) (define-syntax (for*/fold/match stx) (syntax-case stx () ((_ accs seqs body ...) #`(for*/fold/match/derived #,stx accs seqs body ...)))) (module+ test (check-equal? (for/fold/match (((cons sum _) (cons 0 'irrelevant))) (((cons a b) (list (cons 1 2) (cons 7 4)))) (cons (+ a b sum) 'something)) (cons 14 'something))) (module+ test (check-equal? (for/fold/match (((cons sum _) (cons 0 'irrelevant))) (((cons a b) (list (cons 1 2) (cons 7 4))) #:when #t (c (list 10 20)) ) (cons (+ a b c sum) 'something)) (cons (* 2 (+ 1 2 7 4 10 20)) 'something))) (module+ test (check-equal? (for/fold/match (((cons sum keys) (cons 0 (set)))) (((values key (list v0 v1)) (hash 'a (list 1 2) 'b (list 3 4) 'c (list 5 6)))) (cons (+ v0 v1 sum) (set-add keys key))) (cons (+ 1 2 3 4 5 6) (set 'a 'b 'c)))) (module+ test (check-equal? (for/fold/match (((list junk sum) (list '() 0))) ((x (list 1 2 3)) ((list y tag) '((4 i) (5 j) (6 k))) #:when (even? y) (z '(a b c)) ) (list (cons (list tag z) junk) (+ x y sum))) (list (reverse '((i a) (i b) (i c) (k a) (k b) (k c))) (* 3 (+ 1 3 4 6))))) (module+ test (check-equal? (for*/fold/match ((results '())) (((list x y) '((1 2) (3 4))) (sym '(a b))) (cons (list (+ x y) sym) results)) '((7 b) (7 a) (3 b) (3 a)) )) (define-syntax (for_/list/match stx) (syntax-case stx () ((_ cont seqs body ...) (with-syntax ((original stx) (list-acc (datum->syntax #'this 'list-acc))) #'(reverse (cont original ((list-acc '())) seqs (cons (begin body ...) list-acc))))))) (define-syntax for/list/match (syntax-rules () ((_ rest ...) (for_/list/match for/fold/match/derived rest ...)))) (define-syntax for*/list/match (syntax-rules () ((_ rest ...) (for_/list/match for*/fold/match/derived rest ...)))) (module+ test (check-equal? (for/list/match (((list a b) '((a b) (c d))) ((list c d) '((1 2) (3 4)))) (list a b c d)) '((a b 1 2) (c d 3 4)))) (module+ test (check-equal? (for/list/match ((x (list 1 2 3)) ((list y tag) '((4 i) (5 j) (6 k))) #:when (even? y) (z '(a b c)) ) (list tag z (+ x y))) '((i a 5) (i b 5) (i c 5) (k a 9) (k b 9) (k c 9)))) (module+ test (check-equal? (for*/list/match (((list a b) '((a b) (c d))) (c '(1 2))) (list a b c)) '((a b 1) (a b 2) (c d 1) (c d 2))))
57a06adb41e91801ba9e5a4d66ac2a4c613291ee038a1b32323ea8c0d38104c5
soupi/yh
Main.hs
# LANGUAGE LambdaCase # {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} module Main where import Play.Engine.Runner import Play.Engine.Types import Play.Engine.Utils import Play.Engine.Settings import qualified StartScreen as S main :: IO () main = do runGame settings (S.make `Stack` []) settings :: Settings settings = def { _windowSize = Point 800 1000 }
null
https://raw.githubusercontent.com/soupi/yh/4cfbcc7da6f3ca5e330b7fd7d4adeacee7e2dff4/app/Main.hs
haskell
# LANGUAGE OverloadedStrings # # LANGUAGE RankNTypes #
# LANGUAGE LambdaCase # module Main where import Play.Engine.Runner import Play.Engine.Types import Play.Engine.Utils import Play.Engine.Settings import qualified StartScreen as S main :: IO () main = do runGame settings (S.make `Stack` []) settings :: Settings settings = def { _windowSize = Point 800 1000 }
497c38595db153883096bf6c2e04f95300b95610ae05dbb234d8071f30e7bdbe
cky/guile
rnrs.scm
;;; rnrs.scm --- The R6RS composite library Copyright ( C ) 2010 , 2011 Free Software Foundation , Inc. ;; ;; This library is free software; you can redistribute it and/or ;; modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 3 of the License , or ( at your option ) any later version . ;; ;; This library is distributed in the hope that it will be useful, ;; but WITHOUT ANY WARRANTY; without even the implied warranty of ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;; Lesser General Public License for more details. ;; You should have received a copy of the GNU Lesser General Public ;; License along with this library; if not, write to the Free Software Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA (library (rnrs (6)) ( rnrs arithmetic bitwise ) bitwise-not bitwise-and bitwise-ior bitwise-xor bitwise-if bitwise-bit-count bitwise-length bitwise-first-bit-set bitwise-bit-set? bitwise-copy-bit bitwise-bit-field bitwise-copy-bit-field bitwise-arithmetic-shift bitwise-arithmetic-shift-left bitwise-arithmetic-shift-right bitwise-rotate-bit-field bitwise-reverse-bit-field ( rnrs arithmetic fixnums ) fixnum? fixnum-width least-fixnum greatest-fixnum fx=? fx>? fx<? fx>=? fx<=? fxzero? fxpositive? fxnegative? fxodd? fxeven? fxmax fxmin fx+ fx* fx- fxdiv-and-mod fxdiv fxmod fxdiv0-and-mod0 fxdiv0 fxmod0 fx+/carry fx-/carry fx*/carry fxnot fxand fxior fxxor fxif fxbit-count fxlength fxfirst-bit-set fxbit-set? fxcopy-bit fxbit-field fxcopy-bit-field fxarithmetic-shift fxarithmetic-shift-left fxarithmetic-shift-right fxrotate-bit-field fxreverse-bit-field ( rnrs arithmetic flonums ) flonum? real->flonum fl=? fl<? fl<=? fl>? fl>=? flinteger? flzero? flpositive? flnegative? flodd? fleven? flfinite? flinfinite? flnan? flmax flmin fl+ fl* fl- fl/ flabs fldiv-and-mod fldiv flmod fldiv0-and-mod0 fldiv0 flmod0 flnumerator fldenominator flfloor flceiling fltruncate flround flexp fllog flsin flcos fltan flacos flasin flatan flsqrt flexpt &no-infinities make-no-infinities-violation no-infinities-violation? &no-nans make-no-nans-violation no-nans-violation? fixnum->flonum ;; (rnrs base) boolean? symbol? char? vector? null? pair? number? string? procedure? define define-syntax syntax-rules lambda let let* let-values let*-values letrec letrec* begin quote lambda if set! cond case or and not eqv? equal? eq? + - * / max min abs numerator denominator gcd lcm floor ceiling truncate round rationalize real-part imag-part make-rectangular angle div mod div-and-mod div0 mod0 div0-and-mod0 expt exact-integer-sqrt sqrt exp log sin cos tan asin acos atan make-polar magnitude angle complex? real? rational? integer? exact? inexact? real-valued? rational-valued? integer-valued? zero? positive? negative? odd? even? nan? finite? infinite? exact inexact = < > <= >= number->string string->number boolean=? cons car cdr caar cadr cdar cddr caaar caadr cadar cdaar caddr cdadr cddar cdddr caaaar caaadr caadar cadaar cdaaar cddaar cdadar cdaadr cadadr caaddr caddar cadddr cdaddr cddadr cdddar cddddr list? list length append reverse list-tail list-ref map for-each symbol->string string->symbol symbol=? char->integer integer->char char=? char<? char>? char<=? char>=? make-string string string-length string-ref string=? string<? string>? string<=? string>=? substring string-append string->list list->string string-for-each string-copy vector? make-vector vector vector-length vector-ref vector-set! vector->list list->vector vector-fill! vector-map vector-for-each error assertion-violation assert call-with-current-continuation call/cc call-with-values dynamic-wind values apply quasiquote unquote unquote-splicing let-syntax letrec-syntax syntax-rules identifier-syntax ( ) endianness native-endianness bytevector? make-bytevector bytevector-length bytevector=? bytevector-fill! bytevector-copy! bytevector-copy uniform-array->bytevector bytevector-u8-ref bytevector-s8-ref bytevector-u8-set! bytevector-s8-set! bytevector->u8-list u8-list->bytevector bytevector-uint-ref bytevector-uint-set! bytevector-sint-ref bytevector-sint-set! bytevector->sint-list bytevector->uint-list uint-list->bytevector sint-list->bytevector bytevector-u16-ref bytevector-s16-ref bytevector-u16-set! bytevector-s16-set! bytevector-u16-native-ref bytevector-s16-native-ref bytevector-u16-native-set! bytevector-s16-native-set! bytevector-u32-ref bytevector-s32-ref bytevector-u32-set! bytevector-s32-set! bytevector-u32-native-ref bytevector-s32-native-ref bytevector-u32-native-set! bytevector-s32-native-set! bytevector-u64-ref bytevector-s64-ref bytevector-u64-set! bytevector-s64-set! bytevector-u64-native-ref bytevector-s64-native-ref bytevector-u64-native-set! bytevector-s64-native-set! bytevector-ieee-single-ref bytevector-ieee-single-set! bytevector-ieee-single-native-ref bytevector-ieee-single-native-set! bytevector-ieee-double-ref bytevector-ieee-double-set! bytevector-ieee-double-native-ref bytevector-ieee-double-native-set! string->utf8 string->utf16 string->utf32 utf8->string utf16->string utf32->string ;; (rnrs conditions) &condition condition simple-conditions condition? condition-predicate condition-accessor define-condition-type &message make-message-condition message-condition? condition-message &warning make-warning warning? &serious make-serious-condition serious-condition? &error make-error error? &violation make-violation violation? &assertion make-assertion-violation assertion-violation? &irritants make-irritants-condition irritants-condition? condition-irritants &who make-who-condition who-condition? condition-who &non-continuable make-non-continuable-violation non-continuable-violation? &implementation-restriction make-implementation-restriction-violation implementation-restriction-violation? &lexical make-lexical-violation lexical-violation? &syntax make-syntax-violation syntax-violation? syntax-violation-form syntax-violation-subform &undefined make-undefined-violation undefined-violation? ;; (rnrs control) when unless do case-lambda ( ) make-enumeration enum-set-universe enum-set-indexer enum-set-constructor enum-set->list enum-set-member? enum-set-subset? enum-set=? enum-set-union enum-set-intersection enum-set-difference enum-set-complement enum-set-projection define-enumeration ;; (rnrs exceptions) guard with-exception-handler raise raise-continuable ;; (rnrs files) file-exists? delete-file &i/o make-i/o-error i/o-error? &i/o-read make-i/o-read-error i/o-read-error? &i/o-write make-i/o-write-error i/o-write-error? &i/o-invalid-position make-i/o-invalid-position-error i/o-invalid-position-error? i/o-error-position &i/o-filename make-i/o-filename-error i/o-filename-error? i/o-error-filename &i/o-file-protection make-i/o-file-protection-error i/o-file-protection-error? &i/o-file-is-read-only make-i/o-file-is-read-only-error i/o-file-is-read-only-error? &i/o-file-already-exists make-i/o-file-already-exists-error i/o-file-already-exists-error? &i/o-file-does-not-exist make-i/o-file-does-not-exist-error i/o-file-does-not-exist-error? &i/o-port make-i/o-port-error i/o-port-error? i/o-error-port ( ) make-eq-hashtable make-eqv-hashtable make-hashtable hashtable? hashtable-size hashtable-ref hashtable-set! hashtable-delete! hashtable-contains? hashtable-update! hashtable-copy hashtable-clear! hashtable-keys hashtable-entries hashtable-equivalence-function hashtable-hash-function hashtable-mutable? equal-hash string-hash string-ci-hash symbol-hash ( rnrs io ports ) file-options buffer-mode buffer-mode? eol-style native-eol-style error-handling-mode make-transcoder transcoder-codec transcoder-eol-style transcoder-error-handling-mode native-transcoder latin-1-codec utf-8-codec utf-16-codec eof-object? port? input-port? output-port? eof-object port-eof? port-transcoder binary-port? textual-port? transcoded-port port-position set-port-position! port-has-port-position? port-has-set-port-position!? close-port call-with-port open-bytevector-input-port make-custom-binary-input-port get-u8 lookahead-u8 get-bytevector-n get-bytevector-n! get-bytevector-some get-bytevector-all open-bytevector-output-port make-custom-binary-output-port put-u8 put-bytevector open-string-input-port open-string-output-port call-with-bytevector-output-port call-with-string-output-port latin-1-codec utf-8-codec utf-16-codec open-file-input-port open-file-output-port open-file-input/output-port make-custom-textual-output-port call-with-string-output-port flush-output-port put-string get-char get-datum get-line get-string-all get-string-n get-string-n! lookahead-char put-char put-datum put-string standard-input-port standard-output-port standard-error-port ;; (rnrs io simple) call-with-input-file call-with-output-file current-input-port current-output-port current-error-port with-input-from-file with-output-to-file open-input-file open-output-file close-input-port close-output-port read-char peek-char read write-char newline display write ;; (rnrs lists) find for-all exists filter partition fold-left fold-right remp remove remv remq memp member memv memq assp assoc assv assq cons* ;; (rnrs programs) command-line exit ( rnrs records inspection ) record? record-rtd record-type-name record-type-parent record-type-uid record-type-generative? record-type-sealed? record-type-opaque? record-type-field-names record-field-mutable? ( rnrs records procedural ) make-record-type-descriptor record-type-descriptor? make-record-constructor-descriptor record-constructor record-predicate record-accessor record-mutator ( rnrs records syntactic ) define-record-type record-type-descriptor record-constructor-descriptor ;; (rnrs sorting) list-sort vector-sort vector-sort! ;; (rnrs syntax-case) make-variable-transformer syntax ;; Until the deprecated support for a unified modules and ;; bindings namespace is removed, we need to manually resolve a conflict between two bindings : that of the ( rnrs ;; syntax-case) module, and the imported `syntax-case' ;; binding. We do so here and below by renaming the macro ;; import. (rename (syntax-case-hack syntax-case)) identifier? bound-identifier=? free-identifier=? syntax->datum datum->syntax generate-temporaries with-syntax quasisyntax unsyntax unsyntax-splicing syntax-violation ;; (rnrs unicode) char-upcase char-downcase char-titlecase char-foldcase char-ci=? char-ci<? char-ci>? char-ci<=? char-ci>=? char-alphabetic? char-numeric? char-whitespace? char-upper-case? char-lower-case? char-title-case? char-general-category string-upcase string-downcase string-titlecase string-foldcase string-ci=? string-ci<? string-ci>? string-ci<=? string-ci>=? string-normalize-nfd string-normalize-nfkd string-normalize-nfc string-normalize-nfkc) (import (rnrs arithmetic bitwise (6)) (rnrs arithmetic fixnums (6)) (rnrs arithmetic flonums (6)) (rnrs base (6)) (rnrs bytevectors (6)) (rnrs conditions (6)) (rnrs control (6)) (rnrs enums (6)) (rnrs exceptions (6)) (rnrs files (6)) (rnrs hashtables (6)) (rnrs io ports (6)) (rnrs io simple (6)) (rnrs lists (6)) (rnrs programs (6)) (rnrs records inspection (6)) (rnrs records procedural (6)) (rnrs records syntactic (6)) (rnrs sorting (6)) ;; See note above on exporting syntax-case. (rename (rnrs syntax-case (6)) (syntax-case syntax-case-hack)) (rnrs unicode (6))))
null
https://raw.githubusercontent.com/cky/guile/89ce9fb31b00f1f243fe6f2450db50372cc0b86d/module/rnrs.scm
scheme
rnrs.scm --- The R6RS composite library This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public either This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with this library; if not, write to the Free Software (rnrs base) (rnrs conditions) (rnrs control) (rnrs exceptions) (rnrs files) (rnrs io simple) (rnrs lists) (rnrs programs) (rnrs sorting) (rnrs syntax-case) Until the deprecated support for a unified modules and bindings namespace is removed, we need to manually resolve syntax-case) module, and the imported `syntax-case' binding. We do so here and below by renaming the macro import. (rnrs unicode) See note above on exporting syntax-case.
Copyright ( C ) 2010 , 2011 Free Software Foundation , Inc. version 3 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA (library (rnrs (6)) ( rnrs arithmetic bitwise ) bitwise-not bitwise-and bitwise-ior bitwise-xor bitwise-if bitwise-bit-count bitwise-length bitwise-first-bit-set bitwise-bit-set? bitwise-copy-bit bitwise-bit-field bitwise-copy-bit-field bitwise-arithmetic-shift bitwise-arithmetic-shift-left bitwise-arithmetic-shift-right bitwise-rotate-bit-field bitwise-reverse-bit-field ( rnrs arithmetic fixnums ) fixnum? fixnum-width least-fixnum greatest-fixnum fx=? fx>? fx<? fx>=? fx<=? fxzero? fxpositive? fxnegative? fxodd? fxeven? fxmax fxmin fx+ fx* fx- fxdiv-and-mod fxdiv fxmod fxdiv0-and-mod0 fxdiv0 fxmod0 fx+/carry fx-/carry fx*/carry fxnot fxand fxior fxxor fxif fxbit-count fxlength fxfirst-bit-set fxbit-set? fxcopy-bit fxbit-field fxcopy-bit-field fxarithmetic-shift fxarithmetic-shift-left fxarithmetic-shift-right fxrotate-bit-field fxreverse-bit-field ( rnrs arithmetic flonums ) flonum? real->flonum fl=? fl<? fl<=? fl>? fl>=? flinteger? flzero? flpositive? flnegative? flodd? fleven? flfinite? flinfinite? flnan? flmax flmin fl+ fl* fl- fl/ flabs fldiv-and-mod fldiv flmod fldiv0-and-mod0 fldiv0 flmod0 flnumerator fldenominator flfloor flceiling fltruncate flround flexp fllog flsin flcos fltan flacos flasin flatan flsqrt flexpt &no-infinities make-no-infinities-violation no-infinities-violation? &no-nans make-no-nans-violation no-nans-violation? fixnum->flonum boolean? symbol? char? vector? null? pair? number? string? procedure? define define-syntax syntax-rules lambda let let* let-values let*-values letrec letrec* begin quote lambda if set! cond case or and not eqv? equal? eq? + - * / max min abs numerator denominator gcd lcm floor ceiling truncate round rationalize real-part imag-part make-rectangular angle div mod div-and-mod div0 mod0 div0-and-mod0 expt exact-integer-sqrt sqrt exp log sin cos tan asin acos atan make-polar magnitude angle complex? real? rational? integer? exact? inexact? real-valued? rational-valued? integer-valued? zero? positive? negative? odd? even? nan? finite? infinite? exact inexact = < > <= >= number->string string->number boolean=? cons car cdr caar cadr cdar cddr caaar caadr cadar cdaar caddr cdadr cddar cdddr caaaar caaadr caadar cadaar cdaaar cddaar cdadar cdaadr cadadr caaddr caddar cadddr cdaddr cddadr cdddar cddddr list? list length append reverse list-tail list-ref map for-each symbol->string string->symbol symbol=? char->integer integer->char char=? char<? char>? char<=? char>=? make-string string string-length string-ref string=? string<? string>? string<=? string>=? substring string-append string->list list->string string-for-each string-copy vector? make-vector vector vector-length vector-ref vector-set! vector->list list->vector vector-fill! vector-map vector-for-each error assertion-violation assert call-with-current-continuation call/cc call-with-values dynamic-wind values apply quasiquote unquote unquote-splicing let-syntax letrec-syntax syntax-rules identifier-syntax ( ) endianness native-endianness bytevector? make-bytevector bytevector-length bytevector=? bytevector-fill! bytevector-copy! bytevector-copy uniform-array->bytevector bytevector-u8-ref bytevector-s8-ref bytevector-u8-set! bytevector-s8-set! bytevector->u8-list u8-list->bytevector bytevector-uint-ref bytevector-uint-set! bytevector-sint-ref bytevector-sint-set! bytevector->sint-list bytevector->uint-list uint-list->bytevector sint-list->bytevector bytevector-u16-ref bytevector-s16-ref bytevector-u16-set! bytevector-s16-set! bytevector-u16-native-ref bytevector-s16-native-ref bytevector-u16-native-set! bytevector-s16-native-set! bytevector-u32-ref bytevector-s32-ref bytevector-u32-set! bytevector-s32-set! bytevector-u32-native-ref bytevector-s32-native-ref bytevector-u32-native-set! bytevector-s32-native-set! bytevector-u64-ref bytevector-s64-ref bytevector-u64-set! bytevector-s64-set! bytevector-u64-native-ref bytevector-s64-native-ref bytevector-u64-native-set! bytevector-s64-native-set! bytevector-ieee-single-ref bytevector-ieee-single-set! bytevector-ieee-single-native-ref bytevector-ieee-single-native-set! bytevector-ieee-double-ref bytevector-ieee-double-set! bytevector-ieee-double-native-ref bytevector-ieee-double-native-set! string->utf8 string->utf16 string->utf32 utf8->string utf16->string utf32->string &condition condition simple-conditions condition? condition-predicate condition-accessor define-condition-type &message make-message-condition message-condition? condition-message &warning make-warning warning? &serious make-serious-condition serious-condition? &error make-error error? &violation make-violation violation? &assertion make-assertion-violation assertion-violation? &irritants make-irritants-condition irritants-condition? condition-irritants &who make-who-condition who-condition? condition-who &non-continuable make-non-continuable-violation non-continuable-violation? &implementation-restriction make-implementation-restriction-violation implementation-restriction-violation? &lexical make-lexical-violation lexical-violation? &syntax make-syntax-violation syntax-violation? syntax-violation-form syntax-violation-subform &undefined make-undefined-violation undefined-violation? when unless do case-lambda ( ) make-enumeration enum-set-universe enum-set-indexer enum-set-constructor enum-set->list enum-set-member? enum-set-subset? enum-set=? enum-set-union enum-set-intersection enum-set-difference enum-set-complement enum-set-projection define-enumeration guard with-exception-handler raise raise-continuable file-exists? delete-file &i/o make-i/o-error i/o-error? &i/o-read make-i/o-read-error i/o-read-error? &i/o-write make-i/o-write-error i/o-write-error? &i/o-invalid-position make-i/o-invalid-position-error i/o-invalid-position-error? i/o-error-position &i/o-filename make-i/o-filename-error i/o-filename-error? i/o-error-filename &i/o-file-protection make-i/o-file-protection-error i/o-file-protection-error? &i/o-file-is-read-only make-i/o-file-is-read-only-error i/o-file-is-read-only-error? &i/o-file-already-exists make-i/o-file-already-exists-error i/o-file-already-exists-error? &i/o-file-does-not-exist make-i/o-file-does-not-exist-error i/o-file-does-not-exist-error? &i/o-port make-i/o-port-error i/o-port-error? i/o-error-port ( ) make-eq-hashtable make-eqv-hashtable make-hashtable hashtable? hashtable-size hashtable-ref hashtable-set! hashtable-delete! hashtable-contains? hashtable-update! hashtable-copy hashtable-clear! hashtable-keys hashtable-entries hashtable-equivalence-function hashtable-hash-function hashtable-mutable? equal-hash string-hash string-ci-hash symbol-hash ( rnrs io ports ) file-options buffer-mode buffer-mode? eol-style native-eol-style error-handling-mode make-transcoder transcoder-codec transcoder-eol-style transcoder-error-handling-mode native-transcoder latin-1-codec utf-8-codec utf-16-codec eof-object? port? input-port? output-port? eof-object port-eof? port-transcoder binary-port? textual-port? transcoded-port port-position set-port-position! port-has-port-position? port-has-set-port-position!? close-port call-with-port open-bytevector-input-port make-custom-binary-input-port get-u8 lookahead-u8 get-bytevector-n get-bytevector-n! get-bytevector-some get-bytevector-all open-bytevector-output-port make-custom-binary-output-port put-u8 put-bytevector open-string-input-port open-string-output-port call-with-bytevector-output-port call-with-string-output-port latin-1-codec utf-8-codec utf-16-codec open-file-input-port open-file-output-port open-file-input/output-port make-custom-textual-output-port call-with-string-output-port flush-output-port put-string get-char get-datum get-line get-string-all get-string-n get-string-n! lookahead-char put-char put-datum put-string standard-input-port standard-output-port standard-error-port call-with-input-file call-with-output-file current-input-port current-output-port current-error-port with-input-from-file with-output-to-file open-input-file open-output-file close-input-port close-output-port read-char peek-char read write-char newline display write find for-all exists filter partition fold-left fold-right remp remove remv remq memp member memv memq assp assoc assv assq cons* command-line exit ( rnrs records inspection ) record? record-rtd record-type-name record-type-parent record-type-uid record-type-generative? record-type-sealed? record-type-opaque? record-type-field-names record-field-mutable? ( rnrs records procedural ) make-record-type-descriptor record-type-descriptor? make-record-constructor-descriptor record-constructor record-predicate record-accessor record-mutator ( rnrs records syntactic ) define-record-type record-type-descriptor record-constructor-descriptor list-sort vector-sort vector-sort! make-variable-transformer syntax a conflict between two bindings : that of the ( rnrs (rename (syntax-case-hack syntax-case)) identifier? bound-identifier=? free-identifier=? syntax->datum datum->syntax generate-temporaries with-syntax quasisyntax unsyntax unsyntax-splicing syntax-violation char-upcase char-downcase char-titlecase char-foldcase char-ci=? char-ci<? char-ci>? char-ci<=? char-ci>=? char-alphabetic? char-numeric? char-whitespace? char-upper-case? char-lower-case? char-title-case? char-general-category string-upcase string-downcase string-titlecase string-foldcase string-ci=? string-ci<? string-ci>? string-ci<=? string-ci>=? string-normalize-nfd string-normalize-nfkd string-normalize-nfc string-normalize-nfkc) (import (rnrs arithmetic bitwise (6)) (rnrs arithmetic fixnums (6)) (rnrs arithmetic flonums (6)) (rnrs base (6)) (rnrs bytevectors (6)) (rnrs conditions (6)) (rnrs control (6)) (rnrs enums (6)) (rnrs exceptions (6)) (rnrs files (6)) (rnrs hashtables (6)) (rnrs io ports (6)) (rnrs io simple (6)) (rnrs lists (6)) (rnrs programs (6)) (rnrs records inspection (6)) (rnrs records procedural (6)) (rnrs records syntactic (6)) (rnrs sorting (6)) (rename (rnrs syntax-case (6)) (syntax-case syntax-case-hack)) (rnrs unicode (6))))
8e35c07169729c6862cb3a742b60653cb15a2219d3fbc1cc2880827170cea21a
totalperspective/oolon
datalog_test.clj
(ns oolon.datalog-test (:require [oolon.datalog :refer :all] [midje.sweet :refer :all])) (facts "About val->sym" (tabular (fact "Basic types are un touched" (val->sym ?val) => ?val) ?val 1 "two" :three 'four #inst "2010") (tabular (fact "Special keywords are turned into symbols" (val->sym ?val) => ?sym) ?val ?sym :_ '_ :?s '?s)) (facts "About rel->eavt" (rel->eavt :link nil) => nil (rel->eavt :link {}) => '[[?link :link/$id ?link$id]] (rel->eavt :link {:src 1}) => '[[?link :link/src 1] [?link :link/$id ?link$id]] (rel->eavt :link#1 {:src 1}) => '[[?link1 :link/src 1] [?link1 :link/$id ?link1$id]] (rel->eavt :link {:src :?src}) => '[[?link :link/src ?src] [?link :link/$id ?link$id]] (rel->eavt :link {:src :src :_ :dst}) => '[[?link :link/src :src] [?link _ :dst] [?link :link/$id ?link$id]] (rel->eavt :link {:src :?src :dst :?dst} 1) => '[[?link :link/src ?src 1] [?link :link/dst ?dst 1] [?link :link/$id ?link$id]] (rel->eavt :link {:src :?src :dst :dst} :?tx) => '[[?link :link/src ?src ?tx] [?link :link/dst :dst ?tx] [?link :link/$id ?link$id]]) (facts "About generating queries" (query) => nil (query [:link {:src 1}]) => '[[?link :link/src 1] [?link :link/$id ?link$id]] (query [:link#1 {:src 1}] [:link#2 {:src 2}]) => '[[?link1 :link/src 1] [?link1 :link/$id ?link1$id] [?link2 :link/src 2] [?link2 :link/$id ?link2$id]] (query [:link {:src :?src :dst :?via}] [:path {:src :?via :dst :?dst}]) => '[[?link :link/src ?src] [?link :link/dst ?via] [?link :link/$id ?link$id] [?path :path/src ?via] [?path :path/dst ?dst] [?path :path/$id ?path$id]] (query [:link {:src :?src :dst :?via :cost :?c1}] [:path {:src :?via :dst :?dst :cost :?c2}] '[(+ ?c1 ?c2) ?cost]) => '[[?link :link/src ?src] [?link :link/dst ?via] [?link :link/cost ?c1] [?link :link/$id ?link$id] [?path :path/src ?via] [?path :path/dst ?dst] [?path :path/cost ?c2] [?path :path/$id ?path$id] [(+ ?c1 ?c2) ?cost]] (query [:link {:src :?src :dst :?via :cost :?c1}] [:path {:src :?via :dst :?dst :cost :?c2}] '[(+ ?c1 ?c2) ?cost] '(not [:link {:src :?dst}])) => '[[?link :link/src ?src] [?link :link/dst ?via] [?link :link/cost ?c1] [?link :link/$id ?link$id] [?path :path/src ?via] [?path :path/dst ?dst] [?path :path/cost ?c2] [?path :path/$id ?path$id] [(+ ?c1 ?c2) ?cost] (not [?link :link/src ?dst] [?link :link/$id ?link$id])]) (facts "About vars" (lvars '[[?link :link/src 1]]) => '#{?link} (lvars '[[?link :link/src ?src] [?link :link/dst ?via] [?link :link/cost ?c1] [?link :link/$id ?link$id] [?path :path/src ?via] [?path :path/dst ?dst] [?path :path/cost ?c2] [?path :path/$id ?path$id] [(+ ?c1 ?c2) ?cost] (not [?link :link/src ?dst] [?link :link/$id ?link$id])]) => '#{?link ?link$id ?src ?c1 ?path ?path$id ?via ?c2 ?cost ?dst}) (facts "About safety" (tabular (fact "every variable that appears in the head of a clause also appears in a nonarithmetic positive (i.e. not negated) literal in the body of the clause" (safe? ?head ?body) => ?safe) ?head ?body ?safe '[?a] '[?a] true '[] '[?a] true '[?a] '[] false '[] '[[?a]] true '[[?a]] '[] false '{:a ?a} '[[?a] [?b]] true '{:a ?c} '[[?a] [?b]] false '{?b {:b ?a}} '[[?a] [?b]] true) (tabular (fact "requires that every variable appearing in a negative literal in the body of a clause also appears in some positive literal in the body of the clause" (safe? [] ?body) => ?safe) ?body ?safe '[(not [?q])] false '[[?q] (not [?q])] true)) (facts "About rules" (let [link-path (rule [:path {:src :?src :dst :?dst}] [[:link {:src :?src :dst :?dst}]]) path-path (rule [:path {:src :?src :dst :?dst}] [[:link {:src :?src :dst :?via}] [:path {:src :?via :dst :?dst}]]) everyone-likes (rule [:everyone-likes {:name :?x}] [[:person {:name :?x}] '(not-join [?x] [:is-not-liked {:name :?x}])]) is-not-liked (rule [:is-not-liked {:name :?y}] [[:person#x {:name :?x}] [:person#y {:name :?y}] '(not-join [?x ?y] [:likes {:person :?x :likes :?y}])])] (fact "We can ennumerate the positive attrs in the head of each rule" (:head-attrs link-path) => #{:path/src :path/dst} (:head-attrs path-path) => #{:path/src :path/dst} (:head-attrs everyone-likes) => #{:everyone-likes/name} (:head-attrs is-not-liked) => #{:is-not-liked/name}) (fact "We can ennumerate the positive attrs a dule depends on" (:pos-attrs link-path) => #{:link/src :link/dst} (:pos-attrs path-path) => #{:link/src :link/dst :path/src :path/dst} (:pos-attrs everyone-likes) => #{:person/name} (:pos-attrs is-not-liked) => #{:person/name}) (facts "About safety" (:safe? link-path) => true (:safe? path-path) => true (:safe? everyone-likes) => true (:safe? is-not-liked) => true) (facts "About negation" (fact "Rules with a not are negative" (:neg? link-path) => false (:neg? path-path) => false (:neg? everyone-likes) => true (:neg? is-not-liked) => true) (fact "Negative rules have dependant attributes" (:neg-attrs link-path) => #{} (:neg-attrs path-path) => #{} (:neg-attrs everyone-likes) => #{:is-not-liked/name} (:neg-attrs is-not-liked) => #{:likes/person :likes/likes})) (facts "About dependence" (depends-on? link-path path-path) => false (depends-on? path-path link-path) => false (depends-on? is-not-liked everyone-likes) => false (depends-on? everyone-likes is-not-liked) => true) (fact "We can aquire the lvars for the entities that the rule depends on" (:dep-lvars link-path) => (just '#{?link}) (:dep-lvars path-path) => (just '#{?link ?path}) (:dep-lvars everyone-likes) => (just '#{?person}) (:dep-lvars is-not-liked) => (just '#{?personx ?persony}))))
null
https://raw.githubusercontent.com/totalperspective/oolon/a457d2a2d440a25f663bd0508a95e6877eae6f81/test/clj/oolon/datalog_test.clj
clojure
(ns oolon.datalog-test (:require [oolon.datalog :refer :all] [midje.sweet :refer :all])) (facts "About val->sym" (tabular (fact "Basic types are un touched" (val->sym ?val) => ?val) ?val 1 "two" :three 'four #inst "2010") (tabular (fact "Special keywords are turned into symbols" (val->sym ?val) => ?sym) ?val ?sym :_ '_ :?s '?s)) (facts "About rel->eavt" (rel->eavt :link nil) => nil (rel->eavt :link {}) => '[[?link :link/$id ?link$id]] (rel->eavt :link {:src 1}) => '[[?link :link/src 1] [?link :link/$id ?link$id]] (rel->eavt :link#1 {:src 1}) => '[[?link1 :link/src 1] [?link1 :link/$id ?link1$id]] (rel->eavt :link {:src :?src}) => '[[?link :link/src ?src] [?link :link/$id ?link$id]] (rel->eavt :link {:src :src :_ :dst}) => '[[?link :link/src :src] [?link _ :dst] [?link :link/$id ?link$id]] (rel->eavt :link {:src :?src :dst :?dst} 1) => '[[?link :link/src ?src 1] [?link :link/dst ?dst 1] [?link :link/$id ?link$id]] (rel->eavt :link {:src :?src :dst :dst} :?tx) => '[[?link :link/src ?src ?tx] [?link :link/dst :dst ?tx] [?link :link/$id ?link$id]]) (facts "About generating queries" (query) => nil (query [:link {:src 1}]) => '[[?link :link/src 1] [?link :link/$id ?link$id]] (query [:link#1 {:src 1}] [:link#2 {:src 2}]) => '[[?link1 :link/src 1] [?link1 :link/$id ?link1$id] [?link2 :link/src 2] [?link2 :link/$id ?link2$id]] (query [:link {:src :?src :dst :?via}] [:path {:src :?via :dst :?dst}]) => '[[?link :link/src ?src] [?link :link/dst ?via] [?link :link/$id ?link$id] [?path :path/src ?via] [?path :path/dst ?dst] [?path :path/$id ?path$id]] (query [:link {:src :?src :dst :?via :cost :?c1}] [:path {:src :?via :dst :?dst :cost :?c2}] '[(+ ?c1 ?c2) ?cost]) => '[[?link :link/src ?src] [?link :link/dst ?via] [?link :link/cost ?c1] [?link :link/$id ?link$id] [?path :path/src ?via] [?path :path/dst ?dst] [?path :path/cost ?c2] [?path :path/$id ?path$id] [(+ ?c1 ?c2) ?cost]] (query [:link {:src :?src :dst :?via :cost :?c1}] [:path {:src :?via :dst :?dst :cost :?c2}] '[(+ ?c1 ?c2) ?cost] '(not [:link {:src :?dst}])) => '[[?link :link/src ?src] [?link :link/dst ?via] [?link :link/cost ?c1] [?link :link/$id ?link$id] [?path :path/src ?via] [?path :path/dst ?dst] [?path :path/cost ?c2] [?path :path/$id ?path$id] [(+ ?c1 ?c2) ?cost] (not [?link :link/src ?dst] [?link :link/$id ?link$id])]) (facts "About vars" (lvars '[[?link :link/src 1]]) => '#{?link} (lvars '[[?link :link/src ?src] [?link :link/dst ?via] [?link :link/cost ?c1] [?link :link/$id ?link$id] [?path :path/src ?via] [?path :path/dst ?dst] [?path :path/cost ?c2] [?path :path/$id ?path$id] [(+ ?c1 ?c2) ?cost] (not [?link :link/src ?dst] [?link :link/$id ?link$id])]) => '#{?link ?link$id ?src ?c1 ?path ?path$id ?via ?c2 ?cost ?dst}) (facts "About safety" (tabular (fact "every variable that appears in the head of a clause also appears in a nonarithmetic positive (i.e. not negated) literal in the body of the clause" (safe? ?head ?body) => ?safe) ?head ?body ?safe '[?a] '[?a] true '[] '[?a] true '[?a] '[] false '[] '[[?a]] true '[[?a]] '[] false '{:a ?a} '[[?a] [?b]] true '{:a ?c} '[[?a] [?b]] false '{?b {:b ?a}} '[[?a] [?b]] true) (tabular (fact "requires that every variable appearing in a negative literal in the body of a clause also appears in some positive literal in the body of the clause" (safe? [] ?body) => ?safe) ?body ?safe '[(not [?q])] false '[[?q] (not [?q])] true)) (facts "About rules" (let [link-path (rule [:path {:src :?src :dst :?dst}] [[:link {:src :?src :dst :?dst}]]) path-path (rule [:path {:src :?src :dst :?dst}] [[:link {:src :?src :dst :?via}] [:path {:src :?via :dst :?dst}]]) everyone-likes (rule [:everyone-likes {:name :?x}] [[:person {:name :?x}] '(not-join [?x] [:is-not-liked {:name :?x}])]) is-not-liked (rule [:is-not-liked {:name :?y}] [[:person#x {:name :?x}] [:person#y {:name :?y}] '(not-join [?x ?y] [:likes {:person :?x :likes :?y}])])] (fact "We can ennumerate the positive attrs in the head of each rule" (:head-attrs link-path) => #{:path/src :path/dst} (:head-attrs path-path) => #{:path/src :path/dst} (:head-attrs everyone-likes) => #{:everyone-likes/name} (:head-attrs is-not-liked) => #{:is-not-liked/name}) (fact "We can ennumerate the positive attrs a dule depends on" (:pos-attrs link-path) => #{:link/src :link/dst} (:pos-attrs path-path) => #{:link/src :link/dst :path/src :path/dst} (:pos-attrs everyone-likes) => #{:person/name} (:pos-attrs is-not-liked) => #{:person/name}) (facts "About safety" (:safe? link-path) => true (:safe? path-path) => true (:safe? everyone-likes) => true (:safe? is-not-liked) => true) (facts "About negation" (fact "Rules with a not are negative" (:neg? link-path) => false (:neg? path-path) => false (:neg? everyone-likes) => true (:neg? is-not-liked) => true) (fact "Negative rules have dependant attributes" (:neg-attrs link-path) => #{} (:neg-attrs path-path) => #{} (:neg-attrs everyone-likes) => #{:is-not-liked/name} (:neg-attrs is-not-liked) => #{:likes/person :likes/likes})) (facts "About dependence" (depends-on? link-path path-path) => false (depends-on? path-path link-path) => false (depends-on? is-not-liked everyone-likes) => false (depends-on? everyone-likes is-not-liked) => true) (fact "We can aquire the lvars for the entities that the rule depends on" (:dep-lvars link-path) => (just '#{?link}) (:dep-lvars path-path) => (just '#{?link ?path}) (:dep-lvars everyone-likes) => (just '#{?person}) (:dep-lvars is-not-liked) => (just '#{?personx ?persony}))))
d19f43efd0f8c598cc5c0c19ea8b853b86c2ee5899ec44b438f8211c055b2a0c
logseq/logseq
content.cljs
(ns frontend.components.content (:require [clojure.string :as string] [dommy.core :as d] [frontend.commands :as commands] [frontend.components.editor :as editor] [frontend.components.page-menu :as page-menu] [frontend.components.export :as export] [frontend.context.i18n :refer [t]] [frontend.db :as db] [frontend.extensions.srs :as srs] [frontend.handler.common :as common-handler] [frontend.handler.editor :as editor-handler] [frontend.handler.image :as image-handler] [frontend.handler.notification :as notification] [frontend.handler.page :as page-handler] [frontend.handler.common.developer :as dev-common-handler] [frontend.mixins :as mixins] [frontend.state :as state] [frontend.ui :as ui] [frontend.util :as util] [logseq.graph-parser.util :as gp-util] [logseq.graph-parser.util.block-ref :as block-ref] [frontend.util.url :as url-util] [goog.dom :as gdom] [goog.object :as gobj] [rum.core :as rum])) TODO i18n support (rum/defc custom-context-menu-content [] [:.menu-links-wrapper (ui/menu-link {:key "cut" :on-click #(editor-handler/cut-selection-blocks true)} (t :content/cut) nil) (ui/menu-link {:key "delete" :on-click #(do (editor-handler/delete-selection %) (state/hide-custom-context-menu!))} "Delete" nil) (ui/menu-link {:key "copy" :on-click editor-handler/copy-selection-blocks} (t :content/copy) nil) (ui/menu-link {:key "copy as" :on-click (fn [_] (let [block-uuids (editor-handler/get-selected-toplevel-block-uuids)] (state/set-modal! #(export/export-blocks block-uuids))))} "Copy as..." nil) (ui/menu-link {:key "copy block refs" :on-click editor-handler/copy-block-refs} "Copy block refs" nil) (ui/menu-link {:key "copy block embeds" :on-click editor-handler/copy-block-embeds} "Copy block embeds" nil) [:hr.menu-separator] (ui/menu-link {:key "cycle todos" :on-click editor-handler/cycle-todos!} "Cycle todos" nil)]) (defonce *template-including-parent? (atom nil)) (rum/defc template-checkbox [template-including-parent?] [:div.flex.flex-row.w-auto.items-center [:p.text-medium.mr-2 "Including the parent block in the template?"] (ui/toggle template-including-parent? #(swap! *template-including-parent? not))]) (rum/defcs block-template < rum/reactive (rum/local false ::edit?) (rum/local "" ::input) {:will-unmount (fn [state] (reset! *template-including-parent? nil) state)} [state block-id] (let [edit? (get state ::edit?) input (get state ::input) template-including-parent? (rum/react *template-including-parent?) block-id (if (string? block-id) (uuid block-id) block-id) block (db/entity [:block/uuid block-id]) has-children? (seq (:block/_parent block))] (when (and (nil? template-including-parent?) has-children?) (reset! *template-including-parent? true)) (if @edit? (do (state/clear-edit!) [:<> [:div.px-4.py-2.text-sm {:on-click (fn [e] (util/stop e))} [:p "What's the template's name?"] [:input#new-template.form-input.block.w-full.sm:text-sm.sm:leading-5.my-2 {:auto-focus true :on-change (fn [e] (reset! input (util/evalue e)))}] (when has-children? (template-checkbox template-including-parent?)) (ui/button "Submit" :on-click (fn [] (let [title (string/trim @input)] (when (not (string/blank? title)) (if (page-handler/template-exists? title) (notification/show! [:p "Template already exists!"] :error) (do (editor-handler/set-block-property! block-id :template title) (when (false? template-including-parent?) (editor-handler/set-block-property! block-id :template-including-parent false)) (state/hide-custom-context-menu!)))))))] [:hr.menu-separator]]) (ui/menu-link {:key "Make a Template" :on-click (fn [e] (util/stop e) (reset! edit? true))} "Make a Template" nil)))) (rum/defc ^:large-vars/cleanup-todo block-context-menu-content [_target block-id] (when-let [block (db/entity [:block/uuid block-id])] (let [format (:block/format block) heading (-> block :block/properties :heading)] [:.menu-links-wrapper [:div.flex.flex-row.justify-between.py-1.px-2.items-center [:div.flex.flex-row.justify-between.flex-1.mx-2.mt-2 (for [color ui/block-background-colors] [:a.shadow-sm {:title (t (keyword "color" color)) :on-click (fn [_e] (editor-handler/set-block-property! block-id "background-color" color))} [:div.heading-bg {:style {:background-color (str "var(--color-" color "-500)")}}]]) [:a.shadow-sm {:title (t :remove-background) :on-click (fn [_e] (editor-handler/remove-block-property! block-id "background-color"))} [:div.heading-bg.remove "-"]]]] [:div.flex.flex-row.justify-between.pb-2.pt-1.px-2.items-center [:div.flex.flex-row.justify-between.flex-1.px-1 (for [i (range 1 7)] (ui/button "" :disabled (= heading i) :icon (str "h-" i) :title (t :heading i) :class "to-heading-button" :on-click (fn [_e] (editor-handler/set-heading! block-id format i)) :intent "link" :small? true)) (ui/button "" :icon "h-auto" :disabled (= heading true) :icon-props {:extension? true} :class "to-heading-button" :title (t :auto-heading) :on-click (fn [_e] (editor-handler/set-heading! block-id format true)) :intent "link" :small? true) (ui/button "" :icon "heading-off" :disabled (not heading) :icon-props {:extension? true} :class "to-heading-button" :title (t :remove-heading) :on-click (fn [_e] (editor-handler/remove-heading! block-id format)) :intent "link" :small? true)]] [:hr.menu-separator] (ui/menu-link {:key "Open in sidebar" :on-click (fn [_e] (editor-handler/open-block-in-sidebar! block-id))} (t :content/open-in-sidebar) ["⇧" "click"]) [:hr.menu-separator] (ui/menu-link {:key "Copy block ref" :on-click (fn [_e] (editor-handler/copy-block-ref! block-id block-ref/->block-ref))} (t :content/copy-block-ref) nil) (ui/menu-link {:key "Copy block embed" :on-click (fn [_e] (editor-handler/copy-block-ref! block-id #(util/format "{{embed ((%s))}}" %)))} (t :content/copy-block-emebed) nil) ;; TODO Logseq protocol mobile support (when (util/electron?) (ui/menu-link {:key "Copy block URL" :on-click (fn [_e] (let [current-repo (state/get-current-repo) tap-f (fn [block-id] (url-util/get-logseq-graph-uuid-url nil current-repo block-id))] (editor-handler/copy-block-ref! block-id tap-f)))} "Copy block URL" nil)) (ui/menu-link {:key "Copy as" :on-click (fn [_] (state/set-modal! #(export/export-blocks [block-id])))} "Copy as..." nil) (ui/menu-link {:key "Cut" :on-click (fn [_e] (editor-handler/cut-block! block-id))} (t :content/cut) nil) (ui/menu-link {:key "delete" :on-click #(editor-handler/delete-block-aux! block true)} "Delete" nil) [:hr.menu-separator] (block-template block-id) (cond (srs/card-block? block) (ui/menu-link {:key "Preview Card" :on-click #(srs/preview (:db/id block))} "Preview Card" nil) (state/enable-flashcards?) (ui/menu-link {:key "Make a Card" :on-click #(srs/make-block-a-card! block-id)} "Make a Flashcard" nil) :else nil) [:hr.menu-separator] (ui/menu-link {:key "Expand all" :on-click (fn [_e] (editor-handler/expand-all! block-id))} "Expand all" nil) (ui/menu-link {:key "Collapse all" :on-click (fn [_e] (editor-handler/collapse-all! block-id {}))} "Collapse all" nil) (when (state/sub [:plugin/simple-commands]) (when-let [cmds (state/get-plugins-commands-with-type :block-context-menu-item)] (for [[_ {:keys [key label] :as cmd} action pid] cmds] (ui/menu-link {:key key :on-click #(commands/exec-plugin-simple-command! pid (assoc cmd :uuid block-id) action)} label nil)))) (when (state/sub [:ui/developer-mode?]) (ui/menu-link {:key "(Dev) Show block data" :on-click (fn [] (dev-common-handler/show-entity-data [:block/uuid block-id]))} "(Dev) Show block data" nil)) (when (state/sub [:ui/developer-mode?]) (ui/menu-link {:key "(Dev) Show block AST" :on-click (fn [] (let [block (db/pull [:block/uuid block-id])] (dev-common-handler/show-content-ast (:block/content block) (:block/format block))))} "(Dev) Show block AST" nil))]))) (rum/defc block-ref-custom-context-menu-content [block block-ref-id] (when (and block block-ref-id) [:.menu-links-wrapper (ui/menu-link {:key "open-in-sidebar" :on-click (fn [] (state/sidebar-add-block! (state/get-current-repo) block-ref-id :block-ref))} "Open in sidebar" ["⇧" "click"]) (ui/menu-link {:key "copy" :on-click (fn [] (editor-handler/copy-current-ref block-ref-id))} "Copy this reference" nil) (ui/menu-link {:key "delete" :on-click (fn [] (editor-handler/delete-current-ref! block block-ref-id))} "Delete this reference" nil) (ui/menu-link {:key "replace-with-text" :on-click (fn [] (editor-handler/replace-ref-with-text! block block-ref-id))} "Replace with text" nil) (ui/menu-link {:key "replace-with-embed" :on-click (fn [] (editor-handler/replace-ref-with-embed! block block-ref-id))} "Replace with embed" nil)])) (rum/defc page-title-custom-context-menu-content [page] (when-not (string/blank? page) (let [page-menu-options (page-menu/page-menu page)] [:.menu-links-wrapper (for [{:keys [title options]} page-menu-options] (rum/with-key (ui/menu-link options title nil) title))]))) ;; TODO: content could be changed ;; Also, keyboard bindings should only be activated after ;; blocks were already selected. (rum/defc hiccup-content < rum/static (mixins/event-mixin (fn [state] ;; fixme: this mixin will register global event listeners on window ;; which might cause unexpected issues (mixins/listen state js/window "contextmenu" (fn [e] (let [target (gobj/get e "target") block-id (d/attr target "blockid") {:keys [block block-ref]} (state/sub :block-ref/context) {:keys [page]} (state/sub :page-title/context)] (cond page (do (common-handler/show-custom-context-menu! e (page-title-custom-context-menu-content page)) (state/set-state! :page-title/context nil)) block-ref (do (common-handler/show-custom-context-menu! e (block-ref-custom-context-menu-content block block-ref)) (state/set-state! :block-ref/context nil)) (and (state/selection?) (not (d/has-class? target "bullet"))) (common-handler/show-custom-context-menu! e (custom-context-menu-content)) (and block-id (parse-uuid block-id)) (let [block (.closest target ".ls-block")] (when block (util/select-highlight! [block])) (common-handler/show-custom-context-menu! e (block-context-menu-content target (uuid block-id)))) :else nil)))))) [id {:keys [hiccup]}] [:div {:id id} (if hiccup hiccup [:div.cursor (t :content/click-to-edit)])]) (rum/defc non-hiccup-content < rum/reactive [id content on-click on-hide config format] (let [edit? (state/sub [:editor/editing? id])] (if edit? (editor/box {:on-hide on-hide :format format} id config) (let [on-click (fn [e] (when-not (util/link? (gobj/get e "target")) (util/stop e) (editor-handler/reset-cursor-range! (gdom/getElement (str id))) (state/set-edit-content! id content) (state/set-edit-input-id! id) (when on-click (on-click e))))] [:pre.cursor.content.pre-white-space {:id id :on-click on-click} (if (string/blank? content) [:div.cursor (t :content/click-to-edit)] content)])))) (defn- set-draw-iframe-style! [] (let [width (gobj/get js/window "innerWidth")] (when (>= width 1024) (let [draws (d/by-class "draw-iframe") width (- width 200)] (doseq [draw draws] (d/set-style! draw :width (str width "px")) (let [height (max 700 (/ width 2))] (d/set-style! draw :height (str height "px"))) (d/set-style! draw :margin-left (str (- (/ (- width 570) 2)) "px"))))))) (rum/defcs content < rum/reactive {:did-mount (fn [state] (set-draw-iframe-style!) (image-handler/render-local-images!) state) :did-update (fn [state] (set-draw-iframe-style!) (image-handler/render-local-images!) state)} [state id {:keys [format config hiccup content on-click on-hide] :as option}] (if hiccup [:div (hiccup-content id option)] (let [format (gp-util/normalize-format format)] (non-hiccup-content id content on-click on-hide config format))))
null
https://raw.githubusercontent.com/logseq/logseq/2cace8894c5ee725cefd9796f39b900910f55757/src/main/frontend/components/content.cljs
clojure
TODO Logseq protocol mobile support TODO: content could be changed Also, keyboard bindings should only be activated after blocks were already selected. fixme: this mixin will register global event listeners on window which might cause unexpected issues
(ns frontend.components.content (:require [clojure.string :as string] [dommy.core :as d] [frontend.commands :as commands] [frontend.components.editor :as editor] [frontend.components.page-menu :as page-menu] [frontend.components.export :as export] [frontend.context.i18n :refer [t]] [frontend.db :as db] [frontend.extensions.srs :as srs] [frontend.handler.common :as common-handler] [frontend.handler.editor :as editor-handler] [frontend.handler.image :as image-handler] [frontend.handler.notification :as notification] [frontend.handler.page :as page-handler] [frontend.handler.common.developer :as dev-common-handler] [frontend.mixins :as mixins] [frontend.state :as state] [frontend.ui :as ui] [frontend.util :as util] [logseq.graph-parser.util :as gp-util] [logseq.graph-parser.util.block-ref :as block-ref] [frontend.util.url :as url-util] [goog.dom :as gdom] [goog.object :as gobj] [rum.core :as rum])) TODO i18n support (rum/defc custom-context-menu-content [] [:.menu-links-wrapper (ui/menu-link {:key "cut" :on-click #(editor-handler/cut-selection-blocks true)} (t :content/cut) nil) (ui/menu-link {:key "delete" :on-click #(do (editor-handler/delete-selection %) (state/hide-custom-context-menu!))} "Delete" nil) (ui/menu-link {:key "copy" :on-click editor-handler/copy-selection-blocks} (t :content/copy) nil) (ui/menu-link {:key "copy as" :on-click (fn [_] (let [block-uuids (editor-handler/get-selected-toplevel-block-uuids)] (state/set-modal! #(export/export-blocks block-uuids))))} "Copy as..." nil) (ui/menu-link {:key "copy block refs" :on-click editor-handler/copy-block-refs} "Copy block refs" nil) (ui/menu-link {:key "copy block embeds" :on-click editor-handler/copy-block-embeds} "Copy block embeds" nil) [:hr.menu-separator] (ui/menu-link {:key "cycle todos" :on-click editor-handler/cycle-todos!} "Cycle todos" nil)]) (defonce *template-including-parent? (atom nil)) (rum/defc template-checkbox [template-including-parent?] [:div.flex.flex-row.w-auto.items-center [:p.text-medium.mr-2 "Including the parent block in the template?"] (ui/toggle template-including-parent? #(swap! *template-including-parent? not))]) (rum/defcs block-template < rum/reactive (rum/local false ::edit?) (rum/local "" ::input) {:will-unmount (fn [state] (reset! *template-including-parent? nil) state)} [state block-id] (let [edit? (get state ::edit?) input (get state ::input) template-including-parent? (rum/react *template-including-parent?) block-id (if (string? block-id) (uuid block-id) block-id) block (db/entity [:block/uuid block-id]) has-children? (seq (:block/_parent block))] (when (and (nil? template-including-parent?) has-children?) (reset! *template-including-parent? true)) (if @edit? (do (state/clear-edit!) [:<> [:div.px-4.py-2.text-sm {:on-click (fn [e] (util/stop e))} [:p "What's the template's name?"] [:input#new-template.form-input.block.w-full.sm:text-sm.sm:leading-5.my-2 {:auto-focus true :on-change (fn [e] (reset! input (util/evalue e)))}] (when has-children? (template-checkbox template-including-parent?)) (ui/button "Submit" :on-click (fn [] (let [title (string/trim @input)] (when (not (string/blank? title)) (if (page-handler/template-exists? title) (notification/show! [:p "Template already exists!"] :error) (do (editor-handler/set-block-property! block-id :template title) (when (false? template-including-parent?) (editor-handler/set-block-property! block-id :template-including-parent false)) (state/hide-custom-context-menu!)))))))] [:hr.menu-separator]]) (ui/menu-link {:key "Make a Template" :on-click (fn [e] (util/stop e) (reset! edit? true))} "Make a Template" nil)))) (rum/defc ^:large-vars/cleanup-todo block-context-menu-content [_target block-id] (when-let [block (db/entity [:block/uuid block-id])] (let [format (:block/format block) heading (-> block :block/properties :heading)] [:.menu-links-wrapper [:div.flex.flex-row.justify-between.py-1.px-2.items-center [:div.flex.flex-row.justify-between.flex-1.mx-2.mt-2 (for [color ui/block-background-colors] [:a.shadow-sm {:title (t (keyword "color" color)) :on-click (fn [_e] (editor-handler/set-block-property! block-id "background-color" color))} [:div.heading-bg {:style {:background-color (str "var(--color-" color "-500)")}}]]) [:a.shadow-sm {:title (t :remove-background) :on-click (fn [_e] (editor-handler/remove-block-property! block-id "background-color"))} [:div.heading-bg.remove "-"]]]] [:div.flex.flex-row.justify-between.pb-2.pt-1.px-2.items-center [:div.flex.flex-row.justify-between.flex-1.px-1 (for [i (range 1 7)] (ui/button "" :disabled (= heading i) :icon (str "h-" i) :title (t :heading i) :class "to-heading-button" :on-click (fn [_e] (editor-handler/set-heading! block-id format i)) :intent "link" :small? true)) (ui/button "" :icon "h-auto" :disabled (= heading true) :icon-props {:extension? true} :class "to-heading-button" :title (t :auto-heading) :on-click (fn [_e] (editor-handler/set-heading! block-id format true)) :intent "link" :small? true) (ui/button "" :icon "heading-off" :disabled (not heading) :icon-props {:extension? true} :class "to-heading-button" :title (t :remove-heading) :on-click (fn [_e] (editor-handler/remove-heading! block-id format)) :intent "link" :small? true)]] [:hr.menu-separator] (ui/menu-link {:key "Open in sidebar" :on-click (fn [_e] (editor-handler/open-block-in-sidebar! block-id))} (t :content/open-in-sidebar) ["⇧" "click"]) [:hr.menu-separator] (ui/menu-link {:key "Copy block ref" :on-click (fn [_e] (editor-handler/copy-block-ref! block-id block-ref/->block-ref))} (t :content/copy-block-ref) nil) (ui/menu-link {:key "Copy block embed" :on-click (fn [_e] (editor-handler/copy-block-ref! block-id #(util/format "{{embed ((%s))}}" %)))} (t :content/copy-block-emebed) nil) (when (util/electron?) (ui/menu-link {:key "Copy block URL" :on-click (fn [_e] (let [current-repo (state/get-current-repo) tap-f (fn [block-id] (url-util/get-logseq-graph-uuid-url nil current-repo block-id))] (editor-handler/copy-block-ref! block-id tap-f)))} "Copy block URL" nil)) (ui/menu-link {:key "Copy as" :on-click (fn [_] (state/set-modal! #(export/export-blocks [block-id])))} "Copy as..." nil) (ui/menu-link {:key "Cut" :on-click (fn [_e] (editor-handler/cut-block! block-id))} (t :content/cut) nil) (ui/menu-link {:key "delete" :on-click #(editor-handler/delete-block-aux! block true)} "Delete" nil) [:hr.menu-separator] (block-template block-id) (cond (srs/card-block? block) (ui/menu-link {:key "Preview Card" :on-click #(srs/preview (:db/id block))} "Preview Card" nil) (state/enable-flashcards?) (ui/menu-link {:key "Make a Card" :on-click #(srs/make-block-a-card! block-id)} "Make a Flashcard" nil) :else nil) [:hr.menu-separator] (ui/menu-link {:key "Expand all" :on-click (fn [_e] (editor-handler/expand-all! block-id))} "Expand all" nil) (ui/menu-link {:key "Collapse all" :on-click (fn [_e] (editor-handler/collapse-all! block-id {}))} "Collapse all" nil) (when (state/sub [:plugin/simple-commands]) (when-let [cmds (state/get-plugins-commands-with-type :block-context-menu-item)] (for [[_ {:keys [key label] :as cmd} action pid] cmds] (ui/menu-link {:key key :on-click #(commands/exec-plugin-simple-command! pid (assoc cmd :uuid block-id) action)} label nil)))) (when (state/sub [:ui/developer-mode?]) (ui/menu-link {:key "(Dev) Show block data" :on-click (fn [] (dev-common-handler/show-entity-data [:block/uuid block-id]))} "(Dev) Show block data" nil)) (when (state/sub [:ui/developer-mode?]) (ui/menu-link {:key "(Dev) Show block AST" :on-click (fn [] (let [block (db/pull [:block/uuid block-id])] (dev-common-handler/show-content-ast (:block/content block) (:block/format block))))} "(Dev) Show block AST" nil))]))) (rum/defc block-ref-custom-context-menu-content [block block-ref-id] (when (and block block-ref-id) [:.menu-links-wrapper (ui/menu-link {:key "open-in-sidebar" :on-click (fn [] (state/sidebar-add-block! (state/get-current-repo) block-ref-id :block-ref))} "Open in sidebar" ["⇧" "click"]) (ui/menu-link {:key "copy" :on-click (fn [] (editor-handler/copy-current-ref block-ref-id))} "Copy this reference" nil) (ui/menu-link {:key "delete" :on-click (fn [] (editor-handler/delete-current-ref! block block-ref-id))} "Delete this reference" nil) (ui/menu-link {:key "replace-with-text" :on-click (fn [] (editor-handler/replace-ref-with-text! block block-ref-id))} "Replace with text" nil) (ui/menu-link {:key "replace-with-embed" :on-click (fn [] (editor-handler/replace-ref-with-embed! block block-ref-id))} "Replace with embed" nil)])) (rum/defc page-title-custom-context-menu-content [page] (when-not (string/blank? page) (let [page-menu-options (page-menu/page-menu page)] [:.menu-links-wrapper (for [{:keys [title options]} page-menu-options] (rum/with-key (ui/menu-link options title nil) title))]))) (rum/defc hiccup-content < rum/static (mixins/event-mixin (fn [state] (mixins/listen state js/window "contextmenu" (fn [e] (let [target (gobj/get e "target") block-id (d/attr target "blockid") {:keys [block block-ref]} (state/sub :block-ref/context) {:keys [page]} (state/sub :page-title/context)] (cond page (do (common-handler/show-custom-context-menu! e (page-title-custom-context-menu-content page)) (state/set-state! :page-title/context nil)) block-ref (do (common-handler/show-custom-context-menu! e (block-ref-custom-context-menu-content block block-ref)) (state/set-state! :block-ref/context nil)) (and (state/selection?) (not (d/has-class? target "bullet"))) (common-handler/show-custom-context-menu! e (custom-context-menu-content)) (and block-id (parse-uuid block-id)) (let [block (.closest target ".ls-block")] (when block (util/select-highlight! [block])) (common-handler/show-custom-context-menu! e (block-context-menu-content target (uuid block-id)))) :else nil)))))) [id {:keys [hiccup]}] [:div {:id id} (if hiccup hiccup [:div.cursor (t :content/click-to-edit)])]) (rum/defc non-hiccup-content < rum/reactive [id content on-click on-hide config format] (let [edit? (state/sub [:editor/editing? id])] (if edit? (editor/box {:on-hide on-hide :format format} id config) (let [on-click (fn [e] (when-not (util/link? (gobj/get e "target")) (util/stop e) (editor-handler/reset-cursor-range! (gdom/getElement (str id))) (state/set-edit-content! id content) (state/set-edit-input-id! id) (when on-click (on-click e))))] [:pre.cursor.content.pre-white-space {:id id :on-click on-click} (if (string/blank? content) [:div.cursor (t :content/click-to-edit)] content)])))) (defn- set-draw-iframe-style! [] (let [width (gobj/get js/window "innerWidth")] (when (>= width 1024) (let [draws (d/by-class "draw-iframe") width (- width 200)] (doseq [draw draws] (d/set-style! draw :width (str width "px")) (let [height (max 700 (/ width 2))] (d/set-style! draw :height (str height "px"))) (d/set-style! draw :margin-left (str (- (/ (- width 570) 2)) "px"))))))) (rum/defcs content < rum/reactive {:did-mount (fn [state] (set-draw-iframe-style!) (image-handler/render-local-images!) state) :did-update (fn [state] (set-draw-iframe-style!) (image-handler/render-local-images!) state)} [state id {:keys [format config hiccup content on-click on-hide] :as option}] (if hiccup [:div (hiccup-content id option)] (let [format (gp-util/normalize-format format)] (non-hiccup-content id content on-click on-hide config format))))
789877f30e7e348dc8ace79f52aee9efcb0aa373431a202358cc5b53458ee475
craigl64/clim-ccl
cloe-applications.lisp
-*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Package : CLIM - INTERNALS ; Base : 10 ; Lowercase : Yes -*- (in-package :clim-internals) "Copyright (c) 1990, 1991, 1992 Symbolics, Inc. All rights reserved." (defun run-cloe-application (name) (win::start-windows) (unwind-protect (progn (win::show-window (win::get-term-window) :type :minimize) (run-frame-top-level (make-application-frame name :parent (open-root-window :cloe)))) (win::stop-windows))) (defun cloe-debugger-hook (condition hook) (declare (ignore hook)) (let ((term (win::get-term-window))) (win::show-window term :type :show-normal) (unwind-protect (invoke-debugger condition) (when (frame-top-level-sheet *application-frame*) (win::show-window term :type :minimize)))))
null
https://raw.githubusercontent.com/craigl64/clim-ccl/301efbd770745b429f2b00b4e8ca6624de9d9ea9/pre-silica/cloe-applications.lisp
lisp
Syntax : ANSI - Common - Lisp ; Package : CLIM - INTERNALS ; Base : 10 ; Lowercase : Yes -*-
(in-package :clim-internals) "Copyright (c) 1990, 1991, 1992 Symbolics, Inc. All rights reserved." (defun run-cloe-application (name) (win::start-windows) (unwind-protect (progn (win::show-window (win::get-term-window) :type :minimize) (run-frame-top-level (make-application-frame name :parent (open-root-window :cloe)))) (win::stop-windows))) (defun cloe-debugger-hook (condition hook) (declare (ignore hook)) (let ((term (win::get-term-window))) (win::show-window term :type :show-normal) (unwind-protect (invoke-debugger condition) (when (frame-top-level-sheet *application-frame*) (win::show-window term :type :minimize)))))
c63609a473153da9d94b9affa4b45c667dac0d46a9d17706e74a194df9e6fc08
exercism/babashka
luhn_test.clj
(ns luhn-test (:require [clojure.test :refer [deftest is testing]] luhn)) (deftest single-digit-strings (is (false? (luhn/valid? "1")))) (deftest single-zero (is (false? (luhn/valid? "0")))) (deftest sin (is (true? (luhn/valid? " 5 9 ")))) (deftest Canadian-SIN (is (true? (luhn/valid? "046 454 286")))) (deftest invalid-Canadian-SIN (is (false? (luhn/valid? "046 454 287")))) (deftest invalid-credit-card (is (false? (luhn/valid? "8273 1232 7352 0569")))) (deftest non-digit-added (is (false? (luhn/valid? "046a 454 286")))) (deftest punctuation (is (false? (luhn/valid? "055-444-285")))) (deftest symbols (is (false? (luhn/valid? "055£ 444$ 285")))) (deftest single-zero-with-space (is (false? (luhn/valid? " 0")))) (deftest lots-of-zeros (is (true? (luhn/valid? " 00000")))) (deftest another-valid-sin (is (true? (luhn/valid? "055 444 285")))) (deftest nine-doubled (is (true? (luhn/valid? "091"))))
null
https://raw.githubusercontent.com/exercism/babashka/707356c52e08490e66cb1b2e63e4f4439d91cf08/exercises/practice/luhn/test/luhn_test.clj
clojure
(ns luhn-test (:require [clojure.test :refer [deftest is testing]] luhn)) (deftest single-digit-strings (is (false? (luhn/valid? "1")))) (deftest single-zero (is (false? (luhn/valid? "0")))) (deftest sin (is (true? (luhn/valid? " 5 9 ")))) (deftest Canadian-SIN (is (true? (luhn/valid? "046 454 286")))) (deftest invalid-Canadian-SIN (is (false? (luhn/valid? "046 454 287")))) (deftest invalid-credit-card (is (false? (luhn/valid? "8273 1232 7352 0569")))) (deftest non-digit-added (is (false? (luhn/valid? "046a 454 286")))) (deftest punctuation (is (false? (luhn/valid? "055-444-285")))) (deftest symbols (is (false? (luhn/valid? "055£ 444$ 285")))) (deftest single-zero-with-space (is (false? (luhn/valid? " 0")))) (deftest lots-of-zeros (is (true? (luhn/valid? " 00000")))) (deftest another-valid-sin (is (true? (luhn/valid? "055 444 285")))) (deftest nine-doubled (is (true? (luhn/valid? "091"))))
9ed5b4e890ba696e27dd832e97e6da912ed5e19a5406a1465c52a63e062136af
aviaviavi/toodles
Types.hs
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} # LANGUAGE GeneralizedNewtypeDeriving # {-# LANGUAGE OverloadedStrings #-} module Types where import License import Data.Aeson (FromJSON, ToJSON, Value (String), parseJSON, toJSON) import Data.Aeson.Types (typeMismatch) import Data.Data import Data.IORef (IORef) import Data.String (IsString) import Data.Text (Text) import qualified Data.Text as T (unpack) import GHC.Generics (Generic) data SourceFile = SourceFile { fullPath :: FilePath , sourceLines :: [Text] } deriving (Show) type LineNumber = Integer data ToodlesState = ToodlesState { results :: IORef (Maybe TodoListResult), dataPath :: FilePath, userTier :: IORef UserTier } data CommentType = SingleLine | MultiLine deriving (Show, Eq, Generic) instance ToJSON CommentType data TodoEntry = TodoEntryHead { entryId :: Integer , body :: [Text] , assignee :: Maybe Text , sourceFile :: FilePath , lineNumber :: LineNumber , priority :: Maybe Integer , flag :: Flag , customAttributes :: [(Text, Text)] , tags :: [Text] , leadingText :: Text , commentType :: CommentType , entryHeadOpened :: Bool , entryHeadClosed :: Bool } | TodoBodyLine Text -- the body Bool -- has opening tag Bool -- has closing tag | TodoBodyLineCombined [Text] -- the body Bool -- has opening tag Bool -- has closing tag deriving (Show, Generic) instance ToJSON TodoEntry data TodoListResult = TodoListResult { todos :: [TodoEntry] , limited :: Bool } deriving (Show, Generic) instance ToJSON TodoListResult newtype DeleteTodoRequest = DeleteTodoRequest { ids :: [Integer] } deriving (Show, Generic) instance FromJSON DeleteTodoRequest data EditTodoRequest = EditTodoRequest { editIds :: [Integer] , setAssignee :: Maybe Text , addTags :: [Text] , addKeyVals :: [(Text, Text)] , setPriority :: Maybe Integer } deriving (Show, Generic) instance FromJSON EditTodoRequest data GetLicenseResponse = GetLicenseResponse { toodlesTier:: UserTier } deriving (Show, Generic) instance ToJSON GetLicenseResponse data Flag = TODO | FIXME | XXX | UF UserFlag deriving (Generic) newtype UserFlag = UserFlag Text deriving (Show, Eq, IsString, Data, Generic) instance Show Flag where show TODO = "TODO" show FIXME = "FIXME" show XXX = "XXX" show (UF (UserFlag x)) = T.unpack x instance ToJSON Flag where toJSON TODO = Data.Aeson.String "TODO" toJSON FIXME = Data.Aeson.String "FIXME" toJSON XXX = Data.Aeson.String "XXX" toJSON (UF (UserFlag x)) = Data.Aeson.String x instance FromJSON Flag where parseJSON (Data.Aeson.String x) = case x of "TODO" -> pure TODO "FIXME" -> pure FIXME "XXX" -> pure XXX _ -> pure $ UF $ UserFlag x parseJSON invalid = typeMismatch "UserFlag" invalid instance ToJSON UserFlag where toJSON (UserFlag x) = Data.Aeson.String x instance FromJSON UserFlag where parseJSON (Data.Aeson.String x) = pure $ UserFlag x parseJSON invalid = typeMismatch "UserFlag" invalid
null
https://raw.githubusercontent.com/aviaviavi/toodles/cc614616aef18e335f8d920d62371ba2a882d383/src/Types.hs
haskell
# LANGUAGE DeriveDataTypeable # # LANGUAGE DeriveGeneric # # LANGUAGE OverloadedStrings # the body has opening tag has closing tag the body has opening tag has closing tag
# LANGUAGE GeneralizedNewtypeDeriving # module Types where import License import Data.Aeson (FromJSON, ToJSON, Value (String), parseJSON, toJSON) import Data.Aeson.Types (typeMismatch) import Data.Data import Data.IORef (IORef) import Data.String (IsString) import Data.Text (Text) import qualified Data.Text as T (unpack) import GHC.Generics (Generic) data SourceFile = SourceFile { fullPath :: FilePath , sourceLines :: [Text] } deriving (Show) type LineNumber = Integer data ToodlesState = ToodlesState { results :: IORef (Maybe TodoListResult), dataPath :: FilePath, userTier :: IORef UserTier } data CommentType = SingleLine | MultiLine deriving (Show, Eq, Generic) instance ToJSON CommentType data TodoEntry = TodoEntryHead { entryId :: Integer , body :: [Text] , assignee :: Maybe Text , sourceFile :: FilePath , lineNumber :: LineNumber , priority :: Maybe Integer , flag :: Flag , customAttributes :: [(Text, Text)] , tags :: [Text] , leadingText :: Text , commentType :: CommentType , entryHeadOpened :: Bool , entryHeadClosed :: Bool } | TodoBodyLine | TodoBodyLineCombined deriving (Show, Generic) instance ToJSON TodoEntry data TodoListResult = TodoListResult { todos :: [TodoEntry] , limited :: Bool } deriving (Show, Generic) instance ToJSON TodoListResult newtype DeleteTodoRequest = DeleteTodoRequest { ids :: [Integer] } deriving (Show, Generic) instance FromJSON DeleteTodoRequest data EditTodoRequest = EditTodoRequest { editIds :: [Integer] , setAssignee :: Maybe Text , addTags :: [Text] , addKeyVals :: [(Text, Text)] , setPriority :: Maybe Integer } deriving (Show, Generic) instance FromJSON EditTodoRequest data GetLicenseResponse = GetLicenseResponse { toodlesTier:: UserTier } deriving (Show, Generic) instance ToJSON GetLicenseResponse data Flag = TODO | FIXME | XXX | UF UserFlag deriving (Generic) newtype UserFlag = UserFlag Text deriving (Show, Eq, IsString, Data, Generic) instance Show Flag where show TODO = "TODO" show FIXME = "FIXME" show XXX = "XXX" show (UF (UserFlag x)) = T.unpack x instance ToJSON Flag where toJSON TODO = Data.Aeson.String "TODO" toJSON FIXME = Data.Aeson.String "FIXME" toJSON XXX = Data.Aeson.String "XXX" toJSON (UF (UserFlag x)) = Data.Aeson.String x instance FromJSON Flag where parseJSON (Data.Aeson.String x) = case x of "TODO" -> pure TODO "FIXME" -> pure FIXME "XXX" -> pure XXX _ -> pure $ UF $ UserFlag x parseJSON invalid = typeMismatch "UserFlag" invalid instance ToJSON UserFlag where toJSON (UserFlag x) = Data.Aeson.String x instance FromJSON UserFlag where parseJSON (Data.Aeson.String x) = pure $ UserFlag x parseJSON invalid = typeMismatch "UserFlag" invalid
90d08467d0757471d142c156c4f17903388c1e6683b4de8acddeafb440208a26
sigxcpu76/transcode-server
start_app.erl
-module(start_app). -include("commons.hrl"). -export([start/0]). start() -> application:load(?APP_NAME), application:start(?APP_NAME).
null
https://raw.githubusercontent.com/sigxcpu76/transcode-server/8b5e5bd9c672ab22486c9853d8e6ec749745ec12/src/start_app.erl
erlang
-module(start_app). -include("commons.hrl"). -export([start/0]). start() -> application:load(?APP_NAME), application:start(?APP_NAME).
b3057d0624fd86efde37e624a3d87b4097a6737b5e9e4a846161778971d9c9f3
ocurrent/ocaml-multicore-ci
backend_solver.mli
type t val create : ?solver_dir:string -> Uri.t option -> t val local : ?solver_dir:string -> unit -> t val local_ci : t -> Ocaml_multicore_ci_api.Solver.t Lwt.t val solve : t -> Current.Job.t -> Ocaml_multicore_ci_api.Worker.Solve_request.t -> log:Ocaml_multicore_ci_api.Raw.Solve.Builder.Log.t Capnp_rpc_lwt.Capability.t -> Ocaml_multicore_ci_api.Worker.Solve_response.t Lwt.t
null
https://raw.githubusercontent.com/ocurrent/ocaml-multicore-ci/d46eecaf7269283a4b95ee40d2a9d6c7ec34a7bf/lib/backend_solver.mli
ocaml
type t val create : ?solver_dir:string -> Uri.t option -> t val local : ?solver_dir:string -> unit -> t val local_ci : t -> Ocaml_multicore_ci_api.Solver.t Lwt.t val solve : t -> Current.Job.t -> Ocaml_multicore_ci_api.Worker.Solve_request.t -> log:Ocaml_multicore_ci_api.Raw.Solve.Builder.Log.t Capnp_rpc_lwt.Capability.t -> Ocaml_multicore_ci_api.Worker.Solve_response.t Lwt.t
390da7477b040d43ea0de1938cbba10a8fbd1900bf06326686bd306a2979c4f8
backtracking/mlpost
myocamlbuild.ml
open Ocamlbuild_plugin open Command -- no longer needed for OCaml > = 3.10.2 (* these functions are not really officially exported *) let run_and_read = Ocamlbuild_pack.My_unix.run_and_read let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings let split s ch = let x = ref [] in let rec go s = let pos = String.index s ch in x := String.before s pos :: !x; go (String.after s (pos + 1)) in try go s with Not_found -> !x let split_nl s = split s '\n' let before_space s = try String.before s (String.index s ' ') with Not_found -> s (* this lists all supported packages *) let find_packages () = List.map before_space (split_nl & run_and_read "ocamlfind list") (* this is supposed to list available syntaxes, but I don't know how to do it. *) let find_syntaxes () = [ "camlp4o"; "camlp4r" ] (* ocamlfind command *) let ocamlfind x = S [ A "ocamlfind"; x ] let _ = dispatch (function | Before_options -> (* by using Before_options one let command line options have an higher priority *) (* on the contrary using After_options will guarantee to have the higher priority *) (* override default commands by ocamlfind ones *) Options.ocamlc := ocamlfind & A "ocamlc"; Options.ocamlopt := ocamlfind & A "ocamlopt"; Options.ocamldep := ocamlfind & A "ocamldep"; Options.ocamldoc := ocamlfind & A "ocamldoc"; Options.ocamlmktop := ocamlfind & A "ocamlmktop" | After_rules -> When one link an OCaml library / binary / package , one should use -linkpkg flag [ "ocaml"; "link" ] & A "-linkpkg"; For each ocamlfind package one inject the -package option when * compiling , computing dependencies , generating documentation and * linking . * compiling, computing dependencies, generating documentation and * linking. *) List.iter (fun pkg -> flag [ "ocaml"; "compile"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]; flag [ "ocaml"; "ocamldep"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]; flag [ "ocaml"; "doc"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]; flag [ "ocaml"; "link"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]; flag [ "ocaml"; "infer_interface"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]) (find_packages ()); Like -package but for extensions syntax . -syntax is useless * when linking . * when linking. *) List.iter (fun syntax -> flag [ "ocaml"; "compile"; "syntax_" ^ syntax ] & S [ A "-syntax"; A syntax ]; flag [ "ocaml"; "ocamldep"; "syntax_" ^ syntax ] & S [ A "-syntax"; A syntax ]; flag [ "ocaml"; "doc"; "syntax_" ^ syntax ] & S [ A "-syntax"; A syntax ]; flag [ "ocaml"; "infer_interface"; "syntax_" ^ syntax ] & S [ A "-syntax"; A syntax ]) (find_syntaxes ()); The default " thread " tag is not compatible with ocamlfind . Indeed , the default rules add the " threads.cma " or " threads.cmxa " options when using this tag . When using the " -linkpkg " option with ocamlfind , this module will then be added twice on the command line . To solve this , one approach is to add the " -thread " option when using the " threads " package using the previous plugin . Indeed, the default rules add the "threads.cma" or "threads.cmxa" options when using this tag. When using the "-linkpkg" option with ocamlfind, this module will then be added twice on the command line. To solve this, one approach is to add the "-thread" option when using the "threads" package using the previous plugin. *) flag [ "ocaml"; "pkg_threads"; "compile" ] (S [ A "-thread" ]); flag [ "ocaml"; "pkg_threads"; "link" ] (S [ A "-thread" ]); flag [ "ocaml"; "pkg_threads"; "infer_interface" ] (S [ A "-thread" ]) | _ -> ())
null
https://raw.githubusercontent.com/backtracking/mlpost/bd4305289fd64d531b9f42d64dd641d72ab82fd5/examples/myocamlbuild.ml
ocaml
these functions are not really officially exported this lists all supported packages this is supposed to list available syntaxes, but I don't know how to do it. ocamlfind command by using Before_options one let command line options have an higher priority on the contrary using After_options will guarantee to have the higher priority override default commands by ocamlfind ones
open Ocamlbuild_plugin open Command -- no longer needed for OCaml > = 3.10.2 let run_and_read = Ocamlbuild_pack.My_unix.run_and_read let blank_sep_strings = Ocamlbuild_pack.Lexers.blank_sep_strings let split s ch = let x = ref [] in let rec go s = let pos = String.index s ch in x := String.before s pos :: !x; go (String.after s (pos + 1)) in try go s with Not_found -> !x let split_nl s = split s '\n' let before_space s = try String.before s (String.index s ' ') with Not_found -> s let find_packages () = List.map before_space (split_nl & run_and_read "ocamlfind list") let find_syntaxes () = [ "camlp4o"; "camlp4r" ] let ocamlfind x = S [ A "ocamlfind"; x ] let _ = dispatch (function | Before_options -> Options.ocamlc := ocamlfind & A "ocamlc"; Options.ocamlopt := ocamlfind & A "ocamlopt"; Options.ocamldep := ocamlfind & A "ocamldep"; Options.ocamldoc := ocamlfind & A "ocamldoc"; Options.ocamlmktop := ocamlfind & A "ocamlmktop" | After_rules -> When one link an OCaml library / binary / package , one should use -linkpkg flag [ "ocaml"; "link" ] & A "-linkpkg"; For each ocamlfind package one inject the -package option when * compiling , computing dependencies , generating documentation and * linking . * compiling, computing dependencies, generating documentation and * linking. *) List.iter (fun pkg -> flag [ "ocaml"; "compile"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]; flag [ "ocaml"; "ocamldep"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]; flag [ "ocaml"; "doc"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]; flag [ "ocaml"; "link"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]; flag [ "ocaml"; "infer_interface"; "pkg_" ^ pkg ] & S [ A "-package"; A pkg ]) (find_packages ()); Like -package but for extensions syntax . -syntax is useless * when linking . * when linking. *) List.iter (fun syntax -> flag [ "ocaml"; "compile"; "syntax_" ^ syntax ] & S [ A "-syntax"; A syntax ]; flag [ "ocaml"; "ocamldep"; "syntax_" ^ syntax ] & S [ A "-syntax"; A syntax ]; flag [ "ocaml"; "doc"; "syntax_" ^ syntax ] & S [ A "-syntax"; A syntax ]; flag [ "ocaml"; "infer_interface"; "syntax_" ^ syntax ] & S [ A "-syntax"; A syntax ]) (find_syntaxes ()); The default " thread " tag is not compatible with ocamlfind . Indeed , the default rules add the " threads.cma " or " threads.cmxa " options when using this tag . When using the " -linkpkg " option with ocamlfind , this module will then be added twice on the command line . To solve this , one approach is to add the " -thread " option when using the " threads " package using the previous plugin . Indeed, the default rules add the "threads.cma" or "threads.cmxa" options when using this tag. When using the "-linkpkg" option with ocamlfind, this module will then be added twice on the command line. To solve this, one approach is to add the "-thread" option when using the "threads" package using the previous plugin. *) flag [ "ocaml"; "pkg_threads"; "compile" ] (S [ A "-thread" ]); flag [ "ocaml"; "pkg_threads"; "link" ] (S [ A "-thread" ]); flag [ "ocaml"; "pkg_threads"; "infer_interface" ] (S [ A "-thread" ]) | _ -> ())
c5de0b84c47f80b69affd312a6ba752b24eb52075e4698d7c959366700c3cd81
simplex-chat/simplex-chat
Types.hs
# LANGUAGE AllowAmbiguousTypes # {-# LANGUAGE ConstraintKinds #-} # LANGUAGE DataKinds # {-# LANGUAGE DeriveAnyClass #-} # LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # {-# LANGUAGE GADTs #-} # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE PatternSynonyms # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # {-# LANGUAGE StrictData #-} # LANGUAGE TypeApplications # # LANGUAGE TypeFamilyDependencies # # LANGUAGE UndecidableInstances # {-# OPTIONS_GHC -Wno-unrecognised-pragmas #-} {-# HLINT ignore "Use newtype instead of data" #-} module Simplex.Chat.Types where import Control.Applicative ((<|>)) import Crypto.Number.Serialize (os2ip) import Data.Aeson (FromJSON, ToJSON) import qualified Data.Aeson as J import qualified Data.Aeson.Encoding as JE import qualified Data.Aeson.Types as JT import qualified Data.Attoparsec.ByteString.Char8 as A import Data.ByteString.Char8 (ByteString, pack, unpack) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB import Data.Int (Int64) import Data.Maybe (fromMaybe, isJust) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time.Clock (UTCTime) import Data.Typeable import Database.SQLite.Simple (ResultError (..), SQLData (..)) import Database.SQLite.Simple.FromField (FieldParser, FromField (..), returnError) import Database.SQLite.Simple.Internal (Field (..)) import Database.SQLite.Simple.Ok (Ok (Ok)) import Database.SQLite.Simple.ToField (ToField (..)) import GHC.Generics (Generic) import GHC.Records.Compat import Simplex.Messaging.Agent.Protocol (ACommandTag (..), ACorrId, AParty (..), ConnId, ConnectionMode (..), ConnectionRequestUri, InvitationId) import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (dropPrefix, enumJSON, fromTextField_, sumTypeJSON, taggedObjectJSON) import Simplex.Messaging.Protocol (SMPServerWithAuth) import Simplex.Messaging.Util (safeDecodeUtf8, (<$?>)) class IsContact a where contactId' :: a -> ContactId profile' :: a -> LocalProfile localDisplayName' :: a -> ContactName preferences' :: a -> Maybe Preferences instance IsContact User where contactId' = userContactId # INLINE contactId ' # profile' = profile {-# INLINE profile' #-} localDisplayName' = localDisplayName {-# INLINE localDisplayName' #-} preferences' User {profile = LocalProfile {preferences}} = preferences {-# INLINE preferences' #-} instance IsContact Contact where contactId' = contactId # INLINE contactId ' # profile' = profile {-# INLINE profile' #-} localDisplayName' = localDisplayName {-# INLINE localDisplayName' #-} preferences' Contact {profile = LocalProfile {preferences}} = preferences {-# INLINE preferences' #-} newtype AgentUserId = AgentUserId UserId deriving (Eq, Show) instance StrEncoding AgentUserId where strEncode (AgentUserId uId) = strEncode uId strDecode s = AgentUserId <$> strDecode s strP = AgentUserId <$> strP instance FromJSON AgentUserId where parseJSON = strParseJSON "AgentUserId" instance ToJSON AgentUserId where toJSON = strToJSON toEncoding = strToJEncoding instance FromField AgentUserId where fromField f = AgentUserId <$> fromField f instance ToField AgentUserId where toField (AgentUserId uId) = toField uId aUserId :: User -> UserId aUserId User {agentUserId = AgentUserId uId} = uId data User = User { userId :: UserId, agentUserId :: AgentUserId, userContactId :: ContactId, localDisplayName :: ContactName, profile :: LocalProfile, fullPreferences :: FullPreferences, activeUser :: Bool } deriving (Show, Generic, FromJSON) instance ToJSON User where toEncoding = J.genericToEncoding J.defaultOptions data UserInfo = UserInfo { user :: User, unreadCount :: Int } deriving (Show, Generic, FromJSON) instance ToJSON UserInfo where toJSON = J.genericToJSON J.defaultOptions toEncoding = J.genericToEncoding J.defaultOptions type UserId = Int64 type ContactId = Int64 type ProfileId = Int64 data Contact = Contact { contactId :: ContactId, localDisplayName :: ContactName, profile :: LocalProfile, activeConn :: Connection, viaGroup :: Maybe Int64, contactUsed :: Bool, chatSettings :: ChatSettings, userPreferences :: Preferences, mergedPreferences :: ContactUserPreferences, createdAt :: UTCTime, updatedAt :: UTCTime, chatTs :: Maybe UTCTime } deriving (Eq, Show, Generic) instance ToJSON Contact where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} contactConn :: Contact -> Connection contactConn = activeConn contactConnId :: Contact -> ConnId contactConnId = aConnId . contactConn contactConnIncognito :: Contact -> Bool contactConnIncognito = connIncognito . contactConn directOrUsed :: Contact -> Bool directOrUsed Contact {contactUsed, activeConn = Connection {connLevel, viaGroupLink}} = (connLevel == 0 && not viaGroupLink) || contactUsed anyDirectOrUsed :: Contact -> Bool anyDirectOrUsed Contact {contactUsed, activeConn = Connection {connLevel}} = connLevel == 0 || contactUsed contactSecurityCode :: Contact -> Maybe SecurityCode contactSecurityCode Contact {activeConn} = connectionCode activeConn data ContactRef = ContactRef { contactId :: ContactId, connId :: Int64, agentConnId :: AgentConnId, localDisplayName :: ContactName } deriving (Eq, Show, Generic) instance ToJSON ContactRef where toEncoding = J.genericToEncoding J.defaultOptions data UserContact = UserContact { userContactLinkId :: Int64, connReqContact :: ConnReqContact, groupId :: Maybe GroupId } deriving (Eq, Show, Generic) userContactGroupId :: UserContact -> Maybe GroupId userContactGroupId UserContact {groupId} = groupId instance ToJSON UserContact where toJSON = J.genericToJSON J.defaultOptions toEncoding = J.genericToEncoding J.defaultOptions data UserContactRequest = UserContactRequest { contactRequestId :: Int64, agentInvitationId :: AgentInvId, userContactLinkId :: Int64, agentContactConnId :: AgentConnId, -- connection id of user contact localDisplayName :: ContactName, profileId :: Int64, profile :: Profile, createdAt :: UTCTime, updatedAt :: UTCTime, xContactId :: Maybe XContactId } deriving (Eq, Show, Generic) instance ToJSON UserContactRequest where toEncoding = J.genericToEncoding J.defaultOptions newtype XContactId = XContactId ByteString deriving (Eq, Show) instance FromField XContactId where fromField f = XContactId <$> fromField f instance ToField XContactId where toField (XContactId m) = toField m instance StrEncoding XContactId where strEncode (XContactId m) = strEncode m strDecode s = XContactId <$> strDecode s strP = XContactId <$> strP instance FromJSON XContactId where parseJSON = strParseJSON "XContactId" instance ToJSON XContactId where toJSON = strToJSON toEncoding = strToJEncoding newtype ConnReqUriHash = ConnReqUriHash {unConnReqUriHash :: ByteString} deriving (Eq, Show) instance FromField ConnReqUriHash where fromField f = ConnReqUriHash <$> fromField f instance ToField ConnReqUriHash where toField (ConnReqUriHash m) = toField m instance StrEncoding ConnReqUriHash where strEncode (ConnReqUriHash m) = strEncode m strDecode s = ConnReqUriHash <$> strDecode s strP = ConnReqUriHash <$> strP instance FromJSON ConnReqUriHash where parseJSON = strParseJSON "ConnReqUriHash" instance ToJSON ConnReqUriHash where toJSON = strToJSON toEncoding = strToJEncoding data ContactOrRequest = CORContact Contact | CORRequest UserContactRequest type UserName = Text type ContactName = Text type GroupName = Text optionalFullName :: ContactName -> Text -> Text optionalFullName displayName fullName | T.null fullName || displayName == fullName = "" | otherwise = " (" <> fullName <> ")" data Group = Group {groupInfo :: GroupInfo, members :: [GroupMember]} deriving (Eq, Show, Generic) instance ToJSON Group where toEncoding = J.genericToEncoding J.defaultOptions type GroupId = Int64 data GroupInfo = GroupInfo { groupId :: GroupId, localDisplayName :: GroupName, groupProfile :: GroupProfile, fullGroupPreferences :: FullGroupPreferences, membership :: GroupMember, hostConnCustomUserProfileId :: Maybe ProfileId, chatSettings :: ChatSettings, createdAt :: UTCTime, updatedAt :: UTCTime, chatTs :: Maybe UTCTime } deriving (Eq, Show, Generic) instance ToJSON GroupInfo where toEncoding = J.genericToEncoding J.defaultOptions groupName' :: GroupInfo -> GroupName groupName' GroupInfo {localDisplayName = g} = g -- TODO when more settings are added we should create another type to allow partial setting updates (with all Maybe properties) data ChatSettings = ChatSettings { enableNtfs :: Bool } deriving (Eq, Show, Generic, FromJSON) instance ToJSON ChatSettings where toEncoding = J.genericToEncoding J.defaultOptions defaultChatSettings :: ChatSettings defaultChatSettings = ChatSettings {enableNtfs = True} pattern DisableNtfs :: ChatSettings pattern DisableNtfs = ChatSettings {enableNtfs = False} data ChatFeature = CFTimedMessages | CFFullDelete | -- | CFReceipts CFVoice deriving (Show, Generic) data SChatFeature (f :: ChatFeature) where SCFTimedMessages :: SChatFeature 'CFTimedMessages SCFFullDelete :: SChatFeature 'CFFullDelete SCFVoice :: SChatFeature 'CFVoice deriving instance Show (SChatFeature f) data AChatFeature = forall f. FeatureI f => ACF (SChatFeature f) deriving instance Show AChatFeature chatFeatureNameText :: ChatFeature -> Text chatFeatureNameText = \case CFTimedMessages -> "Disappearing messages" CFFullDelete -> "Full deletion" CFVoice -> "Voice messages" chatFeatureNameText' :: SChatFeature f -> Text chatFeatureNameText' = chatFeatureNameText . chatFeature featureAllowed :: SChatFeature f -> (PrefEnabled -> Bool) -> Contact -> Bool featureAllowed feature forWhom Contact {mergedPreferences} = let ContactUserPreference {enabled} = getContactUserPreference feature mergedPreferences in forWhom enabled instance ToJSON ChatFeature where toEncoding = J.genericToEncoding . enumJSON $ dropPrefix "CF" toJSON = J.genericToJSON . enumJSON $ dropPrefix "CF" instance FromJSON ChatFeature where parseJSON = J.genericParseJSON . enumJSON $ dropPrefix "CF" allChatFeatures :: [AChatFeature] allChatFeatures = [ ACF SCFTimedMessages, ACF SCFFullDelete, CFReceipts , ACF SCFVoice ] chatPrefSel :: SChatFeature f -> Preferences -> Maybe (FeaturePreference f) chatPrefSel = \case SCFTimedMessages -> timedMessages SCFFullDelete -> fullDelete CFReceipts - > receipts SCFVoice -> voice chatFeature :: SChatFeature f -> ChatFeature chatFeature = \case SCFTimedMessages -> CFTimedMessages SCFFullDelete -> CFFullDelete SCFVoice -> CFVoice class PreferenceI p where getPreference :: SChatFeature f -> p -> FeaturePreference f instance PreferenceI Preferences where getPreference f prefs = fromMaybe (getPreference f defaultChatPrefs) (chatPrefSel f prefs) instance PreferenceI (Maybe Preferences) where getPreference f prefs = fromMaybe (getPreference f defaultChatPrefs) (chatPrefSel f =<< prefs) instance PreferenceI FullPreferences where getPreference = \case SCFTimedMessages -> timedMessages SCFFullDelete -> fullDelete CFReceipts - > receipts SCFVoice -> voice # INLINE getPreference # setPreference :: forall f. FeatureI f => SChatFeature f -> Maybe FeatureAllowed -> Maybe Preferences -> Preferences setPreference f allow_ prefs_ = setPreference_ f pref $ fromMaybe emptyChatPrefs prefs_ where pref = setAllow <$> allow_ setAllow :: FeatureAllowed -> FeaturePreference f setAllow = setField @"allow" (getPreference f prefs) prefs = mergePreferences Nothing prefs_ setPreference' :: SChatFeature f -> Maybe (FeaturePreference f) -> Maybe Preferences -> Preferences setPreference' f pref_ prefs_ = setPreference_ f pref_ $ fromMaybe emptyChatPrefs prefs_ setPreference_ :: SChatFeature f -> Maybe (FeaturePreference f) -> Preferences -> Preferences setPreference_ f pref_ prefs = case f of SCFTimedMessages -> prefs {timedMessages = pref_} SCFFullDelete -> prefs {fullDelete = pref_} SCFVoice -> prefs {voice = pref_} -- collection of optional chat preferences for the user and the contact data Preferences = Preferences { timedMessages :: Maybe TimedMessagesPreference, fullDelete :: Maybe FullDeletePreference, receipts : : Maybe SimplePreference , voice :: Maybe VoicePreference } deriving (Eq, Show, Generic, FromJSON) instance ToJSON Preferences where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} instance ToField Preferences where toField = toField . encodeJSON instance FromField Preferences where fromField = fromTextField_ decodeJSON data GroupFeature = GFTimedMessages | GFDirectMessages | GFFullDelete | -- | GFReceipts GFVoice deriving (Show, Generic) data SGroupFeature (f :: GroupFeature) where SGFTimedMessages :: SGroupFeature 'GFTimedMessages SGFDirectMessages :: SGroupFeature 'GFDirectMessages SGFFullDelete :: SGroupFeature 'GFFullDelete SGFReceipts SGFVoice :: SGroupFeature 'GFVoice deriving instance Show (SGroupFeature f) data AGroupFeature = forall f. GroupFeatureI f => AGF (SGroupFeature f) deriving instance Show AGroupFeature groupFeatureNameText :: GroupFeature -> Text groupFeatureNameText = \case GFTimedMessages -> "Disappearing messages" GFDirectMessages -> "Direct messages" GFFullDelete -> "Full deletion" GFVoice -> "Voice messages" groupFeatureNameText' :: SGroupFeature f -> Text groupFeatureNameText' = groupFeatureNameText . toGroupFeature groupFeatureAllowed :: GroupFeatureI f => SGroupFeature f -> GroupInfo -> Bool groupFeatureAllowed feature gInfo = groupFeatureAllowed' feature $ fullGroupPreferences gInfo groupFeatureAllowed' :: GroupFeatureI f => SGroupFeature f -> FullGroupPreferences -> Bool groupFeatureAllowed' feature prefs = getField @"enable" (getGroupPreference feature prefs) == FEOn instance ToJSON GroupFeature where toEncoding = J.genericToEncoding . enumJSON $ dropPrefix "GF" toJSON = J.genericToJSON . enumJSON $ dropPrefix "GF" instance FromJSON GroupFeature where parseJSON = J.genericParseJSON . enumJSON $ dropPrefix "GF" allGroupFeatures :: [AGroupFeature] allGroupFeatures = [ AGF SGFTimedMessages, AGF SGFDirectMessages, AGF SGFFullDelete, GFReceipts , AGF SGFVoice ] groupPrefSel :: SGroupFeature f -> GroupPreferences -> Maybe (GroupFeaturePreference f) groupPrefSel = \case SGFTimedMessages -> timedMessages SGFDirectMessages -> directMessages SGFFullDelete -> fullDelete GFReceipts - > receipts SGFVoice -> voice toGroupFeature :: SGroupFeature f -> GroupFeature toGroupFeature = \case SGFTimedMessages -> GFTimedMessages SGFDirectMessages -> GFDirectMessages SGFFullDelete -> GFFullDelete SGFVoice -> GFVoice class GroupPreferenceI p where getGroupPreference :: SGroupFeature f -> p -> GroupFeaturePreference f instance GroupPreferenceI GroupPreferences where getGroupPreference pt prefs = fromMaybe (getGroupPreference pt defaultGroupPrefs) (groupPrefSel pt prefs) instance GroupPreferenceI (Maybe GroupPreferences) where getGroupPreference pt prefs = fromMaybe (getGroupPreference pt defaultGroupPrefs) (groupPrefSel pt =<< prefs) instance GroupPreferenceI FullGroupPreferences where getGroupPreference = \case SGFTimedMessages -> timedMessages SGFDirectMessages -> directMessages SGFFullDelete -> fullDelete GFReceipts - > receipts SGFVoice -> voice # INLINE getGroupPreference # -- collection of optional group preferences data GroupPreferences = GroupPreferences { timedMessages :: Maybe TimedMessagesGroupPreference, directMessages :: Maybe DirectMessagesGroupPreference, fullDelete :: Maybe FullDeleteGroupPreference, receipts : : Maybe GroupPreference , voice :: Maybe VoiceGroupPreference } deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupPreferences where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} instance ToField GroupPreferences where toField = toField . encodeJSON instance FromField GroupPreferences where fromField = fromTextField_ decodeJSON setGroupPreference :: forall f. GroupFeatureI f => SGroupFeature f -> GroupFeatureEnabled -> Maybe GroupPreferences -> GroupPreferences setGroupPreference f enable prefs_ = setGroupPreference_ f pref prefs where prefs = mergeGroupPreferences prefs_ pref :: GroupFeaturePreference f pref = setField @"enable" (getGroupPreference f prefs) enable setGroupPreference' :: SGroupFeature f -> GroupFeaturePreference f -> Maybe GroupPreferences -> GroupPreferences setGroupPreference' f pref prefs_ = setGroupPreference_ f pref prefs where prefs = mergeGroupPreferences prefs_ setGroupPreference_ :: SGroupFeature f -> GroupFeaturePreference f -> FullGroupPreferences -> GroupPreferences setGroupPreference_ f pref prefs = toGroupPreferences $ case f of SGFTimedMessages -> prefs {timedMessages = pref} SGFDirectMessages -> prefs {directMessages = pref} SGFVoice -> prefs {voice = pref} SGFFullDelete -> prefs {fullDelete = pref} setGroupTimedMessagesPreference :: TimedMessagesGroupPreference -> Maybe GroupPreferences -> GroupPreferences setGroupTimedMessagesPreference pref prefs_ = toGroupPreferences $ prefs {timedMessages = pref} where prefs = mergeGroupPreferences prefs_ -- full collection of chat preferences defined in the app - it is used to ensure we include all preferences and to simplify processing -- if some of the preferences are not defined in Preferences, defaults from defaultChatPrefs are used here. data FullPreferences = FullPreferences { timedMessages :: TimedMessagesPreference, fullDelete :: FullDeletePreference, receipts : : SimplePreference , voice :: VoicePreference } deriving (Eq, Show, Generic, FromJSON) instance ToJSON FullPreferences where toEncoding = J.genericToEncoding J.defaultOptions -- full collection of group preferences defined in the app - it is used to ensure we include all preferences and to simplify processing -- if some of the preferences are not defined in GroupPreferences, defaults from defaultGroupPrefs are used here. data FullGroupPreferences = FullGroupPreferences { timedMessages :: TimedMessagesGroupPreference, directMessages :: DirectMessagesGroupPreference, fullDelete :: FullDeleteGroupPreference, receipts : : GroupPreference , voice :: VoiceGroupPreference } deriving (Eq, Show, Generic, FromJSON) instance ToJSON FullGroupPreferences where toEncoding = J.genericToEncoding J.defaultOptions -- merged preferences of user for a given contact - they differentiate between specific preferences for the contact and global user preferences data ContactUserPreferences = ContactUserPreferences { timedMessages :: ContactUserPreference TimedMessagesPreference, fullDelete :: ContactUserPreference FullDeletePreference, receipts : : ContactUserPreference , voice :: ContactUserPreference VoicePreference } deriving (Eq, Show, Generic) data ContactUserPreference p = ContactUserPreference { enabled :: PrefEnabled, userPreference :: ContactUserPref p, contactPreference :: p } deriving (Eq, Show, Generic) data ContactUserPref p = CUPContact {preference :: p} | CUPUser {preference :: p} deriving (Eq, Show, Generic) instance ToJSON ContactUserPreferences where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON p => ToJSON (ContactUserPreference p) where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON p => ToJSON (ContactUserPref p) where toJSON = J.genericToJSON . sumTypeJSON $ dropPrefix "CUP" toEncoding = J.genericToEncoding . sumTypeJSON $ dropPrefix "CUP" toChatPrefs :: FullPreferences -> Preferences toChatPrefs FullPreferences {fullDelete, voice, timedMessages} = Preferences { timedMessages = Just timedMessages, fullDelete = Just fullDelete, -- receipts = Just receipts, voice = Just voice } defaultChatPrefs :: FullPreferences defaultChatPrefs = FullPreferences { timedMessages = TimedMessagesPreference {allow = FANo, ttl = Nothing}, fullDelete = FullDeletePreference {allow = FANo}, receipts = SimplePreference { allow = FANo } , voice = VoicePreference {allow = FAYes} } emptyChatPrefs :: Preferences emptyChatPrefs = Preferences Nothing Nothing Nothing defaultGroupPrefs :: FullGroupPreferences defaultGroupPrefs = FullGroupPreferences { timedMessages = TimedMessagesGroupPreference {enable = FEOff, ttl = 86400}, directMessages = DirectMessagesGroupPreference {enable = FEOff}, fullDelete = FullDeleteGroupPreference {enable = FEOff}, receipts = GroupPreference { enable , voice = VoiceGroupPreference {enable = FEOn} } emptyGroupPrefs :: GroupPreferences emptyGroupPrefs = GroupPreferences Nothing Nothing Nothing Nothing data TimedMessagesPreference = TimedMessagesPreference { allow :: FeatureAllowed, ttl :: Maybe Int } deriving (Eq, Show, Generic, FromJSON) instance ToJSON TimedMessagesPreference where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} data FullDeletePreference = FullDeletePreference {allow :: FeatureAllowed} deriving (Eq, Show, Generic, FromJSON) instance ToJSON FullDeletePreference where toEncoding = J.genericToEncoding J.defaultOptions data VoicePreference = VoicePreference {allow :: FeatureAllowed} deriving (Eq, Show, Generic, FromJSON) instance ToJSON VoicePreference where toEncoding = J.genericToEncoding J.defaultOptions class (Eq (FeaturePreference f), HasField "allow" (FeaturePreference f) FeatureAllowed) => FeatureI f where type FeaturePreference (f :: ChatFeature) = p | p -> f sFeature :: SChatFeature f prefParam :: FeaturePreference f -> Maybe Int instance HasField "allow" TimedMessagesPreference FeatureAllowed where hasField p = (\allow -> p {allow}, allow (p :: TimedMessagesPreference)) instance HasField "allow" FullDeletePreference FeatureAllowed where hasField p = (\allow -> p {allow}, allow (p :: FullDeletePreference)) instance HasField "allow" VoicePreference FeatureAllowed where hasField p = (\allow -> p {allow}, allow (p :: VoicePreference)) instance FeatureI 'CFTimedMessages where type FeaturePreference 'CFTimedMessages = TimedMessagesPreference sFeature = SCFTimedMessages prefParam TimedMessagesPreference {ttl} = ttl instance FeatureI 'CFFullDelete where type FeaturePreference 'CFFullDelete = FullDeletePreference sFeature = SCFFullDelete prefParam _ = Nothing instance FeatureI 'CFVoice where type FeaturePreference 'CFVoice = VoicePreference sFeature = SCFVoice prefParam _ = Nothing data GroupPreference = GroupPreference {enable :: GroupFeatureEnabled} deriving (Eq, Show, Generic, FromJSON) data TimedMessagesGroupPreference = TimedMessagesGroupPreference { enable :: GroupFeatureEnabled, ttl :: Int } deriving (Eq, Show, Generic, FromJSON) data DirectMessagesGroupPreference = DirectMessagesGroupPreference {enable :: GroupFeatureEnabled} deriving (Eq, Show, Generic, FromJSON) data FullDeleteGroupPreference = FullDeleteGroupPreference {enable :: GroupFeatureEnabled} deriving (Eq, Show, Generic, FromJSON) data VoiceGroupPreference = VoiceGroupPreference {enable :: GroupFeatureEnabled} deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupPreference where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON TimedMessagesGroupPreference where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON DirectMessagesGroupPreference where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON FullDeleteGroupPreference where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON VoiceGroupPreference where toEncoding = J.genericToEncoding J.defaultOptions class (Eq (GroupFeaturePreference f), HasField "enable" (GroupFeaturePreference f) GroupFeatureEnabled) => GroupFeatureI f where type GroupFeaturePreference (f :: GroupFeature) = p | p -> f sGroupFeature :: SGroupFeature f groupPrefParam :: GroupFeaturePreference f -> Maybe Int instance HasField "enable" GroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: GroupPreference)) instance HasField "enable" TimedMessagesGroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: TimedMessagesGroupPreference)) instance HasField "enable" DirectMessagesGroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: DirectMessagesGroupPreference)) instance HasField "enable" FullDeleteGroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: FullDeleteGroupPreference)) instance HasField "enable" VoiceGroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: VoiceGroupPreference)) instance GroupFeatureI 'GFTimedMessages where type GroupFeaturePreference 'GFTimedMessages = TimedMessagesGroupPreference sGroupFeature = SGFTimedMessages groupPrefParam TimedMessagesGroupPreference {ttl} = Just ttl instance GroupFeatureI 'GFDirectMessages where type GroupFeaturePreference 'GFDirectMessages = DirectMessagesGroupPreference sGroupFeature = SGFDirectMessages groupPrefParam _ = Nothing instance GroupFeatureI 'GFFullDelete where type GroupFeaturePreference 'GFFullDelete = FullDeleteGroupPreference sGroupFeature = SGFFullDelete groupPrefParam _ = Nothing instance GroupFeatureI 'GFVoice where type GroupFeaturePreference 'GFVoice = VoiceGroupPreference sGroupFeature = SGFVoice groupPrefParam _ = Nothing groupPrefStateText :: HasField "enable" p GroupFeatureEnabled => GroupFeature -> p -> Maybe Int -> Text groupPrefStateText feature pref param = let enabled = getField @"enable" pref paramText = if enabled == FEOn then groupParamText_ feature param else "" in groupFeatureNameText feature <> ": " <> safeDecodeUtf8 (strEncode enabled) <> paramText groupParamText_ :: GroupFeature -> Maybe Int -> Text groupParamText_ feature param = case feature of GFTimedMessages -> maybe "" (\p -> " (" <> timedTTLText p <> ")") param _ -> "" groupPreferenceText :: forall f. GroupFeatureI f => GroupFeaturePreference f -> Text groupPreferenceText pref = let feature = toGroupFeature $ sGroupFeature @f in groupPrefStateText feature pref $ groupPrefParam pref timedTTLText :: Int -> Text timedTTLText 0 = "0 sec" timedTTLText ttl = do let (m', s) = ttl `quotRem` 60 (h', m) = m' `quotRem` 60 (d', h) = h' `quotRem` 24 (mm, d) = d' `quotRem` 30 T.pack . unwords $ [mms mm | mm /= 0] <> [ds d | d /= 0] <> [hs h | h /= 0] <> [ms m | m /= 0] <> [ss s | s /= 0] where ss s = show s <> " sec" ms m = show m <> " min" hs 1 = "1 hour" hs h = show h <> " hours" ds 1 = "1 day" ds 7 = "1 week" ds 14 = "2 weeks" ds d = show d <> " days" mms 1 = "1 month" mms mm = show mm <> " months" toGroupPreference :: GroupFeatureI f => GroupFeaturePreference f -> GroupPreference toGroupPreference p = GroupPreference {enable = getField @"enable" p} data FeatureAllowed = FAAlways -- allow unconditionally | FAYes -- allow, if peer allows it | FANo -- do not allow deriving (Eq, Show, Generic) instance FromField FeatureAllowed where fromField = fromBlobField_ strDecode instance ToField FeatureAllowed where toField = toField . strEncode instance StrEncoding FeatureAllowed where strEncode = \case FAAlways -> "always" FAYes -> "yes" FANo -> "no" strDecode = \case "always" -> Right FAAlways "yes" -> Right FAYes "no" -> Right FANo r -> Left $ "bad FeatureAllowed " <> B.unpack r strP = strDecode <$?> A.takeByteString instance FromJSON FeatureAllowed where parseJSON = strParseJSON "FeatureAllowed" instance ToJSON FeatureAllowed where toJSON = strToJSON toEncoding = strToJEncoding data GroupFeatureEnabled = FEOn | FEOff deriving (Eq, Show, Generic) instance FromField GroupFeatureEnabled where fromField = fromBlobField_ strDecode instance ToField GroupFeatureEnabled where toField = toField . strEncode instance StrEncoding GroupFeatureEnabled where strEncode = \case FEOn -> "on" FEOff -> "off" strDecode = \case "on" -> Right FEOn "off" -> Right FEOff r -> Left $ "bad GroupFeatureEnabled " <> B.unpack r strP = strDecode <$?> A.takeByteString instance FromJSON GroupFeatureEnabled where parseJSON = strParseJSON "GroupFeatureEnabled" instance ToJSON GroupFeatureEnabled where toJSON = strToJSON toEncoding = strToJEncoding groupFeatureState :: GroupFeatureI f => GroupFeaturePreference f -> (GroupFeatureEnabled, Maybe Int) groupFeatureState p = let enable = getField @"enable" p param = if enable == FEOn then groupPrefParam p else Nothing in (enable, param) mergePreferences :: Maybe Preferences -> Maybe Preferences -> FullPreferences mergePreferences contactPrefs userPreferences = FullPreferences { timedMessages = pref SCFTimedMessages, fullDelete = pref SCFFullDelete, receipts = pref CFReceipts , voice = pref SCFVoice } where pref :: SChatFeature f -> FeaturePreference f pref f = let sel = chatPrefSel f in fromMaybe (getPreference f defaultChatPrefs) $ (contactPrefs >>= sel) <|> (userPreferences >>= sel) mergeUserChatPrefs :: User -> Contact -> FullPreferences mergeUserChatPrefs user ct = mergeUserChatPrefs' user (contactConnIncognito ct) (userPreferences ct) mergeUserChatPrefs' :: User -> Bool -> Preferences -> FullPreferences mergeUserChatPrefs' user connectedIncognito userPreferences = let userPrefs = if connectedIncognito then Nothing else preferences' user in mergePreferences (Just userPreferences) userPrefs mergeGroupPreferences :: Maybe GroupPreferences -> FullGroupPreferences mergeGroupPreferences groupPreferences = FullGroupPreferences { timedMessages = pref SGFTimedMessages, directMessages = pref SGFDirectMessages, fullDelete = pref SGFFullDelete, receipts = pref GFReceipts , voice = pref SGFVoice } where pref :: SGroupFeature f -> GroupFeaturePreference f pref pt = fromMaybe (getGroupPreference pt defaultGroupPrefs) (groupPreferences >>= groupPrefSel pt) toGroupPreferences :: FullGroupPreferences -> GroupPreferences toGroupPreferences groupPreferences = GroupPreferences { timedMessages = pref SGFTimedMessages, directMessages = pref SGFDirectMessages, fullDelete = pref SGFFullDelete, receipts = pref GFReceipts , voice = pref SGFVoice } where pref :: SGroupFeature f -> Maybe (GroupFeaturePreference f) pref f = Just $ getGroupPreference f groupPreferences data PrefEnabled = PrefEnabled {forUser :: Bool, forContact :: Bool} deriving (Eq, Show, Generic, FromJSON) instance ToJSON PrefEnabled where toJSON = J.genericToJSON J.defaultOptions toEncoding = J.genericToEncoding J.defaultOptions prefEnabled :: FeatureI f => Bool -> FeaturePreference f -> FeaturePreference f -> PrefEnabled prefEnabled asymmetric user contact = case (getField @"allow" user, getField @"allow" contact) of (FAAlways, FANo) -> PrefEnabled {forUser = False, forContact = asymmetric} (FANo, FAAlways) -> PrefEnabled {forUser = asymmetric, forContact = False} (_, FANo) -> PrefEnabled False False (FANo, _) -> PrefEnabled False False _ -> PrefEnabled True True prefStateText :: ChatFeature -> FeatureAllowed -> Maybe Int -> Text prefStateText feature allowed param = case allowed of FANo -> "cancelled " <> chatFeatureNameText feature _ -> "offered " <> chatFeatureNameText feature <> paramText_ feature param featureStateText :: ChatFeature -> PrefEnabled -> Maybe Int -> Text featureStateText feature enabled param = chatFeatureNameText feature <> ": " <> prefEnabledToText enabled <> case enabled of PrefEnabled {forUser = True} -> paramText_ feature param _ -> "" paramText_ :: ChatFeature -> Maybe Int -> Text paramText_ feature param = case feature of CFTimedMessages -> maybe "" (\p -> " (" <> timedTTLText p <> ")") param _ -> "" prefEnabledToText :: PrefEnabled -> Text prefEnabledToText = \case PrefEnabled True True -> "enabled" PrefEnabled False False -> "off" PrefEnabled {forUser = True, forContact = False} -> "enabled for you" PrefEnabled {forUser = False, forContact = True} -> "enabled for contact" preferenceText :: forall f. FeatureI f => FeaturePreference f -> Text preferenceText p = let feature = chatFeature $ sFeature @f allowed = getField @"allow" p paramText = if allowed == FAAlways || allowed == FAYes then paramText_ feature (prefParam p) else "" in safeDecodeUtf8 (strEncode allowed) <> paramText featureState :: FeatureI f => ContactUserPreference (FeaturePreference f) -> (PrefEnabled, Maybe Int) featureState ContactUserPreference {enabled, userPreference} = let param = if forUser enabled then prefParam $ preference userPreference else Nothing in (enabled, param) preferenceState :: FeatureI f => FeaturePreference f -> (FeatureAllowed, Maybe Int) preferenceState pref = let allow = getField @"allow" pref param = if allow == FAAlways || allow == FAYes then prefParam pref else Nothing in (allow, param) updateMergedPreferences :: User -> Contact -> Contact updateMergedPreferences user ct = let mergedPreferences = contactUserPreferences user (userPreferences ct) (preferences' ct) (contactConnIncognito ct) in ct {mergedPreferences} contactUserPreferences :: User -> Preferences -> Maybe Preferences -> Bool -> ContactUserPreferences contactUserPreferences user userPreferences contactPreferences connectedIncognito = ContactUserPreferences { timedMessages = pref SCFTimedMessages, fullDelete = pref SCFFullDelete, receipts = pref CFReceipts , voice = pref SCFVoice } where pref :: FeatureI f => SChatFeature f -> ContactUserPreference (FeaturePreference f) pref f = ContactUserPreference { enabled = prefEnabled (asymmetric f) userPref ctPref, -- incognito contact cannot have default user preference used userPreference = if connectedIncognito then CUPContact ctUserPref else maybe (CUPUser userPref) CUPContact ctUserPref_, contactPreference = ctPref } where asymmetric SCFTimedMessages = False asymmetric _ = True ctUserPref = getPreference f userPreferences ctUserPref_ = chatPrefSel f userPreferences userPref = getPreference f ctUserPrefs ctPref = getPreference f ctPrefs ctUserPrefs = mergeUserChatPrefs' user connectedIncognito userPreferences ctPrefs = mergePreferences contactPreferences Nothing getContactUserPreference :: SChatFeature f -> ContactUserPreferences -> ContactUserPreference (FeaturePreference f) getContactUserPreference = \case SCFTimedMessages -> timedMessages SCFFullDelete -> fullDelete CFReceipts - > receipts SCFVoice -> voice data Profile = Profile { displayName :: ContactName, fullName :: Text, image :: Maybe ImageData, preferences :: Maybe Preferences -- fields that should not be read into this data type to prevent sending them as part of profile to contacts: -- - contact_profile_id -- - incognito -- - local_alias } deriving (Eq, Show, Generic, FromJSON) instance ToJSON Profile where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} -- check if profiles match ignoring preferences profilesMatch :: Profile -> Profile -> Bool profilesMatch Profile {displayName = n1, fullName = fn1, image = i1} Profile {displayName = n2, fullName = fn2, image = i2} = n1 == n2 && fn1 == fn2 && i1 == i2 data IncognitoProfile = NewIncognito Profile | ExistingIncognito LocalProfile type LocalAlias = Text data LocalProfile = LocalProfile { profileId :: ProfileId, displayName :: ContactName, fullName :: Text, image :: Maybe ImageData, preferences :: Maybe Preferences, localAlias :: LocalAlias } deriving (Eq, Show, Generic, FromJSON) instance ToJSON LocalProfile where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} localProfileId :: LocalProfile -> ProfileId localProfileId = profileId toLocalProfile :: ProfileId -> Profile -> LocalAlias -> LocalProfile toLocalProfile profileId Profile {displayName, fullName, image, preferences} localAlias = LocalProfile {profileId, displayName, fullName, image, preferences, localAlias} fromLocalProfile :: LocalProfile -> Profile fromLocalProfile LocalProfile {displayName, fullName, image, preferences} = Profile {displayName, fullName, image, preferences} data GroupProfile = GroupProfile { displayName :: GroupName, fullName :: Text, description :: Maybe Text, image :: Maybe ImageData, groupPreferences :: Maybe GroupPreferences } deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupProfile where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} newtype ImageData = ImageData Text deriving (Eq, Show) instance FromJSON ImageData where parseJSON = fmap ImageData . J.parseJSON instance ToJSON ImageData where toJSON (ImageData t) = J.toJSON t toEncoding (ImageData t) = J.toEncoding t instance ToField ImageData where toField (ImageData t) = toField t instance FromField ImageData where fromField = fmap ImageData . fromField data CReqClientData = CRDataGroup {groupLinkId :: GroupLinkId} deriving (Generic) instance ToJSON CReqClientData where toJSON = J.genericToJSON . taggedObjectJSON $ dropPrefix "CRData" toEncoding = J.genericToEncoding . taggedObjectJSON $ dropPrefix "CRData" instance FromJSON CReqClientData where parseJSON = J.genericParseJSON . taggedObjectJSON $ dropPrefix "CRData" newtype GroupLinkId = GroupLinkId {unGroupLinkId :: ByteString} -- used to identify invitation via group link deriving (Eq, Show) instance FromField GroupLinkId where fromField f = GroupLinkId <$> fromField f instance ToField GroupLinkId where toField (GroupLinkId g) = toField g instance StrEncoding GroupLinkId where strEncode (GroupLinkId g) = strEncode g strDecode s = GroupLinkId <$> strDecode s strP = GroupLinkId <$> strP instance FromJSON GroupLinkId where parseJSON = strParseJSON "GroupLinkId" instance ToJSON GroupLinkId where toJSON = strToJSON toEncoding = strToJEncoding data GroupInvitation = GroupInvitation { fromMember :: MemberIdRole, invitedMember :: MemberIdRole, connRequest :: ConnReqInvitation, groupProfile :: GroupProfile, groupLinkId :: Maybe GroupLinkId } deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupInvitation where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} data MemberIdRole = MemberIdRole { memberId :: MemberId, memberRole :: GroupMemberRole } deriving (Eq, Show, Generic, FromJSON) instance ToJSON MemberIdRole where toEncoding = J.genericToEncoding J.defaultOptions data IntroInvitation = IntroInvitation { groupConnReq :: ConnReqInvitation, directConnReq :: ConnReqInvitation } deriving (Eq, Show, Generic, FromJSON) instance ToJSON IntroInvitation where toEncoding = J.genericToEncoding J.defaultOptions data MemberInfo = MemberInfo { memberId :: MemberId, memberRole :: GroupMemberRole, profile :: Profile } deriving (Eq, Show, Generic, FromJSON) instance ToJSON MemberInfo where toEncoding = J.genericToEncoding J.defaultOptions memberInfo :: GroupMember -> MemberInfo memberInfo GroupMember {memberId, memberRole, memberProfile} = MemberInfo memberId memberRole (fromLocalProfile memberProfile) data ReceivedGroupInvitation = ReceivedGroupInvitation { fromMember :: GroupMember, connRequest :: ConnReqInvitation, groupInfo :: GroupInfo } deriving (Eq, Show) type GroupMemberId = Int64 -- memberProfile's profileId is COALESCE(member_profile_id, contact_profile_id), member_profile_id is non null -- if incognito profile was saved for member (used for hosts and invitees in incognito groups) data GroupMember = GroupMember { groupMemberId :: GroupMemberId, groupId :: GroupId, memberId :: MemberId, memberRole :: GroupMemberRole, memberCategory :: GroupMemberCategory, memberStatus :: GroupMemberStatus, invitedBy :: InvitedBy, localDisplayName :: ContactName, memberProfile :: LocalProfile, memberContactId :: Maybe ContactId, memberContactProfileId :: ProfileId, activeConn :: Maybe Connection } deriving (Eq, Show, Generic) instance ToJSON GroupMember where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} data GroupMemberRef = GroupMemberRef {groupMemberId :: Int64, profile :: Profile} deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupMemberRef where toEncoding = J.genericToEncoding J.defaultOptions groupMemberRef :: GroupMember -> GroupMemberRef groupMemberRef GroupMember {groupMemberId, memberProfile = p} = GroupMemberRef {groupMemberId, profile = fromLocalProfile p} memberConn :: GroupMember -> Maybe Connection memberConn = activeConn memberConnId :: GroupMember -> Maybe ConnId memberConnId GroupMember {activeConn} = aConnId <$> activeConn groupMemberId' :: GroupMember -> GroupMemberId groupMemberId' GroupMember {groupMemberId} = groupMemberId memberIncognito :: GroupMember -> Bool memberIncognito GroupMember {memberProfile, memberContactProfileId} = localProfileId memberProfile /= memberContactProfileId memberSecurityCode :: GroupMember -> Maybe SecurityCode memberSecurityCode GroupMember {activeConn} = connectionCode =<< activeConn data NewGroupMember = NewGroupMember { memInfo :: MemberInfo, memCategory :: GroupMemberCategory, memStatus :: GroupMemberStatus, memInvitedBy :: InvitedBy, localDisplayName :: ContactName, memProfileId :: Int64, memContactId :: Maybe Int64 } newtype MemberId = MemberId {unMemberId :: ByteString} deriving (Eq, Show) instance FromField MemberId where fromField f = MemberId <$> fromField f instance ToField MemberId where toField (MemberId m) = toField m instance StrEncoding MemberId where strEncode (MemberId m) = strEncode m strDecode s = MemberId <$> strDecode s strP = MemberId <$> strP instance FromJSON MemberId where parseJSON = strParseJSON "MemberId" instance ToJSON MemberId where toJSON = strToJSON toEncoding = strToJEncoding data InvitedBy = IBContact {byContactId :: Int64} | IBUser | IBUnknown deriving (Eq, Show, Generic) instance ToJSON InvitedBy where toJSON = J.genericToJSON . sumTypeJSON $ dropPrefix "IB" toEncoding = J.genericToEncoding . sumTypeJSON $ dropPrefix "IB" toInvitedBy :: Int64 -> Maybe Int64 -> InvitedBy toInvitedBy userCtId (Just ctId) | userCtId == ctId = IBUser | otherwise = IBContact ctId toInvitedBy _ Nothing = IBUnknown fromInvitedBy :: Int64 -> InvitedBy -> Maybe Int64 fromInvitedBy userCtId = \case IBUnknown -> Nothing IBContact ctId -> Just ctId IBUser -> Just userCtId data GroupMemberRole = GRObserver -- connects to all group members and receives all messages, can't send messages | GRAuthor -- reserved, unused | GRMember -- + can send messages to all group members | GRAdmin -- + add/remove members, change member role (excl. Owners) | GROwner -- + delete and change group information, add/remove/change roles for Owners deriving (Eq, Show, Ord) instance FromField GroupMemberRole where fromField = fromBlobField_ strDecode instance ToField GroupMemberRole where toField = toField . strEncode instance StrEncoding GroupMemberRole where strEncode = \case GROwner -> "owner" GRAdmin -> "admin" GRMember -> "member" GRAuthor -> "author" GRObserver -> "observer" strDecode = \case "owner" -> Right GROwner "admin" -> Right GRAdmin "member" -> Right GRMember "author" -> Right GRAuthor "observer" -> Right GRObserver r -> Left $ "bad GroupMemberRole " <> B.unpack r strP = strDecode <$?> A.takeByteString instance FromJSON GroupMemberRole where parseJSON = strParseJSON "GroupMemberRole" instance ToJSON GroupMemberRole where toJSON = strToJSON toEncoding = strToJEncoding fromBlobField_ :: Typeable k => (ByteString -> Either String k) -> FieldParser k fromBlobField_ p = \case f@(Field (SQLBlob b) _) -> case p b of Right k -> Ok k Left e -> returnError ConversionFailed f ("could not parse field: " ++ e) f -> returnError ConversionFailed f "expecting SQLBlob column type" newtype Probe = Probe {unProbe :: ByteString} deriving (Eq, Show) instance StrEncoding Probe where strEncode (Probe p) = strEncode p strDecode s = Probe <$> strDecode s strP = Probe <$> strP instance FromJSON Probe where parseJSON = strParseJSON "Probe" instance ToJSON Probe where toJSON = strToJSON toEncoding = strToJEncoding newtype ProbeHash = ProbeHash {unProbeHash :: ByteString} deriving (Eq, Show) instance StrEncoding ProbeHash where strEncode (ProbeHash p) = strEncode p strDecode s = ProbeHash <$> strDecode s strP = ProbeHash <$> strP instance FromJSON ProbeHash where parseJSON = strParseJSON "ProbeHash" instance ToJSON ProbeHash where toJSON = strToJSON toEncoding = strToJEncoding data GroupMemberCategory = GCUserMember | GCInviteeMember -- member invited by the user | GCHostMember -- member who invited the user | GCPreMember -- member who joined before the user and was introduced to the user (user receives x.grp.mem.intro about such members) | GCPostMember -- member who joined after the user to whom the user was introduced (user receives x.grp.mem.new announcing these members and then x.grp.mem.fwd with invitation from these members) deriving (Eq, Show) instance FromField GroupMemberCategory where fromField = fromTextField_ textDecode instance ToField GroupMemberCategory where toField = toField . textEncode instance ToJSON GroupMemberCategory where toJSON = J.String . textEncode toEncoding = JE.text . textEncode instance TextEncoding GroupMemberCategory where textDecode = \case "user" -> Just GCUserMember "invitee" -> Just GCInviteeMember "host" -> Just GCHostMember "pre" -> Just GCPreMember "post" -> Just GCPostMember _ -> Nothing textEncode = \case GCUserMember -> "user" GCInviteeMember -> "invitee" GCHostMember -> "host" GCPreMember -> "pre" GCPostMember -> "post" data GroupMemberStatus = GSMemRemoved -- member who was removed from the group | GSMemLeft -- member who left the group | GSMemGroupDeleted -- user member of the deleted group | GSMemInvited -- member is sent to or received invitation to join the group user received x.grp.mem.intro for this member ( only with ) | GSMemIntroInvited -- member is sent to or received from intro invitation | GSMemAccepted -- member accepted invitation (only User and Invitee) | GSMemAnnounced -- host announced (x.grp.mem.new) a member (Invitee and PostMember) to the group - at this point this member can send messages and invite other members (if they have sufficient permissions) | GSMemConnected -- member created the group connection with the inviting member host confirmed ( x.grp.mem.all ) that a member ( User , Invitee and PostMember ) created group connections with all previous members | GSMemCreator -- user member that created the group (only GCUserMember) deriving (Eq, Show, Ord) instance FromField GroupMemberStatus where fromField = fromTextField_ textDecode instance ToField GroupMemberStatus where toField = toField . textEncode instance ToJSON GroupMemberStatus where toJSON = J.String . textEncode toEncoding = JE.text . textEncode memberActive :: GroupMember -> Bool memberActive m = case memberStatus m of GSMemRemoved -> False GSMemLeft -> False GSMemGroupDeleted -> False GSMemInvited -> False GSMemIntroduced -> False GSMemIntroInvited -> False GSMemAccepted -> False GSMemAnnounced -> False GSMemConnected -> True GSMemComplete -> True GSMemCreator -> True memberCurrent :: GroupMember -> Bool memberCurrent m = case memberStatus m of GSMemRemoved -> False GSMemLeft -> False GSMemGroupDeleted -> False GSMemInvited -> False GSMemIntroduced -> True GSMemIntroInvited -> True GSMemAccepted -> True GSMemAnnounced -> True GSMemConnected -> True GSMemComplete -> True GSMemCreator -> True memberRemoved :: GroupMember -> Bool memberRemoved m = case memberStatus m of GSMemRemoved -> True GSMemLeft -> True GSMemGroupDeleted -> True GSMemInvited -> False GSMemIntroduced -> False GSMemIntroInvited -> False GSMemAccepted -> False GSMemAnnounced -> False GSMemConnected -> False GSMemComplete -> False GSMemCreator -> False instance TextEncoding GroupMemberStatus where textDecode = \case "removed" -> Just GSMemRemoved "left" -> Just GSMemLeft "deleted" -> Just GSMemGroupDeleted "invited" -> Just GSMemInvited "introduced" -> Just GSMemIntroduced "intro-inv" -> Just GSMemIntroInvited "accepted" -> Just GSMemAccepted "announced" -> Just GSMemAnnounced "connected" -> Just GSMemConnected "complete" -> Just GSMemComplete "creator" -> Just GSMemCreator _ -> Nothing textEncode = \case GSMemRemoved -> "removed" GSMemLeft -> "left" GSMemGroupDeleted -> "deleted" GSMemInvited -> "invited" GSMemIntroduced -> "introduced" GSMemIntroInvited -> "intro-inv" GSMemAccepted -> "accepted" GSMemAnnounced -> "announced" GSMemConnected -> "connected" GSMemComplete -> "complete" GSMemCreator -> "creator" data SndFileTransfer = SndFileTransfer { fileId :: FileTransferId, fileName :: String, filePath :: String, fileSize :: Integer, chunkSize :: Integer, recipientDisplayName :: ContactName, connId :: Int64, agentConnId :: AgentConnId, fileStatus :: FileStatus, fileInline :: Maybe InlineFileMode } deriving (Eq, Show, Generic) instance ToJSON SndFileTransfer where toEncoding = J.genericToEncoding J.defaultOptions sndFileTransferConnId :: SndFileTransfer -> ConnId sndFileTransferConnId SndFileTransfer {agentConnId = AgentConnId acId} = acId type FileTransferId = Int64 data FileInvitation = FileInvitation { fileName :: String, fileSize :: Integer, fileConnReq :: Maybe ConnReqInvitation, fileInline :: Maybe InlineFileMode } deriving (Eq, Show, Generic) instance ToJSON FileInvitation where toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} instance FromJSON FileInvitation where parseJSON = J.genericParseJSON J.defaultOptions {J.omitNothingFields = True} data InlineFileMode = IFMOffer -- file will be sent inline once accepted | IFMSent -- file is sent inline without acceptance deriving (Eq, Show, Generic) instance TextEncoding InlineFileMode where textEncode = \case IFMOffer -> "offer" IFMSent -> "sent" textDecode = \case "offer" -> Just IFMOffer "sent" -> Just IFMSent _ -> Nothing instance FromField InlineFileMode where fromField = fromTextField_ textDecode instance ToField InlineFileMode where toField = toField . textEncode instance FromJSON InlineFileMode where parseJSON = J.withText "InlineFileMode" $ maybe (fail "bad InlineFileMode") pure . textDecode instance ToJSON InlineFileMode where toJSON = J.String . textEncode toEncoding = JE.text . textEncode data RcvFileTransfer = RcvFileTransfer { fileId :: FileTransferId, fileInvitation :: FileInvitation, fileStatus :: RcvFileStatus, rcvFileInline :: Maybe InlineFileMode, senderDisplayName :: ContactName, chunkSize :: Integer, cancelled :: Bool, grpMemberId :: Maybe Int64 } deriving (Eq, Show, Generic) instance ToJSON RcvFileTransfer where toEncoding = J.genericToEncoding J.defaultOptions data RcvFileStatus = RFSNew | RFSAccepted RcvFileInfo | RFSConnected RcvFileInfo | RFSComplete RcvFileInfo | RFSCancelled (Maybe RcvFileInfo) deriving (Eq, Show, Generic) instance ToJSON RcvFileStatus where toJSON = J.genericToJSON . sumTypeJSON $ dropPrefix "RFS" toEncoding = J.genericToEncoding . sumTypeJSON $ dropPrefix "RFS" data RcvFileInfo = RcvFileInfo { filePath :: FilePath, connId :: Maybe Int64, agentConnId :: Maybe AgentConnId } deriving (Eq, Show, Generic) instance ToJSON RcvFileInfo where toEncoding = J.genericToEncoding J.defaultOptions liveRcvFileTransferConnId :: RcvFileTransfer -> Maybe ConnId liveRcvFileTransferConnId RcvFileTransfer {fileStatus} = case fileStatus of RFSAccepted fi -> acId fi RFSConnected fi -> acId fi _ -> Nothing where acId RcvFileInfo {agentConnId = Just (AgentConnId cId)} = Just cId acId _ = Nothing newtype AgentConnId = AgentConnId ConnId deriving (Eq, Show) instance StrEncoding AgentConnId where strEncode (AgentConnId connId) = strEncode connId strDecode s = AgentConnId <$> strDecode s strP = AgentConnId <$> strP instance ToJSON AgentConnId where toJSON = strToJSON toEncoding = strToJEncoding instance FromField AgentConnId where fromField f = AgentConnId <$> fromField f instance ToField AgentConnId where toField (AgentConnId m) = toField m newtype AgentInvId = AgentInvId InvitationId deriving (Eq, Show) instance StrEncoding AgentInvId where strEncode (AgentInvId connId) = strEncode connId strDecode s = AgentInvId <$> strDecode s strP = AgentInvId <$> strP instance ToJSON AgentInvId where toJSON = strToJSON toEncoding = strToJEncoding instance FromField AgentInvId where fromField f = AgentInvId <$> fromField f instance ToField AgentInvId where toField (AgentInvId m) = toField m data FileTransfer = FTSnd { fileTransferMeta :: FileTransferMeta, sndFileTransfers :: [SndFileTransfer] } | FTRcv {rcvFileTransfer :: RcvFileTransfer} deriving (Show, Generic) instance ToJSON FileTransfer where toJSON = J.genericToJSON . sumTypeJSON $ dropPrefix "FT" toEncoding = J.genericToEncoding . sumTypeJSON $ dropPrefix "FT" data FileTransferMeta = FileTransferMeta { fileId :: FileTransferId, fileName :: String, filePath :: String, fileSize :: Integer, fileInline :: Maybe InlineFileMode, chunkSize :: Integer, cancelled :: Bool } deriving (Eq, Show, Generic) instance ToJSON FileTransferMeta where toEncoding = J.genericToEncoding J.defaultOptions fileTransferCancelled :: FileTransfer -> Bool fileTransferCancelled (FTSnd FileTransferMeta {cancelled} _) = cancelled fileTransferCancelled (FTRcv RcvFileTransfer {cancelled}) = cancelled data FileStatus = FSNew | FSAccepted | FSConnected | FSComplete | FSCancelled deriving (Eq, Ord, Show) instance FromField FileStatus where fromField = fromTextField_ textDecode instance ToField FileStatus where toField = toField . textEncode instance ToJSON FileStatus where toJSON = J.String . textEncode toEncoding = JE.text . textEncode instance TextEncoding FileStatus where textDecode = \case "new" -> Just FSNew "accepted" -> Just FSAccepted "connected" -> Just FSConnected "complete" -> Just FSComplete "cancelled" -> Just FSCancelled _ -> Nothing textEncode = \case FSNew -> "new" FSAccepted -> "accepted" FSConnected -> "connected" FSComplete -> "complete" FSCancelled -> "cancelled" data RcvChunkStatus = RcvChunkOk | RcvChunkFinal | RcvChunkDuplicate | RcvChunkError deriving (Eq, Show) type ConnReqInvitation = ConnectionRequestUri 'CMInvitation type ConnReqContact = ConnectionRequestUri 'CMContact data Connection = Connection { connId :: Int64, agentConnId :: AgentConnId, connLevel :: Int, viaContact :: Maybe Int64, -- group member contact ID, if not direct connection viaUserContactLink :: Maybe Int64, -- user contact link ID, if connected via "user address" viaGroupLink :: Bool, -- whether contact connected via group link groupLinkId :: Maybe GroupLinkId, customUserProfileId :: Maybe Int64, connType :: ConnType, connStatus :: ConnStatus, localAlias :: Text, entityId :: Maybe Int64, -- contact, group member, file ID or user contact ID connectionCode :: Maybe SecurityCode, authErrCounter :: Int, createdAt :: UTCTime } deriving (Eq, Show, Generic) authErrDisableCount :: Int authErrDisableCount = 10 connDisabled :: Connection -> Bool connDisabled Connection {authErrCounter} = authErrCounter >= authErrDisableCount data SecurityCode = SecurityCode {securityCode :: Text, verifiedAt :: UTCTime} deriving (Eq, Show, Generic) instance ToJSON SecurityCode where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} verificationCode :: ByteString -> Text verificationCode = T.pack . unwords . chunks 5 . show . os2ip where chunks _ [] = [] chunks n xs = let (h, t) = splitAt n xs in h : chunks n t sameVerificationCode :: Text -> Text -> Bool sameVerificationCode c1 c2 = noSpaces c1 == noSpaces c2 where noSpaces = T.filter (/= ' ') aConnId :: Connection -> ConnId aConnId Connection {agentConnId = AgentConnId cId} = cId connIncognito :: Connection -> Bool connIncognito Connection {customUserProfileId} = isJust customUserProfileId instance ToJSON Connection where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} data PendingContactConnection = PendingContactConnection { pccConnId :: Int64, pccAgentConnId :: AgentConnId, pccConnStatus :: ConnStatus, viaContactUri :: Bool, viaUserContactLink :: Maybe Int64, groupLinkId :: Maybe GroupLinkId, customUserProfileId :: Maybe Int64, connReqInv :: Maybe ConnReqInvitation, localAlias :: Text, createdAt :: UTCTime, updatedAt :: UTCTime } deriving (Eq, Show, Generic) aConnId' :: PendingContactConnection -> ConnId aConnId' PendingContactConnection {pccAgentConnId = AgentConnId cId} = cId instance ToJSON PendingContactConnection where toEncoding = J.genericToEncoding J.defaultOptions data ConnStatus = -- | connection is created by initiating party with agent NEW command (createConnection) ConnNew | -- | connection is joined by joining party with agent JOIN command (joinConnection) ConnJoined | initiating party received CONF notification ( to be renamed to REQ ) ConnRequested | -- | initiating party accepted connection with agent LET command (to be renamed to ACPT) (allowConnection) ConnAccepted | -- | connection can be sent messages to (after joining party received INFO notification) ConnSndReady | -- | connection is ready for both parties to send and receive messages ConnReady | -- | connection deleted ConnDeleted deriving (Eq, Show, Read) instance FromField ConnStatus where fromField = fromTextField_ textDecode instance ToField ConnStatus where toField = toField . textEncode instance ToJSON ConnStatus where toJSON = J.String . textEncode toEncoding = JE.text . textEncode instance TextEncoding ConnStatus where textDecode = \case "new" -> Just ConnNew "joined" -> Just ConnJoined "requested" -> Just ConnRequested "accepted" -> Just ConnAccepted "snd-ready" -> Just ConnSndReady "ready" -> Just ConnReady "deleted" -> Just ConnDeleted _ -> Nothing textEncode = \case ConnNew -> "new" ConnJoined -> "joined" ConnRequested -> "requested" ConnAccepted -> "accepted" ConnSndReady -> "snd-ready" ConnReady -> "ready" ConnDeleted -> "deleted" data ConnType = ConnContact | ConnMember | ConnSndFile | ConnRcvFile | ConnUserContact deriving (Eq, Show) instance FromField ConnType where fromField = fromTextField_ textDecode instance ToField ConnType where toField = toField . textEncode instance ToJSON ConnType where toJSON = J.String . textEncode toEncoding = JE.text . textEncode instance TextEncoding ConnType where textDecode = \case "contact" -> Just ConnContact "member" -> Just ConnMember "snd_file" -> Just ConnSndFile "rcv_file" -> Just ConnRcvFile "user_contact" -> Just ConnUserContact _ -> Nothing textEncode = \case ConnContact -> "contact" ConnMember -> "member" ConnSndFile -> "snd_file" ConnRcvFile -> "rcv_file" ConnUserContact -> "user_contact" data NewConnection = NewConnection { agentConnId :: ByteString, connLevel :: Int, viaConn :: Maybe Int64 } data GroupMemberIntro = GroupMemberIntro { introId :: Int64, reMember :: GroupMember, toMember :: GroupMember, introStatus :: GroupMemberIntroStatus, introInvitation :: Maybe IntroInvitation } deriving (Show) data GroupMemberIntroStatus = GMIntroPending | GMIntroSent | GMIntroInvReceived | GMIntroInvForwarded | GMIntroReConnected | GMIntroToConnected | GMIntroConnected deriving (Show) instance FromField GroupMemberIntroStatus where fromField = fromTextField_ introStatusT instance ToField GroupMemberIntroStatus where toField = toField . serializeIntroStatus introStatusT :: Text -> Maybe GroupMemberIntroStatus introStatusT = \case "new" -> Just GMIntroPending "sent" -> Just GMIntroSent "rcv" -> Just GMIntroInvReceived "fwd" -> Just GMIntroInvForwarded "re-con" -> Just GMIntroReConnected "to-con" -> Just GMIntroToConnected "con" -> Just GMIntroConnected _ -> Nothing serializeIntroStatus :: GroupMemberIntroStatus -> Text serializeIntroStatus = \case GMIntroPending -> "new" GMIntroSent -> "sent" GMIntroInvReceived -> "rcv" GMIntroInvForwarded -> "fwd" GMIntroReConnected -> "re-con" GMIntroToConnected -> "to-con" GMIntroConnected -> "con" data Notification = Notification {title :: Text, text :: Text} type JSONString = String textParseJSON :: TextEncoding a => String -> J.Value -> JT.Parser a textParseJSON name = J.withText name $ maybe (fail $ "bad " <> name) pure . textDecode type CommandId = Int64 aCorrId :: CommandId -> ACorrId aCorrId = pack . show commandId :: ACorrId -> String commandId = unpack data CommandStatus = CSCreated | CSCompleted -- unused - was replaced with deleteCommand internal command error , e.g. not matching connection i d or unexpected response , not related to agent message deriving (Show, Generic) instance FromField CommandStatus where fromField = fromTextField_ textDecode instance ToField CommandStatus where toField = toField . textEncode instance TextEncoding CommandStatus where textDecode = \case "created" -> Just CSCreated "completed" -> Just CSCompleted "error" -> Just CSError _ -> Nothing textEncode = \case CSCreated -> "created" CSCompleted -> "completed" CSError -> "error" data CommandFunction = CFCreateConnGrpMemInv | CFCreateConnGrpInv | CFCreateConnFileInvDirect | CFCreateConnFileInvGroup | CFJoinConn | CFAllowConn | CFAcceptContact | CFAckMessage | CFDeleteConn -- not used deriving (Eq, Show, Generic) instance FromField CommandFunction where fromField = fromTextField_ textDecode instance ToField CommandFunction where toField = toField . textEncode instance TextEncoding CommandFunction where textDecode = \case "create_conn" -> Just CFCreateConnGrpMemInv "create_conn_grp_inv" -> Just CFCreateConnGrpInv "create_conn_file_inv_direct" -> Just CFCreateConnFileInvDirect "create_conn_file_inv_group" -> Just CFCreateConnFileInvGroup "join_conn" -> Just CFJoinConn "allow_conn" -> Just CFAllowConn "accept_contact" -> Just CFAcceptContact "ack_message" -> Just CFAckMessage "delete_conn" -> Just CFDeleteConn _ -> Nothing textEncode = \case CFCreateConnGrpMemInv -> "create_conn" CFCreateConnGrpInv -> "create_conn_grp_inv" CFCreateConnFileInvDirect -> "create_conn_file_inv_direct" CFCreateConnFileInvGroup -> "create_conn_file_inv_group" CFJoinConn -> "join_conn" CFAllowConn -> "allow_conn" CFAcceptContact -> "accept_contact" CFAckMessage -> "ack_message" CFDeleteConn -> "delete_conn" commandExpectedResponse :: CommandFunction -> ACommandTag 'Agent commandExpectedResponse = \case CFCreateConnGrpMemInv -> INV_ CFCreateConnGrpInv -> INV_ CFCreateConnFileInvDirect -> INV_ CFCreateConnFileInvGroup -> INV_ CFJoinConn -> OK_ CFAllowConn -> OK_ CFAcceptContact -> OK_ CFAckMessage -> OK_ CFDeleteConn -> OK_ data CommandData = CommandData { cmdId :: CommandId, cmdConnId :: Maybe Int64, cmdFunction :: CommandFunction, cmdStatus :: CommandStatus } deriving (Show) ad - hoc type for data required for XGrpMemIntro continuation data XGrpMemIntroCont = XGrpMemIntroCont { groupId :: GroupId, groupMemberId :: GroupMemberId, memberId :: MemberId, groupConnReq :: ConnReqInvitation } deriving (Show) encodeJSON :: ToJSON a => a -> Text encodeJSON = safeDecodeUtf8 . LB.toStrict . J.encode decodeJSON :: FromJSON a => Text -> Maybe a decodeJSON = J.decode . LB.fromStrict . encodeUtf8 data ServerCfg = ServerCfg { server :: SMPServerWithAuth, preset :: Bool, tested :: Maybe Bool, enabled :: Bool } deriving (Show, Generic) instance ToJSON ServerCfg where toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} instance FromJSON ServerCfg where parseJSON = J.genericParseJSON J.defaultOptions {J.omitNothingFields = True}
null
https://raw.githubusercontent.com/simplex-chat/simplex-chat/c8fae0ec4390c40675ac9f9aa9924d5da87edbb2/src/Simplex/Chat/Types.hs
haskell
# LANGUAGE ConstraintKinds # # LANGUAGE DeriveAnyClass # # LANGUAGE GADTs # # LANGUAGE OverloadedStrings # # LANGUAGE StrictData # # OPTIONS_GHC -Wno-unrecognised-pragmas # # HLINT ignore "Use newtype instead of data" # # INLINE profile' # # INLINE localDisplayName' # # INLINE preferences' # # INLINE profile' # # INLINE localDisplayName' # # INLINE preferences' # connection id of user contact TODO when more settings are added we should create another type to allow partial setting updates (with all Maybe properties) | CFReceipts collection of optional chat preferences for the user and the contact | GFReceipts collection of optional group preferences full collection of chat preferences defined in the app - it is used to ensure we include all preferences and to simplify processing if some of the preferences are not defined in Preferences, defaults from defaultChatPrefs are used here. full collection of group preferences defined in the app - it is used to ensure we include all preferences and to simplify processing if some of the preferences are not defined in GroupPreferences, defaults from defaultGroupPrefs are used here. merged preferences of user for a given contact - they differentiate between specific preferences for the contact and global user preferences receipts = Just receipts, allow unconditionally allow, if peer allows it do not allow incognito contact cannot have default user preference used fields that should not be read into this data type to prevent sending them as part of profile to contacts: - contact_profile_id - incognito - local_alias check if profiles match ignoring preferences used to identify invitation via group link memberProfile's profileId is COALESCE(member_profile_id, contact_profile_id), member_profile_id is non null if incognito profile was saved for member (used for hosts and invitees in incognito groups) connects to all group members and receives all messages, can't send messages reserved, unused + can send messages to all group members + add/remove members, change member role (excl. Owners) + delete and change group information, add/remove/change roles for Owners member invited by the user member who invited the user member who joined before the user and was introduced to the user (user receives x.grp.mem.intro about such members) member who joined after the user to whom the user was introduced (user receives x.grp.mem.new announcing these members and then x.grp.mem.fwd with invitation from these members) member who was removed from the group member who left the group user member of the deleted group member is sent to or received invitation to join the group member is sent to or received from intro invitation member accepted invitation (only User and Invitee) host announced (x.grp.mem.new) a member (Invitee and PostMember) to the group - at this point this member can send messages and invite other members (if they have sufficient permissions) member created the group connection with the inviting member user member that created the group (only GCUserMember) file will be sent inline once accepted file is sent inline without acceptance group member contact ID, if not direct connection user contact link ID, if connected via "user address" whether contact connected via group link contact, group member, file ID or user contact ID | connection is created by initiating party with agent NEW command (createConnection) | connection is joined by joining party with agent JOIN command (joinConnection) | initiating party accepted connection with agent LET command (to be renamed to ACPT) (allowConnection) | connection can be sent messages to (after joining party received INFO notification) | connection is ready for both parties to send and receive messages | connection deleted unused - was replaced with deleteCommand not used
# LANGUAGE AllowAmbiguousTypes # # LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE DuplicateRecordFields # # LANGUAGE FlexibleContexts # # LANGUAGE FlexibleInstances # # LANGUAGE LambdaCase # # LANGUAGE MultiParamTypeClasses # # LANGUAGE NamedFieldPuns # # LANGUAGE PatternSynonyms # # LANGUAGE ScopedTypeVariables # # LANGUAGE StandaloneDeriving # # LANGUAGE TypeApplications # # LANGUAGE TypeFamilyDependencies # # LANGUAGE UndecidableInstances # module Simplex.Chat.Types where import Control.Applicative ((<|>)) import Crypto.Number.Serialize (os2ip) import Data.Aeson (FromJSON, ToJSON) import qualified Data.Aeson as J import qualified Data.Aeson.Encoding as JE import qualified Data.Aeson.Types as JT import qualified Data.Attoparsec.ByteString.Char8 as A import Data.ByteString.Char8 (ByteString, pack, unpack) import qualified Data.ByteString.Char8 as B import qualified Data.ByteString.Lazy.Char8 as LB import Data.Int (Int64) import Data.Maybe (fromMaybe, isJust) import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (encodeUtf8) import Data.Time.Clock (UTCTime) import Data.Typeable import Database.SQLite.Simple (ResultError (..), SQLData (..)) import Database.SQLite.Simple.FromField (FieldParser, FromField (..), returnError) import Database.SQLite.Simple.Internal (Field (..)) import Database.SQLite.Simple.Ok (Ok (Ok)) import Database.SQLite.Simple.ToField (ToField (..)) import GHC.Generics (Generic) import GHC.Records.Compat import Simplex.Messaging.Agent.Protocol (ACommandTag (..), ACorrId, AParty (..), ConnId, ConnectionMode (..), ConnectionRequestUri, InvitationId) import Simplex.Messaging.Encoding.String import Simplex.Messaging.Parsers (dropPrefix, enumJSON, fromTextField_, sumTypeJSON, taggedObjectJSON) import Simplex.Messaging.Protocol (SMPServerWithAuth) import Simplex.Messaging.Util (safeDecodeUtf8, (<$?>)) class IsContact a where contactId' :: a -> ContactId profile' :: a -> LocalProfile localDisplayName' :: a -> ContactName preferences' :: a -> Maybe Preferences instance IsContact User where contactId' = userContactId # INLINE contactId ' # profile' = profile localDisplayName' = localDisplayName preferences' User {profile = LocalProfile {preferences}} = preferences instance IsContact Contact where contactId' = contactId # INLINE contactId ' # profile' = profile localDisplayName' = localDisplayName preferences' Contact {profile = LocalProfile {preferences}} = preferences newtype AgentUserId = AgentUserId UserId deriving (Eq, Show) instance StrEncoding AgentUserId where strEncode (AgentUserId uId) = strEncode uId strDecode s = AgentUserId <$> strDecode s strP = AgentUserId <$> strP instance FromJSON AgentUserId where parseJSON = strParseJSON "AgentUserId" instance ToJSON AgentUserId where toJSON = strToJSON toEncoding = strToJEncoding instance FromField AgentUserId where fromField f = AgentUserId <$> fromField f instance ToField AgentUserId where toField (AgentUserId uId) = toField uId aUserId :: User -> UserId aUserId User {agentUserId = AgentUserId uId} = uId data User = User { userId :: UserId, agentUserId :: AgentUserId, userContactId :: ContactId, localDisplayName :: ContactName, profile :: LocalProfile, fullPreferences :: FullPreferences, activeUser :: Bool } deriving (Show, Generic, FromJSON) instance ToJSON User where toEncoding = J.genericToEncoding J.defaultOptions data UserInfo = UserInfo { user :: User, unreadCount :: Int } deriving (Show, Generic, FromJSON) instance ToJSON UserInfo where toJSON = J.genericToJSON J.defaultOptions toEncoding = J.genericToEncoding J.defaultOptions type UserId = Int64 type ContactId = Int64 type ProfileId = Int64 data Contact = Contact { contactId :: ContactId, localDisplayName :: ContactName, profile :: LocalProfile, activeConn :: Connection, viaGroup :: Maybe Int64, contactUsed :: Bool, chatSettings :: ChatSettings, userPreferences :: Preferences, mergedPreferences :: ContactUserPreferences, createdAt :: UTCTime, updatedAt :: UTCTime, chatTs :: Maybe UTCTime } deriving (Eq, Show, Generic) instance ToJSON Contact where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} contactConn :: Contact -> Connection contactConn = activeConn contactConnId :: Contact -> ConnId contactConnId = aConnId . contactConn contactConnIncognito :: Contact -> Bool contactConnIncognito = connIncognito . contactConn directOrUsed :: Contact -> Bool directOrUsed Contact {contactUsed, activeConn = Connection {connLevel, viaGroupLink}} = (connLevel == 0 && not viaGroupLink) || contactUsed anyDirectOrUsed :: Contact -> Bool anyDirectOrUsed Contact {contactUsed, activeConn = Connection {connLevel}} = connLevel == 0 || contactUsed contactSecurityCode :: Contact -> Maybe SecurityCode contactSecurityCode Contact {activeConn} = connectionCode activeConn data ContactRef = ContactRef { contactId :: ContactId, connId :: Int64, agentConnId :: AgentConnId, localDisplayName :: ContactName } deriving (Eq, Show, Generic) instance ToJSON ContactRef where toEncoding = J.genericToEncoding J.defaultOptions data UserContact = UserContact { userContactLinkId :: Int64, connReqContact :: ConnReqContact, groupId :: Maybe GroupId } deriving (Eq, Show, Generic) userContactGroupId :: UserContact -> Maybe GroupId userContactGroupId UserContact {groupId} = groupId instance ToJSON UserContact where toJSON = J.genericToJSON J.defaultOptions toEncoding = J.genericToEncoding J.defaultOptions data UserContactRequest = UserContactRequest { contactRequestId :: Int64, agentInvitationId :: AgentInvId, userContactLinkId :: Int64, localDisplayName :: ContactName, profileId :: Int64, profile :: Profile, createdAt :: UTCTime, updatedAt :: UTCTime, xContactId :: Maybe XContactId } deriving (Eq, Show, Generic) instance ToJSON UserContactRequest where toEncoding = J.genericToEncoding J.defaultOptions newtype XContactId = XContactId ByteString deriving (Eq, Show) instance FromField XContactId where fromField f = XContactId <$> fromField f instance ToField XContactId where toField (XContactId m) = toField m instance StrEncoding XContactId where strEncode (XContactId m) = strEncode m strDecode s = XContactId <$> strDecode s strP = XContactId <$> strP instance FromJSON XContactId where parseJSON = strParseJSON "XContactId" instance ToJSON XContactId where toJSON = strToJSON toEncoding = strToJEncoding newtype ConnReqUriHash = ConnReqUriHash {unConnReqUriHash :: ByteString} deriving (Eq, Show) instance FromField ConnReqUriHash where fromField f = ConnReqUriHash <$> fromField f instance ToField ConnReqUriHash where toField (ConnReqUriHash m) = toField m instance StrEncoding ConnReqUriHash where strEncode (ConnReqUriHash m) = strEncode m strDecode s = ConnReqUriHash <$> strDecode s strP = ConnReqUriHash <$> strP instance FromJSON ConnReqUriHash where parseJSON = strParseJSON "ConnReqUriHash" instance ToJSON ConnReqUriHash where toJSON = strToJSON toEncoding = strToJEncoding data ContactOrRequest = CORContact Contact | CORRequest UserContactRequest type UserName = Text type ContactName = Text type GroupName = Text optionalFullName :: ContactName -> Text -> Text optionalFullName displayName fullName | T.null fullName || displayName == fullName = "" | otherwise = " (" <> fullName <> ")" data Group = Group {groupInfo :: GroupInfo, members :: [GroupMember]} deriving (Eq, Show, Generic) instance ToJSON Group where toEncoding = J.genericToEncoding J.defaultOptions type GroupId = Int64 data GroupInfo = GroupInfo { groupId :: GroupId, localDisplayName :: GroupName, groupProfile :: GroupProfile, fullGroupPreferences :: FullGroupPreferences, membership :: GroupMember, hostConnCustomUserProfileId :: Maybe ProfileId, chatSettings :: ChatSettings, createdAt :: UTCTime, updatedAt :: UTCTime, chatTs :: Maybe UTCTime } deriving (Eq, Show, Generic) instance ToJSON GroupInfo where toEncoding = J.genericToEncoding J.defaultOptions groupName' :: GroupInfo -> GroupName groupName' GroupInfo {localDisplayName = g} = g data ChatSettings = ChatSettings { enableNtfs :: Bool } deriving (Eq, Show, Generic, FromJSON) instance ToJSON ChatSettings where toEncoding = J.genericToEncoding J.defaultOptions defaultChatSettings :: ChatSettings defaultChatSettings = ChatSettings {enableNtfs = True} pattern DisableNtfs :: ChatSettings pattern DisableNtfs = ChatSettings {enableNtfs = False} data ChatFeature = CFTimedMessages | CFFullDelete CFVoice deriving (Show, Generic) data SChatFeature (f :: ChatFeature) where SCFTimedMessages :: SChatFeature 'CFTimedMessages SCFFullDelete :: SChatFeature 'CFFullDelete SCFVoice :: SChatFeature 'CFVoice deriving instance Show (SChatFeature f) data AChatFeature = forall f. FeatureI f => ACF (SChatFeature f) deriving instance Show AChatFeature chatFeatureNameText :: ChatFeature -> Text chatFeatureNameText = \case CFTimedMessages -> "Disappearing messages" CFFullDelete -> "Full deletion" CFVoice -> "Voice messages" chatFeatureNameText' :: SChatFeature f -> Text chatFeatureNameText' = chatFeatureNameText . chatFeature featureAllowed :: SChatFeature f -> (PrefEnabled -> Bool) -> Contact -> Bool featureAllowed feature forWhom Contact {mergedPreferences} = let ContactUserPreference {enabled} = getContactUserPreference feature mergedPreferences in forWhom enabled instance ToJSON ChatFeature where toEncoding = J.genericToEncoding . enumJSON $ dropPrefix "CF" toJSON = J.genericToJSON . enumJSON $ dropPrefix "CF" instance FromJSON ChatFeature where parseJSON = J.genericParseJSON . enumJSON $ dropPrefix "CF" allChatFeatures :: [AChatFeature] allChatFeatures = [ ACF SCFTimedMessages, ACF SCFFullDelete, CFReceipts , ACF SCFVoice ] chatPrefSel :: SChatFeature f -> Preferences -> Maybe (FeaturePreference f) chatPrefSel = \case SCFTimedMessages -> timedMessages SCFFullDelete -> fullDelete CFReceipts - > receipts SCFVoice -> voice chatFeature :: SChatFeature f -> ChatFeature chatFeature = \case SCFTimedMessages -> CFTimedMessages SCFFullDelete -> CFFullDelete SCFVoice -> CFVoice class PreferenceI p where getPreference :: SChatFeature f -> p -> FeaturePreference f instance PreferenceI Preferences where getPreference f prefs = fromMaybe (getPreference f defaultChatPrefs) (chatPrefSel f prefs) instance PreferenceI (Maybe Preferences) where getPreference f prefs = fromMaybe (getPreference f defaultChatPrefs) (chatPrefSel f =<< prefs) instance PreferenceI FullPreferences where getPreference = \case SCFTimedMessages -> timedMessages SCFFullDelete -> fullDelete CFReceipts - > receipts SCFVoice -> voice # INLINE getPreference # setPreference :: forall f. FeatureI f => SChatFeature f -> Maybe FeatureAllowed -> Maybe Preferences -> Preferences setPreference f allow_ prefs_ = setPreference_ f pref $ fromMaybe emptyChatPrefs prefs_ where pref = setAllow <$> allow_ setAllow :: FeatureAllowed -> FeaturePreference f setAllow = setField @"allow" (getPreference f prefs) prefs = mergePreferences Nothing prefs_ setPreference' :: SChatFeature f -> Maybe (FeaturePreference f) -> Maybe Preferences -> Preferences setPreference' f pref_ prefs_ = setPreference_ f pref_ $ fromMaybe emptyChatPrefs prefs_ setPreference_ :: SChatFeature f -> Maybe (FeaturePreference f) -> Preferences -> Preferences setPreference_ f pref_ prefs = case f of SCFTimedMessages -> prefs {timedMessages = pref_} SCFFullDelete -> prefs {fullDelete = pref_} SCFVoice -> prefs {voice = pref_} data Preferences = Preferences { timedMessages :: Maybe TimedMessagesPreference, fullDelete :: Maybe FullDeletePreference, receipts : : Maybe SimplePreference , voice :: Maybe VoicePreference } deriving (Eq, Show, Generic, FromJSON) instance ToJSON Preferences where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} instance ToField Preferences where toField = toField . encodeJSON instance FromField Preferences where fromField = fromTextField_ decodeJSON data GroupFeature = GFTimedMessages | GFDirectMessages | GFFullDelete GFVoice deriving (Show, Generic) data SGroupFeature (f :: GroupFeature) where SGFTimedMessages :: SGroupFeature 'GFTimedMessages SGFDirectMessages :: SGroupFeature 'GFDirectMessages SGFFullDelete :: SGroupFeature 'GFFullDelete SGFReceipts SGFVoice :: SGroupFeature 'GFVoice deriving instance Show (SGroupFeature f) data AGroupFeature = forall f. GroupFeatureI f => AGF (SGroupFeature f) deriving instance Show AGroupFeature groupFeatureNameText :: GroupFeature -> Text groupFeatureNameText = \case GFTimedMessages -> "Disappearing messages" GFDirectMessages -> "Direct messages" GFFullDelete -> "Full deletion" GFVoice -> "Voice messages" groupFeatureNameText' :: SGroupFeature f -> Text groupFeatureNameText' = groupFeatureNameText . toGroupFeature groupFeatureAllowed :: GroupFeatureI f => SGroupFeature f -> GroupInfo -> Bool groupFeatureAllowed feature gInfo = groupFeatureAllowed' feature $ fullGroupPreferences gInfo groupFeatureAllowed' :: GroupFeatureI f => SGroupFeature f -> FullGroupPreferences -> Bool groupFeatureAllowed' feature prefs = getField @"enable" (getGroupPreference feature prefs) == FEOn instance ToJSON GroupFeature where toEncoding = J.genericToEncoding . enumJSON $ dropPrefix "GF" toJSON = J.genericToJSON . enumJSON $ dropPrefix "GF" instance FromJSON GroupFeature where parseJSON = J.genericParseJSON . enumJSON $ dropPrefix "GF" allGroupFeatures :: [AGroupFeature] allGroupFeatures = [ AGF SGFTimedMessages, AGF SGFDirectMessages, AGF SGFFullDelete, GFReceipts , AGF SGFVoice ] groupPrefSel :: SGroupFeature f -> GroupPreferences -> Maybe (GroupFeaturePreference f) groupPrefSel = \case SGFTimedMessages -> timedMessages SGFDirectMessages -> directMessages SGFFullDelete -> fullDelete GFReceipts - > receipts SGFVoice -> voice toGroupFeature :: SGroupFeature f -> GroupFeature toGroupFeature = \case SGFTimedMessages -> GFTimedMessages SGFDirectMessages -> GFDirectMessages SGFFullDelete -> GFFullDelete SGFVoice -> GFVoice class GroupPreferenceI p where getGroupPreference :: SGroupFeature f -> p -> GroupFeaturePreference f instance GroupPreferenceI GroupPreferences where getGroupPreference pt prefs = fromMaybe (getGroupPreference pt defaultGroupPrefs) (groupPrefSel pt prefs) instance GroupPreferenceI (Maybe GroupPreferences) where getGroupPreference pt prefs = fromMaybe (getGroupPreference pt defaultGroupPrefs) (groupPrefSel pt =<< prefs) instance GroupPreferenceI FullGroupPreferences where getGroupPreference = \case SGFTimedMessages -> timedMessages SGFDirectMessages -> directMessages SGFFullDelete -> fullDelete GFReceipts - > receipts SGFVoice -> voice # INLINE getGroupPreference # data GroupPreferences = GroupPreferences { timedMessages :: Maybe TimedMessagesGroupPreference, directMessages :: Maybe DirectMessagesGroupPreference, fullDelete :: Maybe FullDeleteGroupPreference, receipts : : Maybe GroupPreference , voice :: Maybe VoiceGroupPreference } deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupPreferences where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} instance ToField GroupPreferences where toField = toField . encodeJSON instance FromField GroupPreferences where fromField = fromTextField_ decodeJSON setGroupPreference :: forall f. GroupFeatureI f => SGroupFeature f -> GroupFeatureEnabled -> Maybe GroupPreferences -> GroupPreferences setGroupPreference f enable prefs_ = setGroupPreference_ f pref prefs where prefs = mergeGroupPreferences prefs_ pref :: GroupFeaturePreference f pref = setField @"enable" (getGroupPreference f prefs) enable setGroupPreference' :: SGroupFeature f -> GroupFeaturePreference f -> Maybe GroupPreferences -> GroupPreferences setGroupPreference' f pref prefs_ = setGroupPreference_ f pref prefs where prefs = mergeGroupPreferences prefs_ setGroupPreference_ :: SGroupFeature f -> GroupFeaturePreference f -> FullGroupPreferences -> GroupPreferences setGroupPreference_ f pref prefs = toGroupPreferences $ case f of SGFTimedMessages -> prefs {timedMessages = pref} SGFDirectMessages -> prefs {directMessages = pref} SGFVoice -> prefs {voice = pref} SGFFullDelete -> prefs {fullDelete = pref} setGroupTimedMessagesPreference :: TimedMessagesGroupPreference -> Maybe GroupPreferences -> GroupPreferences setGroupTimedMessagesPreference pref prefs_ = toGroupPreferences $ prefs {timedMessages = pref} where prefs = mergeGroupPreferences prefs_ data FullPreferences = FullPreferences { timedMessages :: TimedMessagesPreference, fullDelete :: FullDeletePreference, receipts : : SimplePreference , voice :: VoicePreference } deriving (Eq, Show, Generic, FromJSON) instance ToJSON FullPreferences where toEncoding = J.genericToEncoding J.defaultOptions data FullGroupPreferences = FullGroupPreferences { timedMessages :: TimedMessagesGroupPreference, directMessages :: DirectMessagesGroupPreference, fullDelete :: FullDeleteGroupPreference, receipts : : GroupPreference , voice :: VoiceGroupPreference } deriving (Eq, Show, Generic, FromJSON) instance ToJSON FullGroupPreferences where toEncoding = J.genericToEncoding J.defaultOptions data ContactUserPreferences = ContactUserPreferences { timedMessages :: ContactUserPreference TimedMessagesPreference, fullDelete :: ContactUserPreference FullDeletePreference, receipts : : ContactUserPreference , voice :: ContactUserPreference VoicePreference } deriving (Eq, Show, Generic) data ContactUserPreference p = ContactUserPreference { enabled :: PrefEnabled, userPreference :: ContactUserPref p, contactPreference :: p } deriving (Eq, Show, Generic) data ContactUserPref p = CUPContact {preference :: p} | CUPUser {preference :: p} deriving (Eq, Show, Generic) instance ToJSON ContactUserPreferences where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON p => ToJSON (ContactUserPreference p) where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON p => ToJSON (ContactUserPref p) where toJSON = J.genericToJSON . sumTypeJSON $ dropPrefix "CUP" toEncoding = J.genericToEncoding . sumTypeJSON $ dropPrefix "CUP" toChatPrefs :: FullPreferences -> Preferences toChatPrefs FullPreferences {fullDelete, voice, timedMessages} = Preferences { timedMessages = Just timedMessages, fullDelete = Just fullDelete, voice = Just voice } defaultChatPrefs :: FullPreferences defaultChatPrefs = FullPreferences { timedMessages = TimedMessagesPreference {allow = FANo, ttl = Nothing}, fullDelete = FullDeletePreference {allow = FANo}, receipts = SimplePreference { allow = FANo } , voice = VoicePreference {allow = FAYes} } emptyChatPrefs :: Preferences emptyChatPrefs = Preferences Nothing Nothing Nothing defaultGroupPrefs :: FullGroupPreferences defaultGroupPrefs = FullGroupPreferences { timedMessages = TimedMessagesGroupPreference {enable = FEOff, ttl = 86400}, directMessages = DirectMessagesGroupPreference {enable = FEOff}, fullDelete = FullDeleteGroupPreference {enable = FEOff}, receipts = GroupPreference { enable , voice = VoiceGroupPreference {enable = FEOn} } emptyGroupPrefs :: GroupPreferences emptyGroupPrefs = GroupPreferences Nothing Nothing Nothing Nothing data TimedMessagesPreference = TimedMessagesPreference { allow :: FeatureAllowed, ttl :: Maybe Int } deriving (Eq, Show, Generic, FromJSON) instance ToJSON TimedMessagesPreference where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} data FullDeletePreference = FullDeletePreference {allow :: FeatureAllowed} deriving (Eq, Show, Generic, FromJSON) instance ToJSON FullDeletePreference where toEncoding = J.genericToEncoding J.defaultOptions data VoicePreference = VoicePreference {allow :: FeatureAllowed} deriving (Eq, Show, Generic, FromJSON) instance ToJSON VoicePreference where toEncoding = J.genericToEncoding J.defaultOptions class (Eq (FeaturePreference f), HasField "allow" (FeaturePreference f) FeatureAllowed) => FeatureI f where type FeaturePreference (f :: ChatFeature) = p | p -> f sFeature :: SChatFeature f prefParam :: FeaturePreference f -> Maybe Int instance HasField "allow" TimedMessagesPreference FeatureAllowed where hasField p = (\allow -> p {allow}, allow (p :: TimedMessagesPreference)) instance HasField "allow" FullDeletePreference FeatureAllowed where hasField p = (\allow -> p {allow}, allow (p :: FullDeletePreference)) instance HasField "allow" VoicePreference FeatureAllowed where hasField p = (\allow -> p {allow}, allow (p :: VoicePreference)) instance FeatureI 'CFTimedMessages where type FeaturePreference 'CFTimedMessages = TimedMessagesPreference sFeature = SCFTimedMessages prefParam TimedMessagesPreference {ttl} = ttl instance FeatureI 'CFFullDelete where type FeaturePreference 'CFFullDelete = FullDeletePreference sFeature = SCFFullDelete prefParam _ = Nothing instance FeatureI 'CFVoice where type FeaturePreference 'CFVoice = VoicePreference sFeature = SCFVoice prefParam _ = Nothing data GroupPreference = GroupPreference {enable :: GroupFeatureEnabled} deriving (Eq, Show, Generic, FromJSON) data TimedMessagesGroupPreference = TimedMessagesGroupPreference { enable :: GroupFeatureEnabled, ttl :: Int } deriving (Eq, Show, Generic, FromJSON) data DirectMessagesGroupPreference = DirectMessagesGroupPreference {enable :: GroupFeatureEnabled} deriving (Eq, Show, Generic, FromJSON) data FullDeleteGroupPreference = FullDeleteGroupPreference {enable :: GroupFeatureEnabled} deriving (Eq, Show, Generic, FromJSON) data VoiceGroupPreference = VoiceGroupPreference {enable :: GroupFeatureEnabled} deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupPreference where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON TimedMessagesGroupPreference where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON DirectMessagesGroupPreference where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON FullDeleteGroupPreference where toEncoding = J.genericToEncoding J.defaultOptions instance ToJSON VoiceGroupPreference where toEncoding = J.genericToEncoding J.defaultOptions class (Eq (GroupFeaturePreference f), HasField "enable" (GroupFeaturePreference f) GroupFeatureEnabled) => GroupFeatureI f where type GroupFeaturePreference (f :: GroupFeature) = p | p -> f sGroupFeature :: SGroupFeature f groupPrefParam :: GroupFeaturePreference f -> Maybe Int instance HasField "enable" GroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: GroupPreference)) instance HasField "enable" TimedMessagesGroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: TimedMessagesGroupPreference)) instance HasField "enable" DirectMessagesGroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: DirectMessagesGroupPreference)) instance HasField "enable" FullDeleteGroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: FullDeleteGroupPreference)) instance HasField "enable" VoiceGroupPreference GroupFeatureEnabled where hasField p = (\enable -> p {enable}, enable (p :: VoiceGroupPreference)) instance GroupFeatureI 'GFTimedMessages where type GroupFeaturePreference 'GFTimedMessages = TimedMessagesGroupPreference sGroupFeature = SGFTimedMessages groupPrefParam TimedMessagesGroupPreference {ttl} = Just ttl instance GroupFeatureI 'GFDirectMessages where type GroupFeaturePreference 'GFDirectMessages = DirectMessagesGroupPreference sGroupFeature = SGFDirectMessages groupPrefParam _ = Nothing instance GroupFeatureI 'GFFullDelete where type GroupFeaturePreference 'GFFullDelete = FullDeleteGroupPreference sGroupFeature = SGFFullDelete groupPrefParam _ = Nothing instance GroupFeatureI 'GFVoice where type GroupFeaturePreference 'GFVoice = VoiceGroupPreference sGroupFeature = SGFVoice groupPrefParam _ = Nothing groupPrefStateText :: HasField "enable" p GroupFeatureEnabled => GroupFeature -> p -> Maybe Int -> Text groupPrefStateText feature pref param = let enabled = getField @"enable" pref paramText = if enabled == FEOn then groupParamText_ feature param else "" in groupFeatureNameText feature <> ": " <> safeDecodeUtf8 (strEncode enabled) <> paramText groupParamText_ :: GroupFeature -> Maybe Int -> Text groupParamText_ feature param = case feature of GFTimedMessages -> maybe "" (\p -> " (" <> timedTTLText p <> ")") param _ -> "" groupPreferenceText :: forall f. GroupFeatureI f => GroupFeaturePreference f -> Text groupPreferenceText pref = let feature = toGroupFeature $ sGroupFeature @f in groupPrefStateText feature pref $ groupPrefParam pref timedTTLText :: Int -> Text timedTTLText 0 = "0 sec" timedTTLText ttl = do let (m', s) = ttl `quotRem` 60 (h', m) = m' `quotRem` 60 (d', h) = h' `quotRem` 24 (mm, d) = d' `quotRem` 30 T.pack . unwords $ [mms mm | mm /= 0] <> [ds d | d /= 0] <> [hs h | h /= 0] <> [ms m | m /= 0] <> [ss s | s /= 0] where ss s = show s <> " sec" ms m = show m <> " min" hs 1 = "1 hour" hs h = show h <> " hours" ds 1 = "1 day" ds 7 = "1 week" ds 14 = "2 weeks" ds d = show d <> " days" mms 1 = "1 month" mms mm = show mm <> " months" toGroupPreference :: GroupFeatureI f => GroupFeaturePreference f -> GroupPreference toGroupPreference p = GroupPreference {enable = getField @"enable" p} data FeatureAllowed deriving (Eq, Show, Generic) instance FromField FeatureAllowed where fromField = fromBlobField_ strDecode instance ToField FeatureAllowed where toField = toField . strEncode instance StrEncoding FeatureAllowed where strEncode = \case FAAlways -> "always" FAYes -> "yes" FANo -> "no" strDecode = \case "always" -> Right FAAlways "yes" -> Right FAYes "no" -> Right FANo r -> Left $ "bad FeatureAllowed " <> B.unpack r strP = strDecode <$?> A.takeByteString instance FromJSON FeatureAllowed where parseJSON = strParseJSON "FeatureAllowed" instance ToJSON FeatureAllowed where toJSON = strToJSON toEncoding = strToJEncoding data GroupFeatureEnabled = FEOn | FEOff deriving (Eq, Show, Generic) instance FromField GroupFeatureEnabled where fromField = fromBlobField_ strDecode instance ToField GroupFeatureEnabled where toField = toField . strEncode instance StrEncoding GroupFeatureEnabled where strEncode = \case FEOn -> "on" FEOff -> "off" strDecode = \case "on" -> Right FEOn "off" -> Right FEOff r -> Left $ "bad GroupFeatureEnabled " <> B.unpack r strP = strDecode <$?> A.takeByteString instance FromJSON GroupFeatureEnabled where parseJSON = strParseJSON "GroupFeatureEnabled" instance ToJSON GroupFeatureEnabled where toJSON = strToJSON toEncoding = strToJEncoding groupFeatureState :: GroupFeatureI f => GroupFeaturePreference f -> (GroupFeatureEnabled, Maybe Int) groupFeatureState p = let enable = getField @"enable" p param = if enable == FEOn then groupPrefParam p else Nothing in (enable, param) mergePreferences :: Maybe Preferences -> Maybe Preferences -> FullPreferences mergePreferences contactPrefs userPreferences = FullPreferences { timedMessages = pref SCFTimedMessages, fullDelete = pref SCFFullDelete, receipts = pref CFReceipts , voice = pref SCFVoice } where pref :: SChatFeature f -> FeaturePreference f pref f = let sel = chatPrefSel f in fromMaybe (getPreference f defaultChatPrefs) $ (contactPrefs >>= sel) <|> (userPreferences >>= sel) mergeUserChatPrefs :: User -> Contact -> FullPreferences mergeUserChatPrefs user ct = mergeUserChatPrefs' user (contactConnIncognito ct) (userPreferences ct) mergeUserChatPrefs' :: User -> Bool -> Preferences -> FullPreferences mergeUserChatPrefs' user connectedIncognito userPreferences = let userPrefs = if connectedIncognito then Nothing else preferences' user in mergePreferences (Just userPreferences) userPrefs mergeGroupPreferences :: Maybe GroupPreferences -> FullGroupPreferences mergeGroupPreferences groupPreferences = FullGroupPreferences { timedMessages = pref SGFTimedMessages, directMessages = pref SGFDirectMessages, fullDelete = pref SGFFullDelete, receipts = pref GFReceipts , voice = pref SGFVoice } where pref :: SGroupFeature f -> GroupFeaturePreference f pref pt = fromMaybe (getGroupPreference pt defaultGroupPrefs) (groupPreferences >>= groupPrefSel pt) toGroupPreferences :: FullGroupPreferences -> GroupPreferences toGroupPreferences groupPreferences = GroupPreferences { timedMessages = pref SGFTimedMessages, directMessages = pref SGFDirectMessages, fullDelete = pref SGFFullDelete, receipts = pref GFReceipts , voice = pref SGFVoice } where pref :: SGroupFeature f -> Maybe (GroupFeaturePreference f) pref f = Just $ getGroupPreference f groupPreferences data PrefEnabled = PrefEnabled {forUser :: Bool, forContact :: Bool} deriving (Eq, Show, Generic, FromJSON) instance ToJSON PrefEnabled where toJSON = J.genericToJSON J.defaultOptions toEncoding = J.genericToEncoding J.defaultOptions prefEnabled :: FeatureI f => Bool -> FeaturePreference f -> FeaturePreference f -> PrefEnabled prefEnabled asymmetric user contact = case (getField @"allow" user, getField @"allow" contact) of (FAAlways, FANo) -> PrefEnabled {forUser = False, forContact = asymmetric} (FANo, FAAlways) -> PrefEnabled {forUser = asymmetric, forContact = False} (_, FANo) -> PrefEnabled False False (FANo, _) -> PrefEnabled False False _ -> PrefEnabled True True prefStateText :: ChatFeature -> FeatureAllowed -> Maybe Int -> Text prefStateText feature allowed param = case allowed of FANo -> "cancelled " <> chatFeatureNameText feature _ -> "offered " <> chatFeatureNameText feature <> paramText_ feature param featureStateText :: ChatFeature -> PrefEnabled -> Maybe Int -> Text featureStateText feature enabled param = chatFeatureNameText feature <> ": " <> prefEnabledToText enabled <> case enabled of PrefEnabled {forUser = True} -> paramText_ feature param _ -> "" paramText_ :: ChatFeature -> Maybe Int -> Text paramText_ feature param = case feature of CFTimedMessages -> maybe "" (\p -> " (" <> timedTTLText p <> ")") param _ -> "" prefEnabledToText :: PrefEnabled -> Text prefEnabledToText = \case PrefEnabled True True -> "enabled" PrefEnabled False False -> "off" PrefEnabled {forUser = True, forContact = False} -> "enabled for you" PrefEnabled {forUser = False, forContact = True} -> "enabled for contact" preferenceText :: forall f. FeatureI f => FeaturePreference f -> Text preferenceText p = let feature = chatFeature $ sFeature @f allowed = getField @"allow" p paramText = if allowed == FAAlways || allowed == FAYes then paramText_ feature (prefParam p) else "" in safeDecodeUtf8 (strEncode allowed) <> paramText featureState :: FeatureI f => ContactUserPreference (FeaturePreference f) -> (PrefEnabled, Maybe Int) featureState ContactUserPreference {enabled, userPreference} = let param = if forUser enabled then prefParam $ preference userPreference else Nothing in (enabled, param) preferenceState :: FeatureI f => FeaturePreference f -> (FeatureAllowed, Maybe Int) preferenceState pref = let allow = getField @"allow" pref param = if allow == FAAlways || allow == FAYes then prefParam pref else Nothing in (allow, param) updateMergedPreferences :: User -> Contact -> Contact updateMergedPreferences user ct = let mergedPreferences = contactUserPreferences user (userPreferences ct) (preferences' ct) (contactConnIncognito ct) in ct {mergedPreferences} contactUserPreferences :: User -> Preferences -> Maybe Preferences -> Bool -> ContactUserPreferences contactUserPreferences user userPreferences contactPreferences connectedIncognito = ContactUserPreferences { timedMessages = pref SCFTimedMessages, fullDelete = pref SCFFullDelete, receipts = pref CFReceipts , voice = pref SCFVoice } where pref :: FeatureI f => SChatFeature f -> ContactUserPreference (FeaturePreference f) pref f = ContactUserPreference { enabled = prefEnabled (asymmetric f) userPref ctPref, userPreference = if connectedIncognito then CUPContact ctUserPref else maybe (CUPUser userPref) CUPContact ctUserPref_, contactPreference = ctPref } where asymmetric SCFTimedMessages = False asymmetric _ = True ctUserPref = getPreference f userPreferences ctUserPref_ = chatPrefSel f userPreferences userPref = getPreference f ctUserPrefs ctPref = getPreference f ctPrefs ctUserPrefs = mergeUserChatPrefs' user connectedIncognito userPreferences ctPrefs = mergePreferences contactPreferences Nothing getContactUserPreference :: SChatFeature f -> ContactUserPreferences -> ContactUserPreference (FeaturePreference f) getContactUserPreference = \case SCFTimedMessages -> timedMessages SCFFullDelete -> fullDelete CFReceipts - > receipts SCFVoice -> voice data Profile = Profile { displayName :: ContactName, fullName :: Text, image :: Maybe ImageData, preferences :: Maybe Preferences } deriving (Eq, Show, Generic, FromJSON) instance ToJSON Profile where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} profilesMatch :: Profile -> Profile -> Bool profilesMatch Profile {displayName = n1, fullName = fn1, image = i1} Profile {displayName = n2, fullName = fn2, image = i2} = n1 == n2 && fn1 == fn2 && i1 == i2 data IncognitoProfile = NewIncognito Profile | ExistingIncognito LocalProfile type LocalAlias = Text data LocalProfile = LocalProfile { profileId :: ProfileId, displayName :: ContactName, fullName :: Text, image :: Maybe ImageData, preferences :: Maybe Preferences, localAlias :: LocalAlias } deriving (Eq, Show, Generic, FromJSON) instance ToJSON LocalProfile where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} localProfileId :: LocalProfile -> ProfileId localProfileId = profileId toLocalProfile :: ProfileId -> Profile -> LocalAlias -> LocalProfile toLocalProfile profileId Profile {displayName, fullName, image, preferences} localAlias = LocalProfile {profileId, displayName, fullName, image, preferences, localAlias} fromLocalProfile :: LocalProfile -> Profile fromLocalProfile LocalProfile {displayName, fullName, image, preferences} = Profile {displayName, fullName, image, preferences} data GroupProfile = GroupProfile { displayName :: GroupName, fullName :: Text, description :: Maybe Text, image :: Maybe ImageData, groupPreferences :: Maybe GroupPreferences } deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupProfile where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} newtype ImageData = ImageData Text deriving (Eq, Show) instance FromJSON ImageData where parseJSON = fmap ImageData . J.parseJSON instance ToJSON ImageData where toJSON (ImageData t) = J.toJSON t toEncoding (ImageData t) = J.toEncoding t instance ToField ImageData where toField (ImageData t) = toField t instance FromField ImageData where fromField = fmap ImageData . fromField data CReqClientData = CRDataGroup {groupLinkId :: GroupLinkId} deriving (Generic) instance ToJSON CReqClientData where toJSON = J.genericToJSON . taggedObjectJSON $ dropPrefix "CRData" toEncoding = J.genericToEncoding . taggedObjectJSON $ dropPrefix "CRData" instance FromJSON CReqClientData where parseJSON = J.genericParseJSON . taggedObjectJSON $ dropPrefix "CRData" deriving (Eq, Show) instance FromField GroupLinkId where fromField f = GroupLinkId <$> fromField f instance ToField GroupLinkId where toField (GroupLinkId g) = toField g instance StrEncoding GroupLinkId where strEncode (GroupLinkId g) = strEncode g strDecode s = GroupLinkId <$> strDecode s strP = GroupLinkId <$> strP instance FromJSON GroupLinkId where parseJSON = strParseJSON "GroupLinkId" instance ToJSON GroupLinkId where toJSON = strToJSON toEncoding = strToJEncoding data GroupInvitation = GroupInvitation { fromMember :: MemberIdRole, invitedMember :: MemberIdRole, connRequest :: ConnReqInvitation, groupProfile :: GroupProfile, groupLinkId :: Maybe GroupLinkId } deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupInvitation where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} data MemberIdRole = MemberIdRole { memberId :: MemberId, memberRole :: GroupMemberRole } deriving (Eq, Show, Generic, FromJSON) instance ToJSON MemberIdRole where toEncoding = J.genericToEncoding J.defaultOptions data IntroInvitation = IntroInvitation { groupConnReq :: ConnReqInvitation, directConnReq :: ConnReqInvitation } deriving (Eq, Show, Generic, FromJSON) instance ToJSON IntroInvitation where toEncoding = J.genericToEncoding J.defaultOptions data MemberInfo = MemberInfo { memberId :: MemberId, memberRole :: GroupMemberRole, profile :: Profile } deriving (Eq, Show, Generic, FromJSON) instance ToJSON MemberInfo where toEncoding = J.genericToEncoding J.defaultOptions memberInfo :: GroupMember -> MemberInfo memberInfo GroupMember {memberId, memberRole, memberProfile} = MemberInfo memberId memberRole (fromLocalProfile memberProfile) data ReceivedGroupInvitation = ReceivedGroupInvitation { fromMember :: GroupMember, connRequest :: ConnReqInvitation, groupInfo :: GroupInfo } deriving (Eq, Show) type GroupMemberId = Int64 data GroupMember = GroupMember { groupMemberId :: GroupMemberId, groupId :: GroupId, memberId :: MemberId, memberRole :: GroupMemberRole, memberCategory :: GroupMemberCategory, memberStatus :: GroupMemberStatus, invitedBy :: InvitedBy, localDisplayName :: ContactName, memberProfile :: LocalProfile, memberContactId :: Maybe ContactId, memberContactProfileId :: ProfileId, activeConn :: Maybe Connection } deriving (Eq, Show, Generic) instance ToJSON GroupMember where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} data GroupMemberRef = GroupMemberRef {groupMemberId :: Int64, profile :: Profile} deriving (Eq, Show, Generic, FromJSON) instance ToJSON GroupMemberRef where toEncoding = J.genericToEncoding J.defaultOptions groupMemberRef :: GroupMember -> GroupMemberRef groupMemberRef GroupMember {groupMemberId, memberProfile = p} = GroupMemberRef {groupMemberId, profile = fromLocalProfile p} memberConn :: GroupMember -> Maybe Connection memberConn = activeConn memberConnId :: GroupMember -> Maybe ConnId memberConnId GroupMember {activeConn} = aConnId <$> activeConn groupMemberId' :: GroupMember -> GroupMemberId groupMemberId' GroupMember {groupMemberId} = groupMemberId memberIncognito :: GroupMember -> Bool memberIncognito GroupMember {memberProfile, memberContactProfileId} = localProfileId memberProfile /= memberContactProfileId memberSecurityCode :: GroupMember -> Maybe SecurityCode memberSecurityCode GroupMember {activeConn} = connectionCode =<< activeConn data NewGroupMember = NewGroupMember { memInfo :: MemberInfo, memCategory :: GroupMemberCategory, memStatus :: GroupMemberStatus, memInvitedBy :: InvitedBy, localDisplayName :: ContactName, memProfileId :: Int64, memContactId :: Maybe Int64 } newtype MemberId = MemberId {unMemberId :: ByteString} deriving (Eq, Show) instance FromField MemberId where fromField f = MemberId <$> fromField f instance ToField MemberId where toField (MemberId m) = toField m instance StrEncoding MemberId where strEncode (MemberId m) = strEncode m strDecode s = MemberId <$> strDecode s strP = MemberId <$> strP instance FromJSON MemberId where parseJSON = strParseJSON "MemberId" instance ToJSON MemberId where toJSON = strToJSON toEncoding = strToJEncoding data InvitedBy = IBContact {byContactId :: Int64} | IBUser | IBUnknown deriving (Eq, Show, Generic) instance ToJSON InvitedBy where toJSON = J.genericToJSON . sumTypeJSON $ dropPrefix "IB" toEncoding = J.genericToEncoding . sumTypeJSON $ dropPrefix "IB" toInvitedBy :: Int64 -> Maybe Int64 -> InvitedBy toInvitedBy userCtId (Just ctId) | userCtId == ctId = IBUser | otherwise = IBContact ctId toInvitedBy _ Nothing = IBUnknown fromInvitedBy :: Int64 -> InvitedBy -> Maybe Int64 fromInvitedBy userCtId = \case IBUnknown -> Nothing IBContact ctId -> Just ctId IBUser -> Just userCtId data GroupMemberRole deriving (Eq, Show, Ord) instance FromField GroupMemberRole where fromField = fromBlobField_ strDecode instance ToField GroupMemberRole where toField = toField . strEncode instance StrEncoding GroupMemberRole where strEncode = \case GROwner -> "owner" GRAdmin -> "admin" GRMember -> "member" GRAuthor -> "author" GRObserver -> "observer" strDecode = \case "owner" -> Right GROwner "admin" -> Right GRAdmin "member" -> Right GRMember "author" -> Right GRAuthor "observer" -> Right GRObserver r -> Left $ "bad GroupMemberRole " <> B.unpack r strP = strDecode <$?> A.takeByteString instance FromJSON GroupMemberRole where parseJSON = strParseJSON "GroupMemberRole" instance ToJSON GroupMemberRole where toJSON = strToJSON toEncoding = strToJEncoding fromBlobField_ :: Typeable k => (ByteString -> Either String k) -> FieldParser k fromBlobField_ p = \case f@(Field (SQLBlob b) _) -> case p b of Right k -> Ok k Left e -> returnError ConversionFailed f ("could not parse field: " ++ e) f -> returnError ConversionFailed f "expecting SQLBlob column type" newtype Probe = Probe {unProbe :: ByteString} deriving (Eq, Show) instance StrEncoding Probe where strEncode (Probe p) = strEncode p strDecode s = Probe <$> strDecode s strP = Probe <$> strP instance FromJSON Probe where parseJSON = strParseJSON "Probe" instance ToJSON Probe where toJSON = strToJSON toEncoding = strToJEncoding newtype ProbeHash = ProbeHash {unProbeHash :: ByteString} deriving (Eq, Show) instance StrEncoding ProbeHash where strEncode (ProbeHash p) = strEncode p strDecode s = ProbeHash <$> strDecode s strP = ProbeHash <$> strP instance FromJSON ProbeHash where parseJSON = strParseJSON "ProbeHash" instance ToJSON ProbeHash where toJSON = strToJSON toEncoding = strToJEncoding data GroupMemberCategory = GCUserMember deriving (Eq, Show) instance FromField GroupMemberCategory where fromField = fromTextField_ textDecode instance ToField GroupMemberCategory where toField = toField . textEncode instance ToJSON GroupMemberCategory where toJSON = J.String . textEncode toEncoding = JE.text . textEncode instance TextEncoding GroupMemberCategory where textDecode = \case "user" -> Just GCUserMember "invitee" -> Just GCInviteeMember "host" -> Just GCHostMember "pre" -> Just GCPreMember "post" -> Just GCPostMember _ -> Nothing textEncode = \case GCUserMember -> "user" GCInviteeMember -> "invitee" GCHostMember -> "host" GCPreMember -> "pre" GCPostMember -> "post" data GroupMemberStatus user received x.grp.mem.intro for this member ( only with ) host confirmed ( x.grp.mem.all ) that a member ( User , Invitee and PostMember ) created group connections with all previous members deriving (Eq, Show, Ord) instance FromField GroupMemberStatus where fromField = fromTextField_ textDecode instance ToField GroupMemberStatus where toField = toField . textEncode instance ToJSON GroupMemberStatus where toJSON = J.String . textEncode toEncoding = JE.text . textEncode memberActive :: GroupMember -> Bool memberActive m = case memberStatus m of GSMemRemoved -> False GSMemLeft -> False GSMemGroupDeleted -> False GSMemInvited -> False GSMemIntroduced -> False GSMemIntroInvited -> False GSMemAccepted -> False GSMemAnnounced -> False GSMemConnected -> True GSMemComplete -> True GSMemCreator -> True memberCurrent :: GroupMember -> Bool memberCurrent m = case memberStatus m of GSMemRemoved -> False GSMemLeft -> False GSMemGroupDeleted -> False GSMemInvited -> False GSMemIntroduced -> True GSMemIntroInvited -> True GSMemAccepted -> True GSMemAnnounced -> True GSMemConnected -> True GSMemComplete -> True GSMemCreator -> True memberRemoved :: GroupMember -> Bool memberRemoved m = case memberStatus m of GSMemRemoved -> True GSMemLeft -> True GSMemGroupDeleted -> True GSMemInvited -> False GSMemIntroduced -> False GSMemIntroInvited -> False GSMemAccepted -> False GSMemAnnounced -> False GSMemConnected -> False GSMemComplete -> False GSMemCreator -> False instance TextEncoding GroupMemberStatus where textDecode = \case "removed" -> Just GSMemRemoved "left" -> Just GSMemLeft "deleted" -> Just GSMemGroupDeleted "invited" -> Just GSMemInvited "introduced" -> Just GSMemIntroduced "intro-inv" -> Just GSMemIntroInvited "accepted" -> Just GSMemAccepted "announced" -> Just GSMemAnnounced "connected" -> Just GSMemConnected "complete" -> Just GSMemComplete "creator" -> Just GSMemCreator _ -> Nothing textEncode = \case GSMemRemoved -> "removed" GSMemLeft -> "left" GSMemGroupDeleted -> "deleted" GSMemInvited -> "invited" GSMemIntroduced -> "introduced" GSMemIntroInvited -> "intro-inv" GSMemAccepted -> "accepted" GSMemAnnounced -> "announced" GSMemConnected -> "connected" GSMemComplete -> "complete" GSMemCreator -> "creator" data SndFileTransfer = SndFileTransfer { fileId :: FileTransferId, fileName :: String, filePath :: String, fileSize :: Integer, chunkSize :: Integer, recipientDisplayName :: ContactName, connId :: Int64, agentConnId :: AgentConnId, fileStatus :: FileStatus, fileInline :: Maybe InlineFileMode } deriving (Eq, Show, Generic) instance ToJSON SndFileTransfer where toEncoding = J.genericToEncoding J.defaultOptions sndFileTransferConnId :: SndFileTransfer -> ConnId sndFileTransferConnId SndFileTransfer {agentConnId = AgentConnId acId} = acId type FileTransferId = Int64 data FileInvitation = FileInvitation { fileName :: String, fileSize :: Integer, fileConnReq :: Maybe ConnReqInvitation, fileInline :: Maybe InlineFileMode } deriving (Eq, Show, Generic) instance ToJSON FileInvitation where toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} instance FromJSON FileInvitation where parseJSON = J.genericParseJSON J.defaultOptions {J.omitNothingFields = True} data InlineFileMode deriving (Eq, Show, Generic) instance TextEncoding InlineFileMode where textEncode = \case IFMOffer -> "offer" IFMSent -> "sent" textDecode = \case "offer" -> Just IFMOffer "sent" -> Just IFMSent _ -> Nothing instance FromField InlineFileMode where fromField = fromTextField_ textDecode instance ToField InlineFileMode where toField = toField . textEncode instance FromJSON InlineFileMode where parseJSON = J.withText "InlineFileMode" $ maybe (fail "bad InlineFileMode") pure . textDecode instance ToJSON InlineFileMode where toJSON = J.String . textEncode toEncoding = JE.text . textEncode data RcvFileTransfer = RcvFileTransfer { fileId :: FileTransferId, fileInvitation :: FileInvitation, fileStatus :: RcvFileStatus, rcvFileInline :: Maybe InlineFileMode, senderDisplayName :: ContactName, chunkSize :: Integer, cancelled :: Bool, grpMemberId :: Maybe Int64 } deriving (Eq, Show, Generic) instance ToJSON RcvFileTransfer where toEncoding = J.genericToEncoding J.defaultOptions data RcvFileStatus = RFSNew | RFSAccepted RcvFileInfo | RFSConnected RcvFileInfo | RFSComplete RcvFileInfo | RFSCancelled (Maybe RcvFileInfo) deriving (Eq, Show, Generic) instance ToJSON RcvFileStatus where toJSON = J.genericToJSON . sumTypeJSON $ dropPrefix "RFS" toEncoding = J.genericToEncoding . sumTypeJSON $ dropPrefix "RFS" data RcvFileInfo = RcvFileInfo { filePath :: FilePath, connId :: Maybe Int64, agentConnId :: Maybe AgentConnId } deriving (Eq, Show, Generic) instance ToJSON RcvFileInfo where toEncoding = J.genericToEncoding J.defaultOptions liveRcvFileTransferConnId :: RcvFileTransfer -> Maybe ConnId liveRcvFileTransferConnId RcvFileTransfer {fileStatus} = case fileStatus of RFSAccepted fi -> acId fi RFSConnected fi -> acId fi _ -> Nothing where acId RcvFileInfo {agentConnId = Just (AgentConnId cId)} = Just cId acId _ = Nothing newtype AgentConnId = AgentConnId ConnId deriving (Eq, Show) instance StrEncoding AgentConnId where strEncode (AgentConnId connId) = strEncode connId strDecode s = AgentConnId <$> strDecode s strP = AgentConnId <$> strP instance ToJSON AgentConnId where toJSON = strToJSON toEncoding = strToJEncoding instance FromField AgentConnId where fromField f = AgentConnId <$> fromField f instance ToField AgentConnId where toField (AgentConnId m) = toField m newtype AgentInvId = AgentInvId InvitationId deriving (Eq, Show) instance StrEncoding AgentInvId where strEncode (AgentInvId connId) = strEncode connId strDecode s = AgentInvId <$> strDecode s strP = AgentInvId <$> strP instance ToJSON AgentInvId where toJSON = strToJSON toEncoding = strToJEncoding instance FromField AgentInvId where fromField f = AgentInvId <$> fromField f instance ToField AgentInvId where toField (AgentInvId m) = toField m data FileTransfer = FTSnd { fileTransferMeta :: FileTransferMeta, sndFileTransfers :: [SndFileTransfer] } | FTRcv {rcvFileTransfer :: RcvFileTransfer} deriving (Show, Generic) instance ToJSON FileTransfer where toJSON = J.genericToJSON . sumTypeJSON $ dropPrefix "FT" toEncoding = J.genericToEncoding . sumTypeJSON $ dropPrefix "FT" data FileTransferMeta = FileTransferMeta { fileId :: FileTransferId, fileName :: String, filePath :: String, fileSize :: Integer, fileInline :: Maybe InlineFileMode, chunkSize :: Integer, cancelled :: Bool } deriving (Eq, Show, Generic) instance ToJSON FileTransferMeta where toEncoding = J.genericToEncoding J.defaultOptions fileTransferCancelled :: FileTransfer -> Bool fileTransferCancelled (FTSnd FileTransferMeta {cancelled} _) = cancelled fileTransferCancelled (FTRcv RcvFileTransfer {cancelled}) = cancelled data FileStatus = FSNew | FSAccepted | FSConnected | FSComplete | FSCancelled deriving (Eq, Ord, Show) instance FromField FileStatus where fromField = fromTextField_ textDecode instance ToField FileStatus where toField = toField . textEncode instance ToJSON FileStatus where toJSON = J.String . textEncode toEncoding = JE.text . textEncode instance TextEncoding FileStatus where textDecode = \case "new" -> Just FSNew "accepted" -> Just FSAccepted "connected" -> Just FSConnected "complete" -> Just FSComplete "cancelled" -> Just FSCancelled _ -> Nothing textEncode = \case FSNew -> "new" FSAccepted -> "accepted" FSConnected -> "connected" FSComplete -> "complete" FSCancelled -> "cancelled" data RcvChunkStatus = RcvChunkOk | RcvChunkFinal | RcvChunkDuplicate | RcvChunkError deriving (Eq, Show) type ConnReqInvitation = ConnectionRequestUri 'CMInvitation type ConnReqContact = ConnectionRequestUri 'CMContact data Connection = Connection { connId :: Int64, agentConnId :: AgentConnId, connLevel :: Int, groupLinkId :: Maybe GroupLinkId, customUserProfileId :: Maybe Int64, connType :: ConnType, connStatus :: ConnStatus, localAlias :: Text, connectionCode :: Maybe SecurityCode, authErrCounter :: Int, createdAt :: UTCTime } deriving (Eq, Show, Generic) authErrDisableCount :: Int authErrDisableCount = 10 connDisabled :: Connection -> Bool connDisabled Connection {authErrCounter} = authErrCounter >= authErrDisableCount data SecurityCode = SecurityCode {securityCode :: Text, verifiedAt :: UTCTime} deriving (Eq, Show, Generic) instance ToJSON SecurityCode where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} verificationCode :: ByteString -> Text verificationCode = T.pack . unwords . chunks 5 . show . os2ip where chunks _ [] = [] chunks n xs = let (h, t) = splitAt n xs in h : chunks n t sameVerificationCode :: Text -> Text -> Bool sameVerificationCode c1 c2 = noSpaces c1 == noSpaces c2 where noSpaces = T.filter (/= ' ') aConnId :: Connection -> ConnId aConnId Connection {agentConnId = AgentConnId cId} = cId connIncognito :: Connection -> Bool connIncognito Connection {customUserProfileId} = isJust customUserProfileId instance ToJSON Connection where toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} data PendingContactConnection = PendingContactConnection { pccConnId :: Int64, pccAgentConnId :: AgentConnId, pccConnStatus :: ConnStatus, viaContactUri :: Bool, viaUserContactLink :: Maybe Int64, groupLinkId :: Maybe GroupLinkId, customUserProfileId :: Maybe Int64, connReqInv :: Maybe ConnReqInvitation, localAlias :: Text, createdAt :: UTCTime, updatedAt :: UTCTime } deriving (Eq, Show, Generic) aConnId' :: PendingContactConnection -> ConnId aConnId' PendingContactConnection {pccAgentConnId = AgentConnId cId} = cId instance ToJSON PendingContactConnection where toEncoding = J.genericToEncoding J.defaultOptions data ConnStatus ConnNew ConnJoined | initiating party received CONF notification ( to be renamed to REQ ) ConnRequested ConnAccepted ConnSndReady ConnReady ConnDeleted deriving (Eq, Show, Read) instance FromField ConnStatus where fromField = fromTextField_ textDecode instance ToField ConnStatus where toField = toField . textEncode instance ToJSON ConnStatus where toJSON = J.String . textEncode toEncoding = JE.text . textEncode instance TextEncoding ConnStatus where textDecode = \case "new" -> Just ConnNew "joined" -> Just ConnJoined "requested" -> Just ConnRequested "accepted" -> Just ConnAccepted "snd-ready" -> Just ConnSndReady "ready" -> Just ConnReady "deleted" -> Just ConnDeleted _ -> Nothing textEncode = \case ConnNew -> "new" ConnJoined -> "joined" ConnRequested -> "requested" ConnAccepted -> "accepted" ConnSndReady -> "snd-ready" ConnReady -> "ready" ConnDeleted -> "deleted" data ConnType = ConnContact | ConnMember | ConnSndFile | ConnRcvFile | ConnUserContact deriving (Eq, Show) instance FromField ConnType where fromField = fromTextField_ textDecode instance ToField ConnType where toField = toField . textEncode instance ToJSON ConnType where toJSON = J.String . textEncode toEncoding = JE.text . textEncode instance TextEncoding ConnType where textDecode = \case "contact" -> Just ConnContact "member" -> Just ConnMember "snd_file" -> Just ConnSndFile "rcv_file" -> Just ConnRcvFile "user_contact" -> Just ConnUserContact _ -> Nothing textEncode = \case ConnContact -> "contact" ConnMember -> "member" ConnSndFile -> "snd_file" ConnRcvFile -> "rcv_file" ConnUserContact -> "user_contact" data NewConnection = NewConnection { agentConnId :: ByteString, connLevel :: Int, viaConn :: Maybe Int64 } data GroupMemberIntro = GroupMemberIntro { introId :: Int64, reMember :: GroupMember, toMember :: GroupMember, introStatus :: GroupMemberIntroStatus, introInvitation :: Maybe IntroInvitation } deriving (Show) data GroupMemberIntroStatus = GMIntroPending | GMIntroSent | GMIntroInvReceived | GMIntroInvForwarded | GMIntroReConnected | GMIntroToConnected | GMIntroConnected deriving (Show) instance FromField GroupMemberIntroStatus where fromField = fromTextField_ introStatusT instance ToField GroupMemberIntroStatus where toField = toField . serializeIntroStatus introStatusT :: Text -> Maybe GroupMemberIntroStatus introStatusT = \case "new" -> Just GMIntroPending "sent" -> Just GMIntroSent "rcv" -> Just GMIntroInvReceived "fwd" -> Just GMIntroInvForwarded "re-con" -> Just GMIntroReConnected "to-con" -> Just GMIntroToConnected "con" -> Just GMIntroConnected _ -> Nothing serializeIntroStatus :: GroupMemberIntroStatus -> Text serializeIntroStatus = \case GMIntroPending -> "new" GMIntroSent -> "sent" GMIntroInvReceived -> "rcv" GMIntroInvForwarded -> "fwd" GMIntroReConnected -> "re-con" GMIntroToConnected -> "to-con" GMIntroConnected -> "con" data Notification = Notification {title :: Text, text :: Text} type JSONString = String textParseJSON :: TextEncoding a => String -> J.Value -> JT.Parser a textParseJSON name = J.withText name $ maybe (fail $ "bad " <> name) pure . textDecode type CommandId = Int64 aCorrId :: CommandId -> ACorrId aCorrId = pack . show commandId :: ACorrId -> String commandId = unpack data CommandStatus = CSCreated internal command error , e.g. not matching connection i d or unexpected response , not related to agent message deriving (Show, Generic) instance FromField CommandStatus where fromField = fromTextField_ textDecode instance ToField CommandStatus where toField = toField . textEncode instance TextEncoding CommandStatus where textDecode = \case "created" -> Just CSCreated "completed" -> Just CSCompleted "error" -> Just CSError _ -> Nothing textEncode = \case CSCreated -> "created" CSCompleted -> "completed" CSError -> "error" data CommandFunction = CFCreateConnGrpMemInv | CFCreateConnGrpInv | CFCreateConnFileInvDirect | CFCreateConnFileInvGroup | CFJoinConn | CFAllowConn | CFAcceptContact | CFAckMessage deriving (Eq, Show, Generic) instance FromField CommandFunction where fromField = fromTextField_ textDecode instance ToField CommandFunction where toField = toField . textEncode instance TextEncoding CommandFunction where textDecode = \case "create_conn" -> Just CFCreateConnGrpMemInv "create_conn_grp_inv" -> Just CFCreateConnGrpInv "create_conn_file_inv_direct" -> Just CFCreateConnFileInvDirect "create_conn_file_inv_group" -> Just CFCreateConnFileInvGroup "join_conn" -> Just CFJoinConn "allow_conn" -> Just CFAllowConn "accept_contact" -> Just CFAcceptContact "ack_message" -> Just CFAckMessage "delete_conn" -> Just CFDeleteConn _ -> Nothing textEncode = \case CFCreateConnGrpMemInv -> "create_conn" CFCreateConnGrpInv -> "create_conn_grp_inv" CFCreateConnFileInvDirect -> "create_conn_file_inv_direct" CFCreateConnFileInvGroup -> "create_conn_file_inv_group" CFJoinConn -> "join_conn" CFAllowConn -> "allow_conn" CFAcceptContact -> "accept_contact" CFAckMessage -> "ack_message" CFDeleteConn -> "delete_conn" commandExpectedResponse :: CommandFunction -> ACommandTag 'Agent commandExpectedResponse = \case CFCreateConnGrpMemInv -> INV_ CFCreateConnGrpInv -> INV_ CFCreateConnFileInvDirect -> INV_ CFCreateConnFileInvGroup -> INV_ CFJoinConn -> OK_ CFAllowConn -> OK_ CFAcceptContact -> OK_ CFAckMessage -> OK_ CFDeleteConn -> OK_ data CommandData = CommandData { cmdId :: CommandId, cmdConnId :: Maybe Int64, cmdFunction :: CommandFunction, cmdStatus :: CommandStatus } deriving (Show) ad - hoc type for data required for XGrpMemIntro continuation data XGrpMemIntroCont = XGrpMemIntroCont { groupId :: GroupId, groupMemberId :: GroupMemberId, memberId :: MemberId, groupConnReq :: ConnReqInvitation } deriving (Show) encodeJSON :: ToJSON a => a -> Text encodeJSON = safeDecodeUtf8 . LB.toStrict . J.encode decodeJSON :: FromJSON a => Text -> Maybe a decodeJSON = J.decode . LB.fromStrict . encodeUtf8 data ServerCfg = ServerCfg { server :: SMPServerWithAuth, preset :: Bool, tested :: Maybe Bool, enabled :: Bool } deriving (Show, Generic) instance ToJSON ServerCfg where toEncoding = J.genericToEncoding J.defaultOptions {J.omitNothingFields = True} toJSON = J.genericToJSON J.defaultOptions {J.omitNothingFields = True} instance FromJSON ServerCfg where parseJSON = J.genericParseJSON J.defaultOptions {J.omitNothingFields = True}
e8f05b3e6dbeec0eb8ab858deed6aaa2bb4e96775e95993678f11b43d5751bfe
rigetti/oqaml
oqaml.mli
Copyright 2017 Rigetti Computing , Inc. 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 . 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. *) * This module implements the basic functionality of the { b O}Caml { b Q}uantum { b A}bastract { b M}achine { b L}anguange , a QASM ( Quantum Abstract State Machine ) {b O}Caml {b Q}uantum {b A}bastract {b M}achine {b L}anguange, a QASM (Quantum Abstract State Machine) *) module M = Owl.Dense.Matrix.C module V = Owl.Dense.Vector.C * The QVM is a record type containing the number of qubits , a wave - function connected to the quantum state of the quibits and a classical register that can be used to read out the qubits into classical bits connected to the quantum state of the quibits and a classical register that can be used to read out the qubits into classical bits *) type qvm = { num_qubits: int; wf: V.vec; reg: int array; } * Gate operations on a qvm containing operations on the classical bit register and the quantum state . The target qubits and bits are indexed by integers denoting their position in the wave - function and classical register . and the quantum state. The target qubits and bits are indexed by integers denoting their position in the wave-function and classical register. *) type gate = | I of int (** Reversible quantum operation on the wave-function*) | X of int (** Reversible quantum operation on the wave-function*) | Y of int (** Reversible quantum operation on the wave-function*) | Z of int (** Reversible quantum operation on the wave-function*) | H of int (** Reversible quantum operation on the wave-function*) | PHASE of float (** Reversible quantum operation on the wave-function*) | RX of float * int (** Reversible quantum operation on the wave-function*) | RY of float * int (** Reversible quantum operation on the wave-function*) | RZ of float * int (** Reversible quantum operation on the wave-function*) | CNOT of int * int (** Reversible quantum operation on the wave-function*) | SWAP of int * int (** Reversible quantum operation on the wave-function*) | CIRCUIT of gate list (** Recursive type for circuits *) | MEASURE of int (** Projective measurement gate *) * Classic operation on the bit register * Classic operation on the bit register * Classic operation on the bit register * Classic operation on the bit register * Initializes a QVM with a classical register of [ reg_size ] bist and [ int ] qubits in their ground - states qubits in their ground-states*) val init_qvm : ?reg_size:int -> int -> qvm * Applies [ gate ] to a [ qvm ] resulting in a new [ qvm ] state val apply : gate -> qvm -> qvm * Returns the probabilities to find the [ qvm ] in a certain quantum state val get_probs : qvm -> float list (** Measures all qubits in the [qvm] [int]-times and returns the results in a [list] of [int list]*) val measure_all : qvm -> int -> int list list
null
https://raw.githubusercontent.com/rigetti/oqaml/e51696fc54e34e0dcb4237b8760dc5cfe280937c/src/oqaml.mli
ocaml
* Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Reversible quantum operation on the wave-function * Recursive type for circuits * Projective measurement gate * Measures all qubits in the [qvm] [int]-times and returns the results in a [list] of [int list]
Copyright 2017 Rigetti Computing , Inc. 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 . 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. *) * This module implements the basic functionality of the { b O}Caml { b Q}uantum { b A}bastract { b M}achine { b L}anguange , a QASM ( Quantum Abstract State Machine ) {b O}Caml {b Q}uantum {b A}bastract {b M}achine {b L}anguange, a QASM (Quantum Abstract State Machine) *) module M = Owl.Dense.Matrix.C module V = Owl.Dense.Vector.C * The QVM is a record type containing the number of qubits , a wave - function connected to the quantum state of the quibits and a classical register that can be used to read out the qubits into classical bits connected to the quantum state of the quibits and a classical register that can be used to read out the qubits into classical bits *) type qvm = { num_qubits: int; wf: V.vec; reg: int array; } * Gate operations on a qvm containing operations on the classical bit register and the quantum state . The target qubits and bits are indexed by integers denoting their position in the wave - function and classical register . and the quantum state. The target qubits and bits are indexed by integers denoting their position in the wave-function and classical register. *) type gate = * Classic operation on the bit register * Classic operation on the bit register * Classic operation on the bit register * Classic operation on the bit register * Initializes a QVM with a classical register of [ reg_size ] bist and [ int ] qubits in their ground - states qubits in their ground-states*) val init_qvm : ?reg_size:int -> int -> qvm * Applies [ gate ] to a [ qvm ] resulting in a new [ qvm ] state val apply : gate -> qvm -> qvm * Returns the probabilities to find the [ qvm ] in a certain quantum state val get_probs : qvm -> float list val measure_all : qvm -> int -> int list list
df54711486e68a009a2c420cc4415f03f6a7b8badd40360bc07237d15722973e
alvatar/spheres
serialization.scm
;;!!! FFI object serialization .author , 2013 - 2014 . All Rights Reserved . (cond-expand (optimize (declare (standard-bindings) (extended-bindings) (not safe) (block))) (debug (declare (safe) (debug) (debug-location) (debug-source) (debug-environments))) (else (void))) ;;------------------------------------------------------------------------------ (include "c-define-base-macros#.scm") (include "c-define-reader#.scm") ;;!! C Types: readers/writers ;; ;; Use like this: ;; (call-with-output-file ;; "f64test" ;; (lambda (port) ;; (write-f64 -1.5 port) ;; (write-f64 +inf.0 port) ;; (write-f64 3.1415926 port))) ;; ;; (call-with-input-file ;; "f64test" ;; (lambda (port) ;; (let* ((a (read-f64 port)) ;; (b (read-f64 port)) ;; (c (read-f64 port)) ;; (d (read-f64 port))) ;; (pp (list a b c d))))) ;;!! C Types: readers/writers generation (define u8vector-subtype (##subtype (u8vector))) (define s8vector-subtype (##subtype (s8vector))) (define u16vector-subtype (##subtype (u16vector))) (define s16vector-subtype (##subtype (s16vector))) (define u32vector-subtype (##subtype (u32vector))) (define s32vector-subtype (##subtype (s32vector))) (define u64vector-subtype (##subtype (u64vector))) (define s64vector-subtype (##subtype (s64vector))) (define f32vector-subtype (##subtype (f32vector))) (define f64vector-subtype (##subtype (f64vector))) ;;! u8vector reader/writer ;; Already defined in Gambit ;;! s8vector reader/writer (define-writer write-s8 s8vector) (define-reader read-s8 s8vector s8vector-subtype s8vector-ref 0) ;;! u16vector reader/writer (define-writer write-u16 u16vector) (define-reader read-u16 u16vector u16vector-subtype u16vector-ref 0) ;;! s16vector reader/writer (define-writer write-s16 s16vector) (define-reader read-s16 s16vector s16vector-subtype s16vector-ref 0) ;;! u32vector reader/writer (define-writer write-u32 u32vector) (define-reader read-u32 u32vector u32vector-subtype u32vector-ref 0) ;;! s32vector reader/writer (define-writer write-s32 s32vector) (define-reader read-s32 s32vector s32vector-subtype s32vector-ref 0) ;;! u64vector reader/writer (define-writer write-u64 u64vector) (define-reader read-u64 u64vector u64vector-subtype u64vector-ref 0) ! s64vector reader / writer (define-writer write-s64 s64vector) (define-reader read-s64 s64vector s64vector-subtype s64vector-ref 0) ;;! f32vector reader/writer (define-writer write-f32 f32vector) (define-reader read-f32 f32vector f32vector-subtype f32vector-ref 0.0) ;;! f64vector reader/writer (define-writer write-f64 f64vector) (define-reader read-f64 f64vector f64vector-subtype f64vector-ref 0.0) ;;------------------------------------------------------------------------------ ;;!! FFI types serialization ! Adds ability to properly serialize FFI types on ( write ) and properly deserialize them on ( read ) . .author More . MIT License . ;; ref: -list/2013-March/006510.html ;; ;; Usage: ;; (ffi-write-transformer-add! ;; 'name-of-your-ffi-type ;; (lambda (v) `(name-of-constructor-procedure-to-create-an-instance-of-this-ffi-type ;; [ arguments needed to constructor to produce an instance exactly like ;; the one in the v variable ]))) ;; Example: ;; ;; (c-declare #<<end-of-c-declare ;; #include <stdlib.h> ;; typedef struct { int x, y; } point; ;; point *make_point( int x, int y ) { ;; point *p = ___CAST(point*, malloc(sizeof(point))); ; ;; p->y = y; return p ; ;; } int point_x ( point * p ) { return ; } ;; int point_y( point* p ) { return p->y; } ;; end-of-c-declare ;; ) ;; ;; (c-define-type point "point") ;; (c-define-type point* (pointer point)) ;; (define make-point (c-lambda (int int) point* "make_point")) ;; (define point-x (c-lambda (point*) int "point_x")) ;; (define point-y (c-lambda (point*) int "point_y")) ;; ;; (ffi-write-transformer-add! 'point* (lambda (v) `(make-point ,(point-x v) ,(point-y v)))) ;; REPL will show: ;; #.(make-point 2 1) ;; Instead of # < point * # 2 0x1160a90 > Serialize : ;; (object->string (make-point 3 4)) : ;; (string->object "#.(make-point 2 1)") (define *ffi-writer-transformers* (make-table test: eq?)) (define *writer-default* #f) (define (ffi-write-transformer-add! type serializer-proc) (table-set! *ffi-writer-transformers* type serializer-proc)) (define (%%sexp-ext:wr we obj) (if (##foreign? obj) (let* ((name (let ((v (foreign-tags obj))) (and (pair? v) (car v)))) (transformer (table-ref *ffi-writer-transformers* name #f))) (if transformer (let ((transformed-to (transformer obj))) (##wr-str we "#.") ;; (##wr-pair we transformed-to) - transformed-to may be sth else for instance a symbol ;; so instead go with the universal: (*writer-default* we transformed-to)) (##wr-foreign we obj))) (*writer-default* we obj))) ! Initialize FFI serialization extension (define (%%sexp-ext-install!) (and (not (eq? *writer-default* ##wr)) (begin (set! *writer-default* ##wr) (set! ##wr %%sexp-ext:wr) (let* ((port (repl-input-port)) (rt (input-port-readtable port))) ;; (##readtable-char-sharp-handler-set! rt #\< sexp-ext:read-sharp-less) (input-port-readtable-set! port (readtable-eval-allowed?-set rt #t)) (void))))) ! Call to initialize FFI serialization extension (%%sexp-ext-install!) ;;! Object from string (define (string->object s) (call-with-input-string s (lambda (port) (input-port-readtable-set! port (readtable-eval-allowed?-set (input-port-readtable port) #t)) (read port))))
null
https://raw.githubusercontent.com/alvatar/spheres/568836f234a469ef70c69f4a2d9b56d41c3fc5bd/spheres/gambit/ffi/serialization.scm
scheme
!!! FFI object serialization ------------------------------------------------------------------------------ !! C Types: readers/writers Use like this: (call-with-output-file "f64test" (lambda (port) (write-f64 -1.5 port) (write-f64 +inf.0 port) (write-f64 3.1415926 port))) (call-with-input-file "f64test" (lambda (port) (let* ((a (read-f64 port)) (b (read-f64 port)) (c (read-f64 port)) (d (read-f64 port))) (pp (list a b c d))))) !! C Types: readers/writers generation ! u8vector reader/writer Already defined in Gambit ! s8vector reader/writer ! u16vector reader/writer ! s16vector reader/writer ! u32vector reader/writer ! s32vector reader/writer ! u64vector reader/writer ! f32vector reader/writer ! f64vector reader/writer ------------------------------------------------------------------------------ !! FFI types serialization ref: -list/2013-March/006510.html Usage: (ffi-write-transformer-add! 'name-of-your-ffi-type (lambda (v) `(name-of-constructor-procedure-to-create-an-instance-of-this-ffi-type [ arguments needed to constructor to produce an instance exactly like the one in the v variable ]))) Example: (c-declare #<<end-of-c-declare #include <stdlib.h> typedef struct { int x, y; } point; point *make_point( int x, int y ) { point *p = ___CAST(point*, malloc(sizeof(point))); p->y = y; } } int point_y( point* p ) { return p->y; } end-of-c-declare ) (c-define-type point "point") (c-define-type point* (pointer point)) (define make-point (c-lambda (int int) point* "make_point")) (define point-x (c-lambda (point*) int "point_x")) (define point-y (c-lambda (point*) int "point_y")) (ffi-write-transformer-add! 'point* (lambda (v) `(make-point ,(point-x v) ,(point-y v)))) REPL will show: #.(make-point 2 1) Instead of (object->string (make-point 3 4)) (string->object "#.(make-point 2 1)") (##wr-pair we transformed-to) - transformed-to may be sth else for instance a symbol so instead go with the universal: (##readtable-char-sharp-handler-set! rt #\< sexp-ext:read-sharp-less) ! Object from string
.author , 2013 - 2014 . All Rights Reserved . (cond-expand (optimize (declare (standard-bindings) (extended-bindings) (not safe) (block))) (debug (declare (safe) (debug) (debug-location) (debug-source) (debug-environments))) (else (void))) (include "c-define-base-macros#.scm") (include "c-define-reader#.scm") (define u8vector-subtype (##subtype (u8vector))) (define s8vector-subtype (##subtype (s8vector))) (define u16vector-subtype (##subtype (u16vector))) (define s16vector-subtype (##subtype (s16vector))) (define u32vector-subtype (##subtype (u32vector))) (define s32vector-subtype (##subtype (s32vector))) (define u64vector-subtype (##subtype (u64vector))) (define s64vector-subtype (##subtype (s64vector))) (define f32vector-subtype (##subtype (f32vector))) (define f64vector-subtype (##subtype (f64vector))) (define-writer write-s8 s8vector) (define-reader read-s8 s8vector s8vector-subtype s8vector-ref 0) (define-writer write-u16 u16vector) (define-reader read-u16 u16vector u16vector-subtype u16vector-ref 0) (define-writer write-s16 s16vector) (define-reader read-s16 s16vector s16vector-subtype s16vector-ref 0) (define-writer write-u32 u32vector) (define-reader read-u32 u32vector u32vector-subtype u32vector-ref 0) (define-writer write-s32 s32vector) (define-reader read-s32 s32vector s32vector-subtype s32vector-ref 0) (define-writer write-u64 u64vector) (define-reader read-u64 u64vector u64vector-subtype u64vector-ref 0) ! s64vector reader / writer (define-writer write-s64 s64vector) (define-reader read-s64 s64vector s64vector-subtype s64vector-ref 0) (define-writer write-f32 f32vector) (define-reader read-f32 f32vector f32vector-subtype f32vector-ref 0.0) (define-writer write-f64 f64vector) (define-reader read-f64 f64vector f64vector-subtype f64vector-ref 0.0) ! Adds ability to properly serialize FFI types on ( write ) and properly deserialize them on ( read ) . .author More . MIT License . # < point * # 2 0x1160a90 > Serialize : : (define *ffi-writer-transformers* (make-table test: eq?)) (define *writer-default* #f) (define (ffi-write-transformer-add! type serializer-proc) (table-set! *ffi-writer-transformers* type serializer-proc)) (define (%%sexp-ext:wr we obj) (if (##foreign? obj) (let* ((name (let ((v (foreign-tags obj))) (and (pair? v) (car v)))) (transformer (table-ref *ffi-writer-transformers* name #f))) (if transformer (let ((transformed-to (transformer obj))) (##wr-str we "#.") (*writer-default* we transformed-to)) (##wr-foreign we obj))) (*writer-default* we obj))) ! Initialize FFI serialization extension (define (%%sexp-ext-install!) (and (not (eq? *writer-default* ##wr)) (begin (set! *writer-default* ##wr) (set! ##wr %%sexp-ext:wr) (let* ((port (repl-input-port)) (rt (input-port-readtable port))) (input-port-readtable-set! port (readtable-eval-allowed?-set rt #t)) (void))))) ! Call to initialize FFI serialization extension (%%sexp-ext-install!) (define (string->object s) (call-with-input-string s (lambda (port) (input-port-readtable-set! port (readtable-eval-allowed?-set (input-port-readtable port) #t)) (read port))))
95f1845d2a4a4b64bb78db1e7e85c9c51574926c35bcd1411e66c1d8f0693cb6
racket/frtime
fred.rkt
#lang frtime (provide (all-defined-out) (all-from-out racket/class) (all-from-out "mixin-macros.rkt") (all-from-out "aux-mixin-macros.rkt")) (require framework racket/class racket/gui/base racket/string texpict/mrpict "mixin-macros.rkt" "aux-mixin-macros.rkt") ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; Helpers ;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; adding assumed methods (define (add-void-set-value super-class) (class super-class (define/public (set-value v) (void)) (super-new))) (define (callback->pub-meth super-class) (class super-class (define/public (callback-method w e) (void)) (super-new (callback (lambda (w e) (callback-method w e)))))) (define (add-shown super-class) (class super-class (init (shown #f)) (define shown-val shown) (super-new) (inherit show) (show shown-val))) ;; *-event-processor init-argument values (define event-is-val (lambda (es) (map-e car es))) ; (send x get-mouse-events) returns a split procedure over the event-type (define split-mouse-events/type (lambda (evt-src) (split (map-e cadr evt-src) (lambda (evt) (send evt get-event-type))))) ; (send x get-key-events) returns a split procedure over the key code (define split-key-events/type (lambda (evt-src) (split (map-e cadr evt-src) (lambda (evt) (send evt get-key-code))))) (define (send-for-value w e) (send w get-value)) (define (send-for-selection w e) (send w get-selection)) (define (send-for-selections w e) (send w get-selections)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; make state available as eventstreams ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (add-mouse-access super-class) ((callbacks->args-evts mouse-events ; Name of event stream on-subwindow-event ; proc overriding ) split-mouse-events/type super-class)) (define (add-focus-access super-class) ((callbacks->args-evts focus-events on-focus) event-is-val super-class)) (define (add-keypress-split super-class) ((callbacks->args-evts key-events on-subwindow-char) split-key-events/type super-class)) (define (add-size-access super-class) ((callbacks->args-evts size-events on-size) (lambda (x) x) (class super-class (super-new) (define/public (get-size-as-list) (list (send this get-width) (send this get-height)))))) (define (add-size-b super-class) ((mixin-hold size-b get-size-as-list get-size-events) (add-size-access super-class))) (define (add-position-access super-class) ((callbacks->args-evts position-events on-move) (lambda (x) x) (class super-class (super-new) (define/public (get-position-as-list) (list (send this get-x) (send this get-y)))))) (define (add-position-b super-class) ((mixin-hold position-b get-position-as-list get-position-events) (add-position-access super-class))) (define (monitor-set-value super-class) ((callbacks->args-evts set-value-events set-value) event-is-val super-class)) (define (monitor-callback-method super-class) ((callbacks->args-evts callback-events callback-method) (lambda (x) x) super-class)) (define (add-callback-access val-ext super-class) ((mixin-merge-e value-e get-set-value-events get-callback-events) (class (monitor-set-value (monitor-callback-method (callback->pub-meth super-class))) (super-new (callback-events-event-processor (lambda (es) (map-e (lambda (e) (apply val-ext e)) es))))))) (define (add-callback-access/selection val-ext super-class) ((mixin-merge-e selection-e get-set-value-events get-callback-events) (class (monitor-set-value (monitor-callback-method (callback->pub-meth super-class))) (super-new (callback-events-event-processor (lambda (es) (map-e (lambda (e) (apply val-ext e)) es))))))) (define (add-callback-access/selections val-ext super-class) ((mixin-merge-e selections-e get-set-value-events get-callback-events) (class (monitor-set-value (monitor-callback-method (callback->pub-meth super-class))) (super-new (callback-events-event-processor (lambda (es) (map-e (lambda (e) (apply val-ext e)) es))))))) (define add-value-b (mixin-hold value-b get-value get-value-e)) (define add-selection-b (mixin-hold selection-b get-selection get-selection-e)) (define add-selections-b (mixin-hold selections-b get-selections get-selections-e)) ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;; using events to drive object interaction ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define (add-callback-access/loop val-ext super-class) ((events->callbacks value-set set-value) (add-callback-access val-ext super-class))) (define (add-focus-on-event super-class) (class ((events->callbacks focus-when carries-args-for focus) super-class) (init (focus-when (event-receiver))) (define focus-map (map-e (lambda (_) '()) focus-when)) (super-new (focus-when focus-map)))) (define (control-stretchability default widget) (add-signal-controls widget (stretchable-width stretchable-width default) (stretchable-height stretchable-width default))) Standard mixin combinations (define (standard-lift widget) (add-size-b (add-position-b (add-keypress-split (add-focus-on-event (add-mouse-access (add-focus-access (add-signal-controls widget (label set-label "") (enabled enable #t) (min-width min-width 0) (min-height min-height 0) )))))))) (define (standard-container-lift widget) (control-stretchability #t (standard-lift widget))) (define (standard-input-lift accessor val-ext) (lambda (super-class) (add-value-b (accessor val-ext super-class)))) (define (selection-input-lift accessor val-ext) (lambda (super-class) (add-selection-b (accessor val-ext super-class)))) (define (selections-input-lift accessor val-ext) (lambda (super-class) (add-selections-b (accessor val-ext super-class)))) (define ft-frame% ((behavior->callbacks shown show) #f (add-shown (standard-container-lift frame%)))) (define ft-message% (standard-lift message%)) (define ft-button% (add-callback-access (lambda (w e) e) (add-void-set-value (standard-lift button%)))) (define ft-check-box% ((standard-input-lift add-callback-access/loop send-for-value) (standard-lift check-box%))) (define ft-slider% ((standard-input-lift add-callback-access/loop send-for-value) (standard-lift slider%))) ;ideally the default should be the minimum value (define ft-text-field% ((standard-input-lift add-callback-access/loop send-for-value) (standard-lift text-field%))) (define ft-radio-box% ((selection-input-lift add-callback-access/selection send-for-selection) (add-void-set-value (standard-lift radio-box%)))) (define ft-choice% ((selection-input-lift add-callback-access/selection send-for-selection) (add-void-set-value (standard-lift choice%)))) (define ft-list-box% (class ((selections-input-lift add-callback-access/selections send-for-selections) (add-void-set-value (standard-lift list-box%))) (super-new) (define/public (get-selection-b) (let ([selections-b (send this get-selections-b)]) (if (null? selections-b) #f (car selections-b)))))) (define ft-canvas% (class (standard-lift canvas%) (inherit get-dc refresh get-width get-height) (init-field pict) (define bitmap #f) (define bitmap-dc #f) (super-new [paint-callback (lambda (canvas dc) (unless (and bitmap (= (send bitmap get-width) (get-width)) (= (send bitmap get-height) (get-height))) (set! bitmap (make-object bitmap% (get-width) (get-height))) (set! bitmap-dc (new bitmap-dc% [bitmap bitmap]))) (unless (undefined? (value-now pict)) (send bitmap-dc clear) (draw-pict (value-now pict) bitmap-dc 0 0) (send dc draw-bitmap bitmap 0 0)))]) (for-each-e! (changes pict) (lambda (_) (refresh))))) ;; Special case widgets (define specialized-gauge% (add-signal-controls (class gauge% (init value) (super-new) (send this set-value value)) (value set-value 0) (range set-range 1))) (define ft-gauge% (standard-lift specialized-gauge%)) (define ft-menu-item% (add-callback-access list (add-void-set-value menu-item%)))
null
https://raw.githubusercontent.com/racket/frtime/9b9db67581107f4d7b995541c70f2d08f03ae89e/gui/fred.rkt
racket
Helpers adding assumed methods *-event-processor init-argument values (send x get-mouse-events) returns a split procedure over the event-type (send x get-key-events) returns a split procedure over the key code make state available as eventstreams Name of event stream proc overriding using events to drive object interaction ideally the default should be the minimum value Special case widgets
#lang frtime (provide (all-defined-out) (all-from-out racket/class) (all-from-out "mixin-macros.rkt") (all-from-out "aux-mixin-macros.rkt")) (require framework racket/class racket/gui/base racket/string texpict/mrpict "mixin-macros.rkt" "aux-mixin-macros.rkt") (define (add-void-set-value super-class) (class super-class (define/public (set-value v) (void)) (super-new))) (define (callback->pub-meth super-class) (class super-class (define/public (callback-method w e) (void)) (super-new (callback (lambda (w e) (callback-method w e)))))) (define (add-shown super-class) (class super-class (init (shown #f)) (define shown-val shown) (super-new) (inherit show) (show shown-val))) (define event-is-val (lambda (es) (map-e car es))) (define split-mouse-events/type (lambda (evt-src) (split (map-e cadr evt-src) (lambda (evt) (send evt get-event-type))))) (define split-key-events/type (lambda (evt-src) (split (map-e cadr evt-src) (lambda (evt) (send evt get-key-code))))) (define (send-for-value w e) (send w get-value)) (define (send-for-selection w e) (send w get-selection)) (define (send-for-selections w e) (send w get-selections)) (define (add-mouse-access super-class) ) split-mouse-events/type super-class)) (define (add-focus-access super-class) ((callbacks->args-evts focus-events on-focus) event-is-val super-class)) (define (add-keypress-split super-class) ((callbacks->args-evts key-events on-subwindow-char) split-key-events/type super-class)) (define (add-size-access super-class) ((callbacks->args-evts size-events on-size) (lambda (x) x) (class super-class (super-new) (define/public (get-size-as-list) (list (send this get-width) (send this get-height)))))) (define (add-size-b super-class) ((mixin-hold size-b get-size-as-list get-size-events) (add-size-access super-class))) (define (add-position-access super-class) ((callbacks->args-evts position-events on-move) (lambda (x) x) (class super-class (super-new) (define/public (get-position-as-list) (list (send this get-x) (send this get-y)))))) (define (add-position-b super-class) ((mixin-hold position-b get-position-as-list get-position-events) (add-position-access super-class))) (define (monitor-set-value super-class) ((callbacks->args-evts set-value-events set-value) event-is-val super-class)) (define (monitor-callback-method super-class) ((callbacks->args-evts callback-events callback-method) (lambda (x) x) super-class)) (define (add-callback-access val-ext super-class) ((mixin-merge-e value-e get-set-value-events get-callback-events) (class (monitor-set-value (monitor-callback-method (callback->pub-meth super-class))) (super-new (callback-events-event-processor (lambda (es) (map-e (lambda (e) (apply val-ext e)) es))))))) (define (add-callback-access/selection val-ext super-class) ((mixin-merge-e selection-e get-set-value-events get-callback-events) (class (monitor-set-value (monitor-callback-method (callback->pub-meth super-class))) (super-new (callback-events-event-processor (lambda (es) (map-e (lambda (e) (apply val-ext e)) es))))))) (define (add-callback-access/selections val-ext super-class) ((mixin-merge-e selections-e get-set-value-events get-callback-events) (class (monitor-set-value (monitor-callback-method (callback->pub-meth super-class))) (super-new (callback-events-event-processor (lambda (es) (map-e (lambda (e) (apply val-ext e)) es))))))) (define add-value-b (mixin-hold value-b get-value get-value-e)) (define add-selection-b (mixin-hold selection-b get-selection get-selection-e)) (define add-selections-b (mixin-hold selections-b get-selections get-selections-e)) (define (add-callback-access/loop val-ext super-class) ((events->callbacks value-set set-value) (add-callback-access val-ext super-class))) (define (add-focus-on-event super-class) (class ((events->callbacks focus-when carries-args-for focus) super-class) (init (focus-when (event-receiver))) (define focus-map (map-e (lambda (_) '()) focus-when)) (super-new (focus-when focus-map)))) (define (control-stretchability default widget) (add-signal-controls widget (stretchable-width stretchable-width default) (stretchable-height stretchable-width default))) Standard mixin combinations (define (standard-lift widget) (add-size-b (add-position-b (add-keypress-split (add-focus-on-event (add-mouse-access (add-focus-access (add-signal-controls widget (label set-label "") (enabled enable #t) (min-width min-width 0) (min-height min-height 0) )))))))) (define (standard-container-lift widget) (control-stretchability #t (standard-lift widget))) (define (standard-input-lift accessor val-ext) (lambda (super-class) (add-value-b (accessor val-ext super-class)))) (define (selection-input-lift accessor val-ext) (lambda (super-class) (add-selection-b (accessor val-ext super-class)))) (define (selections-input-lift accessor val-ext) (lambda (super-class) (add-selections-b (accessor val-ext super-class)))) (define ft-frame% ((behavior->callbacks shown show) #f (add-shown (standard-container-lift frame%)))) (define ft-message% (standard-lift message%)) (define ft-button% (add-callback-access (lambda (w e) e) (add-void-set-value (standard-lift button%)))) (define ft-check-box% ((standard-input-lift add-callback-access/loop send-for-value) (standard-lift check-box%))) (define ft-slider% ((standard-input-lift add-callback-access/loop send-for-value) (define ft-text-field% ((standard-input-lift add-callback-access/loop send-for-value) (standard-lift text-field%))) (define ft-radio-box% ((selection-input-lift add-callback-access/selection send-for-selection) (add-void-set-value (standard-lift radio-box%)))) (define ft-choice% ((selection-input-lift add-callback-access/selection send-for-selection) (add-void-set-value (standard-lift choice%)))) (define ft-list-box% (class ((selections-input-lift add-callback-access/selections send-for-selections) (add-void-set-value (standard-lift list-box%))) (super-new) (define/public (get-selection-b) (let ([selections-b (send this get-selections-b)]) (if (null? selections-b) #f (car selections-b)))))) (define ft-canvas% (class (standard-lift canvas%) (inherit get-dc refresh get-width get-height) (init-field pict) (define bitmap #f) (define bitmap-dc #f) (super-new [paint-callback (lambda (canvas dc) (unless (and bitmap (= (send bitmap get-width) (get-width)) (= (send bitmap get-height) (get-height))) (set! bitmap (make-object bitmap% (get-width) (get-height))) (set! bitmap-dc (new bitmap-dc% [bitmap bitmap]))) (unless (undefined? (value-now pict)) (send bitmap-dc clear) (draw-pict (value-now pict) bitmap-dc 0 0) (send dc draw-bitmap bitmap 0 0)))]) (for-each-e! (changes pict) (lambda (_) (refresh))))) (define specialized-gauge% (add-signal-controls (class gauge% (init value) (super-new) (send this set-value value)) (value set-value 0) (range set-range 1))) (define ft-gauge% (standard-lift specialized-gauge%)) (define ft-menu-item% (add-callback-access list (add-void-set-value menu-item%)))
9c87f0cde693d5af2679eea7c66d4213d0182eebe5032bd1dbb1f0f3ebfff9a3
expipiplus1/vulkan
VK_NV_device_diagnostic_checkpoints.hs
{-# language CPP #-} -- | = Name -- VK_NV_device_diagnostic_checkpoints - device extension -- = = VK_NV_device_diagnostic_checkpoints -- -- [__Name String__] @VK_NV_device_diagnostic_checkpoints@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] 207 -- -- [__Revision__] 2 -- -- [__Extension and Version Dependencies__] -- - Requires support for Vulkan 1.0 -- -- - Requires @VK_KHR_get_physical_device_properties2@ to be enabled -- for any device-level functionality -- -- [__Contact__] -- - < -Docs/issues/new?body=[VK_NV_device_diagnostic_checkpoints ] @nsubtil%0A*Here describe the issue or question you have about the VK_NV_device_diagnostic_checkpoints extension * > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] 2018 - 07 - 16 -- -- [__Contributors__] -- - , NVIDIA -- - , NVIDIA -- - , NVIDIA -- - , NVIDIA -- - , NVIDIA -- -- == Description -- -- This extension allows applications to insert markers in the command -- stream and associate them with custom data. -- -- If a device lost error occurs, the application /may/ then query the -- implementation for the last markers to cross specific -- implementation-defined pipeline stages, in order to narrow down which -- commands were executing at the time and might have caused the failure. -- -- == New Commands -- -- - 'cmdSetCheckpointNV' -- -- - 'getQueueCheckpointDataNV' -- -- == New Structures -- - ' CheckpointDataNV ' -- -- - Extending ' Vulkan . ' : -- - ' QueueFamilyCheckpointPropertiesNV ' -- -- == New Enum Constants -- -- - 'NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME' -- - ' NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION ' -- - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : -- - ' Vulkan . Core10.Enums . StructureType . ' -- - ' Vulkan . Core10.Enums . StructureType . ' -- -- == Version History -- - Revision 1 , 2018 - 07 - 16 ( ) -- -- - Internal revisions -- - Revision 2 , 2018 - 07 - 16 ( ) -- -- - ??? -- -- == See Also -- -- 'CheckpointDataNV', 'QueueFamilyCheckpointPropertiesNV', -- 'cmdSetCheckpointNV', 'getQueueCheckpointDataNV' -- -- == Document Notes -- -- For more information, see the -- <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_NV_device_diagnostic_checkpoints ( cmdSetCheckpointNV , getQueueCheckpointDataNV , QueueFamilyCheckpointPropertiesNV(..) , CheckpointDataNV(..) , NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION , pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION , NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME , pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.NamedType ((:::)) import Vulkan.Core10.Handles (CommandBuffer) import Vulkan.Core10.Handles (CommandBuffer(..)) import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer)) import Vulkan.Core10.Handles (CommandBuffer_T) import Vulkan.Dynamic (DeviceCmds(pVkCmdSetCheckpointNV)) import Vulkan.Dynamic (DeviceCmds(pVkGetQueueCheckpointDataNV)) import Vulkan.Core10.Enums.PipelineStageFlagBits (PipelineStageFlagBits) import Vulkan.Core10.Enums.PipelineStageFlagBits (PipelineStageFlags) import Vulkan.Core10.Handles (Queue) import Vulkan.Core10.Handles (Queue(..)) import Vulkan.Core10.Handles (Queue(Queue)) import Vulkan.Core10.Handles (Queue_T) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_CHECKPOINT_DATA_NV)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_QUEUE_FAMILY_CHECKPOINT_PROPERTIES_NV)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCmdSetCheckpointNV :: FunPtr (Ptr CommandBuffer_T -> Ptr () -> IO ()) -> Ptr CommandBuffer_T -> Ptr () -> IO () -- | vkCmdSetCheckpointNV - Insert diagnostic checkpoint in command stream -- -- == Valid Usage (Implicit) -- -- - #VUID-vkCmdSetCheckpointNV-commandBuffer-parameter# @commandBuffer@ /must/ be a valid ' Vulkan . Core10.Handles . CommandBuffer ' handle -- - # VUID - vkCmdSetCheckpointNV - commandBuffer - recording # @commandBuffer@ -- /must/ be in the -- <-extensions/html/vkspec.html#commandbuffers-lifecycle recording state> -- -- - #VUID-vkCmdSetCheckpointNV-commandBuffer-cmdpool# The ' Vulkan . Core10.Handles . ' that @commandBuffer@ was -- allocated from /must/ support graphics, compute, or transfer -- operations -- -- - #VUID-vkCmdSetCheckpointNV-videocoding# This command /must/ only be -- called outside of a video coding scope -- -- == Host Synchronization -- -- - Host access to @commandBuffer@ /must/ be externally synchronized -- - Host access to the ' Vulkan . Core10.Handles . ' that -- @commandBuffer@ was allocated from /must/ be externally synchronized -- -- == Command Properties -- -- \' -- -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+ | < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > | -- +============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+ -- | Primary | Both | Outside | Graphics | Action | -- | Secondary | | | Compute | | -- | | | | Transfer | | -- +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+ -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints VK_NV_device_diagnostic_checkpoints>, ' Vulkan . Core10.Handles . CommandBuffer ' cmdSetCheckpointNV :: forall io . (MonadIO io) => -- | @commandBuffer@ is the command buffer that will receive the marker CommandBuffer -> -- | @pCheckpointMarker@ is an opaque application-provided value that will be -- associated with the checkpoint. ("checkpointMarker" ::: Ptr ()) -> io () cmdSetCheckpointNV commandBuffer checkpointMarker = liftIO $ do let vkCmdSetCheckpointNVPtr = pVkCmdSetCheckpointNV (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds) unless (vkCmdSetCheckpointNVPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetCheckpointNV is null" Nothing Nothing let vkCmdSetCheckpointNV' = mkVkCmdSetCheckpointNV vkCmdSetCheckpointNVPtr traceAroundEvent "vkCmdSetCheckpointNV" (vkCmdSetCheckpointNV' (commandBufferHandle (commandBuffer)) (checkpointMarker)) pure $ () foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetQueueCheckpointDataNV :: FunPtr (Ptr Queue_T -> Ptr Word32 -> Ptr CheckpointDataNV -> IO ()) -> Ptr Queue_T -> Ptr Word32 -> Ptr CheckpointDataNV -> IO () -- | vkGetQueueCheckpointDataNV - Retrieve diagnostic checkpoint data -- -- = Description -- If @pCheckpointData@ is @NULL@ , then the number of checkpoint markers -- available is returned in @pCheckpointDataCount@. -- Otherwise , @pCheckpointDataCount@ /must/ point to a variable set by the user to the number of elements in the @pCheckpointData@ array , and on -- return the variable is overwritten with the number of structures actually written to @pCheckpointData@. -- If @pCheckpointDataCount@ is less than the number of checkpoint markers available , at most @pCheckpointDataCount@ structures will be written . -- -- == Valid Usage -- -- - #VUID-vkGetQueueCheckpointDataNV-queue-02025# The device that -- @queue@ belongs to /must/ be in the lost state -- -- == Valid Usage (Implicit) -- -- - #VUID-vkGetQueueCheckpointDataNV-queue-parameter# @queue@ /must/ be a valid ' Vulkan . Core10.Handles . Queue ' handle -- -- - #VUID-vkGetQueueCheckpointDataNV-pCheckpointDataCount-parameter# @pCheckpointDataCount@ /must/ be a valid pointer to a @uint32_t@ -- value -- -- - #VUID-vkGetQueueCheckpointDataNV-pCheckpointData-parameter# If the value referenced by @pCheckpointDataCount@ is not @0@ , and @pCheckpointData@ is not @NULL@ , @pCheckpointData@ /must/ be a valid pointer to an array of @pCheckpointDataCount@ ' CheckpointDataNV ' -- structures -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints VK_NV_device_diagnostic_checkpoints>, ' CheckpointDataNV ' , ' Vulkan . Core10.Handles . Queue ' getQueueCheckpointDataNV :: forall io . (MonadIO io) | @queue@ is the ' Vulkan . Core10.Handles . Queue ' object the caller would -- like to retrieve checkpoint data for Queue -> io (("checkpointData" ::: Vector CheckpointDataNV)) getQueueCheckpointDataNV queue = liftIO . evalContT $ do let vkGetQueueCheckpointDataNVPtr = pVkGetQueueCheckpointDataNV (case queue of Queue{deviceCmds} -> deviceCmds) lift $ unless (vkGetQueueCheckpointDataNVPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetQueueCheckpointDataNV is null" Nothing Nothing let vkGetQueueCheckpointDataNV' = mkVkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNVPtr let queue' = queueHandle (queue) pPCheckpointDataCount <- ContT $ bracket (callocBytes @Word32 4) free lift $ traceAroundEvent "vkGetQueueCheckpointDataNV" (vkGetQueueCheckpointDataNV' queue' (pPCheckpointDataCount) (nullPtr)) pCheckpointDataCount <- lift $ peek @Word32 pPCheckpointDataCount pPCheckpointData <- ContT $ bracket (callocBytes @CheckpointDataNV ((fromIntegral (pCheckpointDataCount)) * 32)) free _ <- traverse (\i -> ContT $ pokeZeroCStruct (pPCheckpointData `advancePtrBytes` (i * 32) :: Ptr CheckpointDataNV) . ($ ())) [0..(fromIntegral (pCheckpointDataCount)) - 1] lift $ traceAroundEvent "vkGetQueueCheckpointDataNV" (vkGetQueueCheckpointDataNV' queue' (pPCheckpointDataCount) ((pPCheckpointData))) pCheckpointDataCount' <- lift $ peek @Word32 pPCheckpointDataCount pCheckpointData' <- lift $ generateM (fromIntegral (pCheckpointDataCount')) (\i -> peekCStruct @CheckpointDataNV (((pPCheckpointData) `advancePtrBytes` (32 * (i)) :: Ptr CheckpointDataNV))) pure $ (pCheckpointData') -- | VkQueueFamilyCheckpointPropertiesNV - Return structure for queue family -- checkpoint information query -- -- = Description -- -- Additional queue family information can be queried by setting ' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.QueueFamilyProperties2'::@pNext@ -- to point to a 'QueueFamilyCheckpointPropertiesNV' structure. -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints VK_NV_device_diagnostic_checkpoints>, ' Vulkan . Core10.Enums . . PipelineStageFlags ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data QueueFamilyCheckpointPropertiesNV = QueueFamilyCheckpointPropertiesNV { -- | @checkpointExecutionStageMask@ is a mask indicating which pipeline -- stages the implementation can execute checkpoint markers in. checkpointExecutionStageMask :: PipelineStageFlags } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (QueueFamilyCheckpointPropertiesNV) #endif deriving instance Show QueueFamilyCheckpointPropertiesNV instance ToCStruct QueueFamilyCheckpointPropertiesNV where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p QueueFamilyCheckpointPropertiesNV{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_QUEUE_FAMILY_CHECKPOINT_PROPERTIES_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr PipelineStageFlags)) (checkpointExecutionStageMask) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_QUEUE_FAMILY_CHECKPOINT_PROPERTIES_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr PipelineStageFlags)) (zero) f instance FromCStruct QueueFamilyCheckpointPropertiesNV where peekCStruct p = do checkpointExecutionStageMask <- peek @PipelineStageFlags ((p `plusPtr` 16 :: Ptr PipelineStageFlags)) pure $ QueueFamilyCheckpointPropertiesNV checkpointExecutionStageMask instance Storable QueueFamilyCheckpointPropertiesNV where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero QueueFamilyCheckpointPropertiesNV where zero = QueueFamilyCheckpointPropertiesNV zero -- | VkCheckpointDataNV - Return structure for command buffer checkpoint data -- -- = Description -- -- The stages at which a checkpoint marker /can/ be executed are implementation - defined and be queried by calling ' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceQueueFamilyProperties2 ' . -- -- == Valid Usage (Implicit) -- -- = See Also -- -- <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints VK_NV_device_diagnostic_checkpoints>, ' Vulkan . Core10.Enums . . ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' , -- 'getQueueCheckpointDataNV' data CheckpointDataNV = CheckpointDataNV { -- | @stage@ is a ' Vulkan . Core10.Enums . . ' value -- specifying which pipeline stage the checkpoint marker data refers to. stage :: PipelineStageFlagBits , -- | @pCheckpointMarker@ contains the value of the last checkpoint marker -- executed in the stage that @stage@ refers to. checkpointMarker :: Ptr () } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (CheckpointDataNV) #endif deriving instance Show CheckpointDataNV instance ToCStruct CheckpointDataNV where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p CheckpointDataNV{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_CHECKPOINT_DATA_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr PipelineStageFlagBits)) (stage) poke ((p `plusPtr` 24 :: Ptr (Ptr ()))) (checkpointMarker) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_CHECKPOINT_DATA_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr PipelineStageFlagBits)) (zero) poke ((p `plusPtr` 24 :: Ptr (Ptr ()))) (zero) f instance FromCStruct CheckpointDataNV where peekCStruct p = do stage <- peek @PipelineStageFlagBits ((p `plusPtr` 16 :: Ptr PipelineStageFlagBits)) pCheckpointMarker <- peek @(Ptr ()) ((p `plusPtr` 24 :: Ptr (Ptr ()))) pure $ CheckpointDataNV stage pCheckpointMarker instance Storable CheckpointDataNV where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero CheckpointDataNV where zero = CheckpointDataNV zero zero type NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION = 2 No documentation found for TopLevel " VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION " pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION :: forall a . Integral a => a pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION = 2 type NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME = "VK_NV_device_diagnostic_checkpoints" No documentation found for TopLevel " VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME " pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME = "VK_NV_device_diagnostic_checkpoints"
null
https://raw.githubusercontent.com/expipiplus1/vulkan/ebc0dde0bcd9cf251f18538de6524eb4f2ab3e9d/src/Vulkan/Extensions/VK_NV_device_diagnostic_checkpoints.hs
haskell
# language CPP # | = Name [__Name String__] [__Extension Type__] Device extension [__Registered Extension Number__] [__Revision__] [__Extension and Version Dependencies__] - Requires @VK_KHR_get_physical_device_properties2@ to be enabled for any device-level functionality [__Contact__] == Other Extension Metadata [__Last Modified Date__] [__Contributors__] == Description This extension allows applications to insert markers in the command stream and associate them with custom data. If a device lost error occurs, the application /may/ then query the implementation for the last markers to cross specific implementation-defined pipeline stages, in order to narrow down which commands were executing at the time and might have caused the failure. == New Commands - 'cmdSetCheckpointNV' - 'getQueueCheckpointDataNV' == New Structures - Extending == New Enum Constants - 'NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME' == Version History - Internal revisions - ??? == See Also 'CheckpointDataNV', 'QueueFamilyCheckpointPropertiesNV', 'cmdSetCheckpointNV', 'getQueueCheckpointDataNV' == Document Notes For more information, see the <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints Vulkan Specification> This page is a generated document. Fixes and changes should be made to the generator scripts, not directly. | vkCmdSetCheckpointNV - Insert diagnostic checkpoint in command stream == Valid Usage (Implicit) - #VUID-vkCmdSetCheckpointNV-commandBuffer-parameter# @commandBuffer@ /must/ be in the <-extensions/html/vkspec.html#commandbuffers-lifecycle recording state> - #VUID-vkCmdSetCheckpointNV-commandBuffer-cmdpool# The allocated from /must/ support graphics, compute, or transfer operations - #VUID-vkCmdSetCheckpointNV-videocoding# This command /must/ only be called outside of a video coding scope == Host Synchronization - Host access to @commandBuffer@ /must/ be externally synchronized @commandBuffer@ was allocated from /must/ be externally synchronized == Command Properties \' +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+ +============================================================================================================================+========================================================================================================================+=============================================================================================================================+=======================================================================================================================+========================================================================================================================================+ | Primary | Both | Outside | Graphics | Action | | Secondary | | | Compute | | | | | | Transfer | | +----------------------------------------------------------------------------------------------------------------------------+------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------------+----------------------------------------------------------------------------------------------------------------------------------------+ = See Also <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints VK_NV_device_diagnostic_checkpoints>, | @commandBuffer@ is the command buffer that will receive the marker | @pCheckpointMarker@ is an opaque application-provided value that will be associated with the checkpoint. | vkGetQueueCheckpointDataNV - Retrieve diagnostic checkpoint data = Description available is returned in @pCheckpointDataCount@. return the variable is overwritten with the number of structures == Valid Usage - #VUID-vkGetQueueCheckpointDataNV-queue-02025# The device that @queue@ belongs to /must/ be in the lost state == Valid Usage (Implicit) - #VUID-vkGetQueueCheckpointDataNV-queue-parameter# @queue@ /must/ be - #VUID-vkGetQueueCheckpointDataNV-pCheckpointDataCount-parameter# value - #VUID-vkGetQueueCheckpointDataNV-pCheckpointData-parameter# If the structures = See Also <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints VK_NV_device_diagnostic_checkpoints>, like to retrieve checkpoint data for | VkQueueFamilyCheckpointPropertiesNV - Return structure for queue family checkpoint information query = Description Additional queue family information can be queried by setting to point to a 'QueueFamilyCheckpointPropertiesNV' structure. == Valid Usage (Implicit) = See Also <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints VK_NV_device_diagnostic_checkpoints>, | @checkpointExecutionStageMask@ is a mask indicating which pipeline stages the implementation can execute checkpoint markers in. | VkCheckpointDataNV - Return structure for command buffer checkpoint data = Description The stages at which a checkpoint marker /can/ be executed are == Valid Usage (Implicit) = See Also <-extensions/html/vkspec.html#VK_NV_device_diagnostic_checkpoints VK_NV_device_diagnostic_checkpoints>, 'getQueueCheckpointDataNV' | @stage@ is a specifying which pipeline stage the checkpoint marker data refers to. | @pCheckpointMarker@ contains the value of the last checkpoint marker executed in the stage that @stage@ refers to.
VK_NV_device_diagnostic_checkpoints - device extension = = VK_NV_device_diagnostic_checkpoints @VK_NV_device_diagnostic_checkpoints@ 207 2 - Requires support for Vulkan 1.0 - < -Docs/issues/new?body=[VK_NV_device_diagnostic_checkpoints ] @nsubtil%0A*Here describe the issue or question you have about the VK_NV_device_diagnostic_checkpoints extension * > 2018 - 07 - 16 - , NVIDIA - , NVIDIA - , NVIDIA - , NVIDIA - , NVIDIA - ' CheckpointDataNV ' ' Vulkan . ' : - ' QueueFamilyCheckpointPropertiesNV ' - ' NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION ' - Extending ' Vulkan . Core10.Enums . StructureType . StructureType ' : - ' Vulkan . Core10.Enums . StructureType . ' - ' Vulkan . Core10.Enums . StructureType . ' - Revision 1 , 2018 - 07 - 16 ( ) - Revision 2 , 2018 - 07 - 16 ( ) module Vulkan.Extensions.VK_NV_device_diagnostic_checkpoints ( cmdSetCheckpointNV , getQueueCheckpointDataNV , QueueFamilyCheckpointPropertiesNV(..) , CheckpointDataNV(..) , NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION , pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION , NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME , pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Exception.Base (bracket) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import Foreign.Marshal.Alloc (callocBytes) import Foreign.Marshal.Alloc (free) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import Data.Vector (generateM) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.CStruct.Utils (advancePtrBytes) import Vulkan.NamedType ((:::)) import Vulkan.Core10.Handles (CommandBuffer) import Vulkan.Core10.Handles (CommandBuffer(..)) import Vulkan.Core10.Handles (CommandBuffer(CommandBuffer)) import Vulkan.Core10.Handles (CommandBuffer_T) import Vulkan.Dynamic (DeviceCmds(pVkCmdSetCheckpointNV)) import Vulkan.Dynamic (DeviceCmds(pVkGetQueueCheckpointDataNV)) import Vulkan.Core10.Enums.PipelineStageFlagBits (PipelineStageFlagBits) import Vulkan.Core10.Enums.PipelineStageFlagBits (PipelineStageFlags) import Vulkan.Core10.Handles (Queue) import Vulkan.Core10.Handles (Queue(..)) import Vulkan.Core10.Handles (Queue(Queue)) import Vulkan.Core10.Handles (Queue_T) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_CHECKPOINT_DATA_NV)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_QUEUE_FAMILY_CHECKPOINT_PROPERTIES_NV)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkCmdSetCheckpointNV :: FunPtr (Ptr CommandBuffer_T -> Ptr () -> IO ()) -> Ptr CommandBuffer_T -> Ptr () -> IO () /must/ be a valid ' Vulkan . Core10.Handles . CommandBuffer ' handle - # VUID - vkCmdSetCheckpointNV - commandBuffer - recording # @commandBuffer@ ' Vulkan . Core10.Handles . ' that @commandBuffer@ was - Host access to the ' Vulkan . Core10.Handles . ' that | < -extensions/html/vkspec.html#VkCommandBufferLevel Command Buffer Levels > | < -extensions/html/vkspec.html#vkCmdBeginRenderPass Render Pass Scope > | < -extensions/html/vkspec.html#vkCmdBeginVideoCodingKHR Video Coding Scope > | < -extensions/html/vkspec.html#VkQueueFlagBits Supported Queue Types > | < -extensions/html/vkspec.html#fundamentals-queueoperation-command-types Command Type > | ' Vulkan . Core10.Handles . CommandBuffer ' cmdSetCheckpointNV :: forall io . (MonadIO io) CommandBuffer ("checkpointMarker" ::: Ptr ()) -> io () cmdSetCheckpointNV commandBuffer checkpointMarker = liftIO $ do let vkCmdSetCheckpointNVPtr = pVkCmdSetCheckpointNV (case commandBuffer of CommandBuffer{deviceCmds} -> deviceCmds) unless (vkCmdSetCheckpointNVPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkCmdSetCheckpointNV is null" Nothing Nothing let vkCmdSetCheckpointNV' = mkVkCmdSetCheckpointNV vkCmdSetCheckpointNVPtr traceAroundEvent "vkCmdSetCheckpointNV" (vkCmdSetCheckpointNV' (commandBufferHandle (commandBuffer)) (checkpointMarker)) pure $ () foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkGetQueueCheckpointDataNV :: FunPtr (Ptr Queue_T -> Ptr Word32 -> Ptr CheckpointDataNV -> IO ()) -> Ptr Queue_T -> Ptr Word32 -> Ptr CheckpointDataNV -> IO () If @pCheckpointData@ is @NULL@ , then the number of checkpoint markers Otherwise , @pCheckpointDataCount@ /must/ point to a variable set by the user to the number of elements in the @pCheckpointData@ array , and on actually written to @pCheckpointData@. If @pCheckpointDataCount@ is less than the number of checkpoint markers available , at most @pCheckpointDataCount@ structures will be written . a valid ' Vulkan . Core10.Handles . Queue ' handle @pCheckpointDataCount@ /must/ be a valid pointer to a @uint32_t@ value referenced by @pCheckpointDataCount@ is not @0@ , and @pCheckpointData@ is not @NULL@ , @pCheckpointData@ /must/ be a valid pointer to an array of @pCheckpointDataCount@ ' CheckpointDataNV ' ' CheckpointDataNV ' , ' Vulkan . Core10.Handles . Queue ' getQueueCheckpointDataNV :: forall io . (MonadIO io) | @queue@ is the ' Vulkan . Core10.Handles . Queue ' object the caller would Queue -> io (("checkpointData" ::: Vector CheckpointDataNV)) getQueueCheckpointDataNV queue = liftIO . evalContT $ do let vkGetQueueCheckpointDataNVPtr = pVkGetQueueCheckpointDataNV (case queue of Queue{deviceCmds} -> deviceCmds) lift $ unless (vkGetQueueCheckpointDataNVPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkGetQueueCheckpointDataNV is null" Nothing Nothing let vkGetQueueCheckpointDataNV' = mkVkGetQueueCheckpointDataNV vkGetQueueCheckpointDataNVPtr let queue' = queueHandle (queue) pPCheckpointDataCount <- ContT $ bracket (callocBytes @Word32 4) free lift $ traceAroundEvent "vkGetQueueCheckpointDataNV" (vkGetQueueCheckpointDataNV' queue' (pPCheckpointDataCount) (nullPtr)) pCheckpointDataCount <- lift $ peek @Word32 pPCheckpointDataCount pPCheckpointData <- ContT $ bracket (callocBytes @CheckpointDataNV ((fromIntegral (pCheckpointDataCount)) * 32)) free _ <- traverse (\i -> ContT $ pokeZeroCStruct (pPCheckpointData `advancePtrBytes` (i * 32) :: Ptr CheckpointDataNV) . ($ ())) [0..(fromIntegral (pCheckpointDataCount)) - 1] lift $ traceAroundEvent "vkGetQueueCheckpointDataNV" (vkGetQueueCheckpointDataNV' queue' (pPCheckpointDataCount) ((pPCheckpointData))) pCheckpointDataCount' <- lift $ peek @Word32 pPCheckpointDataCount pCheckpointData' <- lift $ generateM (fromIntegral (pCheckpointDataCount')) (\i -> peekCStruct @CheckpointDataNV (((pPCheckpointData) `advancePtrBytes` (32 * (i)) :: Ptr CheckpointDataNV))) pure $ (pCheckpointData') ' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.QueueFamilyProperties2'::@pNext@ ' Vulkan . Core10.Enums . . PipelineStageFlags ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' data QueueFamilyCheckpointPropertiesNV = QueueFamilyCheckpointPropertiesNV checkpointExecutionStageMask :: PipelineStageFlags } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (QueueFamilyCheckpointPropertiesNV) #endif deriving instance Show QueueFamilyCheckpointPropertiesNV instance ToCStruct QueueFamilyCheckpointPropertiesNV where withCStruct x f = allocaBytes 24 $ \p -> pokeCStruct p x (f p) pokeCStruct p QueueFamilyCheckpointPropertiesNV{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_QUEUE_FAMILY_CHECKPOINT_PROPERTIES_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr PipelineStageFlags)) (checkpointExecutionStageMask) f cStructSize = 24 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_QUEUE_FAMILY_CHECKPOINT_PROPERTIES_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr PipelineStageFlags)) (zero) f instance FromCStruct QueueFamilyCheckpointPropertiesNV where peekCStruct p = do checkpointExecutionStageMask <- peek @PipelineStageFlags ((p `plusPtr` 16 :: Ptr PipelineStageFlags)) pure $ QueueFamilyCheckpointPropertiesNV checkpointExecutionStageMask instance Storable QueueFamilyCheckpointPropertiesNV where sizeOf ~_ = 24 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero QueueFamilyCheckpointPropertiesNV where zero = QueueFamilyCheckpointPropertiesNV zero implementation - defined and be queried by calling ' Vulkan . Core11.Promoted_From_VK_KHR_get_physical_device_properties2.getPhysicalDeviceQueueFamilyProperties2 ' . ' Vulkan . Core10.Enums . . ' , ' Vulkan . Core10.Enums . StructureType . StructureType ' , data CheckpointDataNV = CheckpointDataNV ' Vulkan . Core10.Enums . . ' value stage :: PipelineStageFlagBits checkpointMarker :: Ptr () } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (CheckpointDataNV) #endif deriving instance Show CheckpointDataNV instance ToCStruct CheckpointDataNV where withCStruct x f = allocaBytes 32 $ \p -> pokeCStruct p x (f p) pokeCStruct p CheckpointDataNV{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_CHECKPOINT_DATA_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr PipelineStageFlagBits)) (stage) poke ((p `plusPtr` 24 :: Ptr (Ptr ()))) (checkpointMarker) f cStructSize = 32 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_CHECKPOINT_DATA_NV) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr PipelineStageFlagBits)) (zero) poke ((p `plusPtr` 24 :: Ptr (Ptr ()))) (zero) f instance FromCStruct CheckpointDataNV where peekCStruct p = do stage <- peek @PipelineStageFlagBits ((p `plusPtr` 16 :: Ptr PipelineStageFlagBits)) pCheckpointMarker <- peek @(Ptr ()) ((p `plusPtr` 24 :: Ptr (Ptr ()))) pure $ CheckpointDataNV stage pCheckpointMarker instance Storable CheckpointDataNV where sizeOf ~_ = 32 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero CheckpointDataNV where zero = CheckpointDataNV zero zero type NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION = 2 No documentation found for TopLevel " VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION " pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION :: forall a . Integral a => a pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_SPEC_VERSION = 2 type NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME = "VK_NV_device_diagnostic_checkpoints" No documentation found for TopLevel " VK_NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME " pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern NV_DEVICE_DIAGNOSTIC_CHECKPOINTS_EXTENSION_NAME = "VK_NV_device_diagnostic_checkpoints"
77ac21411e04eee72403b81e89db12893be23cf04c1b0ba9efd8e471a1838bb0
jixiuf/helloerlang
emysql_execute.erl
-module(emysql_execute). -export([execute/1]). -include("tbl_fileds.hrl"). -include("game_log_server_macro.hrl"). -include_lib("emysql/include/emysql.hrl"). -import(emysql_center, [quote/1]). execute({insert_tbl_reg,#tbl_reg{}=Record}) -> try Sql="call insert_tbl_reg(" ++ quote(Record#tbl_reg.accountType ) ++","++ quote(Record#tbl_reg.playerId ) ++","++ quote(Record#tbl_reg.playerName ) ++","++ quote(Record#tbl_reg.logTime ) ++","++ quote(Record#tbl_reg.clientVersion ) ++","++ quote(Record#tbl_reg.clientType ) ++","++ quote(Record#tbl_reg.issuers ) ++","++ quote(Record#tbl_reg.flashPlayerVersion ) ++","++ quote(Record#tbl_reg.connectType ) ++","++ quote(Record#tbl_reg.gameServerName ) ++","++ quote(Record#tbl_reg.ipAddr ) ++","++ quote(Record#tbl_reg.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_onlinenum,#tbl_onlinenum{}=Record}) -> try Sql="call insert_tbl_onlinenum(" ++ quote(Record#tbl_onlinenum.onlinenum ) ++","++ quote(Record#tbl_onlinenum.gameServerName ) ++","++ quote(Record#tbl_onlinenum.logTime ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_item_change,#tbl_item_change{}=Record}) -> try Sql="call insert_tbl_item_change(" ++ quote(Record#tbl_item_change.accountType ) ++","++ quote(Record#tbl_item_change.playerId ) ++","++ quote(Record#tbl_item_change.playerName ) ++","++ quote(Record#tbl_item_change.itemId ) ++","++ quote(Record#tbl_item_change.itemTid ) ++","++ quote(Record#tbl_item_change.itemPosId ) ++","++ quote(Record#tbl_item_change.extList ) ++","++ quote(Record#tbl_item_change.oT_OLDEQUIP_ID ) ++","++ quote(Record#tbl_item_change.oT_OLDEQUIP_SOURCE_DATA_INDEX ) ++","++ quote(Record#tbl_item_change.oT_ACTION_TYPE ) ++","++ quote(Record#tbl_item_change.oT_ACTION_TIME ) ++","++ quote(Record#tbl_item_change.oT_EQUIPMENT_MAP ) ++","++ quote(Record#tbl_item_change.oT_EQUIPMENT_NOTE ) ++","++ quote(Record#tbl_item_change.oT_ISSUERS_ID ) ++","++ quote(Record#tbl_item_change.oT_GAME_SERVER_NAME ) ++","++ quote(Record#tbl_item_change.oT_GAME_ZONE_NAME ) ++","++ quote(Record#tbl_item_change.account ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_consume_item,#tbl_consume_item{}=Record}) -> try Sql="call insert_tbl_consume_item(" ++ quote(Record#tbl_consume_item.accountType ) ++","++ quote(Record#tbl_consume_item.playerId ) ++","++ quote(Record#tbl_consume_item.playerName ) ++","++ quote(Record#tbl_consume_item.consumeItem ) ++","++ quote(Record#tbl_consume_item.consumeCount ) ++","++ quote(Record#tbl_consume_item.itemType ) ++","++ quote(Record#tbl_consume_item.itemTid ) ++","++ quote(Record#tbl_consume_item.itemId ) ++","++ quote(Record#tbl_consume_item.itemSellCoin ) ++","++ quote(Record#tbl_consume_item.logTime ) ++","++ quote(Record#tbl_consume_item.mapId ) ++","++ quote(Record#tbl_consume_item.sellNpcId ) ++","++ quote(Record#tbl_consume_item.clientVersion ) ++","++ quote(Record#tbl_consume_item.clientType ) ++","++ quote(Record#tbl_consume_item.issuers ) ++","++ quote(Record#tbl_consume_item.flashPlayerVersion ) ++","++ quote(Record#tbl_consume_item.connectType ) ++","++ quote(Record#tbl_consume_item.gameServerName ) ++","++ quote(Record#tbl_consume_item.ipAddr ) ++","++ quote(Record#tbl_consume_item.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_add_item,#tbl_add_item{}=Record}) -> try Sql="call insert_tbl_add_item(" ++ quote(Record#tbl_add_item.accountType ) ++","++ quote(Record#tbl_add_item.playerId ) ++","++ quote(Record#tbl_add_item.playerName ) ++","++ quote(Record#tbl_add_item.addItemType ) ++","++ quote(Record#tbl_add_item.itemCount ) ++","++ quote(Record#tbl_add_item.itemType ) ++","++ quote(Record#tbl_add_item.itemTid ) ++","++ quote(Record#tbl_add_item.itemId ) ++","++ quote(Record#tbl_add_item.needCoin ) ++","++ quote(Record#tbl_add_item.needMoney ) ++","++ quote(Record#tbl_add_item.logTime ) ++","++ quote(Record#tbl_add_item.mapId ) ++","++ quote(Record#tbl_add_item.giverId ) ++","++ quote(Record#tbl_add_item.taskId ) ++","++ quote(Record#tbl_add_item.addItemResult ) ++","++ quote(Record#tbl_add_item.clientVersion ) ++","++ quote(Record#tbl_add_item.clientType ) ++","++ quote(Record#tbl_add_item.issuers ) ++","++ quote(Record#tbl_add_item.flashPlayerVersion ) ++","++ quote(Record#tbl_add_item.connectType ) ++","++ quote(Record#tbl_add_item.gameServerName ) ++","++ quote(Record#tbl_add_item.ipAddr ) ++","++ quote(Record#tbl_add_item.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_add_gold,#tbl_add_gold{}=Record}) -> try Sql="call insert_tbl_add_gold(" ++ quote(Record#tbl_add_gold.accountType ) ++","++ quote(Record#tbl_add_gold.playerId ) ++","++ quote(Record#tbl_add_gold.playerName ) ++","++ quote(Record#tbl_add_gold.addGoldType ) ++","++ quote(Record#tbl_add_gold.addMoney ) ++","++ quote(Record#tbl_add_gold.addCoin ) ++","++ quote(Record#tbl_add_gold.giverId ) ++","++ quote(Record#tbl_add_gold.taskId ) ++","++ quote(Record#tbl_add_gold.logTime ) ++","++ quote(Record#tbl_add_gold.mapId ) ++","++ quote(Record#tbl_add_gold.sellItemType ) ++","++ quote(Record#tbl_add_gold.sellItemTid ) ++","++ quote(Record#tbl_add_gold.sellItemId ) ++","++ quote(Record#tbl_add_gold.clientVersion ) ++","++ quote(Record#tbl_add_gold.clientType ) ++","++ quote(Record#tbl_add_gold.issuers ) ++","++ quote(Record#tbl_add_gold.flashPlayerVersion ) ++","++ quote(Record#tbl_add_gold.gameServerName ) ++","++ quote(Record#tbl_add_gold.ipAddr ) ++","++ quote(Record#tbl_add_gold.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_add_exp,#tbl_add_exp{}=Record}) -> try Sql="call insert_tbl_add_exp(" ++ quote(Record#tbl_add_exp.accountType ) ++","++ quote(Record#tbl_add_exp.playerId ) ++","++ quote(Record#tbl_add_exp.playerName ) ++","++ quote(Record#tbl_add_exp.addExpType ) ++","++ quote(Record#tbl_add_exp.isLevelUp ) ++","++ quote(Record#tbl_add_exp.oldLevel ) ++","++ quote(Record#tbl_add_exp.newLevel ) ++","++ quote(Record#tbl_add_exp.addExp ) ++","++ quote(Record#tbl_add_exp.giverId ) ++","++ quote(Record#tbl_add_exp.taskId ) ++","++ quote(Record#tbl_add_exp.logTime ) ++","++ quote(Record#tbl_add_exp.mapId ) ++","++ quote(Record#tbl_add_exp.clientVersion ) ++","++ quote(Record#tbl_add_exp.clientType ) ++","++ quote(Record#tbl_add_exp.issuers ) ++","++ quote(Record#tbl_add_exp.flashPlayerVersion ) ++","++ quote(Record#tbl_add_exp.connectType ) ++","++ quote(Record#tbl_add_exp.gameServerName ) ++","++ quote(Record#tbl_add_exp.ipAddr ) ++","++ quote(Record#tbl_add_exp.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_on_off,#tbl_on_off{}=Record}) -> try Sql="call insert_tbl_on_off(" ++ quote(Record#tbl_on_off.accountId ) ++","++ quote(Record#tbl_on_off.accountType ) ++","++ quote(Record#tbl_on_off.playerId ) ++","++ quote(Record#tbl_on_off.headHeroId ) ++","++ quote(Record#tbl_on_off.playerLevel ) ++","++ quote(Record#tbl_on_off.playerName ) ++","++ quote(Record#tbl_on_off.logTime ) ++","++ quote(Record#tbl_on_off.clientVersion ) ++","++ quote(Record#tbl_on_off.clientType ) ++","++ quote(Record#tbl_on_off.issuers ) ++","++ quote(Record#tbl_on_off.flashPlayerVersion ) ++","++ quote(Record#tbl_on_off.connectType ) ++","++ quote(Record#tbl_on_off.gameServerName ) ++","++ quote(Record#tbl_on_off.ipAddr ) ++","++ quote(Record#tbl_on_off.onOffType ) ++ ")", %% io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> %% io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end.
null
https://raw.githubusercontent.com/jixiuf/helloerlang/3960eb4237b026f98edf35d6064539259a816d58/gls/src/emysql_execute.erl
erlang
io:format("sql:~p~n",[Sql]) , io:format("~p~n",[R]) ,
-module(emysql_execute). -export([execute/1]). -include("tbl_fileds.hrl"). -include("game_log_server_macro.hrl"). -include_lib("emysql/include/emysql.hrl"). -import(emysql_center, [quote/1]). execute({insert_tbl_reg,#tbl_reg{}=Record}) -> try Sql="call insert_tbl_reg(" ++ quote(Record#tbl_reg.accountType ) ++","++ quote(Record#tbl_reg.playerId ) ++","++ quote(Record#tbl_reg.playerName ) ++","++ quote(Record#tbl_reg.logTime ) ++","++ quote(Record#tbl_reg.clientVersion ) ++","++ quote(Record#tbl_reg.clientType ) ++","++ quote(Record#tbl_reg.issuers ) ++","++ quote(Record#tbl_reg.flashPlayerVersion ) ++","++ quote(Record#tbl_reg.connectType ) ++","++ quote(Record#tbl_reg.gameServerName ) ++","++ quote(Record#tbl_reg.ipAddr ) ++","++ quote(Record#tbl_reg.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_onlinenum,#tbl_onlinenum{}=Record}) -> try Sql="call insert_tbl_onlinenum(" ++ quote(Record#tbl_onlinenum.onlinenum ) ++","++ quote(Record#tbl_onlinenum.gameServerName ) ++","++ quote(Record#tbl_onlinenum.logTime ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_item_change,#tbl_item_change{}=Record}) -> try Sql="call insert_tbl_item_change(" ++ quote(Record#tbl_item_change.accountType ) ++","++ quote(Record#tbl_item_change.playerId ) ++","++ quote(Record#tbl_item_change.playerName ) ++","++ quote(Record#tbl_item_change.itemId ) ++","++ quote(Record#tbl_item_change.itemTid ) ++","++ quote(Record#tbl_item_change.itemPosId ) ++","++ quote(Record#tbl_item_change.extList ) ++","++ quote(Record#tbl_item_change.oT_OLDEQUIP_ID ) ++","++ quote(Record#tbl_item_change.oT_OLDEQUIP_SOURCE_DATA_INDEX ) ++","++ quote(Record#tbl_item_change.oT_ACTION_TYPE ) ++","++ quote(Record#tbl_item_change.oT_ACTION_TIME ) ++","++ quote(Record#tbl_item_change.oT_EQUIPMENT_MAP ) ++","++ quote(Record#tbl_item_change.oT_EQUIPMENT_NOTE ) ++","++ quote(Record#tbl_item_change.oT_ISSUERS_ID ) ++","++ quote(Record#tbl_item_change.oT_GAME_SERVER_NAME ) ++","++ quote(Record#tbl_item_change.oT_GAME_ZONE_NAME ) ++","++ quote(Record#tbl_item_change.account ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_consume_item,#tbl_consume_item{}=Record}) -> try Sql="call insert_tbl_consume_item(" ++ quote(Record#tbl_consume_item.accountType ) ++","++ quote(Record#tbl_consume_item.playerId ) ++","++ quote(Record#tbl_consume_item.playerName ) ++","++ quote(Record#tbl_consume_item.consumeItem ) ++","++ quote(Record#tbl_consume_item.consumeCount ) ++","++ quote(Record#tbl_consume_item.itemType ) ++","++ quote(Record#tbl_consume_item.itemTid ) ++","++ quote(Record#tbl_consume_item.itemId ) ++","++ quote(Record#tbl_consume_item.itemSellCoin ) ++","++ quote(Record#tbl_consume_item.logTime ) ++","++ quote(Record#tbl_consume_item.mapId ) ++","++ quote(Record#tbl_consume_item.sellNpcId ) ++","++ quote(Record#tbl_consume_item.clientVersion ) ++","++ quote(Record#tbl_consume_item.clientType ) ++","++ quote(Record#tbl_consume_item.issuers ) ++","++ quote(Record#tbl_consume_item.flashPlayerVersion ) ++","++ quote(Record#tbl_consume_item.connectType ) ++","++ quote(Record#tbl_consume_item.gameServerName ) ++","++ quote(Record#tbl_consume_item.ipAddr ) ++","++ quote(Record#tbl_consume_item.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_add_item,#tbl_add_item{}=Record}) -> try Sql="call insert_tbl_add_item(" ++ quote(Record#tbl_add_item.accountType ) ++","++ quote(Record#tbl_add_item.playerId ) ++","++ quote(Record#tbl_add_item.playerName ) ++","++ quote(Record#tbl_add_item.addItemType ) ++","++ quote(Record#tbl_add_item.itemCount ) ++","++ quote(Record#tbl_add_item.itemType ) ++","++ quote(Record#tbl_add_item.itemTid ) ++","++ quote(Record#tbl_add_item.itemId ) ++","++ quote(Record#tbl_add_item.needCoin ) ++","++ quote(Record#tbl_add_item.needMoney ) ++","++ quote(Record#tbl_add_item.logTime ) ++","++ quote(Record#tbl_add_item.mapId ) ++","++ quote(Record#tbl_add_item.giverId ) ++","++ quote(Record#tbl_add_item.taskId ) ++","++ quote(Record#tbl_add_item.addItemResult ) ++","++ quote(Record#tbl_add_item.clientVersion ) ++","++ quote(Record#tbl_add_item.clientType ) ++","++ quote(Record#tbl_add_item.issuers ) ++","++ quote(Record#tbl_add_item.flashPlayerVersion ) ++","++ quote(Record#tbl_add_item.connectType ) ++","++ quote(Record#tbl_add_item.gameServerName ) ++","++ quote(Record#tbl_add_item.ipAddr ) ++","++ quote(Record#tbl_add_item.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_add_gold,#tbl_add_gold{}=Record}) -> try Sql="call insert_tbl_add_gold(" ++ quote(Record#tbl_add_gold.accountType ) ++","++ quote(Record#tbl_add_gold.playerId ) ++","++ quote(Record#tbl_add_gold.playerName ) ++","++ quote(Record#tbl_add_gold.addGoldType ) ++","++ quote(Record#tbl_add_gold.addMoney ) ++","++ quote(Record#tbl_add_gold.addCoin ) ++","++ quote(Record#tbl_add_gold.giverId ) ++","++ quote(Record#tbl_add_gold.taskId ) ++","++ quote(Record#tbl_add_gold.logTime ) ++","++ quote(Record#tbl_add_gold.mapId ) ++","++ quote(Record#tbl_add_gold.sellItemType ) ++","++ quote(Record#tbl_add_gold.sellItemTid ) ++","++ quote(Record#tbl_add_gold.sellItemId ) ++","++ quote(Record#tbl_add_gold.clientVersion ) ++","++ quote(Record#tbl_add_gold.clientType ) ++","++ quote(Record#tbl_add_gold.issuers ) ++","++ quote(Record#tbl_add_gold.flashPlayerVersion ) ++","++ quote(Record#tbl_add_gold.gameServerName ) ++","++ quote(Record#tbl_add_gold.ipAddr ) ++","++ quote(Record#tbl_add_gold.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_add_exp,#tbl_add_exp{}=Record}) -> try Sql="call insert_tbl_add_exp(" ++ quote(Record#tbl_add_exp.accountType ) ++","++ quote(Record#tbl_add_exp.playerId ) ++","++ quote(Record#tbl_add_exp.playerName ) ++","++ quote(Record#tbl_add_exp.addExpType ) ++","++ quote(Record#tbl_add_exp.isLevelUp ) ++","++ quote(Record#tbl_add_exp.oldLevel ) ++","++ quote(Record#tbl_add_exp.newLevel ) ++","++ quote(Record#tbl_add_exp.addExp ) ++","++ quote(Record#tbl_add_exp.giverId ) ++","++ quote(Record#tbl_add_exp.taskId ) ++","++ quote(Record#tbl_add_exp.logTime ) ++","++ quote(Record#tbl_add_exp.mapId ) ++","++ quote(Record#tbl_add_exp.clientVersion ) ++","++ quote(Record#tbl_add_exp.clientType ) ++","++ quote(Record#tbl_add_exp.issuers ) ++","++ quote(Record#tbl_add_exp.flashPlayerVersion ) ++","++ quote(Record#tbl_add_exp.connectType ) ++","++ quote(Record#tbl_add_exp.gameServerName ) ++","++ quote(Record#tbl_add_exp.ipAddr ) ++","++ quote(Record#tbl_add_exp.accountId ) ++ ")", io:format("sql:~p~n",[Sql]) , Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> io:format("~p~n",[R]) , error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end; execute({insert_tbl_on_off,#tbl_on_off{}=Record}) -> try Sql="call insert_tbl_on_off(" ++ quote(Record#tbl_on_off.accountId ) ++","++ quote(Record#tbl_on_off.accountType ) ++","++ quote(Record#tbl_on_off.playerId ) ++","++ quote(Record#tbl_on_off.headHeroId ) ++","++ quote(Record#tbl_on_off.playerLevel ) ++","++ quote(Record#tbl_on_off.playerName ) ++","++ quote(Record#tbl_on_off.logTime ) ++","++ quote(Record#tbl_on_off.clientVersion ) ++","++ quote(Record#tbl_on_off.clientType ) ++","++ quote(Record#tbl_on_off.issuers ) ++","++ quote(Record#tbl_on_off.flashPlayerVersion ) ++","++ quote(Record#tbl_on_off.connectType ) ++","++ quote(Record#tbl_on_off.gameServerName ) ++","++ quote(Record#tbl_on_off.ipAddr ) ++","++ quote(Record#tbl_on_off.onOffType ) ++ ")", Result=emysql:execute(?DEF_POOL_ID, list_to_binary(Sql)), case Result of #error_packet{}=R-> error; #ok_packet{}-> ok end catch error:Error-> io:format("error:~p~n",[Error]), error end.
1e96aa09567fdc9a08ee7f231d1b8d9aea1f8ef546be0492bf191c26c0de5c66
postspectacular/devart-codefactory
user.clj
(ns thi.ng.gae.services.user (:require [thi.ng.gae.services.core :refer [defservice]]) (:import [com.google.appengine.api.users User UserService UserServiceFactory])) (defservice get-user-service *user-service* UserService (UserServiceFactory/getUserService)) (defn ^User current-user [] (.getCurrentUser (get-user-service))) (defn logged-in? [] (.isUserLoggedIn (get-user-service))) (defn admin? [] (.isUserAdmin (get-user-service))) (defn login-url [^String redirect] (.createLoginURL (get-user-service) redirect)) (defn logout-url [^String redirect] (.createLogoutURL (get-user-service) redirect)) (defn user-id [^User user] (.getUserId user)) (defn user-email [^User user] (.getEmail user)) (defn user-nickname [^User user] (.getNickname user)) (defn user-auth-domain [^User user] (.getAuthDomain user))
null
https://raw.githubusercontent.com/postspectacular/devart-codefactory/9bccdc10e58fa4861a69767e9ae4be0bb8d7f650/src-gae/thi/ng/gae/services/user.clj
clojure
(ns thi.ng.gae.services.user (:require [thi.ng.gae.services.core :refer [defservice]]) (:import [com.google.appengine.api.users User UserService UserServiceFactory])) (defservice get-user-service *user-service* UserService (UserServiceFactory/getUserService)) (defn ^User current-user [] (.getCurrentUser (get-user-service))) (defn logged-in? [] (.isUserLoggedIn (get-user-service))) (defn admin? [] (.isUserAdmin (get-user-service))) (defn login-url [^String redirect] (.createLoginURL (get-user-service) redirect)) (defn logout-url [^String redirect] (.createLogoutURL (get-user-service) redirect)) (defn user-id [^User user] (.getUserId user)) (defn user-email [^User user] (.getEmail user)) (defn user-nickname [^User user] (.getNickname user)) (defn user-auth-domain [^User user] (.getAuthDomain user))
6c39a0b64a00f342c30fafa0ba2c64dc1c91d21d4f0e4bc5fc54eb86b0b414ab
folivetti/ITEA
Algorithms.hs
| Module : IT.Algorithms Description : Basic algorithms data structures Copyright : ( c ) , 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Definitions for a Solution , Population of solutions , fitness function and mutation function . Module : IT.Algorithms Description : Basic algorithms data structures Copyright : (c) Fabricio Olivetti de Franca, 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Definitions for a Solution, Population of solutions, fitness function and mutation function. -} module IT.Algorithms where import IT import IT.Random import IT.Metrics import Control.DeepSeq import qualified Numeric.LinearAlgebra as LA -- | data type containing a solution, its fitness and weight vector ' a ' refers to the type of , ' b ' refers to a container of statistics . data Solution = Sol { _expr :: Expr -- ^ The IT expression of type a , _fit :: [Double] -- ^ Fitness and other measures for evaluating the expression , _constr :: Double -- ^ Amount of Shape Constraint violation associated with the expression, always positive ^ Expression size as per -benchmark/blob/dev/CONTRIBUTING.md , _penalty :: Double -- ^ penalty of fitness , _weights :: [Vector] -- ^ Weights associated with the expression (they count towards the length) } instance Show Solution where show (Sol e f c l _ w) = concat ["Expression: " , expr, "\n" , "Fitness: " , fit, "\n" , "Weights: " , weights, "\n" , "Constraints: ", constr, "\n" , "Length: " , len, "\n"] where expr = toExprStr e (LA.toList $ head w) fit = (show . head) f weights = show w constr = show c len = show l -- | These instances are only to find the best and worst individuals -- of a population. instance Eq Solution where | ' ' instance to sort a sequence -- of solutions by fitness s1 == s2 = (head._fit) s1 + _penalty s1 == (head._fit) s2 + _penalty s2 instance Ord Solution where | ' ' instance to sort a sequence -- of solutions by fitness s1 <= s2 = (head._fit) s1 + _penalty s1 <= (head._fit) s2 + _penalty s2 -- | A population of 'Solution a b' type Population = [Solution] instance NFData Solution where rnf _ = () -- | 'Fitness' function that takes a list of expressions and -- returns an evaluated population. -- This function is a good candidate for parallelization. type Fitness a b = [ a ] - > Population a b -- ( a , Double , b ) type Fitness = Expr -> Maybe Solution -- | 'Constraint' is a function that receives an expression and its coefficients -- and return the penalty associated with the constraint violation. type Constraint = Expr -> [Double] -> Double -- | 'Mutation' function with signature 'Solution a b -> Rnd (Solution a b)' type Mutation = Expr -> Rnd Expr
null
https://raw.githubusercontent.com/folivetti/ITEA/fc13e52bc7297ef5142591ee56b7973498fb8770/src/IT/Algorithms.hs
haskell
| data type containing a solution, its fitness and weight vector ^ The IT expression of type a ^ Fitness and other measures for evaluating the expression ^ Amount of Shape Constraint violation associated with the expression, always positive ^ penalty of fitness ^ Weights associated with the expression (they count towards the length) | These instances are only to find the best and worst individuals of a population. of solutions by fitness of solutions by fitness | A population of 'Solution a b' | 'Fitness' function that takes a list of expressions and returns an evaluated population. This function is a good candidate for parallelization. ( a , Double , b ) | 'Constraint' is a function that receives an expression and its coefficients and return the penalty associated with the constraint violation. | 'Mutation' function with signature 'Solution a b -> Rnd (Solution a b)'
| Module : IT.Algorithms Description : Basic algorithms data structures Copyright : ( c ) , 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Definitions for a Solution , Population of solutions , fitness function and mutation function . Module : IT.Algorithms Description : Basic algorithms data structures Copyright : (c) Fabricio Olivetti de Franca, 2020 License : GPL-3 Maintainer : Stability : experimental Portability : POSIX Definitions for a Solution, Population of solutions, fitness function and mutation function. -} module IT.Algorithms where import IT import IT.Random import IT.Metrics import Control.DeepSeq import qualified Numeric.LinearAlgebra as LA ' a ' refers to the type of , ' b ' refers to a container of statistics . ^ Expression size as per -benchmark/blob/dev/CONTRIBUTING.md } instance Show Solution where show (Sol e f c l _ w) = concat ["Expression: " , expr, "\n" , "Fitness: " , fit, "\n" , "Weights: " , weights, "\n" , "Constraints: ", constr, "\n" , "Length: " , len, "\n"] where expr = toExprStr e (LA.toList $ head w) fit = (show . head) f weights = show w constr = show c len = show l instance Eq Solution where | ' ' instance to sort a sequence s1 == s2 = (head._fit) s1 + _penalty s1 == (head._fit) s2 + _penalty s2 instance Ord Solution where | ' ' instance to sort a sequence s1 <= s2 = (head._fit) s1 + _penalty s1 <= (head._fit) s2 + _penalty s2 type Population = [Solution] instance NFData Solution where rnf _ = () type Fitness = Expr -> Maybe Solution type Constraint = Expr -> [Double] -> Double type Mutation = Expr -> Rnd Expr
53dc5889aa2ebe46424c38c7b525d1bbe591c24718fccab22c430e4663eafebc
Octachron/rational_in_types
fraction.ml
module N = Natural module L = Logic_gates module Int = Integer module A = Opt_integer_ops type +'a t = 'num Int.t * 'div Int.t constraint 'a = < num: 'num; div: 'div > ;; let frac: 'a Int.t -> 'b Int.t -> <num:'a;div:'b> t = fun x y -> x,y let num (a,b : 'a t) = a let div (a,b : 'a t) = b let transmute : 'a t -> 'b t = fun (x,y) -> N.(transmute x, transmute y) let duplicate : 'a t -> 'b t * 'c t = fun (x,y) -> let x,x' = Int.duplicate x and y, y' = Int.duplicate y in frac x y, frac x' y' let if_ :('a,'b,'c,'r) L.if_ -> 'a N.t -> 'b t -> 'c t -> 'r t = fun _ a b c -> if N.to_int a = 0 then transmute b else transmute c let if_ a b = if_ L.If a b let uminus (a,b : 'a t) = frac (A.uminus a) b let add x y = let num1, num1' = Int.duplicate @@ num x in let num2, num2' = Int.duplicate @@ num y in let div1_t, div1',div1_r = Int.duplicate2 @@ div x in let div2_t, div2', div2'' = Int.duplicate2 @@ div y in let div1'',div1''' = Int.duplicate div1_r in let best = frac A.Ops.( num1 + num2) div1' in let gen = frac A.Ops.( num1' * div2'' + num2' * div1''') A.Ops.(div1'' * div2' ) in let test = Int.eq div1_t div2_t in if_ test best gen let minus x y = add x @@ uminus y let mult (a,b : 'a t) (c,d: 'b t) = frac A.Ops.(a*c) A.Ops.(b*d) let inv (a,b : 'a t ) = frac b a let div x y = mult x @@ inv y let eq (num_x,div_x) (num_y,div_y) = todo : 2n bits operation Int.( eq l r ) module Eq = struct type absurd type +'a proof = Proof constraint 'a = 'x * 'y let convert: ('a * 'b) proof -> 'a t -> 'b t = fun _ x -> transmute x let transmute: 'a proof -> 'b proof = fun eq -> Proof let if_ :('a, absurd*absurd,'b, 'r) L.if_ -> 'a N.t -> 'b proof -> 'r proof = fun _ a b -> Proof let if_ x y = if_ L.If x y let mk_proof x y = let (x:'a t), (num_x,div_x) = duplicate x and (y:' b t), (num_y,div_y) = duplicate y in todo : 2n bits operation let test = Int.( eq l r ) in if_ test ( Proof: ('a * 'b) proof ) end let ( %->% ) x y = let open Eq in convert (mk_proof x y) x module Ops = struct let ( + ) x y = add x y let ( ~- ) x = uminus x let ( - ) x y = minus x y let ( * ) x y = mult x y let ( ~/ ) x = inv x let ( / ) x y = div x y let ( // ) x y = frac x y end
null
https://raw.githubusercontent.com/Octachron/rational_in_types/c4351c805cbeff2c2843f8ea1e7899bfc3859be5/src/fraction.ml
ocaml
module N = Natural module L = Logic_gates module Int = Integer module A = Opt_integer_ops type +'a t = 'num Int.t * 'div Int.t constraint 'a = < num: 'num; div: 'div > ;; let frac: 'a Int.t -> 'b Int.t -> <num:'a;div:'b> t = fun x y -> x,y let num (a,b : 'a t) = a let div (a,b : 'a t) = b let transmute : 'a t -> 'b t = fun (x,y) -> N.(transmute x, transmute y) let duplicate : 'a t -> 'b t * 'c t = fun (x,y) -> let x,x' = Int.duplicate x and y, y' = Int.duplicate y in frac x y, frac x' y' let if_ :('a,'b,'c,'r) L.if_ -> 'a N.t -> 'b t -> 'c t -> 'r t = fun _ a b c -> if N.to_int a = 0 then transmute b else transmute c let if_ a b = if_ L.If a b let uminus (a,b : 'a t) = frac (A.uminus a) b let add x y = let num1, num1' = Int.duplicate @@ num x in let num2, num2' = Int.duplicate @@ num y in let div1_t, div1',div1_r = Int.duplicate2 @@ div x in let div2_t, div2', div2'' = Int.duplicate2 @@ div y in let div1'',div1''' = Int.duplicate div1_r in let best = frac A.Ops.( num1 + num2) div1' in let gen = frac A.Ops.( num1' * div2'' + num2' * div1''') A.Ops.(div1'' * div2' ) in let test = Int.eq div1_t div2_t in if_ test best gen let minus x y = add x @@ uminus y let mult (a,b : 'a t) (c,d: 'b t) = frac A.Ops.(a*c) A.Ops.(b*d) let inv (a,b : 'a t ) = frac b a let div x y = mult x @@ inv y let eq (num_x,div_x) (num_y,div_y) = todo : 2n bits operation Int.( eq l r ) module Eq = struct type absurd type +'a proof = Proof constraint 'a = 'x * 'y let convert: ('a * 'b) proof -> 'a t -> 'b t = fun _ x -> transmute x let transmute: 'a proof -> 'b proof = fun eq -> Proof let if_ :('a, absurd*absurd,'b, 'r) L.if_ -> 'a N.t -> 'b proof -> 'r proof = fun _ a b -> Proof let if_ x y = if_ L.If x y let mk_proof x y = let (x:'a t), (num_x,div_x) = duplicate x and (y:' b t), (num_y,div_y) = duplicate y in todo : 2n bits operation let test = Int.( eq l r ) in if_ test ( Proof: ('a * 'b) proof ) end let ( %->% ) x y = let open Eq in convert (mk_proof x y) x module Ops = struct let ( + ) x y = add x y let ( ~- ) x = uminus x let ( - ) x y = minus x y let ( * ) x y = mult x y let ( ~/ ) x = inv x let ( / ) x y = div x y let ( // ) x y = frac x y end
5c5cf4e6943ba38b810d110633e056bd49d6ca0b5e51a5f4b29a4fab65a0e572
tfausak/monadoc-5
Prelude.hs
module Monadoc.Prelude ( Control.Applicative.Applicative , Control.Applicative.pure , Control.Exception.Exception , Control.Exception.SomeException(SomeException) , Control.Exception.displayException , Control.Exception.evaluate , Control.Exception.fromException , Control.Exception.toException , Control.Monad.Monad , Control.Monad.forever , Control.Monad.guard , Control.Monad.join , Control.Monad.unless , Control.Monad.when , Control.Monad.Catch.MonadThrow , Control.Monad.Catch.MonadCatch , Control.Monad.Catch.bracket , Control.Monad.Catch.catch , Control.Monad.Catch.finally , Control.Monad.Catch.handle , Control.Monad.Catch.try , Control.Monad.Fail.MonadFail , Control.Monad.Fail.fail , Control.Monad.IO.Class.MonadIO , Control.Monad.Trans.Class.MonadTrans , Control.Monad.Trans.Class.lift , Control.Monad.Trans.Except.ExceptT , Control.Monad.Trans.Except.runExceptT , Control.Monad.Trans.Maybe.MaybeT , Control.Monad.Trans.Maybe.runMaybeT , Control.Monad.Trans.Reader.ReaderT , Control.Monad.Trans.Reader.runReaderT , Control.Monad.Trans.State.StateT , Control.Monad.Trans.State.runStateT , Control.Monad.Trans.Writer.WriterT , Control.Monad.Trans.Writer.runWriterT , Data.Bool.Bool(False, True) , Data.Bool.not , Data.Bool.otherwise , (Data.Bool.&&) , (Data.Bool.||) , Data.ByteString.ByteString , Data.Char.Char , Data.Data.Data , Data.Either.Either(Left, Right) , Data.Either.either , Data.Eq.Eq , (Data.Eq./=) , (Data.Eq.==) , Data.Fixed.Fixed , Data.Foldable.Foldable , Data.Foldable.all , Data.Foldable.any , Data.Foldable.elem , Data.Foldable.fold , Data.Foldable.foldl , Data.Foldable.foldMap , Data.Foldable.foldr , Data.Foldable.for_ , Data.Foldable.length , Data.Foldable.notElem , Data.Foldable.sequence_ , Data.Foldable.toList , Data.Foldable.traverse_ , Data.Function.flip , Data.Functor.Functor , Data.Functor.void , Data.Functor.Identity.Identity , Data.Functor.Identity.runIdentity , Data.Int.Int , Data.Int.Int8 , Data.Int.Int16 , Data.Int.Int32 , Data.Int.Int64 , Data.List.break , Data.List.cycle , Data.List.drop , Data.List.dropWhile , Data.List.filter , Data.List.repeat , Data.List.replicate , Data.List.reverse , Data.List.span , Data.List.splitAt , Data.List.take , Data.List.takeWhile , Data.List.unzip , Data.List.zip , Data.List.zipWith , Data.List.NonEmpty.NonEmpty , Data.Map.Map , Data.Maybe.Maybe(Nothing, Just) , Data.Maybe.maybe , Data.Monoid.Monoid , Data.Monoid.mempty , Data.Ord.Ord , Data.Ord.Ordering(LT, EQ, GT) , Data.Ord.compare , Data.Ord.comparing , Data.Ord.max , Data.Ord.min , (Data.Ord.<) , (Data.Ord.<=) , (Data.Ord.>) , (Data.Ord.>=) , Data.Ratio.Ratio , Data.Ratio.Rational , Data.Ratio.denominator , Data.Ratio.numerator , Data.Semigroup.Semigroup , (Data.Semigroup.<>) , Data.Set.Set , Data.String.IsString , Data.String.String , Data.String.fromString , Data.String.lines , Data.String.unlines , Data.String.unwords , Data.String.words , Data.Text.Text , Data.Time.UTCTime , Data.Traversable.Traversable , Data.Traversable.for , Data.Traversable.sequence , Data.Traversable.traverse , Data.Tuple.curry , Data.Tuple.fst , Data.Tuple.snd , Data.Tuple.uncurry , Data.Typeable.Proxy(Proxy) , Data.Typeable.Typeable , Data.Typeable.cast , Data.UUID.UUID , Data.Void.Void , Data.Void.absurd , Data.Word.Word , Data.Word.Word8 , Data.Word.Word16 , Data.Word.Word32 , Data.Word.Word64 , GHC.Enum.Bounded , GHC.Enum.Enum , GHC.Enum.fromEnum , GHC.Enum.maxBound , GHC.Enum.minBound , GHC.Err.error , GHC.Err.undefined , GHC.Exts.IsList , GHC.Exts.fromList , GHC.Float.Float , GHC.Float.Floating , GHC.Float.isInfinite , GHC.Float.isNaN , GHC.Float.logBase , GHC.Float.sqrt , (GHC.Float.**) , GHC.Float.Double , GHC.Generics.Generic , GHC.Integer.Integer , GHC.Num.Num , GHC.Num.abs , GHC.Num.fromInteger , GHC.Num.negate , (GHC.Num.+) , (GHC.Num.-) , GHC.Prim.seq , GHC.Real.Fractional , GHC.Real.Integral , GHC.Real.Real , GHC.Real.RealFrac , GHC.Real.ceiling , GHC.Real.even , GHC.Real.floor , GHC.Real.fromIntegral , GHC.Real.fromRational , GHC.Real.odd , GHC.Real.realToFrac , GHC.Real.round , GHC.Real.toInteger , GHC.Real.toRational , GHC.Real.truncate , (GHC.Real./) , (GHC.Real.^) , (GHC.Real.^^) , Numeric.Natural.Natural , System.IO.FilePath , System.IO.IO , System.IO.appendFile , System.IO.getChar , System.IO.getContents , System.IO.getLine , System.IO.interact , System.IO.print , System.IO.putChar , System.IO.putStr , System.IO.putStrLn , System.IO.readFile , System.IO.writeFile , System.IO.Error.IOError , System.IO.Error.userError , Text.Printf.printf , Text.Read.Read , Text.Show.Show , Text.Show.show , always , blank , identity , io , lookup , map , present , read , throw , toEnum , (*) , (//) , (%) , (<<<) , (<|) , (>>>) , (|>) ) where import qualified Control.Applicative import qualified Control.Category import qualified Control.Exception import qualified Control.Monad import qualified Control.Monad.Catch import qualified Control.Monad.Fail import qualified Control.Monad.IO.Class import qualified Control.Monad.Trans.Class import qualified Control.Monad.Trans.Except import qualified Control.Monad.Trans.Maybe import qualified Control.Monad.Trans.Reader import qualified Control.Monad.Trans.State import qualified Control.Monad.Trans.Writer import qualified Data.Bool import qualified Data.ByteString import qualified Data.Char import qualified Data.Data import qualified Data.Either import qualified Data.Eq import qualified Data.Fixed import qualified Data.Foldable import qualified Data.Function import qualified Data.Functor import qualified Data.Functor.Identity import qualified Data.Int import qualified Data.List import qualified Data.List.NonEmpty import qualified Data.Map import qualified Data.Maybe import qualified Data.Monoid import qualified Data.Ord import qualified Data.Ratio import qualified Data.Semigroup import qualified Data.Set import qualified Data.String import qualified Data.Text import qualified Data.Time import qualified Data.Traversable import qualified Data.Tuple import qualified Data.Typeable import qualified Data.UUID import qualified Data.Void import qualified Data.Word import qualified GHC.Enum import qualified GHC.Err import qualified GHC.Exts import qualified GHC.Float import qualified GHC.Generics import qualified GHC.Integer import qualified GHC.Num import qualified GHC.Prim import qualified GHC.Real import qualified Numeric.Natural import qualified System.IO import qualified System.IO.Error import qualified Text.Printf import qualified Text.Read import qualified Text.Show always :: a -> b -> a always = Data.Function.const blank :: Data.Foldable.Foldable t => t a -> Data.Bool.Bool blank = Data.Foldable.null identity :: a -> a identity = Data.Function.id io :: Control.Monad.IO.Class.MonadIO m => System.IO.IO a -> m a io = Control.Monad.IO.Class.liftIO lookup :: (Data.Foldable.Foldable t, Data.Eq.Eq k) => k -> t (k, v) -> Data.Maybe.Maybe v lookup k xs = Data.List.lookup k (Data.Foldable.toList xs) map :: Data.Functor.Functor f => (a -> b) -> f a -> f b map = Data.Functor.fmap present :: Data.Foldable.Foldable t => t a -> Data.Bool.Bool present xs = Data.Bool.not (blank xs) read :: Text.Read.Read a => Data.String.String -> Data.Maybe.Maybe a read = Text.Read.readMaybe throw :: (Control.Exception.Exception e, Control.Monad.Catch.MonadCatch m) => e -> m a throw = Control.Monad.Catch.throwM toEnum :: forall a . (GHC.Enum.Bounded a, GHC.Enum.Enum a) => Data.Int.Int -> Data.Maybe.Maybe a toEnum n = let tooSmall = n Data.Ord.< GHC.Enum.fromEnum @a GHC.Enum.minBound tooLarge = n Data.Ord.> GHC.Enum.fromEnum @a GHC.Enum.maxBound in if tooSmall Data.Bool.|| tooLarge then Data.Maybe.Nothing else Data.Maybe.Just (GHC.Enum.toEnum n) -- Redefined here to avoid a stylish-haskell bug. (*) :: GHC.Num.Num a => a -> a -> a (*) = (GHC.Num.*) infixl 7 * (//) :: GHC.Real.Integral a => a -> a -> a (//) = GHC.Real.div infixl 7 // (%) :: GHC.Real.Integral a => a -> a -> a (%) = GHC.Real.mod infixl 7 % (<<<) :: (b -> c) -> (a -> b) -> (a -> c) (<<<) = (Control.Category.<<<) infixr 9 <<< (<|) :: (a -> b) -> a -> b (<|) = (Data.Function.$) infixr 0 <| (>>>) :: (a -> b) -> (b -> c) -> (a -> c) (>>>) = (Control.Category.>>>) infixl 9 >>> (|>) :: a -> (a -> b) -> b (|>) = (Data.Function.&) infixl 0 |>
null
https://raw.githubusercontent.com/tfausak/monadoc-5/5361dd1870072cf2771857adbe92658118ddaa27/src/lib/Monadoc/Prelude.hs
haskell
Redefined here to avoid a stylish-haskell bug.
module Monadoc.Prelude ( Control.Applicative.Applicative , Control.Applicative.pure , Control.Exception.Exception , Control.Exception.SomeException(SomeException) , Control.Exception.displayException , Control.Exception.evaluate , Control.Exception.fromException , Control.Exception.toException , Control.Monad.Monad , Control.Monad.forever , Control.Monad.guard , Control.Monad.join , Control.Monad.unless , Control.Monad.when , Control.Monad.Catch.MonadThrow , Control.Monad.Catch.MonadCatch , Control.Monad.Catch.bracket , Control.Monad.Catch.catch , Control.Monad.Catch.finally , Control.Monad.Catch.handle , Control.Monad.Catch.try , Control.Monad.Fail.MonadFail , Control.Monad.Fail.fail , Control.Monad.IO.Class.MonadIO , Control.Monad.Trans.Class.MonadTrans , Control.Monad.Trans.Class.lift , Control.Monad.Trans.Except.ExceptT , Control.Monad.Trans.Except.runExceptT , Control.Monad.Trans.Maybe.MaybeT , Control.Monad.Trans.Maybe.runMaybeT , Control.Monad.Trans.Reader.ReaderT , Control.Monad.Trans.Reader.runReaderT , Control.Monad.Trans.State.StateT , Control.Monad.Trans.State.runStateT , Control.Monad.Trans.Writer.WriterT , Control.Monad.Trans.Writer.runWriterT , Data.Bool.Bool(False, True) , Data.Bool.not , Data.Bool.otherwise , (Data.Bool.&&) , (Data.Bool.||) , Data.ByteString.ByteString , Data.Char.Char , Data.Data.Data , Data.Either.Either(Left, Right) , Data.Either.either , Data.Eq.Eq , (Data.Eq./=) , (Data.Eq.==) , Data.Fixed.Fixed , Data.Foldable.Foldable , Data.Foldable.all , Data.Foldable.any , Data.Foldable.elem , Data.Foldable.fold , Data.Foldable.foldl , Data.Foldable.foldMap , Data.Foldable.foldr , Data.Foldable.for_ , Data.Foldable.length , Data.Foldable.notElem , Data.Foldable.sequence_ , Data.Foldable.toList , Data.Foldable.traverse_ , Data.Function.flip , Data.Functor.Functor , Data.Functor.void , Data.Functor.Identity.Identity , Data.Functor.Identity.runIdentity , Data.Int.Int , Data.Int.Int8 , Data.Int.Int16 , Data.Int.Int32 , Data.Int.Int64 , Data.List.break , Data.List.cycle , Data.List.drop , Data.List.dropWhile , Data.List.filter , Data.List.repeat , Data.List.replicate , Data.List.reverse , Data.List.span , Data.List.splitAt , Data.List.take , Data.List.takeWhile , Data.List.unzip , Data.List.zip , Data.List.zipWith , Data.List.NonEmpty.NonEmpty , Data.Map.Map , Data.Maybe.Maybe(Nothing, Just) , Data.Maybe.maybe , Data.Monoid.Monoid , Data.Monoid.mempty , Data.Ord.Ord , Data.Ord.Ordering(LT, EQ, GT) , Data.Ord.compare , Data.Ord.comparing , Data.Ord.max , Data.Ord.min , (Data.Ord.<) , (Data.Ord.<=) , (Data.Ord.>) , (Data.Ord.>=) , Data.Ratio.Ratio , Data.Ratio.Rational , Data.Ratio.denominator , Data.Ratio.numerator , Data.Semigroup.Semigroup , (Data.Semigroup.<>) , Data.Set.Set , Data.String.IsString , Data.String.String , Data.String.fromString , Data.String.lines , Data.String.unlines , Data.String.unwords , Data.String.words , Data.Text.Text , Data.Time.UTCTime , Data.Traversable.Traversable , Data.Traversable.for , Data.Traversable.sequence , Data.Traversable.traverse , Data.Tuple.curry , Data.Tuple.fst , Data.Tuple.snd , Data.Tuple.uncurry , Data.Typeable.Proxy(Proxy) , Data.Typeable.Typeable , Data.Typeable.cast , Data.UUID.UUID , Data.Void.Void , Data.Void.absurd , Data.Word.Word , Data.Word.Word8 , Data.Word.Word16 , Data.Word.Word32 , Data.Word.Word64 , GHC.Enum.Bounded , GHC.Enum.Enum , GHC.Enum.fromEnum , GHC.Enum.maxBound , GHC.Enum.minBound , GHC.Err.error , GHC.Err.undefined , GHC.Exts.IsList , GHC.Exts.fromList , GHC.Float.Float , GHC.Float.Floating , GHC.Float.isInfinite , GHC.Float.isNaN , GHC.Float.logBase , GHC.Float.sqrt , (GHC.Float.**) , GHC.Float.Double , GHC.Generics.Generic , GHC.Integer.Integer , GHC.Num.Num , GHC.Num.abs , GHC.Num.fromInteger , GHC.Num.negate , (GHC.Num.+) , (GHC.Num.-) , GHC.Prim.seq , GHC.Real.Fractional , GHC.Real.Integral , GHC.Real.Real , GHC.Real.RealFrac , GHC.Real.ceiling , GHC.Real.even , GHC.Real.floor , GHC.Real.fromIntegral , GHC.Real.fromRational , GHC.Real.odd , GHC.Real.realToFrac , GHC.Real.round , GHC.Real.toInteger , GHC.Real.toRational , GHC.Real.truncate , (GHC.Real./) , (GHC.Real.^) , (GHC.Real.^^) , Numeric.Natural.Natural , System.IO.FilePath , System.IO.IO , System.IO.appendFile , System.IO.getChar , System.IO.getContents , System.IO.getLine , System.IO.interact , System.IO.print , System.IO.putChar , System.IO.putStr , System.IO.putStrLn , System.IO.readFile , System.IO.writeFile , System.IO.Error.IOError , System.IO.Error.userError , Text.Printf.printf , Text.Read.Read , Text.Show.Show , Text.Show.show , always , blank , identity , io , lookup , map , present , read , throw , toEnum , (*) , (//) , (%) , (<<<) , (<|) , (>>>) , (|>) ) where import qualified Control.Applicative import qualified Control.Category import qualified Control.Exception import qualified Control.Monad import qualified Control.Monad.Catch import qualified Control.Monad.Fail import qualified Control.Monad.IO.Class import qualified Control.Monad.Trans.Class import qualified Control.Monad.Trans.Except import qualified Control.Monad.Trans.Maybe import qualified Control.Monad.Trans.Reader import qualified Control.Monad.Trans.State import qualified Control.Monad.Trans.Writer import qualified Data.Bool import qualified Data.ByteString import qualified Data.Char import qualified Data.Data import qualified Data.Either import qualified Data.Eq import qualified Data.Fixed import qualified Data.Foldable import qualified Data.Function import qualified Data.Functor import qualified Data.Functor.Identity import qualified Data.Int import qualified Data.List import qualified Data.List.NonEmpty import qualified Data.Map import qualified Data.Maybe import qualified Data.Monoid import qualified Data.Ord import qualified Data.Ratio import qualified Data.Semigroup import qualified Data.Set import qualified Data.String import qualified Data.Text import qualified Data.Time import qualified Data.Traversable import qualified Data.Tuple import qualified Data.Typeable import qualified Data.UUID import qualified Data.Void import qualified Data.Word import qualified GHC.Enum import qualified GHC.Err import qualified GHC.Exts import qualified GHC.Float import qualified GHC.Generics import qualified GHC.Integer import qualified GHC.Num import qualified GHC.Prim import qualified GHC.Real import qualified Numeric.Natural import qualified System.IO import qualified System.IO.Error import qualified Text.Printf import qualified Text.Read import qualified Text.Show always :: a -> b -> a always = Data.Function.const blank :: Data.Foldable.Foldable t => t a -> Data.Bool.Bool blank = Data.Foldable.null identity :: a -> a identity = Data.Function.id io :: Control.Monad.IO.Class.MonadIO m => System.IO.IO a -> m a io = Control.Monad.IO.Class.liftIO lookup :: (Data.Foldable.Foldable t, Data.Eq.Eq k) => k -> t (k, v) -> Data.Maybe.Maybe v lookup k xs = Data.List.lookup k (Data.Foldable.toList xs) map :: Data.Functor.Functor f => (a -> b) -> f a -> f b map = Data.Functor.fmap present :: Data.Foldable.Foldable t => t a -> Data.Bool.Bool present xs = Data.Bool.not (blank xs) read :: Text.Read.Read a => Data.String.String -> Data.Maybe.Maybe a read = Text.Read.readMaybe throw :: (Control.Exception.Exception e, Control.Monad.Catch.MonadCatch m) => e -> m a throw = Control.Monad.Catch.throwM toEnum :: forall a . (GHC.Enum.Bounded a, GHC.Enum.Enum a) => Data.Int.Int -> Data.Maybe.Maybe a toEnum n = let tooSmall = n Data.Ord.< GHC.Enum.fromEnum @a GHC.Enum.minBound tooLarge = n Data.Ord.> GHC.Enum.fromEnum @a GHC.Enum.maxBound in if tooSmall Data.Bool.|| tooLarge then Data.Maybe.Nothing else Data.Maybe.Just (GHC.Enum.toEnum n) (*) :: GHC.Num.Num a => a -> a -> a (*) = (GHC.Num.*) infixl 7 * (//) :: GHC.Real.Integral a => a -> a -> a (//) = GHC.Real.div infixl 7 // (%) :: GHC.Real.Integral a => a -> a -> a (%) = GHC.Real.mod infixl 7 % (<<<) :: (b -> c) -> (a -> b) -> (a -> c) (<<<) = (Control.Category.<<<) infixr 9 <<< (<|) :: (a -> b) -> a -> b (<|) = (Data.Function.$) infixr 0 <| (>>>) :: (a -> b) -> (b -> c) -> (a -> c) (>>>) = (Control.Category.>>>) infixl 9 >>> (|>) :: a -> (a -> b) -> b (|>) = (Data.Function.&) infixl 0 |>
340c610b5c2a8171ac30d8ac7b816d6d6cac1f6673e30be5fe17a7d5a30c34bc
madjestic/Haskell-OpenGL-Tutorial
LoadShaders.hs
module LoadShaders ( ShaderSource(..), ShaderInfo(..), loadShaders ) where import Control.Exception import Control.Monad import qualified Data.ByteString as B import Graphics.Rendering.OpenGL -------------------------------------------------------------------------------- -- | The source of the shader source code. data ShaderSource = ByteStringSource B.ByteString -- ^ The shader source code is directly given as a 'B.ByteString'. | StringSource String -- ^ The shader source code is directly given as a 'String'. | FileSource FilePath -- ^ The shader source code is located in the file at the given 'FilePath'. deriving ( Eq, Ord, Show ) getSource :: ShaderSource -> IO B.ByteString getSource (ByteStringSource bs) = return bs getSource (StringSource str) = return $ packUtf8 str getSource (FileSource path) = B.readFile path -------------------------------------------------------------------------------- -- | A description of a shader: The type of the shader plus its source code. data ShaderInfo = ShaderInfo ShaderType ShaderSource deriving ( Eq, Ord, Show ) -------------------------------------------------------------------------------- -- | Create a new program object from the given shaders, throwing an -- 'IOException' if something goes wrong. loadShaders :: [ShaderInfo] -> IO Program loadShaders infos = createProgram `bracketOnError` deleteObjectName $ \program -> do loadCompileAttach program infos linkAndCheck program return program linkAndCheck :: Program -> IO () linkAndCheck = checked linkProgram linkStatus programInfoLog "link" loadCompileAttach :: Program -> [ShaderInfo] -> IO () loadCompileAttach _ [] = return () loadCompileAttach program (ShaderInfo shType source : infos) = createShader shType `bracketOnError` deleteObjectName $ \shader -> do src <- getSource source shaderSourceBS shader $= src compileAndCheck shader attachShader program shader loadCompileAttach program infos compileAndCheck :: Shader -> IO () compileAndCheck = checked compileShader compileStatus shaderInfoLog "compile" checked :: (t -> IO ()) -> (t -> GettableStateVar Bool) -> (t -> GettableStateVar String) -> String -> t -> IO () checked action getStatus getInfoLog message object = do action object ok <- get (getStatus object) unless ok $ do infoLog <- get (getInfoLog object) fail (message ++ " log: " ++ infoLog)
null
https://raw.githubusercontent.com/madjestic/Haskell-OpenGL-Tutorial/9f685ddde9d6c5d2cc9c2c62f214ca0d43e717c7/tutorial02/LoadShaders.hs
haskell
------------------------------------------------------------------------------ | The source of the shader source code. ^ The shader source code is directly given as a 'B.ByteString'. ^ The shader source code is directly given as a 'String'. ^ The shader source code is located in the file at the given 'FilePath'. ------------------------------------------------------------------------------ | A description of a shader: The type of the shader plus its source code. ------------------------------------------------------------------------------ | Create a new program object from the given shaders, throwing an 'IOException' if something goes wrong.
module LoadShaders ( ShaderSource(..), ShaderInfo(..), loadShaders ) where import Control.Exception import Control.Monad import qualified Data.ByteString as B import Graphics.Rendering.OpenGL data ShaderSource = ByteStringSource B.ByteString | StringSource String | FileSource FilePath deriving ( Eq, Ord, Show ) getSource :: ShaderSource -> IO B.ByteString getSource (ByteStringSource bs) = return bs getSource (StringSource str) = return $ packUtf8 str getSource (FileSource path) = B.readFile path data ShaderInfo = ShaderInfo ShaderType ShaderSource deriving ( Eq, Ord, Show ) loadShaders :: [ShaderInfo] -> IO Program loadShaders infos = createProgram `bracketOnError` deleteObjectName $ \program -> do loadCompileAttach program infos linkAndCheck program return program linkAndCheck :: Program -> IO () linkAndCheck = checked linkProgram linkStatus programInfoLog "link" loadCompileAttach :: Program -> [ShaderInfo] -> IO () loadCompileAttach _ [] = return () loadCompileAttach program (ShaderInfo shType source : infos) = createShader shType `bracketOnError` deleteObjectName $ \shader -> do src <- getSource source shaderSourceBS shader $= src compileAndCheck shader attachShader program shader loadCompileAttach program infos compileAndCheck :: Shader -> IO () compileAndCheck = checked compileShader compileStatus shaderInfoLog "compile" checked :: (t -> IO ()) -> (t -> GettableStateVar Bool) -> (t -> GettableStateVar String) -> String -> t -> IO () checked action getStatus getInfoLog message object = do action object ok <- get (getStatus object) unless ok $ do infoLog <- get (getInfoLog object) fail (message ++ " log: " ++ infoLog)
94a848639f0b81e0c188bea04729cb83435bc1d0a18fc7e0794dc7e3ee860e82
hasufell/hpath
Traversals.hs
-- | Module : System . . RawFilePath . Directory . Copyright : © 2016 -- License : BSD3 -- Maintainer : < > -- Stability : experimental -- Portability : portable -- Traversal and read operations on directories . # LANGUAGE CApiFFI # # LANGUAGE CPP # # LANGUAGE ForeignFunctionInterface # {-# LANGUAGE OverloadedStrings #-} # LANGUAGE TupleSections # # LANGUAGE ViewPatterns # # OPTIONS_GHC -Wall # module System.Posix.RawFilePath.Directory.Traversals ( getDirectoryContents , getDirectoryContents' , allDirectoryContents , allDirectoryContents' , traverseDirectory -- lower-level stuff , readDirEnt , packDirStream , unpackDirStream , fdOpendir , realpath ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) #endif import Control.Monad import System.Posix.FilePath ((</>)) import System.Posix.Foreign import qualified System.Posix as Posix import System.IO.Error import Control.Exception import qualified Data.ByteString.Char8 as BS import System.Posix.ByteString.FilePath import System.Posix.Directory.ByteString as PosixBS import System.Posix.Files.ByteString import System.IO.Unsafe import "unix" System.Posix.IO.ByteString (closeFd) import Unsafe.Coerce (unsafeCoerce) import Foreign.C.Error import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc (alloca,allocaBytes) import Foreign.Ptr import Foreign.Storable ---------------------------------------------------------- -- | Get all files from a directory and its subdirectories. -- -- Upon entering a directory, 'allDirectoryContents' will get all entries -- strictly. However the returned list is lazy in that directories will only -- be accessed on demand. -- -- Follows symbolic links for the input dir. allDirectoryContents :: RawFilePath -> IO [RawFilePath] allDirectoryContents topdir = do namesAndTypes <- getDirectoryContents topdir let properNames = filter ((`notElem` [".", ".."]) . snd) namesAndTypes paths <- forM properNames $ \(typ,name) -> unsafeInterleaveIO $ do let path = topdir </> name case () of () | typ == dtDir -> allDirectoryContents path | typ == dtUnknown -> do isDir <- isDirectory <$> getFileStatus path if isDir then allDirectoryContents path else return [path] | otherwise -> return [path] return (topdir : concat paths) -- | Get all files from a directory and its subdirectories strictly. -- -- Follows symbolic links for the input dir. allDirectoryContents' :: RawFilePath -> IO [RawFilePath] allDirectoryContents' = fmap reverse . traverseDirectory (\acc fp -> return (fp:acc)) [] this uses because it 's more efficient than forcing the -- lazy version. -- | Recursively apply the 'action' to the parent directory and all -- files/subdirectories. -- -- This function allows for memory-efficient traversals. -- -- Follows symbolic links for the input dir. traverseDirectory :: (s -> RawFilePath -> IO s) -> s -> RawFilePath -> IO s traverseDirectory act s0 topdir = toploop where toploop = do isDir <- isDirectory <$> getFileStatus topdir s' <- act s0 topdir if isDir then actOnDirContents topdir s' loop else return s' loop typ path acc = do isDir <- case () of () | typ == dtDir -> return True | typ == dtUnknown -> isDirectory <$> getFileStatus path | otherwise -> return False if isDir then act acc path >>= \acc' -> actOnDirContents path acc' loop else act acc path actOnDirContents :: RawFilePath -> b -> (DirType -> RawFilePath -> b -> IO b) -> IO b actOnDirContents pathRelToTop b f = modifyIOError ((`ioeSetFileName` (BS.unpack pathRelToTop)) . (`ioeSetLocation` "findBSTypRel")) $ bracket (openDirStream pathRelToTop) Posix.closeDirStream (\dirp -> loop dirp b) where loop dirp b' = do (typ,e) <- readDirEnt dirp if (e == "") then return b' else if (e == "." || e == "..") then loop dirp b' else f typ (pathRelToTop </> e) b' >>= loop dirp ---------------------------------------------------------- -- dodgy stuff type CDir = () type CDirent = () does n't export DirStream , so to re - use that type we need to use -- unsafeCoerce. It's just a newtype, so this is a legitimate usage. -- ugly trick. unpackDirStream :: DirStream -> Ptr CDir unpackDirStream = unsafeCoerce packDirStream :: Ptr CDir -> DirStream packDirStream = unsafeCoerce -- the __hscore_* functions are defined in the unix package. We can import them and let -- the linker figure it out. foreign import ccall unsafe "__hscore_readdir" c_readdir :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt foreign import ccall unsafe "__hscore_free_dirent" c_freeDirEnt :: Ptr CDirent -> IO () foreign import ccall unsafe "__hscore_d_name" c_name :: Ptr CDirent -> IO CString foreign import ccall unsafe "__posixdir_d_type" c_type :: Ptr CDirent -> IO DirType foreign import capi "stdlib.h realpath" c_realpath :: CString -> CString -> IO CString -- Using normal 'ccall' here lead to memory bugs, crashes and corrupted d_name entries . It appears there are two fdopendirs : -- -1244.1.7/include/dirent.h.auto.html -- The capi call picks the correct one. foreign import capi unsafe "dirent.h fdopendir" c_fdopendir :: Posix.Fd -> IO (Ptr CDir) ---------------------------------------------------------- -- less dodgy but still lower-level readDirEnt :: DirStream -> IO (DirType, RawFilePath) readDirEnt (unpackDirStream -> dirp) = alloca $ \ptr_dEnt -> loop ptr_dEnt where loop ptr_dEnt = do resetErrno r <- c_readdir dirp ptr_dEnt if (r == 0) then do dEnt <- peek ptr_dEnt if (dEnt == nullPtr) then return (dtUnknown,BS.empty) else do dName <- c_name dEnt >>= peekFilePath dType <- c_type dEnt c_freeDirEnt dEnt return (dType, dName) else do errno <- getErrno if (errno == eINTR) then loop ptr_dEnt else do let (Errno eo) = errno if (eo == 0) then return (dtUnknown,BS.empty) else throwErrno "readDirEnt" -- |Gets all directory contents (not recursively). getDirectoryContents :: RawFilePath -> IO [(DirType, RawFilePath)] getDirectoryContents path = modifyIOError ((`ioeSetFileName` (BS.unpack path)) . (`ioeSetLocation` "System.Posix.RawFilePath.Directory.Traversals.getDirectoryContents")) $ bracket (PosixBS.openDirStream path) PosixBS.closeDirStream _dirloop |Binding to @fdopendir(3)@. fdOpendir :: Posix.Fd -> IO DirStream fdOpendir fd = packDirStream <$> throwErrnoIfNull "fdOpendir" (c_fdopendir fd) -- |Like `getDirectoryContents` except for a file descriptor. -- -- To avoid complicated error checks, the file descriptor is _ _ always _ _ closed , even if ` fdOpendir ` fails . Usually , this only happens on successful ` fdOpendir ` and after the directory -- stream is closed. Also see the manpage of @fdopendir(3)@ for -- more details. getDirectoryContents' :: Posix.Fd -> IO [(DirType, RawFilePath)] getDirectoryContents' fd = do dirstream <- fdOpendir fd `catchIOError` \e -> do closeFd fd ioError e -- closeDirStream closes the filedescriptor finally (_dirloop dirstream) (PosixBS.closeDirStream dirstream) _dirloop :: DirStream -> IO [(DirType, RawFilePath)] {-# INLINE _dirloop #-} _dirloop dirp = do t@(_typ,e) <- readDirEnt dirp if BS.null e then return [] else do es <- _dirloop dirp return (t:es) -- | return the canonicalized absolute pathname -- -- like canonicalizePath, but uses @realpath(3)@ realpath :: RawFilePath -> IO RawFilePath realpath inp = allocaBytes pathMax $ \tmp -> do void $ BS.useAsCString inp $ \cstr -> throwErrnoIfNull "realpath" $ c_realpath cstr tmp BS.packCString tmp
null
https://raw.githubusercontent.com/hasufell/hpath/9fcc1890596e5b838bf3be9ed303165fbc692d11/hpath-posix/src/System/Posix/RawFilePath/Directory/Traversals.hs
haskell
| License : BSD3 Stability : experimental Portability : portable # LANGUAGE OverloadedStrings # lower-level stuff -------------------------------------------------------- | Get all files from a directory and its subdirectories. Upon entering a directory, 'allDirectoryContents' will get all entries strictly. However the returned list is lazy in that directories will only be accessed on demand. Follows symbolic links for the input dir. | Get all files from a directory and its subdirectories strictly. Follows symbolic links for the input dir. lazy version. | Recursively apply the 'action' to the parent directory and all files/subdirectories. This function allows for memory-efficient traversals. Follows symbolic links for the input dir. -------------------------------------------------------- dodgy stuff unsafeCoerce. It's just a newtype, so this is a legitimate usage. ugly trick. the __hscore_* functions are defined in the unix package. We can import them and let the linker figure it out. Using normal 'ccall' here lead to memory bugs, crashes -1244.1.7/include/dirent.h.auto.html The capi call picks the correct one. -------------------------------------------------------- less dodgy but still lower-level |Gets all directory contents (not recursively). |Like `getDirectoryContents` except for a file descriptor. To avoid complicated error checks, the file descriptor is stream is closed. Also see the manpage of @fdopendir(3)@ for more details. closeDirStream closes the filedescriptor # INLINE _dirloop # | return the canonicalized absolute pathname like canonicalizePath, but uses @realpath(3)@
Module : System . . RawFilePath . Directory . Copyright : © 2016 Maintainer : < > Traversal and read operations on directories . # LANGUAGE CApiFFI # # LANGUAGE CPP # # LANGUAGE ForeignFunctionInterface # # LANGUAGE TupleSections # # LANGUAGE ViewPatterns # # OPTIONS_GHC -Wall # module System.Posix.RawFilePath.Directory.Traversals ( getDirectoryContents , getDirectoryContents' , allDirectoryContents , allDirectoryContents' , traverseDirectory , readDirEnt , packDirStream , unpackDirStream , fdOpendir , realpath ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>)) #endif import Control.Monad import System.Posix.FilePath ((</>)) import System.Posix.Foreign import qualified System.Posix as Posix import System.IO.Error import Control.Exception import qualified Data.ByteString.Char8 as BS import System.Posix.ByteString.FilePath import System.Posix.Directory.ByteString as PosixBS import System.Posix.Files.ByteString import System.IO.Unsafe import "unix" System.Posix.IO.ByteString (closeFd) import Unsafe.Coerce (unsafeCoerce) import Foreign.C.Error import Foreign.C.String import Foreign.C.Types import Foreign.Marshal.Alloc (alloca,allocaBytes) import Foreign.Ptr import Foreign.Storable allDirectoryContents :: RawFilePath -> IO [RawFilePath] allDirectoryContents topdir = do namesAndTypes <- getDirectoryContents topdir let properNames = filter ((`notElem` [".", ".."]) . snd) namesAndTypes paths <- forM properNames $ \(typ,name) -> unsafeInterleaveIO $ do let path = topdir </> name case () of () | typ == dtDir -> allDirectoryContents path | typ == dtUnknown -> do isDir <- isDirectory <$> getFileStatus path if isDir then allDirectoryContents path else return [path] | otherwise -> return [path] return (topdir : concat paths) allDirectoryContents' :: RawFilePath -> IO [RawFilePath] allDirectoryContents' = fmap reverse . traverseDirectory (\acc fp -> return (fp:acc)) [] this uses because it 's more efficient than forcing the traverseDirectory :: (s -> RawFilePath -> IO s) -> s -> RawFilePath -> IO s traverseDirectory act s0 topdir = toploop where toploop = do isDir <- isDirectory <$> getFileStatus topdir s' <- act s0 topdir if isDir then actOnDirContents topdir s' loop else return s' loop typ path acc = do isDir <- case () of () | typ == dtDir -> return True | typ == dtUnknown -> isDirectory <$> getFileStatus path | otherwise -> return False if isDir then act acc path >>= \acc' -> actOnDirContents path acc' loop else act acc path actOnDirContents :: RawFilePath -> b -> (DirType -> RawFilePath -> b -> IO b) -> IO b actOnDirContents pathRelToTop b f = modifyIOError ((`ioeSetFileName` (BS.unpack pathRelToTop)) . (`ioeSetLocation` "findBSTypRel")) $ bracket (openDirStream pathRelToTop) Posix.closeDirStream (\dirp -> loop dirp b) where loop dirp b' = do (typ,e) <- readDirEnt dirp if (e == "") then return b' else if (e == "." || e == "..") then loop dirp b' else f typ (pathRelToTop </> e) b' >>= loop dirp type CDir = () type CDirent = () does n't export DirStream , so to re - use that type we need to use unpackDirStream :: DirStream -> Ptr CDir unpackDirStream = unsafeCoerce packDirStream :: Ptr CDir -> DirStream packDirStream = unsafeCoerce foreign import ccall unsafe "__hscore_readdir" c_readdir :: Ptr CDir -> Ptr (Ptr CDirent) -> IO CInt foreign import ccall unsafe "__hscore_free_dirent" c_freeDirEnt :: Ptr CDirent -> IO () foreign import ccall unsafe "__hscore_d_name" c_name :: Ptr CDirent -> IO CString foreign import ccall unsafe "__posixdir_d_type" c_type :: Ptr CDirent -> IO DirType foreign import capi "stdlib.h realpath" c_realpath :: CString -> CString -> IO CString and corrupted d_name entries . It appears there are two fdopendirs : foreign import capi unsafe "dirent.h fdopendir" c_fdopendir :: Posix.Fd -> IO (Ptr CDir) readDirEnt :: DirStream -> IO (DirType, RawFilePath) readDirEnt (unpackDirStream -> dirp) = alloca $ \ptr_dEnt -> loop ptr_dEnt where loop ptr_dEnt = do resetErrno r <- c_readdir dirp ptr_dEnt if (r == 0) then do dEnt <- peek ptr_dEnt if (dEnt == nullPtr) then return (dtUnknown,BS.empty) else do dName <- c_name dEnt >>= peekFilePath dType <- c_type dEnt c_freeDirEnt dEnt return (dType, dName) else do errno <- getErrno if (errno == eINTR) then loop ptr_dEnt else do let (Errno eo) = errno if (eo == 0) then return (dtUnknown,BS.empty) else throwErrno "readDirEnt" getDirectoryContents :: RawFilePath -> IO [(DirType, RawFilePath)] getDirectoryContents path = modifyIOError ((`ioeSetFileName` (BS.unpack path)) . (`ioeSetLocation` "System.Posix.RawFilePath.Directory.Traversals.getDirectoryContents")) $ bracket (PosixBS.openDirStream path) PosixBS.closeDirStream _dirloop |Binding to @fdopendir(3)@. fdOpendir :: Posix.Fd -> IO DirStream fdOpendir fd = packDirStream <$> throwErrnoIfNull "fdOpendir" (c_fdopendir fd) _ _ always _ _ closed , even if ` fdOpendir ` fails . Usually , this only happens on successful ` fdOpendir ` and after the directory getDirectoryContents' :: Posix.Fd -> IO [(DirType, RawFilePath)] getDirectoryContents' fd = do dirstream <- fdOpendir fd `catchIOError` \e -> do closeFd fd ioError e finally (_dirloop dirstream) (PosixBS.closeDirStream dirstream) _dirloop :: DirStream -> IO [(DirType, RawFilePath)] _dirloop dirp = do t@(_typ,e) <- readDirEnt dirp if BS.null e then return [] else do es <- _dirloop dirp return (t:es) realpath :: RawFilePath -> IO RawFilePath realpath inp = allocaBytes pathMax $ \tmp -> do void $ BS.useAsCString inp $ \cstr -> throwErrnoIfNull "realpath" $ c_realpath cstr tmp BS.packCString tmp
7f35df794d74276a8c7ae35b025c4b2084153963bf669a686d5d9d35aff63bb1
AlacrisIO/legicash-facts
ethereum_user.ml
open Legilogic_lib open Lib open Yojsoning open Marshaling open Persisting open Types open Signing open Action open Lwt_exn open Json_rpc open Trie open Ethereum_chain open Ethereum_json_rpc open Ethereum_transaction let ethereum_user_log = true TODO : A much better state machine to get wanted transactions confirmed . It is a very bad idea to have more than one ongoing transaction in the : you might hope everything goes right and they are added in the correct order , but in practice so many things can go wrong and then the mitigations become hell , and attackers can get you to fail to transact , to deadlock , to replay your spending , to fail to meet a deadline , or more generally fail to meet your contractual obligations . Obvious strategies do n't work : - If you never re - send a transaction , but for some reason one transaction does n't go through because it was received out - of - order by the winning PoW nodes and dropped on the ground , or otherwise was lost in the shuffle of network packet drops , then you deadlock - If you always re - send a transaction , but never update the nonce , and some other client using the same private key ( WHY ? That should be a red alert anyway , unless it 's actually another copy of yourself sending another variant of the same transaction due to netsplit , and you re - synch after netmerge ) , or some other transaction on the same client races me ( if you fail to sequentialize transactions one at a time through a single thread ) , then you deadlock . - If you always re - send a transaction , and you update the nonce if you see yours is out - of - date , then you can race yourself and/or other transactions into sending multiple copies of a same transaction and end up spending many times over what you wanted to spend ( very bad ) . - Whatever decisions you make based on what the ethereum node tells you , it can give you _ hints _ about things that are going on , but nothing it says is authoritative until it is , which is only 30 minutes later ( or say 10 minutes , if you accept the risk of lower security ) . Until confirmation , whatever it says is subject to revision . - The safest would be to nurse each and every transaction to either completion or definite failure before even attempting the next one , but then that 's only one transaction per account every 30 minutes minimum ( NB : binance is OK with 36 confirmations ~10 minutes ) , and maybe much worse depending on how " definite failure " is defined . This suggests that having multiple accounts could be a requirement for playing safe with smart contracts : each " system " ( itself distributed with redundant workers for reliability ) has its own private key that wo n't race with other systems . One problem is that your local ethereum node ( and/or , in a real network , whichever remote node will eventually issue the blocks ) , sometimes will just drop your signed transactions , for whatever reasons : not enough ether , not enough gas , gas price too low , nonce out of synch , network error , network split , denial - of - service attack , selective censorship , block - buying attack , local reverts due to PoW attacks even less than 33 % , etc . You have to resend , sometimes with updated gas price , sometimes with updated nonce , sometimes even with updated contract parameters , etc . Yet , you should be wary of changing anything substantive ( to your application ) about a transaction being sent , or you can race yourselves , and end up paying twice ( or many more times ) to receive a counterpart only once ( or not at all ) . A good strategy might take into account what did or did n't happen in not - fully - confirmed blocks , yet ( obviously ) would not consider anything confirmed until it 's confirmed . It is unclear how best to deal with multiple queued transactions — the happy case of sending consecutive nonces automatically is great , but when things break down ( including due to the aforementioned re - send issues ) it 's a hell that 's hard to recover from , since new transactions will race the old ones , and any sequential dependency between them becomes quite tricky to enforce . One solution : a * batching contract * . Multiple transactions are sent atomically via a single call to some generic contract that plays them in sequence . Caveat : you better get you gas computation damn right ! Also mind the size limits to your overall transaction , the possibly more complex gas price computation to convince miners to get it through in a timely fashion , etc . If you do it right , though , you only have to deal with a single network event , which makes the limit of one nursed transaction per 30 minute much more bearable . This strategy implies or at least suggests developing a better - than - trivial batching strategy to group transactions , similar to what we use in db.ml for batching database writes , possibly with its own notion of atomic " transaction sets " that group " transactions " together . Additional feature : a * replay barrier * . The same generic contract can also help , onerously , with avoiding to replay a transaction multiple time in the context where you do want to be able to race yourself . Good reasons to race yourself is when you have strong obligations to fulfill in a short deadline , but the current chain is wobbly due to some attack , particularly network splits : multiple of your workers might be victims of the network split ( maybe targetted ! ) , and would trigger racing variants of the queued transactions . In this case , the contract may associate a semaphore to each application - defined atomic set of transactions ( for a shared multi - user contract , salted with sender ID ) ; it would check that the semaphore was n't set before to actually play the transaction set , and set the semaphore afterwards . Once again , miscompute worst - case gas and you 're dead . You need to pay extra gas to read and write a semaphore , and will lose gas in case that multiple copies make it to the blockchain ; but at least you wo n't lose the principal . To avoid the need for a replay barrier , you must always wait for * some * transaction with the given nonce to be fully confirmed before you start using the next nonce . When you have a tight deadline for some transactions and not others , you may have to up the gas price for the transactions you really want to get through , with an understanding of the algorithm used by the miners and of the strategy used by whoever is trying to bribe the miners out of including your transaction . Maybe you have to fill the block gas limit . Or maybe you have to split your transaction batch into smaller ones . An experimental study may be necessary , as well as regular updates to the software agents --- quite unlike the contracts that are immutable by design , transaction posting strategies may have to be mutable and evolving by design In some case , the right thing to do might be to consult back with the user , and ask them to add more ether , to update their gas price strategy , to deal with potentially or actually broken contracts , to watch the missing nodes of their personal database , etc . By default , we probably want to queue transactions one by one to avoid nonce - overlap issues ; we may be more or less aggressive in terms of using nonces without partial or total confirmation from previous transactions , depending on the nature of the transactions . In any case , to definitely want a single system ( even if possibly split into partitions ) to issue transactions from a given address to minimize races . There is potentially a LOT of complexity , and if possible we want to partner with other people to define sound strategies ... just that is a topic for itself , and there are sometimes games that people can play with lock out strategy via paying extra in gas to buy enough blocks to lock rivals out of a contract , etc . A generic strategy , DSL for strategies , etc . , could be a research topic in itself . Sigh . Most people do n't hit this issue , because they do n't abide by a contract binding them to partake in distributed transactions across multiple blockchains with a priori untrustworthy other parties within tight deadlines . And most of the few who do possibly have n't thought deep enough about the ins and outs of these issues . Scary . Here , for now , we follow a very dumb strategy , of having only one active transaction per address . Furthermore , we only sign once , and resending blindly afterwards , trusting the gas computation , and trusting the nonce until it 's found to be too low . : implement an asynchronous way for the UI to peek at the status of a transaction while it 's going along its slow progress . : look at how OMiseGo does it , tells me they have something public ( and he has something private ) . It is a very bad idea to have more than one ongoing transaction in the mempool: you might hope everything goes right and they are added in the correct order, but in practice so many things can go wrong and then the mitigations become hell, and attackers can get you to fail to transact, to deadlock, to replay your spending, to fail to meet a deadline, or more generally fail to meet your contractual obligations. Obvious strategies don't work: - If you never re-send a transaction, but for some reason one transaction doesn't go through because it was received out-of-order by the winning PoW nodes and dropped on the ground, or otherwise was lost in the shuffle of network packet drops, then you deadlock - If you always re-send a transaction, but never update the nonce, and some other client using the same private key (WHY? That should be a red alert anyway, unless it's actually another copy of yourself sending another variant of the same transaction due to netsplit, and you re-synch after netmerge), or some other transaction on the same client races me (if you fail to sequentialize transactions one at a time through a single thread), then you deadlock. - If you always re-send a transaction, and you update the nonce if you see yours is out-of-date, then you can race yourself and/or other transactions into sending multiple copies of a same transaction and end up spending many times over what you wanted to spend (very bad). - Whatever decisions you make based on what the ethereum node tells you, it can give you _hints_ about things that are going on, but nothing it says is authoritative until it is, which is only 30 minutes later (or say 10 minutes, if you accept the risk of lower security). Until confirmation, whatever it says is subject to revision. - The safest would be to nurse each and every transaction to either completion or definite failure before even attempting the next one, but then that's only one transaction per account every 30 minutes minimum (NB: binance is OK with 36 confirmations ~10 minutes), and maybe much worse depending on how "definite failure" is defined. This suggests that having multiple accounts could be a requirement for playing safe with smart contracts: each "system" (itself distributed with redundant workers for reliability) has its own private key that won't race with other systems. One problem is that your local ethereum node (and/or, in a real network, whichever remote node will eventually issue the blocks), sometimes will just drop your signed transactions, for whatever reasons: not enough ether, not enough gas, gas price too low, nonce out of synch, network error, network split, denial-of-service attack, selective censorship, block-buying attack, local reverts due to PoW attacks even less than 33%, etc. You have to resend, sometimes with updated gas price, sometimes with updated nonce, sometimes even with updated contract parameters, etc. Yet, you should be wary of changing anything substantive (to your application) about a transaction being sent, or you can race yourselves, and end up paying twice (or many more times) to receive a counterpart only once (or not at all). A good strategy might take into account what did or didn't happen in not-fully-confirmed blocks, yet (obviously) would not consider anything confirmed until it's confirmed. It is unclear how best to deal with multiple queued transactions — the happy case of sending consecutive nonces automatically is great, but when things break down (including due to the aforementioned re-send issues) it's a hell that's hard to recover from, since new transactions will race the old ones, and any sequential dependency between them becomes quite tricky to enforce. One solution: a *batching contract*. Multiple transactions are sent atomically via a single call to some generic contract that plays them in sequence. Caveat: you better get you gas computation damn right! Also mind the size limits to your overall transaction, the possibly more complex gas price computation to convince miners to get it through in a timely fashion, etc. If you do it right, though, you only have to deal with a single network event, which makes the limit of one nursed transaction per 30 minute much more bearable. This strategy implies or at least suggests developing a better-than-trivial batching strategy to group transactions, similar to what we use in db.ml for batching database writes, possibly with its own notion of atomic "transaction sets" that group "transactions" together. Additional feature: a *replay barrier*. The same generic contract can also help, onerously, with avoiding to replay a transaction multiple time in the context where you do want to be able to race yourself. Good reasons to race yourself is when you have strong obligations to fulfill in a short deadline, but the current chain is wobbly due to some attack, particularly network splits: multiple of your workers might be victims of the network split (maybe targetted!), and would trigger racing variants of the queued transactions. In this case, the contract may associate a semaphore to each application-defined atomic set of transactions (for a shared multi-user contract, salted with sender ID); it would check that the semaphore wasn't set before to actually play the transaction set, and set the semaphore afterwards. Once again, miscompute worst-case gas and you're dead. You need to pay extra gas to read and write a semaphore, and will lose gas in case that multiple copies make it to the blockchain; but at least you won't lose the principal. To avoid the need for a replay barrier, you must always wait for *some* transaction with the given nonce to be fully confirmed before you start using the next nonce. When you have a tight deadline for some transactions and not others, you may have to up the gas price for the transactions you really want to get through, with an understanding of the algorithm used by the miners and of the strategy used by whoever is trying to bribe the miners out of including your transaction. Maybe you have to fill the block gas limit. Or maybe you have to split your transaction batch into smaller ones. An experimental study may be necessary, as well as regular updates to the software agents --- quite unlike the contracts that are immutable by design, transaction posting strategies may have to be mutable and evolving by design In some case, the right thing to do might be to consult back with the user, and ask them to add more ether, to update their gas price strategy, to deal with potentially or actually broken contracts, to watch the missing nodes of their personal database, etc. By default, we probably want to queue transactions one by one to avoid nonce-overlap issues; we may be more or less aggressive in terms of using nonces without partial or total confirmation from previous transactions, depending on the nature of the transactions. In any case, to definitely want a single system (even if possibly split into partitions) to issue transactions from a given address to minimize races. There is potentially a LOT of complexity, and if possible we want to partner with other people to define sound strategies... just that is a topic for itself, and there are sometimes games that people can play with lock out strategy via paying extra in gas to buy enough blocks to lock rivals out of a contract, etc. A generic strategy, DSL for strategies, etc., could be a research topic in itself. Sigh. Most people don't hit this issue, because they don't abide by a contract binding them to partake in distributed transactions across multiple blockchains with a priori untrustworthy other parties within tight deadlines. And most of the few who do possibly haven't thought deep enough about the ins and outs of these issues. Scary. Here, for now, we follow a very dumb strategy, of having only one active transaction per address. Furthermore, we only sign once, and resending blindly afterwards, trusting the gas computation, and trusting the nonce until it's found to be too low. TODO: implement an asynchronous way for the UI to peek at the status of a transaction while it's going along its slow progress. TODO: look at how OMiseGo does it, Andrew Redden tells me they have something public (and he has something private). *) module OngoingTransactionStatus = struct [@warning "-39"] type t = | Wanted of PreTransaction.t | Signed of Transaction.t * SignedTransaction.t [@@deriving yojson] include (YojsonPersistable (struct type nonrec t = t let yojsoning = {to_yojson;of_yojson} end) : (PersistableS with type t := t)) let pre_transaction : t -> PreTransaction.t = function | Wanted p -> p | Signed (tx, _) -> Transaction.pre_transaction tx end module FinalTransactionStatus = struct [@@@warning "-39"] type t = | Confirmed of Transaction.t * SignedTransaction.t * TransactionReceipt.t | Failed of OngoingTransactionStatus.t * exn [@@deriving yojson] include (YojsonPersistable (struct type nonrec t = t let yojsoning = {to_yojson;of_yojson} end) : (PersistableS with type t := t)) let pre_transaction : t -> PreTransaction.t = function | Confirmed (tx, _, _) -> Transaction.pre_transaction tx | Failed (ots, _) -> OngoingTransactionStatus.pre_transaction ots end module TransactionStatus = struct [@warning "-39"] type t = | Ongoing of OngoingTransactionStatus.t | Final of FinalTransactionStatus.t [@@deriving yojson] include (YojsonPersistable (struct type nonrec t = t let yojsoning = {to_yojson;of_yojson} end) : (PersistableS with type t := t)) let of_ongoing : OngoingTransactionStatus.t -> t = fun x -> Ongoing x let of_final : FinalTransactionStatus.t -> t = fun x -> Final x let pre_transaction : t -> PreTransaction.t = function | Ongoing x -> OngoingTransactionStatus.pre_transaction x | Final x -> FinalTransactionStatus.pre_transaction x let operation = fun x -> (x |> pre_transaction).operation end exception TransactionFailed of OngoingTransactionStatus.t * exn exception NonceTooLow type nonce_operation = Peek | Next | Reset [@@deriving yojson] module NonceTracker = struct open Lwter module Base = struct type context = unit module Key = Address type key = Key.t let key_prefix = "ETNT" module State = TrivialPersistable(struct type t = Nonce.t option [@@deriving yojson, rlp] let yojsoning = {to_yojson;of_yojson} let marshaling = marshaling_of_rlping rlping end) type state = State.t (* zero is often wrong, but just let it fail and resynchronize *) let make_default_state _ _ = None type t = (nonce_operation, Nonce.t) Lwter.arr let make_activity () address saving = sequentialize @@ fun op state -> let rec reset () = Lwt_exn.run_lwt (retry ~retry_window:0.01 ~max_window:5.0 ~max_retries:None Ethereum_json_rpc.eth_get_transaction_count) (address, BlockParameter.Latest) and continue result state = saving state >>= const (result, state) and next nonce = continue nonce (Some Nonce.(add one nonce)) in match (op, state) with | (Reset, _) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Reset"; continue Nonce.zero None | (Peek, None) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Peek/None"; reset () >>= fun nonce -> if ethereum_user_log then Logging.log "ETHUSR: nonce=%s" (Revision.to_string nonce); continue nonce (Some nonce) | (Peek, Some nonce) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Peek/Some nonce, nonce=%s" (Revision.to_string nonce); return (nonce, Some nonce) | (Next, None) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Next/None"; reset () >>= next | (Next, Some nonce) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Next/Some nonce, nonce=%s" (Revision.to_string nonce); next nonce end include PersistentActivity(Base) module State = Base.State let reset address = get () address Reset >>= const () let peek address = get () address Peek let next address = get () address Next end let make_tx_header : Address.t -> TokenAmount.t -> TokenAmount.t -> TxHeader.t Lwt_exn.t = fun sender value gas_limit -> TODO : get gas price and nonce from geth eth_gas_price () >>= fun gas_price -> of_lwt NonceTracker.next sender >>= fun nonce -> if ethereum_user_log then Logging.log "ETHUSR: make_tx_header sender=%s value=%s gas_limit=%s gas_price=%s nonce=%s" (Address.to_0x sender) (TokenAmount.to_string value) (TokenAmount.to_string gas_limit) (TokenAmount.to_string gas_price) (Nonce.to_0x nonce); return TxHeader.{sender; nonce; gas_price; gas_limit; value} exception Missing_password let sign_transaction : (Transaction.t, Transaction.t * SignedTransaction.t) Lwt_exn.arr = fun transaction -> if ethereum_user_log then Logging.log "ETHUSR: Beginning of sign_transaction"; let address = transaction.tx_header.sender in (try return (keypair_of_address address).password with | Not_found -> if ethereum_user_log then Logging.log "ETHUSR: Couldn't find registered keypair for %s" (nicknamed_string_of_address address); fail Missing_password) >>= fun password -> if ethereum_user_log then Logging.log "ETHUSR: Before personal_sign_transaction"; personal_sign_transaction (TransactionParameters.of_transaction transaction, password) >>= fun signed -> if ethereum_user_log then Logging.log "ETHUSR: Before final return in sign_transaction"; return (transaction, signed) * Prepare a signed transaction , that you may later issue onto Ethereum network , from given address , with given operation , value and gas_limit from given address, with given operation, value and gas_limit *) let make_signed_transaction : Address.t -> Operation.t -> TokenAmount.t -> TokenAmount.t -> (Transaction.t * SignedTransaction.t) Lwt_exn.t = fun sender operation value gas_limit -> make_tx_header sender value gas_limit >>= fun tx_header -> if ethereum_user_log then Logging.log "Before the sign_transaction"; sign_transaction Transaction.{tx_header; operation} (* TODO: move as many functions as possible ethereum_transaction ? *) let nonce_too_low address = if ethereum_user_log then Logging.log "ETHUSR: nonce too low for %s" (nicknamed_string_of_address address); (* TODO: Send Notification to end-user via UI! *) Lwter.(NonceTracker.reset address >>= const (Error NonceTooLow)) let confirmed_or_known_issue : Address.t -> (Digest.t, TransactionReceipt.t) Lwt_exn.arr = fun sender hash -> let open Lwter in Ethereum_json_rpc.eth_get_transaction_receipt hash >>= function | Ok None -> if ethereum_user_log then Logging.log "ETHUSR: confirmed_or_nonce_too_low CASE: Ok None"; nonce_too_low sender | Ok (Some receipt) -> if ethereum_user_log then Logging.log "ETHUSR: confirmed_or_nonce_too_low CASE: Ok (Some receipt)"; check_transaction_receipt_status receipt | Error e -> if ethereum_user_log then Logging.log "ETHUSR: confirmed_or_nonce_too_low CASE: Error e"; Lwt_exn.fail e exception Replacement_transaction_underpriced let send_raw_transaction : Address.t -> (SignedTransaction.t, Digest.t) Lwt_exn.arr = fun sender signed -> if ethereum_user_log then Logging.log "ETHUSR: send_raw_transaction %s" (SignedTransaction.to_yojson_string signed); match signed with | SignedTransaction.{raw;tx={hash}} -> Lwter.bind (eth_send_raw_transaction raw) (function | Error (Rpc_error {code= -32000; message="nonce too low"}) -> confirmed_or_known_issue sender hash >>= const hash | Error (Rpc_error {code= -32000; message}) when message = "known transaction: " ^ Digest.to_hex_string hash -> return hash | Error (Rpc_error {code= -32000; message}) when message = "replacement transaction underpriced" -> fail Replacement_transaction_underpriced | Error e -> fail e | Ok transaction_hash -> if transaction_hash = hash then return hash else bork "eth_send_raw_transaction: invalid hash %s instead of %s" (Digest.to_0x transaction_hash) (Digest.to_0x hash)) let send_and_confirm_transaction : (Transaction.t * SignedTransaction.t) -> TransactionReceipt.t Lwt_exn.t = fun (transaction, signed) -> if ethereum_user_log then Logging.log "Sending_and_confirm_transaction transaction=%s signed=%s" (Transaction.to_yojson_string transaction) (SignedTransaction.to_yojson_string signed); let sender = transaction.tx_header.sender in let hash = signed.SignedTransaction.tx.hash in let open Lwt_exn in send_raw_transaction sender signed >>= (fun hash -> if ethereum_user_log then Logging.log "sent txhash=%s" (Digest.to_hex_string hash); return hash) >>= Ethereum_json_rpc.eth_get_transaction_receipt >>= (fun receipt -> if ethereum_user_log then Logging.log "got receipt %s" (option_to_yojson TransactionReceipt.to_yojson receipt |> string_of_yojson); return receipt) >>= (function | Some receipt -> check_transaction_receipt_status receipt | None -> if ethereum_user_log then Logging.log "send_and_confirm: None case"; let nonce = transaction.tx_header.nonce in Ethereum_json_rpc.eth_get_transaction_count (sender, BlockParameter.Latest) >>= fun sender_nonce -> if ethereum_user_log then Logging.log "sender_nonce=%s nonce=%s" (Revision.to_string sender_nonce) (Revision.to_string nonce); if Nonce.(compare sender_nonce nonce > 0) then (if ethereum_user_log then Logging.log "Before call of confirmed_or_known_issue"; confirmed_or_known_issue sender hash) else (if ethereum_user_log then Logging.log "Before call of fail Still_pending"; fail Still_pending)) >>= check_receipt_sufficiently_confirmed module TransactionTracker = struct open Lwter module Base = struct type context = unit module Key = struct [@@@warning "-39"] type t = { user : Address.t; revision : Revision.t } [@@deriving yojson, rlp] include (YojsonMarshalable(struct type nonrec t = t let yojsoning = {to_yojson;of_yojson} let marshaling = marshaling_of_rlping rlping end): YojsonMarshalableS with type t := t) end type key = Key.t let key_prefix = "ETTT" module State = TransactionStatus type state = State.t let make_default_state = persistent_actor_no_default_state key_prefix Key.to_yojson_string (* TODO: inspection? cancellation? *) type t = Key.t * FinalTransactionStatus.t Lwt.t * unit Lwt.u let make_activity () key saving state = let (ready, notify_ready) = Lwt.task () in let rec update (status : TransactionStatus.t) = saving status >>= Db.committing >>= loop and continue (status : OngoingTransactionStatus.t) = TransactionStatus.Ongoing status |> update and finalize (status : FinalTransactionStatus.t) = if ethereum_user_log then Logging.log "Ethereum_user: beginning of finalize operation"; TransactionStatus.Final status |> update and invalidate transaction_status error = if ethereum_user_log then Logging.log "Ethereum_user: beginning of invalidate operation"; finalize (Failed (transaction_status, error)) and loop (status : TransactionStatus.t) : FinalTransactionStatus.t Lwt.t = " Stepping into % s " ( TransactionStatus.to_yojson_string status ) ; match status with | Ongoing ongoing -> (match ongoing with | Wanted {operation; value; gas_limit} -> make_signed_transaction key.Key.user operation value gas_limit >>= (function | Ok (t,c) -> OngoingTransactionStatus.Signed (t,c) |> continue | Error error -> invalidate ongoing error) | Signed (transaction, signed) -> if ethereum_user_log then Logging.log "Ethereum_User: Signed"; (transaction, signed) |> Lwt_exn.(run_lwt (retry ~retry_window:0.05 ~max_window:30.0 ~max_retries:None (trying send_and_confirm_transaction >>> function | Ok receipt -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Ok receipt A"; return (Ok receipt) | Error NonceTooLow -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error NonceTooLow A"; return (Error NonceTooLow) | Error TransactionRejected -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error TransactionRejected"; return (Error TransactionRejected) | Error e -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error e=%s" (Printexc.to_string e); fail e))) >>= function | Ok receipt -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Ok receipt B"; FinalTransactionStatus.Confirmed (transaction, signed, receipt) |> finalize | Error NonceTooLow -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error NonceTooLow B"; OngoingTransactionStatus.Wanted (Transaction.pre_transaction transaction) |> continue | Error error -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error error"; invalidate ongoing error) | Final x -> return x in key, (ready >>= fun () -> loop state), notify_ready end include PersistentActivity(Base) module Key = Base.Key end module UserState = struct [@warning "-39"] type t = { address: Address.t ; transaction_counter: Revision.t ; ongoing_transactions: RevisionSet.t } [@@deriving lens { prefix=true }, yojson, rlp] let marshaling = marshaling_of_rlping rlping include (TrivialPersistable (struct type nonrec t = t let marshaling = marshaling let yojsoning = {to_yojson;of_yojson} end) : PersistableS with type t := t) end module UserAsyncAction = AsyncAction(UserState) module User = struct open Lwter module Base = struct module Key = Address type key = Key.t let key_prefix = "ETUS" module State = UserState type state = UserState.t type t = state SimpleActor.t type context = Address.t -> t let make_default_state _get_user user = UserState. { address= user ; transaction_counter= Revision.zero ; ongoing_transactions= RevisionSet.empty } let rec resume_transaction get_user user revision = " resume_transaction % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ; let (_, promise, notify_ready) = TransactionTracker.get () {user; revision} in Lwt.wakeup_later notify_ready (); Lwt.async (fun () -> promise >>= fun _final_status -> " SCHEDULING a remove_transaction % s % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ) ; SimpleActor.action (get_user user) (remove_transaction get_user user) revision) and resume_transactions get_user user (state : State.t) = RevisionSet.min_elt_opt state.ongoing_transactions |> Option.iter (resume_transaction get_user user) and remove_transaction : context -> Address.t -> (Revision.t, unit) UserAsyncAction.arr = fun get_user user revision user_state -> " REMOVE_TRANSACTION % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ; let new_state = user_state |> Lens.modify UserState.lens_ongoing_transactions (RevisionSet.remove revision) in resume_transactions get_user user new_state; UserAsyncAction.return () new_state let make_activity get_user user saving state = (* TODO: use Db.with_transaction here, or have all callers use it appropriately *) let wrapper transform = Lwter.(transform >>> saving) . ( fun state - > " Actor for % s called , state % s " ( Address.to_0x user ) ( State.to_yojson_string state ) ; state | > transform > > = fun state - > " Actor for % s returned , state % s ; saving ... " ( Address.to_0x user ) ( State.to_yojson_string state ) ; saving state > > = fun state - > " Actor for % s saved % s " ( Address.to_0x user ) ( State.to_yojson_string state ) ; return state ) fun state -> Logging.log "Actor for %s called, state %s" (Address.to_0x user) (State.to_yojson_string state); state |> transform >>= fun state -> Logging.log "Actor for %s returned, state %s; saving..." (Address.to_0x user) (State.to_yojson_string state); saving state >>= fun state -> Logging.log "Actor for %s saved %s" (Address.to_0x user) (State.to_yojson_string state); return state)*) in let actor = SimpleActor.make ~wrapper state in (* TODO: maybe just use Lwt_mvar.create state and leave it to users to transact on it ? *) resume_transactions get_user user state; (* TODO: pass the actor as context to that? *) actor end include PersistentActivity(Base) let rec get_user user = get get_user user let add_transaction : (OngoingTransactionStatus.t, TransactionTracker.t) UserAsyncAction.arr = fun transaction_status user_state -> if ethereum_user_log then Logging.log "ETHUSR: beginning of add_transaction"; let open Lwt in let user = user_state.UserState.address in let revision = user_state.transaction_counter in " add_transaction % s % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ( OngoingTransactionStatus.to_yojson_string transaction_status ) ; TransactionTracker.(make () Key.{user; revision} (Lwter.const (TransactionStatus.Ongoing transaction_status))) >>= fun tracker -> if ethereum_user_log then Logging.log "ETHUSR: second step of add_transaction"; if RevisionSet.is_empty (UserState.lens_ongoing_transactions.get user_state) then Base.resume_transaction get_user user revision; " ADD_TRANSACTION % s % s = > % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ( OngoingTransactionStatus.to_yojson_string transaction_status ) ( TransactionTracker . Key.to_yojson_string ( match tracker with ( key , _ , _ ) - > key ) ) ; UserAsyncAction.return tracker (user_state |> Lens.modify UserState.lens_transaction_counter Revision.(add one) |> Lens.modify UserState.lens_ongoing_transactions (RevisionSet.add revision)) end let user_action : user:Address.t -> ('i, 'o) UserAsyncAction.arr -> ('i, 'o) Lwt_exn.arr = fun ~user action input -> if ethereum_user_log then Logging.log "ETHUSR: beginning of user_action"; SimpleActor.action (User.get_user user) action input let add_ongoing_transaction : user:Address.t -> (OngoingTransactionStatus.t, TransactionTracker.t) Lwt_exn.arr = fun ~user status -> if ethereum_user_log then Logging.log "ETHUSR: beginning of add_ongoing_transaction"; user_action ~user User.add_transaction status let issue_pre_transaction : Address.t -> (PreTransaction.t, TransactionTracker.t) Lwt_exn.arr = fun sender pre -> if ethereum_user_log then Logging.log "ETHUSR: beginning of issue_pre_transaction"; OngoingTransactionStatus.Wanted pre |> add_ongoing_transaction ~user:sender let track_transaction : (TransactionTracker.t, FinalTransactionStatus.t) Lwter.arr = fun (_key_t, promise, _unit_lwt_u) -> if ethereum_user_log then Logging.log "ETHUSR: track_transaction, returning promise"; promise let check_transaction_confirmed : (FinalTransactionStatus.t, Transaction.t * SignedTransaction.t * TransactionReceipt.t) Lwt_exn.arr = fun final_transaction_status -> if ethereum_user_log then Logging.log "ETHUSR: Beginning of check_transaction_confirmed"; match final_transaction_status with | FinalTransactionStatus.Confirmed (t, s, r) -> if ethereum_user_log then Logging.log "ETHUSR: check_transaction_confirmed, Case Confirmed"; return (t, s, r) | FinalTransactionStatus.Failed (t, e) -> if ethereum_user_log then Logging.log "ETHUSR: check_transaction_confirmed, Case Failed e=%s" (Printexc.to_string e); fail (TransactionFailed (t, e)) let confirm_pre_transaction : Address.t -> (PreTransaction.t, Transaction.t * SignedTransaction.t * TransactionReceipt.t) Lwt_exn.arr = fun address -> issue_pre_transaction address >>> of_lwt track_transaction >>> check_transaction_confirmed * Gas used for a transfer transaction . Hardcoded value defined in the Yellowpaper . let transfer_gas_used = TokenAmount.of_int 21000 (* Used only in tests *) let transfer_tokens ~recipient value = PreTransaction.{operation=(Operation.TransferTokens recipient); value; gas_limit=transfer_gas_used} let make_pre_transaction ~sender operation ?gas_limit ~value : PreTransaction.t Lwt_exn.t = if ethereum_user_log then Logging.log "ETHUSR: Beginning of make_pre_transaction"; (match gas_limit with | Some x -> return x | None -> eth_estimate_gas (TransactionParameters.of_operation sender operation value)) >>= fun gas_limit -> if ethereum_user_log then Logging.log "ETHUSR: make_pre_transaction gas_limit=%s value=%s" (TokenAmount.to_string gas_limit) (TokenAmount.to_string value); TODO : The multiplication by 2 is a hack that needs to be addressed let gas_limit_n_fold = (TokenAmount.mul (TokenAmount.of_int 2) gas_limit) in if ethereum_user_log then Logging.log "ETHUSR: gas_limit_n_fold=%s" (TokenAmount.to_string gas_limit_n_fold); return PreTransaction.{operation; value; gas_limit=gas_limit_n_fold} let create_contract ~sender ~code ?gas_limit ~value = make_pre_transaction ~sender (Operation.CreateContract code) ?gas_limit ~value let call_function ~sender ~contract ~call ?gas_limit ~value = make_pre_transaction ~sender (Operation.CallFunction (contract, call)) ?gas_limit ~value let get_status_receipt : TransactionReceipt.t -> bool = fun tr -> TokenAmount.equal tr.status TokenAmount.one let post_pretransaction : PreTransaction.t -> Address.t -> TransactionReceipt.t Lwt_exn.t = fun pre_transaction sender -> add_ongoing_transaction ~user:sender (Wanted pre_transaction) >>= fun (tracker_key, _, _) -> let (_, promise, _) = TransactionTracker.get () tracker_key in (Lwt.bind promise (function | FinalTransactionStatus.Failed (_, error) -> fail error (* bork "Cannot match this" *) | FinalTransactionStatus.Confirmed (_transaction, _signed, receipt) -> if ethereum_user_log then Logging.log "transaction status=%B" (get_status_receipt receipt); Lwt_exn.return receipt)) let post_operation_kernel : Ethereum_chain.Operation.t -> Address.t -> TokenAmount.t -> TransactionReceipt.t Lwt_exn.t = fun operation sender value -> let gas_limit_val = None in (* Some kind of arbitrary choice *) if ethereum_user_log then Logging.log "post_operation_general_kernel : before make_pre_transaction"; make_pre_transaction ~sender operation ?gas_limit:gas_limit_val ~value >>= fun pre_transaction -> post_pretransaction pre_transaction sender let post_operation : operation:Ethereum_chain.Operation.t -> sender:Address.t -> value:TokenAmount.t -> TransactionReceipt.t Lwt_exn.t = fun ~operation ~sender ~value -> let rec submit_operation : unit -> TransactionReceipt.t Lwt_exn.t = fun () -> post_operation_kernel operation sender value >>= fun ereceipt -> if get_status_receipt ereceipt then return ereceipt else (if ethereum_user_log then Logging.log "receipt is not true, ereceipt=%s" (TokenAmount.to_string ereceipt.status); sleep_delay_exn 1.0 >>= submit_operation ) in submit_operation () module Test = struct open Lwt_exn open Digesting open Signing.Test open Ethereum_abi let prefunded_address_mutex = Lwt_mutex.create () let prefunded_address = ref None let get_prefunded_address () = Lwt_mutex.with_lock prefunded_address_mutex (fun () -> match !prefunded_address with | Some x -> return x | None -> Ethereum_transaction.get_first_account () >>= fun address -> register_keypair "Croesus" {(keypair_of_0x (* KLUGE: Unrelated keypair, wherein we override the address *) "0xd56984dc083d769701714eeb1d4c47a454255a3bbc3e9f4484208c52bda3b64e" "0x0423a7cd9a03fa9c5857e514ae5acb18ca91e07d69453ed85136ea6a00361067b860a5b20f1153333aef2d1ba13b1d7a52de2869d1f62371bf81bf803c21c67aca" "") with address}; prefunded_address := Some address; return address) * Has a transaction given by a hash successfully executed , and does the Ethereum network report information that match what we expected ? and does the Ethereum network report information that match what we expected? *) [@@@warning "-32"] let check_transaction_execution (transaction_hash: digest) (transaction: Transaction.t) : bool Lwt_exn.t = eth_get_transaction_receipt transaction_hash >>= arr (function | Some TransactionReceipt.{status} -> TokenAmount.sign status = 1 | _ -> false) >>= fun executed -> assert executed; Ethereum_json_rpc.eth_get_transaction_by_hash transaction_hash >>= fun info -> let tx_header = transaction.tx_header in assert (info.from = Some tx_header.sender); assert (info.nonce = tx_header.nonce); assert (TokenAmount.compare info.gas tx_header.gas_limit <= 0); assert (TokenAmount.compare info.gas_price tx_header.gas_price <= 0); assert (TokenAmount.compare info.value tx_header.value = 0); assert (match transaction.operation with (* operation-specific checks *) | TransferTokens recipient_address -> info.to_ = Some recipient_address | CreateContract data -> info.input = data | CallFunction (contract_address, call_input) -> info.to_ = Some contract_address && info.input = call_input) ; return true let%test "Ethereum-testnet-transfer" = Logging.log "\nTEST: Ethereum-testnet-transfer\n"; Lwt_exn.run (fun () -> of_lwt Db.open_connection "unit_test_db" >>= fun () -> get_prefunded_address () >>= fun croesus -> transfer_tokens ~recipient:alice_address (TokenAmount.of_int 1000000000) |> confirm_pre_transaction croesus >>= fun (transaction, _signed_tx, TransactionReceipt.{transaction_hash}) -> check_transaction_execution transaction_hash transaction) () let test_contract_code () = "contracts/test/HelloWorld.bin" |> Config.get_build_filename |> read_file |> Hex.parse_hex_string |> Bytes.of_string let list_only_element = function (* TODO: move to Legilogic_lib ? *) | [x] -> x | _ -> Lib.bork "list isn't a singleton" let%test "Ethereum-testnet-contract-failure" = (Logging.log "\nTEST: contract-failure-on-Ethereum-testnet!!\n"; Lwt_exn.run (fun () -> of_lwt Db.open_connection "unit_test_db" >>= fun () -> get_prefunded_address () >>= fun sender -> let code = test_contract_code () in create_contract ~sender ~code (* Failure due to bogus gas_limit *) ~gas_limit:(TokenAmount.of_int 100000) ~value:TokenAmount.zero >>= (trying (confirm_pre_transaction sender) >>> (function | Ok _ -> return false TransactionTracker returns a FinalTransactionStatus after TransactionRejected is thrown | Error TransactionFailed (_, _) -> return true | Error _ -> return false)))) () let%test "Ethereum-testnet-contract-success" = Logging.log "\nTEST: contract-success-on-Ethereum-testnet!!\n"; Logging.log "SUBTEST: create the contract\n"; Lwt_exn.run (fun () -> of_lwt Db.open_connection "unit_test_db" >>= fun () -> get_prefunded_address () >>= fun sender -> let code = test_contract_code () in create_contract ~sender ~code ?gas_limit:None ~value:TokenAmount.zero >>= confirm_pre_transaction sender >>= (function | (_, _, {contract_address=(Some contract)}) -> return contract | _ -> bork "Failed to create contract") >>= fun contract -> Logging.log "SUBTEST: call contract function hello with no argument\n"; let call = encode_function_call { function_name = "hello"; parameters = [] } in call_function ~sender ~contract ~call ?gas_limit:None ~value:TokenAmount.zero >>= confirm_pre_transaction sender >>= fun (tx, _, {block_number}) -> eth_call (CallParameters.of_transaction tx, Block_number Revision.(sub block_number one)) >>= fun data -> Logging.log "hello replied: %s\n" (Hex.unparse_0x_data data); Logging.log "SUBTEST: call contract function mul42 with one number argument\n"; let call = encode_function_call { function_name = "mul42"; parameters = [ abi_uint (Z.of_int 47) ] } in call_function ~sender ~contract ~call ?gas_limit:None ~value:TokenAmount.zero >>= confirm_pre_transaction sender >>= fun (tx, _, {block_number}) -> eth_call (CallParameters.of_transaction tx, Block_number Revision.(sub block_number one)) >>= fun data -> Logging.log "mul42 replied: %s\n" (Hex.unparse_0x_data data); let mul42_encoding = let tuple_value, tuple_ty = abi_tuple_of_abi_values [abi_uint (Z.of_int 1974)] in encode_abi_value tuple_value tuple_ty in assert (data = Bytes.to_string mul42_encoding); Logging.log "SUBTEST: call contract function greetings with one string argument\n"; let call = encode_function_call { function_name = "greetings"; parameters = [ abi_string "Croesus" ] } in call_function ~sender ~contract ~call ?gas_limit:None ~value:TokenAmount.zero >>= confirm_pre_transaction sender >>= fun (tx, _, {block_number; logs}) -> let receipt_log = list_only_element logs in let log_contract_address = receipt_log.address in assert (log_contract_address = contract) ; let topic_event = list_only_element receipt_log.topics in let greetings_croesus = (String_value "Greetings, Croesus", String) in let greetings_encoding = let tuple_value, tuple_ty = abi_tuple_of_abi_values [greetings_croesus] in encode_abi_value tuple_value tuple_ty in Logging.log "expecting: %s\n" (Hex.unparse_0x_bytes greetings_encoding); let function_signature = {function_name= "greetingsEvent"; parameters= [greetings_croesus]} in let function_signature_digest = function_signature |> function_signature_digest in assert (Digest.equal topic_event function_signature_digest) ; (* the log data is the encoding of the parameter passed to the event *) let data = receipt_log.data in Logging.log "receipt log data: %s\n" (Hex.unparse_0x_bytes data); eth_call (CallParameters.of_transaction tx, Block_number Revision.(sub block_number one)) >>= fun result -> Logging.log "computed reply: %s\n" (Hex.unparse_0x_data result); assert (result = Bytes.to_string data); assert (data = greetings_encoding); TODO : add a stateful function , and check the behavior of eth_call wrt block_number return true) () end
null
https://raw.githubusercontent.com/AlacrisIO/legicash-facts/5d3663bade68c09bed47b3f58fa12580f38fdb46/src/legilogic_ethereum/ethereum_user.ml
ocaml
zero is often wrong, but just let it fail and resynchronize TODO: move as many functions as possible ethereum_transaction ? TODO: Send Notification to end-user via UI! TODO: inspection? cancellation? TODO: use Db.with_transaction here, or have all callers use it appropriately TODO: maybe just use Lwt_mvar.create state and leave it to users to transact on it ? TODO: pass the actor as context to that? Used only in tests bork "Cannot match this" Some kind of arbitrary choice KLUGE: Unrelated keypair, wherein we override the address operation-specific checks TODO: move to Legilogic_lib ? Failure due to bogus gas_limit the log data is the encoding of the parameter passed to the event
open Legilogic_lib open Lib open Yojsoning open Marshaling open Persisting open Types open Signing open Action open Lwt_exn open Json_rpc open Trie open Ethereum_chain open Ethereum_json_rpc open Ethereum_transaction let ethereum_user_log = true TODO : A much better state machine to get wanted transactions confirmed . It is a very bad idea to have more than one ongoing transaction in the : you might hope everything goes right and they are added in the correct order , but in practice so many things can go wrong and then the mitigations become hell , and attackers can get you to fail to transact , to deadlock , to replay your spending , to fail to meet a deadline , or more generally fail to meet your contractual obligations . Obvious strategies do n't work : - If you never re - send a transaction , but for some reason one transaction does n't go through because it was received out - of - order by the winning PoW nodes and dropped on the ground , or otherwise was lost in the shuffle of network packet drops , then you deadlock - If you always re - send a transaction , but never update the nonce , and some other client using the same private key ( WHY ? That should be a red alert anyway , unless it 's actually another copy of yourself sending another variant of the same transaction due to netsplit , and you re - synch after netmerge ) , or some other transaction on the same client races me ( if you fail to sequentialize transactions one at a time through a single thread ) , then you deadlock . - If you always re - send a transaction , and you update the nonce if you see yours is out - of - date , then you can race yourself and/or other transactions into sending multiple copies of a same transaction and end up spending many times over what you wanted to spend ( very bad ) . - Whatever decisions you make based on what the ethereum node tells you , it can give you _ hints _ about things that are going on , but nothing it says is authoritative until it is , which is only 30 minutes later ( or say 10 minutes , if you accept the risk of lower security ) . Until confirmation , whatever it says is subject to revision . - The safest would be to nurse each and every transaction to either completion or definite failure before even attempting the next one , but then that 's only one transaction per account every 30 minutes minimum ( NB : binance is OK with 36 confirmations ~10 minutes ) , and maybe much worse depending on how " definite failure " is defined . This suggests that having multiple accounts could be a requirement for playing safe with smart contracts : each " system " ( itself distributed with redundant workers for reliability ) has its own private key that wo n't race with other systems . One problem is that your local ethereum node ( and/or , in a real network , whichever remote node will eventually issue the blocks ) , sometimes will just drop your signed transactions , for whatever reasons : not enough ether , not enough gas , gas price too low , nonce out of synch , network error , network split , denial - of - service attack , selective censorship , block - buying attack , local reverts due to PoW attacks even less than 33 % , etc . You have to resend , sometimes with updated gas price , sometimes with updated nonce , sometimes even with updated contract parameters , etc . Yet , you should be wary of changing anything substantive ( to your application ) about a transaction being sent , or you can race yourselves , and end up paying twice ( or many more times ) to receive a counterpart only once ( or not at all ) . A good strategy might take into account what did or did n't happen in not - fully - confirmed blocks , yet ( obviously ) would not consider anything confirmed until it 's confirmed . It is unclear how best to deal with multiple queued transactions — the happy case of sending consecutive nonces automatically is great , but when things break down ( including due to the aforementioned re - send issues ) it 's a hell that 's hard to recover from , since new transactions will race the old ones , and any sequential dependency between them becomes quite tricky to enforce . One solution : a * batching contract * . Multiple transactions are sent atomically via a single call to some generic contract that plays them in sequence . Caveat : you better get you gas computation damn right ! Also mind the size limits to your overall transaction , the possibly more complex gas price computation to convince miners to get it through in a timely fashion , etc . If you do it right , though , you only have to deal with a single network event , which makes the limit of one nursed transaction per 30 minute much more bearable . This strategy implies or at least suggests developing a better - than - trivial batching strategy to group transactions , similar to what we use in db.ml for batching database writes , possibly with its own notion of atomic " transaction sets " that group " transactions " together . Additional feature : a * replay barrier * . The same generic contract can also help , onerously , with avoiding to replay a transaction multiple time in the context where you do want to be able to race yourself . Good reasons to race yourself is when you have strong obligations to fulfill in a short deadline , but the current chain is wobbly due to some attack , particularly network splits : multiple of your workers might be victims of the network split ( maybe targetted ! ) , and would trigger racing variants of the queued transactions . In this case , the contract may associate a semaphore to each application - defined atomic set of transactions ( for a shared multi - user contract , salted with sender ID ) ; it would check that the semaphore was n't set before to actually play the transaction set , and set the semaphore afterwards . Once again , miscompute worst - case gas and you 're dead . You need to pay extra gas to read and write a semaphore , and will lose gas in case that multiple copies make it to the blockchain ; but at least you wo n't lose the principal . To avoid the need for a replay barrier , you must always wait for * some * transaction with the given nonce to be fully confirmed before you start using the next nonce . When you have a tight deadline for some transactions and not others , you may have to up the gas price for the transactions you really want to get through , with an understanding of the algorithm used by the miners and of the strategy used by whoever is trying to bribe the miners out of including your transaction . Maybe you have to fill the block gas limit . Or maybe you have to split your transaction batch into smaller ones . An experimental study may be necessary , as well as regular updates to the software agents --- quite unlike the contracts that are immutable by design , transaction posting strategies may have to be mutable and evolving by design In some case , the right thing to do might be to consult back with the user , and ask them to add more ether , to update their gas price strategy , to deal with potentially or actually broken contracts , to watch the missing nodes of their personal database , etc . By default , we probably want to queue transactions one by one to avoid nonce - overlap issues ; we may be more or less aggressive in terms of using nonces without partial or total confirmation from previous transactions , depending on the nature of the transactions . In any case , to definitely want a single system ( even if possibly split into partitions ) to issue transactions from a given address to minimize races . There is potentially a LOT of complexity , and if possible we want to partner with other people to define sound strategies ... just that is a topic for itself , and there are sometimes games that people can play with lock out strategy via paying extra in gas to buy enough blocks to lock rivals out of a contract , etc . A generic strategy , DSL for strategies , etc . , could be a research topic in itself . Sigh . Most people do n't hit this issue , because they do n't abide by a contract binding them to partake in distributed transactions across multiple blockchains with a priori untrustworthy other parties within tight deadlines . And most of the few who do possibly have n't thought deep enough about the ins and outs of these issues . Scary . Here , for now , we follow a very dumb strategy , of having only one active transaction per address . Furthermore , we only sign once , and resending blindly afterwards , trusting the gas computation , and trusting the nonce until it 's found to be too low . : implement an asynchronous way for the UI to peek at the status of a transaction while it 's going along its slow progress . : look at how OMiseGo does it , tells me they have something public ( and he has something private ) . It is a very bad idea to have more than one ongoing transaction in the mempool: you might hope everything goes right and they are added in the correct order, but in practice so many things can go wrong and then the mitigations become hell, and attackers can get you to fail to transact, to deadlock, to replay your spending, to fail to meet a deadline, or more generally fail to meet your contractual obligations. Obvious strategies don't work: - If you never re-send a transaction, but for some reason one transaction doesn't go through because it was received out-of-order by the winning PoW nodes and dropped on the ground, or otherwise was lost in the shuffle of network packet drops, then you deadlock - If you always re-send a transaction, but never update the nonce, and some other client using the same private key (WHY? That should be a red alert anyway, unless it's actually another copy of yourself sending another variant of the same transaction due to netsplit, and you re-synch after netmerge), or some other transaction on the same client races me (if you fail to sequentialize transactions one at a time through a single thread), then you deadlock. - If you always re-send a transaction, and you update the nonce if you see yours is out-of-date, then you can race yourself and/or other transactions into sending multiple copies of a same transaction and end up spending many times over what you wanted to spend (very bad). - Whatever decisions you make based on what the ethereum node tells you, it can give you _hints_ about things that are going on, but nothing it says is authoritative until it is, which is only 30 minutes later (or say 10 minutes, if you accept the risk of lower security). Until confirmation, whatever it says is subject to revision. - The safest would be to nurse each and every transaction to either completion or definite failure before even attempting the next one, but then that's only one transaction per account every 30 minutes minimum (NB: binance is OK with 36 confirmations ~10 minutes), and maybe much worse depending on how "definite failure" is defined. This suggests that having multiple accounts could be a requirement for playing safe with smart contracts: each "system" (itself distributed with redundant workers for reliability) has its own private key that won't race with other systems. One problem is that your local ethereum node (and/or, in a real network, whichever remote node will eventually issue the blocks), sometimes will just drop your signed transactions, for whatever reasons: not enough ether, not enough gas, gas price too low, nonce out of synch, network error, network split, denial-of-service attack, selective censorship, block-buying attack, local reverts due to PoW attacks even less than 33%, etc. You have to resend, sometimes with updated gas price, sometimes with updated nonce, sometimes even with updated contract parameters, etc. Yet, you should be wary of changing anything substantive (to your application) about a transaction being sent, or you can race yourselves, and end up paying twice (or many more times) to receive a counterpart only once (or not at all). A good strategy might take into account what did or didn't happen in not-fully-confirmed blocks, yet (obviously) would not consider anything confirmed until it's confirmed. It is unclear how best to deal with multiple queued transactions — the happy case of sending consecutive nonces automatically is great, but when things break down (including due to the aforementioned re-send issues) it's a hell that's hard to recover from, since new transactions will race the old ones, and any sequential dependency between them becomes quite tricky to enforce. One solution: a *batching contract*. Multiple transactions are sent atomically via a single call to some generic contract that plays them in sequence. Caveat: you better get you gas computation damn right! Also mind the size limits to your overall transaction, the possibly more complex gas price computation to convince miners to get it through in a timely fashion, etc. If you do it right, though, you only have to deal with a single network event, which makes the limit of one nursed transaction per 30 minute much more bearable. This strategy implies or at least suggests developing a better-than-trivial batching strategy to group transactions, similar to what we use in db.ml for batching database writes, possibly with its own notion of atomic "transaction sets" that group "transactions" together. Additional feature: a *replay barrier*. The same generic contract can also help, onerously, with avoiding to replay a transaction multiple time in the context where you do want to be able to race yourself. Good reasons to race yourself is when you have strong obligations to fulfill in a short deadline, but the current chain is wobbly due to some attack, particularly network splits: multiple of your workers might be victims of the network split (maybe targetted!), and would trigger racing variants of the queued transactions. In this case, the contract may associate a semaphore to each application-defined atomic set of transactions (for a shared multi-user contract, salted with sender ID); it would check that the semaphore wasn't set before to actually play the transaction set, and set the semaphore afterwards. Once again, miscompute worst-case gas and you're dead. You need to pay extra gas to read and write a semaphore, and will lose gas in case that multiple copies make it to the blockchain; but at least you won't lose the principal. To avoid the need for a replay barrier, you must always wait for *some* transaction with the given nonce to be fully confirmed before you start using the next nonce. When you have a tight deadline for some transactions and not others, you may have to up the gas price for the transactions you really want to get through, with an understanding of the algorithm used by the miners and of the strategy used by whoever is trying to bribe the miners out of including your transaction. Maybe you have to fill the block gas limit. Or maybe you have to split your transaction batch into smaller ones. An experimental study may be necessary, as well as regular updates to the software agents --- quite unlike the contracts that are immutable by design, transaction posting strategies may have to be mutable and evolving by design In some case, the right thing to do might be to consult back with the user, and ask them to add more ether, to update their gas price strategy, to deal with potentially or actually broken contracts, to watch the missing nodes of their personal database, etc. By default, we probably want to queue transactions one by one to avoid nonce-overlap issues; we may be more or less aggressive in terms of using nonces without partial or total confirmation from previous transactions, depending on the nature of the transactions. In any case, to definitely want a single system (even if possibly split into partitions) to issue transactions from a given address to minimize races. There is potentially a LOT of complexity, and if possible we want to partner with other people to define sound strategies... just that is a topic for itself, and there are sometimes games that people can play with lock out strategy via paying extra in gas to buy enough blocks to lock rivals out of a contract, etc. A generic strategy, DSL for strategies, etc., could be a research topic in itself. Sigh. Most people don't hit this issue, because they don't abide by a contract binding them to partake in distributed transactions across multiple blockchains with a priori untrustworthy other parties within tight deadlines. And most of the few who do possibly haven't thought deep enough about the ins and outs of these issues. Scary. Here, for now, we follow a very dumb strategy, of having only one active transaction per address. Furthermore, we only sign once, and resending blindly afterwards, trusting the gas computation, and trusting the nonce until it's found to be too low. TODO: implement an asynchronous way for the UI to peek at the status of a transaction while it's going along its slow progress. TODO: look at how OMiseGo does it, Andrew Redden tells me they have something public (and he has something private). *) module OngoingTransactionStatus = struct [@warning "-39"] type t = | Wanted of PreTransaction.t | Signed of Transaction.t * SignedTransaction.t [@@deriving yojson] include (YojsonPersistable (struct type nonrec t = t let yojsoning = {to_yojson;of_yojson} end) : (PersistableS with type t := t)) let pre_transaction : t -> PreTransaction.t = function | Wanted p -> p | Signed (tx, _) -> Transaction.pre_transaction tx end module FinalTransactionStatus = struct [@@@warning "-39"] type t = | Confirmed of Transaction.t * SignedTransaction.t * TransactionReceipt.t | Failed of OngoingTransactionStatus.t * exn [@@deriving yojson] include (YojsonPersistable (struct type nonrec t = t let yojsoning = {to_yojson;of_yojson} end) : (PersistableS with type t := t)) let pre_transaction : t -> PreTransaction.t = function | Confirmed (tx, _, _) -> Transaction.pre_transaction tx | Failed (ots, _) -> OngoingTransactionStatus.pre_transaction ots end module TransactionStatus = struct [@warning "-39"] type t = | Ongoing of OngoingTransactionStatus.t | Final of FinalTransactionStatus.t [@@deriving yojson] include (YojsonPersistable (struct type nonrec t = t let yojsoning = {to_yojson;of_yojson} end) : (PersistableS with type t := t)) let of_ongoing : OngoingTransactionStatus.t -> t = fun x -> Ongoing x let of_final : FinalTransactionStatus.t -> t = fun x -> Final x let pre_transaction : t -> PreTransaction.t = function | Ongoing x -> OngoingTransactionStatus.pre_transaction x | Final x -> FinalTransactionStatus.pre_transaction x let operation = fun x -> (x |> pre_transaction).operation end exception TransactionFailed of OngoingTransactionStatus.t * exn exception NonceTooLow type nonce_operation = Peek | Next | Reset [@@deriving yojson] module NonceTracker = struct open Lwter module Base = struct type context = unit module Key = Address type key = Key.t let key_prefix = "ETNT" module State = TrivialPersistable(struct type t = Nonce.t option [@@deriving yojson, rlp] let yojsoning = {to_yojson;of_yojson} let marshaling = marshaling_of_rlping rlping end) type state = State.t let make_default_state _ _ = None type t = (nonce_operation, Nonce.t) Lwter.arr let make_activity () address saving = sequentialize @@ fun op state -> let rec reset () = Lwt_exn.run_lwt (retry ~retry_window:0.01 ~max_window:5.0 ~max_retries:None Ethereum_json_rpc.eth_get_transaction_count) (address, BlockParameter.Latest) and continue result state = saving state >>= const (result, state) and next nonce = continue nonce (Some Nonce.(add one nonce)) in match (op, state) with | (Reset, _) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Reset"; continue Nonce.zero None | (Peek, None) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Peek/None"; reset () >>= fun nonce -> if ethereum_user_log then Logging.log "ETHUSR: nonce=%s" (Revision.to_string nonce); continue nonce (Some nonce) | (Peek, Some nonce) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Peek/Some nonce, nonce=%s" (Revision.to_string nonce); return (nonce, Some nonce) | (Next, None) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Next/None"; reset () >>= next | (Next, Some nonce) -> if ethereum_user_log then Logging.log "ETHUSR: nonce tracker Next/Some nonce, nonce=%s" (Revision.to_string nonce); next nonce end include PersistentActivity(Base) module State = Base.State let reset address = get () address Reset >>= const () let peek address = get () address Peek let next address = get () address Next end let make_tx_header : Address.t -> TokenAmount.t -> TokenAmount.t -> TxHeader.t Lwt_exn.t = fun sender value gas_limit -> TODO : get gas price and nonce from geth eth_gas_price () >>= fun gas_price -> of_lwt NonceTracker.next sender >>= fun nonce -> if ethereum_user_log then Logging.log "ETHUSR: make_tx_header sender=%s value=%s gas_limit=%s gas_price=%s nonce=%s" (Address.to_0x sender) (TokenAmount.to_string value) (TokenAmount.to_string gas_limit) (TokenAmount.to_string gas_price) (Nonce.to_0x nonce); return TxHeader.{sender; nonce; gas_price; gas_limit; value} exception Missing_password let sign_transaction : (Transaction.t, Transaction.t * SignedTransaction.t) Lwt_exn.arr = fun transaction -> if ethereum_user_log then Logging.log "ETHUSR: Beginning of sign_transaction"; let address = transaction.tx_header.sender in (try return (keypair_of_address address).password with | Not_found -> if ethereum_user_log then Logging.log "ETHUSR: Couldn't find registered keypair for %s" (nicknamed_string_of_address address); fail Missing_password) >>= fun password -> if ethereum_user_log then Logging.log "ETHUSR: Before personal_sign_transaction"; personal_sign_transaction (TransactionParameters.of_transaction transaction, password) >>= fun signed -> if ethereum_user_log then Logging.log "ETHUSR: Before final return in sign_transaction"; return (transaction, signed) * Prepare a signed transaction , that you may later issue onto Ethereum network , from given address , with given operation , value and gas_limit from given address, with given operation, value and gas_limit *) let make_signed_transaction : Address.t -> Operation.t -> TokenAmount.t -> TokenAmount.t -> (Transaction.t * SignedTransaction.t) Lwt_exn.t = fun sender operation value gas_limit -> make_tx_header sender value gas_limit >>= fun tx_header -> if ethereum_user_log then Logging.log "Before the sign_transaction"; sign_transaction Transaction.{tx_header; operation} let nonce_too_low address = if ethereum_user_log then Logging.log "ETHUSR: nonce too low for %s" (nicknamed_string_of_address address); Lwter.(NonceTracker.reset address >>= const (Error NonceTooLow)) let confirmed_or_known_issue : Address.t -> (Digest.t, TransactionReceipt.t) Lwt_exn.arr = fun sender hash -> let open Lwter in Ethereum_json_rpc.eth_get_transaction_receipt hash >>= function | Ok None -> if ethereum_user_log then Logging.log "ETHUSR: confirmed_or_nonce_too_low CASE: Ok None"; nonce_too_low sender | Ok (Some receipt) -> if ethereum_user_log then Logging.log "ETHUSR: confirmed_or_nonce_too_low CASE: Ok (Some receipt)"; check_transaction_receipt_status receipt | Error e -> if ethereum_user_log then Logging.log "ETHUSR: confirmed_or_nonce_too_low CASE: Error e"; Lwt_exn.fail e exception Replacement_transaction_underpriced let send_raw_transaction : Address.t -> (SignedTransaction.t, Digest.t) Lwt_exn.arr = fun sender signed -> if ethereum_user_log then Logging.log "ETHUSR: send_raw_transaction %s" (SignedTransaction.to_yojson_string signed); match signed with | SignedTransaction.{raw;tx={hash}} -> Lwter.bind (eth_send_raw_transaction raw) (function | Error (Rpc_error {code= -32000; message="nonce too low"}) -> confirmed_or_known_issue sender hash >>= const hash | Error (Rpc_error {code= -32000; message}) when message = "known transaction: " ^ Digest.to_hex_string hash -> return hash | Error (Rpc_error {code= -32000; message}) when message = "replacement transaction underpriced" -> fail Replacement_transaction_underpriced | Error e -> fail e | Ok transaction_hash -> if transaction_hash = hash then return hash else bork "eth_send_raw_transaction: invalid hash %s instead of %s" (Digest.to_0x transaction_hash) (Digest.to_0x hash)) let send_and_confirm_transaction : (Transaction.t * SignedTransaction.t) -> TransactionReceipt.t Lwt_exn.t = fun (transaction, signed) -> if ethereum_user_log then Logging.log "Sending_and_confirm_transaction transaction=%s signed=%s" (Transaction.to_yojson_string transaction) (SignedTransaction.to_yojson_string signed); let sender = transaction.tx_header.sender in let hash = signed.SignedTransaction.tx.hash in let open Lwt_exn in send_raw_transaction sender signed >>= (fun hash -> if ethereum_user_log then Logging.log "sent txhash=%s" (Digest.to_hex_string hash); return hash) >>= Ethereum_json_rpc.eth_get_transaction_receipt >>= (fun receipt -> if ethereum_user_log then Logging.log "got receipt %s" (option_to_yojson TransactionReceipt.to_yojson receipt |> string_of_yojson); return receipt) >>= (function | Some receipt -> check_transaction_receipt_status receipt | None -> if ethereum_user_log then Logging.log "send_and_confirm: None case"; let nonce = transaction.tx_header.nonce in Ethereum_json_rpc.eth_get_transaction_count (sender, BlockParameter.Latest) >>= fun sender_nonce -> if ethereum_user_log then Logging.log "sender_nonce=%s nonce=%s" (Revision.to_string sender_nonce) (Revision.to_string nonce); if Nonce.(compare sender_nonce nonce > 0) then (if ethereum_user_log then Logging.log "Before call of confirmed_or_known_issue"; confirmed_or_known_issue sender hash) else (if ethereum_user_log then Logging.log "Before call of fail Still_pending"; fail Still_pending)) >>= check_receipt_sufficiently_confirmed module TransactionTracker = struct open Lwter module Base = struct type context = unit module Key = struct [@@@warning "-39"] type t = { user : Address.t; revision : Revision.t } [@@deriving yojson, rlp] include (YojsonMarshalable(struct type nonrec t = t let yojsoning = {to_yojson;of_yojson} let marshaling = marshaling_of_rlping rlping end): YojsonMarshalableS with type t := t) end type key = Key.t let key_prefix = "ETTT" module State = TransactionStatus type state = State.t let make_default_state = persistent_actor_no_default_state key_prefix Key.to_yojson_string type t = Key.t * FinalTransactionStatus.t Lwt.t * unit Lwt.u let make_activity () key saving state = let (ready, notify_ready) = Lwt.task () in let rec update (status : TransactionStatus.t) = saving status >>= Db.committing >>= loop and continue (status : OngoingTransactionStatus.t) = TransactionStatus.Ongoing status |> update and finalize (status : FinalTransactionStatus.t) = if ethereum_user_log then Logging.log "Ethereum_user: beginning of finalize operation"; TransactionStatus.Final status |> update and invalidate transaction_status error = if ethereum_user_log then Logging.log "Ethereum_user: beginning of invalidate operation"; finalize (Failed (transaction_status, error)) and loop (status : TransactionStatus.t) : FinalTransactionStatus.t Lwt.t = " Stepping into % s " ( TransactionStatus.to_yojson_string status ) ; match status with | Ongoing ongoing -> (match ongoing with | Wanted {operation; value; gas_limit} -> make_signed_transaction key.Key.user operation value gas_limit >>= (function | Ok (t,c) -> OngoingTransactionStatus.Signed (t,c) |> continue | Error error -> invalidate ongoing error) | Signed (transaction, signed) -> if ethereum_user_log then Logging.log "Ethereum_User: Signed"; (transaction, signed) |> Lwt_exn.(run_lwt (retry ~retry_window:0.05 ~max_window:30.0 ~max_retries:None (trying send_and_confirm_transaction >>> function | Ok receipt -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Ok receipt A"; return (Ok receipt) | Error NonceTooLow -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error NonceTooLow A"; return (Error NonceTooLow) | Error TransactionRejected -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error TransactionRejected"; return (Error TransactionRejected) | Error e -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error e=%s" (Printexc.to_string e); fail e))) >>= function | Ok receipt -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Ok receipt B"; FinalTransactionStatus.Confirmed (transaction, signed, receipt) |> finalize | Error NonceTooLow -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error NonceTooLow B"; OngoingTransactionStatus.Wanted (Transaction.pre_transaction transaction) |> continue | Error error -> if ethereum_user_log then Logging.log "ETHUSR: TransactionTracker, Error error"; invalidate ongoing error) | Final x -> return x in key, (ready >>= fun () -> loop state), notify_ready end include PersistentActivity(Base) module Key = Base.Key end module UserState = struct [@warning "-39"] type t = { address: Address.t ; transaction_counter: Revision.t ; ongoing_transactions: RevisionSet.t } [@@deriving lens { prefix=true }, yojson, rlp] let marshaling = marshaling_of_rlping rlping include (TrivialPersistable (struct type nonrec t = t let marshaling = marshaling let yojsoning = {to_yojson;of_yojson} end) : PersistableS with type t := t) end module UserAsyncAction = AsyncAction(UserState) module User = struct open Lwter module Base = struct module Key = Address type key = Key.t let key_prefix = "ETUS" module State = UserState type state = UserState.t type t = state SimpleActor.t type context = Address.t -> t let make_default_state _get_user user = UserState. { address= user ; transaction_counter= Revision.zero ; ongoing_transactions= RevisionSet.empty } let rec resume_transaction get_user user revision = " resume_transaction % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ; let (_, promise, notify_ready) = TransactionTracker.get () {user; revision} in Lwt.wakeup_later notify_ready (); Lwt.async (fun () -> promise >>= fun _final_status -> " SCHEDULING a remove_transaction % s % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ) ; SimpleActor.action (get_user user) (remove_transaction get_user user) revision) and resume_transactions get_user user (state : State.t) = RevisionSet.min_elt_opt state.ongoing_transactions |> Option.iter (resume_transaction get_user user) and remove_transaction : context -> Address.t -> (Revision.t, unit) UserAsyncAction.arr = fun get_user user revision user_state -> " REMOVE_TRANSACTION % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ; let new_state = user_state |> Lens.modify UserState.lens_ongoing_transactions (RevisionSet.remove revision) in resume_transactions get_user user new_state; UserAsyncAction.return () new_state let make_activity get_user user saving state = let wrapper transform = Lwter.(transform >>> saving) . ( fun state - > " Actor for % s called , state % s " ( Address.to_0x user ) ( State.to_yojson_string state ) ; state | > transform > > = fun state - > " Actor for % s returned , state % s ; saving ... " ( Address.to_0x user ) ( State.to_yojson_string state ) ; saving state > > = fun state - > " Actor for % s saved % s " ( Address.to_0x user ) ( State.to_yojson_string state ) ; return state ) fun state -> Logging.log "Actor for %s called, state %s" (Address.to_0x user) (State.to_yojson_string state); state |> transform >>= fun state -> Logging.log "Actor for %s returned, state %s; saving..." (Address.to_0x user) (State.to_yojson_string state); saving state >>= fun state -> Logging.log "Actor for %s saved %s" (Address.to_0x user) (State.to_yojson_string state); return state)*) in let actor = SimpleActor.make ~wrapper state in actor end include PersistentActivity(Base) let rec get_user user = get get_user user let add_transaction : (OngoingTransactionStatus.t, TransactionTracker.t) UserAsyncAction.arr = fun transaction_status user_state -> if ethereum_user_log then Logging.log "ETHUSR: beginning of add_transaction"; let open Lwt in let user = user_state.UserState.address in let revision = user_state.transaction_counter in " add_transaction % s % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ( OngoingTransactionStatus.to_yojson_string transaction_status ) ; TransactionTracker.(make () Key.{user; revision} (Lwter.const (TransactionStatus.Ongoing transaction_status))) >>= fun tracker -> if ethereum_user_log then Logging.log "ETHUSR: second step of add_transaction"; if RevisionSet.is_empty (UserState.lens_ongoing_transactions.get user_state) then Base.resume_transaction get_user user revision; " ADD_TRANSACTION % s % s = > % s " TransactionTracker.(Key.to_yojson_string Key.{user;revision } ) ( OngoingTransactionStatus.to_yojson_string transaction_status ) ( TransactionTracker . Key.to_yojson_string ( match tracker with ( key , _ , _ ) - > key ) ) ; UserAsyncAction.return tracker (user_state |> Lens.modify UserState.lens_transaction_counter Revision.(add one) |> Lens.modify UserState.lens_ongoing_transactions (RevisionSet.add revision)) end let user_action : user:Address.t -> ('i, 'o) UserAsyncAction.arr -> ('i, 'o) Lwt_exn.arr = fun ~user action input -> if ethereum_user_log then Logging.log "ETHUSR: beginning of user_action"; SimpleActor.action (User.get_user user) action input let add_ongoing_transaction : user:Address.t -> (OngoingTransactionStatus.t, TransactionTracker.t) Lwt_exn.arr = fun ~user status -> if ethereum_user_log then Logging.log "ETHUSR: beginning of add_ongoing_transaction"; user_action ~user User.add_transaction status let issue_pre_transaction : Address.t -> (PreTransaction.t, TransactionTracker.t) Lwt_exn.arr = fun sender pre -> if ethereum_user_log then Logging.log "ETHUSR: beginning of issue_pre_transaction"; OngoingTransactionStatus.Wanted pre |> add_ongoing_transaction ~user:sender let track_transaction : (TransactionTracker.t, FinalTransactionStatus.t) Lwter.arr = fun (_key_t, promise, _unit_lwt_u) -> if ethereum_user_log then Logging.log "ETHUSR: track_transaction, returning promise"; promise let check_transaction_confirmed : (FinalTransactionStatus.t, Transaction.t * SignedTransaction.t * TransactionReceipt.t) Lwt_exn.arr = fun final_transaction_status -> if ethereum_user_log then Logging.log "ETHUSR: Beginning of check_transaction_confirmed"; match final_transaction_status with | FinalTransactionStatus.Confirmed (t, s, r) -> if ethereum_user_log then Logging.log "ETHUSR: check_transaction_confirmed, Case Confirmed"; return (t, s, r) | FinalTransactionStatus.Failed (t, e) -> if ethereum_user_log then Logging.log "ETHUSR: check_transaction_confirmed, Case Failed e=%s" (Printexc.to_string e); fail (TransactionFailed (t, e)) let confirm_pre_transaction : Address.t -> (PreTransaction.t, Transaction.t * SignedTransaction.t * TransactionReceipt.t) Lwt_exn.arr = fun address -> issue_pre_transaction address >>> of_lwt track_transaction >>> check_transaction_confirmed * Gas used for a transfer transaction . Hardcoded value defined in the Yellowpaper . let transfer_gas_used = TokenAmount.of_int 21000 let transfer_tokens ~recipient value = PreTransaction.{operation=(Operation.TransferTokens recipient); value; gas_limit=transfer_gas_used} let make_pre_transaction ~sender operation ?gas_limit ~value : PreTransaction.t Lwt_exn.t = if ethereum_user_log then Logging.log "ETHUSR: Beginning of make_pre_transaction"; (match gas_limit with | Some x -> return x | None -> eth_estimate_gas (TransactionParameters.of_operation sender operation value)) >>= fun gas_limit -> if ethereum_user_log then Logging.log "ETHUSR: make_pre_transaction gas_limit=%s value=%s" (TokenAmount.to_string gas_limit) (TokenAmount.to_string value); TODO : The multiplication by 2 is a hack that needs to be addressed let gas_limit_n_fold = (TokenAmount.mul (TokenAmount.of_int 2) gas_limit) in if ethereum_user_log then Logging.log "ETHUSR: gas_limit_n_fold=%s" (TokenAmount.to_string gas_limit_n_fold); return PreTransaction.{operation; value; gas_limit=gas_limit_n_fold} let create_contract ~sender ~code ?gas_limit ~value = make_pre_transaction ~sender (Operation.CreateContract code) ?gas_limit ~value let call_function ~sender ~contract ~call ?gas_limit ~value = make_pre_transaction ~sender (Operation.CallFunction (contract, call)) ?gas_limit ~value let get_status_receipt : TransactionReceipt.t -> bool = fun tr -> TokenAmount.equal tr.status TokenAmount.one let post_pretransaction : PreTransaction.t -> Address.t -> TransactionReceipt.t Lwt_exn.t = fun pre_transaction sender -> add_ongoing_transaction ~user:sender (Wanted pre_transaction) >>= fun (tracker_key, _, _) -> let (_, promise, _) = TransactionTracker.get () tracker_key in (Lwt.bind promise (function | FinalTransactionStatus.Failed (_, error) -> | FinalTransactionStatus.Confirmed (_transaction, _signed, receipt) -> if ethereum_user_log then Logging.log "transaction status=%B" (get_status_receipt receipt); Lwt_exn.return receipt)) let post_operation_kernel : Ethereum_chain.Operation.t -> Address.t -> TokenAmount.t -> TransactionReceipt.t Lwt_exn.t = fun operation sender value -> if ethereum_user_log then Logging.log "post_operation_general_kernel : before make_pre_transaction"; make_pre_transaction ~sender operation ?gas_limit:gas_limit_val ~value >>= fun pre_transaction -> post_pretransaction pre_transaction sender let post_operation : operation:Ethereum_chain.Operation.t -> sender:Address.t -> value:TokenAmount.t -> TransactionReceipt.t Lwt_exn.t = fun ~operation ~sender ~value -> let rec submit_operation : unit -> TransactionReceipt.t Lwt_exn.t = fun () -> post_operation_kernel operation sender value >>= fun ereceipt -> if get_status_receipt ereceipt then return ereceipt else (if ethereum_user_log then Logging.log "receipt is not true, ereceipt=%s" (TokenAmount.to_string ereceipt.status); sleep_delay_exn 1.0 >>= submit_operation ) in submit_operation () module Test = struct open Lwt_exn open Digesting open Signing.Test open Ethereum_abi let prefunded_address_mutex = Lwt_mutex.create () let prefunded_address = ref None let get_prefunded_address () = Lwt_mutex.with_lock prefunded_address_mutex (fun () -> match !prefunded_address with | Some x -> return x | None -> Ethereum_transaction.get_first_account () >>= fun address -> register_keypair "Croesus" "0xd56984dc083d769701714eeb1d4c47a454255a3bbc3e9f4484208c52bda3b64e" "0x0423a7cd9a03fa9c5857e514ae5acb18ca91e07d69453ed85136ea6a00361067b860a5b20f1153333aef2d1ba13b1d7a52de2869d1f62371bf81bf803c21c67aca" "") with address}; prefunded_address := Some address; return address) * Has a transaction given by a hash successfully executed , and does the Ethereum network report information that match what we expected ? and does the Ethereum network report information that match what we expected? *) [@@@warning "-32"] let check_transaction_execution (transaction_hash: digest) (transaction: Transaction.t) : bool Lwt_exn.t = eth_get_transaction_receipt transaction_hash >>= arr (function | Some TransactionReceipt.{status} -> TokenAmount.sign status = 1 | _ -> false) >>= fun executed -> assert executed; Ethereum_json_rpc.eth_get_transaction_by_hash transaction_hash >>= fun info -> let tx_header = transaction.tx_header in assert (info.from = Some tx_header.sender); assert (info.nonce = tx_header.nonce); assert (TokenAmount.compare info.gas tx_header.gas_limit <= 0); assert (TokenAmount.compare info.gas_price tx_header.gas_price <= 0); assert (TokenAmount.compare info.value tx_header.value = 0); | TransferTokens recipient_address -> info.to_ = Some recipient_address | CreateContract data -> info.input = data | CallFunction (contract_address, call_input) -> info.to_ = Some contract_address && info.input = call_input) ; return true let%test "Ethereum-testnet-transfer" = Logging.log "\nTEST: Ethereum-testnet-transfer\n"; Lwt_exn.run (fun () -> of_lwt Db.open_connection "unit_test_db" >>= fun () -> get_prefunded_address () >>= fun croesus -> transfer_tokens ~recipient:alice_address (TokenAmount.of_int 1000000000) |> confirm_pre_transaction croesus >>= fun (transaction, _signed_tx, TransactionReceipt.{transaction_hash}) -> check_transaction_execution transaction_hash transaction) () let test_contract_code () = "contracts/test/HelloWorld.bin" |> Config.get_build_filename |> read_file |> Hex.parse_hex_string |> Bytes.of_string | [x] -> x | _ -> Lib.bork "list isn't a singleton" let%test "Ethereum-testnet-contract-failure" = (Logging.log "\nTEST: contract-failure-on-Ethereum-testnet!!\n"; Lwt_exn.run (fun () -> of_lwt Db.open_connection "unit_test_db" >>= fun () -> get_prefunded_address () >>= fun sender -> let code = test_contract_code () in create_contract ~sender ~code ~gas_limit:(TokenAmount.of_int 100000) ~value:TokenAmount.zero >>= (trying (confirm_pre_transaction sender) >>> (function | Ok _ -> return false TransactionTracker returns a FinalTransactionStatus after TransactionRejected is thrown | Error TransactionFailed (_, _) -> return true | Error _ -> return false)))) () let%test "Ethereum-testnet-contract-success" = Logging.log "\nTEST: contract-success-on-Ethereum-testnet!!\n"; Logging.log "SUBTEST: create the contract\n"; Lwt_exn.run (fun () -> of_lwt Db.open_connection "unit_test_db" >>= fun () -> get_prefunded_address () >>= fun sender -> let code = test_contract_code () in create_contract ~sender ~code ?gas_limit:None ~value:TokenAmount.zero >>= confirm_pre_transaction sender >>= (function | (_, _, {contract_address=(Some contract)}) -> return contract | _ -> bork "Failed to create contract") >>= fun contract -> Logging.log "SUBTEST: call contract function hello with no argument\n"; let call = encode_function_call { function_name = "hello"; parameters = [] } in call_function ~sender ~contract ~call ?gas_limit:None ~value:TokenAmount.zero >>= confirm_pre_transaction sender >>= fun (tx, _, {block_number}) -> eth_call (CallParameters.of_transaction tx, Block_number Revision.(sub block_number one)) >>= fun data -> Logging.log "hello replied: %s\n" (Hex.unparse_0x_data data); Logging.log "SUBTEST: call contract function mul42 with one number argument\n"; let call = encode_function_call { function_name = "mul42"; parameters = [ abi_uint (Z.of_int 47) ] } in call_function ~sender ~contract ~call ?gas_limit:None ~value:TokenAmount.zero >>= confirm_pre_transaction sender >>= fun (tx, _, {block_number}) -> eth_call (CallParameters.of_transaction tx, Block_number Revision.(sub block_number one)) >>= fun data -> Logging.log "mul42 replied: %s\n" (Hex.unparse_0x_data data); let mul42_encoding = let tuple_value, tuple_ty = abi_tuple_of_abi_values [abi_uint (Z.of_int 1974)] in encode_abi_value tuple_value tuple_ty in assert (data = Bytes.to_string mul42_encoding); Logging.log "SUBTEST: call contract function greetings with one string argument\n"; let call = encode_function_call { function_name = "greetings"; parameters = [ abi_string "Croesus" ] } in call_function ~sender ~contract ~call ?gas_limit:None ~value:TokenAmount.zero >>= confirm_pre_transaction sender >>= fun (tx, _, {block_number; logs}) -> let receipt_log = list_only_element logs in let log_contract_address = receipt_log.address in assert (log_contract_address = contract) ; let topic_event = list_only_element receipt_log.topics in let greetings_croesus = (String_value "Greetings, Croesus", String) in let greetings_encoding = let tuple_value, tuple_ty = abi_tuple_of_abi_values [greetings_croesus] in encode_abi_value tuple_value tuple_ty in Logging.log "expecting: %s\n" (Hex.unparse_0x_bytes greetings_encoding); let function_signature = {function_name= "greetingsEvent"; parameters= [greetings_croesus]} in let function_signature_digest = function_signature |> function_signature_digest in assert (Digest.equal topic_event function_signature_digest) ; let data = receipt_log.data in Logging.log "receipt log data: %s\n" (Hex.unparse_0x_bytes data); eth_call (CallParameters.of_transaction tx, Block_number Revision.(sub block_number one)) >>= fun result -> Logging.log "computed reply: %s\n" (Hex.unparse_0x_data result); assert (result = Bytes.to_string data); assert (data = greetings_encoding); TODO : add a stateful function , and check the behavior of eth_call wrt block_number return true) () end
63bf32831f14e51a4aa6953a137ab2aa7cb30767e8c33300e6cd0174d73a714b
racket/racket7
stream.rkt
#lang racket/base (require racket/private/generic racket/generic racket/contract/base racket/contract/combinator racket/generator (rename-in "private/for.rkt" [stream-ref stream-get-generics]) "private/sequence.rkt" (only-in "private/stream-cons.rkt" stream-cons) "private/generic-methods.rkt" (for-syntax racket/base)) (provide empty-stream stream-cons stream? gen:stream ;; we don't need the generics versions of these because ;; the original sequence functions will work fine ;; for the dispatch. (the method table layout is ;; identical) stream-empty? stream-first stream-rest prop:stream in-stream stream stream* stream->list stream-length stream-ref stream-tail stream-append stream-map stream-andmap stream-ormap stream-for-each stream-fold stream-filter stream-add-between stream-count stream/c for/stream for*/stream) (define-syntax gen:stream (make-generic-info (quote-syntax gen:stream) (quote-syntax prop:stream) (quote-syntax stream-via-prop?) (quote-syntax stream-get-generics) (list (quote-syntax stream-empty?) (quote-syntax stream-first) (quote-syntax stream-rest)) (list (quote-syntax stream-empty?) (quote-syntax stream-first) (quote-syntax stream-rest)))) (define-syntax stream (syntax-rules () ((_) empty-stream) ((_ hd tl ...) (stream-cons hd (stream tl ...))))) (define-syntax stream* (syntax-rules () [(_ hd tl) (stream-cons hd tl)] [(_ hd tl ...) (stream-cons hd (stream* tl ...))])) (define (stream->list s) (for/list ([v (in-stream s)]) v)) (define (stream-length s) (unless (stream? s) (raise-argument-error 'stream-length "stream?" s)) (let loop ([s s] [len 0]) (if (stream-empty? s) len (loop (stream-rest s) (add1 len))))) (define (stream-ref st i) (unless (stream? st) (raise-argument-error 'stream-ref "stream?" st)) (unless (exact-nonnegative-integer? i) (raise-argument-error 'stream-ref "exact-nonnegative-integer?" i)) (let loop ([n i] [s st]) (cond [(stream-empty? s) (raise-arguments-error 'stream-ref "stream ended before index" "index" i "stream" st)] [(zero? n) (stream-first s)] [else (loop (sub1 n) (stream-rest s))]))) (define (stream-tail st i) (unless (stream? st) (raise-argument-error 'stream-tail "stream?" st)) (unless (exact-nonnegative-integer? i) (raise-argument-error 'stream-tail "exact-nonnegative-integer?" i)) (let loop ([n i] [s st]) (cond [(zero? n) s] [(stream-empty? s) (raise-arguments-error 'stream-tail "stream ended before index" "index" i "stream" st)] [else (loop (sub1 n) (stream-rest s))]))) (define (stream-append . l) (for ([s (in-list l)]) (unless (stream? s) (raise-argument-error 'stream-append "stream?" s))) (streams-append l)) (define (streams-append l) (cond [(null? l) empty-stream] [(null? (cdr l)) (car l)] [(stream-empty? (car l)) (streams-append (cdr l))] [else (make-do-stream (lambda () #f) (lambda () (stream-first (car l))) (lambda () (streams-append (cons (stream-rest (car l)) (cdr l)))))])) (define (stream-map f s) (unless (procedure? f) (raise-argument-error 'stream-map "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-map "stream?" s)) (let loop ([s s]) (if (stream-empty? s) empty-stream (stream-cons (f (stream-first s)) (loop (stream-rest s)))))) (define (stream-andmap f s) (unless (procedure? f) (raise-argument-error 'stream-andmap "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-andmap "stream?" s)) (sequence-andmap f s)) (define (stream-ormap f s) (unless (procedure? f) (raise-argument-error 'stream-ormap "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-ormap "stream?" s)) (sequence-ormap f s)) (define (stream-for-each f s) (unless (procedure? f) (raise-argument-error 'stream-for-each "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-for-each "stream?" s)) (sequence-for-each f s)) (define (stream-fold f i s) (unless (procedure? f) (raise-argument-error 'stream-fold "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-fold "stream?" s)) (sequence-fold f i s)) (define (stream-count f s) (unless (procedure? f) (raise-argument-error 'stream-count "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-count "stream?" s)) (sequence-count f s)) (define (stream-filter f s) (unless (procedure? f) (raise-argument-error 'stream-filter "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-filter "stream?" s)) (cond [(stream-empty? s) empty-stream] [else (let ([done? #f] [empty? #f] [fst #f] [rst #f]) (define (force!) (unless done? (let loop ([s s]) (cond [(stream-empty? s) (set! done? #t) (set! empty? #t)] [(f (stream-first s)) (set! fst (stream-first s)) (set! rst (stream-filter f (stream-rest s)))] [else (loop (stream-rest s))])) (set! done? #t))) (make-do-stream (lambda () (force!) empty?) (lambda () (force!) fst) (lambda () (force!) rst)))])) (define (stream-add-between s e) (unless (stream? s) (raise-argument-error 'stream-add-between "stream?" s)) (if (stream-empty? s) empty-stream (stream-cons (stream-first s) (let loop ([s (stream-rest s)]) (cond [(stream-empty? s) empty-stream] [else (stream-cons e (stream-cons (stream-first s) (loop (stream-rest s))))]))))) ;; Impersonators and Chaperones ---------------------------------------------------------------------- ;; (these are private because they would fail on lists, which satisfy `stream?`) (define (impersonate-stream s first-proc rest-proc . props) (impersonate-generics gen:stream s [stream-first (λ (stream-first) (impersonate-procedure stream-first (λ (s) (values (λ (v) (first-proc v)) s))))] [stream-rest (λ (stream-rest) (impersonate-procedure stream-rest (λ (s) (values (λ (v) (rest-proc v)) s))))] #:properties props)) (define (chaperone-stream s first-proc rest-proc . props) (chaperone-generics gen:stream s [stream-first (λ (stream-first) (chaperone-procedure stream-first (λ (s) (values (λ (v) (first-proc v)) s))))] [stream-rest (λ (stream-rest) (chaperone-procedure stream-rest (λ (s) (values (λ (v) (rest-proc v)) s))))] #:properties props)) ;; Stream contracts ---------------------------------------------------------------------------------- (define (stream/c-name ctc) (define elem-name (contract-name (base-stream/c-content ctc))) (apply build-compound-type-name 'stream/c elem-name '())) (define (add-stream-context blame) (blame-add-context blame "a value generated by")) (define (stream/c-stronger? a b) (contract-stronger? (base-stream/c-content a) (base-stream/c-content b))) (define ((late-neg-projection impersonate/chaperone-stream) ctc) (define elem-ctc (base-stream/c-content ctc)) (define listof-elem-ctc (listof elem-ctc)) (define elem-ctc-late-neg (get/build-late-neg-projection elem-ctc)) (define listof-elem-ctc-late-neg (get/build-late-neg-projection listof-elem-ctc)) (λ (blame) (define stream-blame (add-stream-context blame)) (define elem-ctc-late-neg-acceptor (elem-ctc-late-neg stream-blame)) (define listof-elem-ctc-neg-acceptor (listof-elem-ctc-late-neg stream-blame)) (define (stream/c-late-neg-proj-val-acceptor val neg-party) (unless (stream? val) (raise-blame-error blame #:missing-party neg-party val '(expected "a stream" given: "~e") val)) (define blame+neg-party (cons blame neg-party)) (if (list? val) (listof-elem-ctc-neg-acceptor val neg-party) (impersonate/chaperone-stream val (λ (v) (with-contract-continuation-mark blame+neg-party (elem-ctc-late-neg-acceptor v neg-party))) (λ (v) (with-contract-continuation-mark blame+neg-party (if (list? v) (listof-elem-ctc-neg-acceptor v neg-party) (stream/c-late-neg-proj-val-acceptor v neg-party)))) impersonator-prop:contracted ctc impersonator-prop:blame stream-blame))) stream/c-late-neg-proj-val-acceptor)) (struct base-stream/c (content)) (struct chaperone-stream/c base-stream/c () #:property prop:custom-write custom-write-property-proc #:property prop:chaperone-contract (parameterize ([skip-projection-wrapper? #t]) (build-chaperone-contract-property #:name stream/c-name #:first-order stream? #:stronger stream/c-stronger? #:late-neg-projection (late-neg-projection chaperone-stream)))) (struct impersonator-stream/c base-stream/c () #:property prop:custom-write custom-write-property-proc #:property prop:contract (build-contract-property #:name stream/c-name #:first-order stream? #:stronger stream/c-stronger? #:late-neg-projection (late-neg-projection impersonate-stream))) (define (stream/c elem) (define ctc (coerce-contract 'stream/c elem)) (if (chaperone-contract? ctc) (chaperone-stream/c ctc) (impersonator-stream/c ctc))) ;; Stream comprehensions ----------------------------------------------------------------------------- (define-syntaxes (for/stream for*/stream) (let () (define ((make-for/stream derived-stx) stx) (syntax-case stx () [(_ clauses . body) (begin (when (null? (syntax->list #'body)) (raise-syntax-error (syntax-e #'derived-stx) "missing body expression after sequence bindings" stx #'body)) (with-syntax ([((pre-body ...) body*) (split-for-body stx #'body)]) #`(sequence->stream (in-generator (#,derived-stx #,stx () clauses pre-body ... (yield (let () . body*)) (values))))))])) (values (make-for/stream #'for/fold/derived) (make-for/stream #'for*/fold/derived))))
null
https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/collects/racket/stream.rkt
racket
we don't need the generics versions of these because the original sequence functions will work fine for the dispatch. (the method table layout is identical) Impersonators and Chaperones ---------------------------------------------------------------------- (these are private because they would fail on lists, which satisfy `stream?`) Stream contracts ---------------------------------------------------------------------------------- Stream comprehensions -----------------------------------------------------------------------------
#lang racket/base (require racket/private/generic racket/generic racket/contract/base racket/contract/combinator racket/generator (rename-in "private/for.rkt" [stream-ref stream-get-generics]) "private/sequence.rkt" (only-in "private/stream-cons.rkt" stream-cons) "private/generic-methods.rkt" (for-syntax racket/base)) (provide empty-stream stream-cons stream? gen:stream stream-empty? stream-first stream-rest prop:stream in-stream stream stream* stream->list stream-length stream-ref stream-tail stream-append stream-map stream-andmap stream-ormap stream-for-each stream-fold stream-filter stream-add-between stream-count stream/c for/stream for*/stream) (define-syntax gen:stream (make-generic-info (quote-syntax gen:stream) (quote-syntax prop:stream) (quote-syntax stream-via-prop?) (quote-syntax stream-get-generics) (list (quote-syntax stream-empty?) (quote-syntax stream-first) (quote-syntax stream-rest)) (list (quote-syntax stream-empty?) (quote-syntax stream-first) (quote-syntax stream-rest)))) (define-syntax stream (syntax-rules () ((_) empty-stream) ((_ hd tl ...) (stream-cons hd (stream tl ...))))) (define-syntax stream* (syntax-rules () [(_ hd tl) (stream-cons hd tl)] [(_ hd tl ...) (stream-cons hd (stream* tl ...))])) (define (stream->list s) (for/list ([v (in-stream s)]) v)) (define (stream-length s) (unless (stream? s) (raise-argument-error 'stream-length "stream?" s)) (let loop ([s s] [len 0]) (if (stream-empty? s) len (loop (stream-rest s) (add1 len))))) (define (stream-ref st i) (unless (stream? st) (raise-argument-error 'stream-ref "stream?" st)) (unless (exact-nonnegative-integer? i) (raise-argument-error 'stream-ref "exact-nonnegative-integer?" i)) (let loop ([n i] [s st]) (cond [(stream-empty? s) (raise-arguments-error 'stream-ref "stream ended before index" "index" i "stream" st)] [(zero? n) (stream-first s)] [else (loop (sub1 n) (stream-rest s))]))) (define (stream-tail st i) (unless (stream? st) (raise-argument-error 'stream-tail "stream?" st)) (unless (exact-nonnegative-integer? i) (raise-argument-error 'stream-tail "exact-nonnegative-integer?" i)) (let loop ([n i] [s st]) (cond [(zero? n) s] [(stream-empty? s) (raise-arguments-error 'stream-tail "stream ended before index" "index" i "stream" st)] [else (loop (sub1 n) (stream-rest s))]))) (define (stream-append . l) (for ([s (in-list l)]) (unless (stream? s) (raise-argument-error 'stream-append "stream?" s))) (streams-append l)) (define (streams-append l) (cond [(null? l) empty-stream] [(null? (cdr l)) (car l)] [(stream-empty? (car l)) (streams-append (cdr l))] [else (make-do-stream (lambda () #f) (lambda () (stream-first (car l))) (lambda () (streams-append (cons (stream-rest (car l)) (cdr l)))))])) (define (stream-map f s) (unless (procedure? f) (raise-argument-error 'stream-map "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-map "stream?" s)) (let loop ([s s]) (if (stream-empty? s) empty-stream (stream-cons (f (stream-first s)) (loop (stream-rest s)))))) (define (stream-andmap f s) (unless (procedure? f) (raise-argument-error 'stream-andmap "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-andmap "stream?" s)) (sequence-andmap f s)) (define (stream-ormap f s) (unless (procedure? f) (raise-argument-error 'stream-ormap "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-ormap "stream?" s)) (sequence-ormap f s)) (define (stream-for-each f s) (unless (procedure? f) (raise-argument-error 'stream-for-each "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-for-each "stream?" s)) (sequence-for-each f s)) (define (stream-fold f i s) (unless (procedure? f) (raise-argument-error 'stream-fold "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-fold "stream?" s)) (sequence-fold f i s)) (define (stream-count f s) (unless (procedure? f) (raise-argument-error 'stream-count "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-count "stream?" s)) (sequence-count f s)) (define (stream-filter f s) (unless (procedure? f) (raise-argument-error 'stream-filter "procedure?" f)) (unless (stream? s) (raise-argument-error 'stream-filter "stream?" s)) (cond [(stream-empty? s) empty-stream] [else (let ([done? #f] [empty? #f] [fst #f] [rst #f]) (define (force!) (unless done? (let loop ([s s]) (cond [(stream-empty? s) (set! done? #t) (set! empty? #t)] [(f (stream-first s)) (set! fst (stream-first s)) (set! rst (stream-filter f (stream-rest s)))] [else (loop (stream-rest s))])) (set! done? #t))) (make-do-stream (lambda () (force!) empty?) (lambda () (force!) fst) (lambda () (force!) rst)))])) (define (stream-add-between s e) (unless (stream? s) (raise-argument-error 'stream-add-between "stream?" s)) (if (stream-empty? s) empty-stream (stream-cons (stream-first s) (let loop ([s (stream-rest s)]) (cond [(stream-empty? s) empty-stream] [else (stream-cons e (stream-cons (stream-first s) (loop (stream-rest s))))]))))) (define (impersonate-stream s first-proc rest-proc . props) (impersonate-generics gen:stream s [stream-first (λ (stream-first) (impersonate-procedure stream-first (λ (s) (values (λ (v) (first-proc v)) s))))] [stream-rest (λ (stream-rest) (impersonate-procedure stream-rest (λ (s) (values (λ (v) (rest-proc v)) s))))] #:properties props)) (define (chaperone-stream s first-proc rest-proc . props) (chaperone-generics gen:stream s [stream-first (λ (stream-first) (chaperone-procedure stream-first (λ (s) (values (λ (v) (first-proc v)) s))))] [stream-rest (λ (stream-rest) (chaperone-procedure stream-rest (λ (s) (values (λ (v) (rest-proc v)) s))))] #:properties props)) (define (stream/c-name ctc) (define elem-name (contract-name (base-stream/c-content ctc))) (apply build-compound-type-name 'stream/c elem-name '())) (define (add-stream-context blame) (blame-add-context blame "a value generated by")) (define (stream/c-stronger? a b) (contract-stronger? (base-stream/c-content a) (base-stream/c-content b))) (define ((late-neg-projection impersonate/chaperone-stream) ctc) (define elem-ctc (base-stream/c-content ctc)) (define listof-elem-ctc (listof elem-ctc)) (define elem-ctc-late-neg (get/build-late-neg-projection elem-ctc)) (define listof-elem-ctc-late-neg (get/build-late-neg-projection listof-elem-ctc)) (λ (blame) (define stream-blame (add-stream-context blame)) (define elem-ctc-late-neg-acceptor (elem-ctc-late-neg stream-blame)) (define listof-elem-ctc-neg-acceptor (listof-elem-ctc-late-neg stream-blame)) (define (stream/c-late-neg-proj-val-acceptor val neg-party) (unless (stream? val) (raise-blame-error blame #:missing-party neg-party val '(expected "a stream" given: "~e") val)) (define blame+neg-party (cons blame neg-party)) (if (list? val) (listof-elem-ctc-neg-acceptor val neg-party) (impersonate/chaperone-stream val (λ (v) (with-contract-continuation-mark blame+neg-party (elem-ctc-late-neg-acceptor v neg-party))) (λ (v) (with-contract-continuation-mark blame+neg-party (if (list? v) (listof-elem-ctc-neg-acceptor v neg-party) (stream/c-late-neg-proj-val-acceptor v neg-party)))) impersonator-prop:contracted ctc impersonator-prop:blame stream-blame))) stream/c-late-neg-proj-val-acceptor)) (struct base-stream/c (content)) (struct chaperone-stream/c base-stream/c () #:property prop:custom-write custom-write-property-proc #:property prop:chaperone-contract (parameterize ([skip-projection-wrapper? #t]) (build-chaperone-contract-property #:name stream/c-name #:first-order stream? #:stronger stream/c-stronger? #:late-neg-projection (late-neg-projection chaperone-stream)))) (struct impersonator-stream/c base-stream/c () #:property prop:custom-write custom-write-property-proc #:property prop:contract (build-contract-property #:name stream/c-name #:first-order stream? #:stronger stream/c-stronger? #:late-neg-projection (late-neg-projection impersonate-stream))) (define (stream/c elem) (define ctc (coerce-contract 'stream/c elem)) (if (chaperone-contract? ctc) (chaperone-stream/c ctc) (impersonator-stream/c ctc))) (define-syntaxes (for/stream for*/stream) (let () (define ((make-for/stream derived-stx) stx) (syntax-case stx () [(_ clauses . body) (begin (when (null? (syntax->list #'body)) (raise-syntax-error (syntax-e #'derived-stx) "missing body expression after sequence bindings" stx #'body)) (with-syntax ([((pre-body ...) body*) (split-for-body stx #'body)]) #`(sequence->stream (in-generator (#,derived-stx #,stx () clauses pre-body ... (yield (let () . body*)) (values))))))])) (values (make-for/stream #'for/fold/derived) (make-for/stream #'for*/fold/derived))))
8ff76123efc8d154ab95570c3556f4d4958753f46b96c5005738b8b2c1aa24d1
sebashack/servantRestfulAPI
API.hs
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} # LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedStrings # {-# LANGUAGE ScopedTypeVariables #-} # LANGUAGE TypeFamilies # {-# LANGUAGE TypeOperators #-} # LANGUAGE UndecidableInstances # # LANGUAGE ScopedTypeVariables # module Domains.BookingDomain.Property.API ( PropertyAPI ) where import Domains.BookingDomain.Property.DataTypes import Servant.API import Codec.Picture.Types import Servant.JuicyPixels import qualified Data.Time as TM import qualified Data.Text as T type UserToken = T.Text type Name = T.Text type PropertyId = T.Text type PropType = T.Text type ImageId = T.Text type Description = T.Text type Facilities = [T.Text] type Rules = [T.Text] type ContactPhones = [T.Text] type ProfileName = T.Text type PropertyAPI = 1 -- "property" :> Capture "propertyId" PropertyId :> Get '[JSON] PropertyWithImgIds 2 -- :<|> "property" :> Header "Authorization" UserToken :> ReqBody '[JSON] BasicPropData :> PostCreated '[JSON] Property 3 -- :<|> "property" :> "location" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Region :> Put '[JSON] () 4 -- :<|> "property" :> "name" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Name :> Put '[JSON] () 5 -- :<|> "property" :> "type" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] PropType :> Put '[JSON] () 6 -- :<|> "property" :> "descriptionES" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Description :> Put '[JSON] () 7 -- :<|> "property" :> "descriptionEN" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Description :> Put '[JSON] () 8 -- :<|> "property" :> "facilities" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Facilities :> Put '[JSON] () 9 -- :<|> "property" :> "rules" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Rules :> Put '[JSON] () 10 -- :<|> "property" :> "contactPhones" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] ContactPhones :> Put '[JSON] () 11 -- :<|> "property" :> "mainImg" :> Capture "propertyId" PropertyId :> Capture "imgId" ImageId :> Header "Authorization" UserToken :> Put '[JSON] () 12 -- :<|> "property" :> "postImg" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JPEG 100] DynamicImage :> PostCreated '[JSON] ImageId 13 -- :<|> "property" :> "deleteImg" :> Capture "propertyId" PropertyId :> Capture "imgId" ImageId :> Header "Authorization" UserToken :> Delete '[JSON] () 14 -- :<|> "property" :> "imageIds" :> Capture "propertyId" PropertyId :> Get '[JSON] [ImageId] 15 -- :<|> "properties" :> QueryParam "from" Int :> QueryParam "size" Int :> Get '[JSON] [Property] 16 -- :<|> "properties" :> "admin" :> Header "Authorization" UserToken :> Get '[JSON] [Property] 17 -- :<|> "properties" :> "search" :> Capture "countryCode" T.Text :> QueryParam "queryString" T.Text :> QueryParam "from" Int :> QueryParam "size" Int :> Get '[JSON] [Property]
null
https://raw.githubusercontent.com/sebashack/servantRestfulAPI/e625535d196acefaff4f5bf03108816be668fe4d/libs/Domains/BookingDomain/Property/API.hs
haskell
# LANGUAGE DataKinds # # LANGUAGE DeriveGeneric # # LANGUAGE FlexibleContexts # # LANGUAGE ScopedTypeVariables # # LANGUAGE TypeOperators #
# LANGUAGE FlexibleInstances # # LANGUAGE MultiParamTypeClasses # # LANGUAGE OverloadedStrings # # LANGUAGE TypeFamilies # # LANGUAGE UndecidableInstances # # LANGUAGE ScopedTypeVariables # module Domains.BookingDomain.Property.API ( PropertyAPI ) where import Domains.BookingDomain.Property.DataTypes import Servant.API import Codec.Picture.Types import Servant.JuicyPixels import qualified Data.Time as TM import qualified Data.Text as T type UserToken = T.Text type Name = T.Text type PropertyId = T.Text type PropType = T.Text type ImageId = T.Text type Description = T.Text type Facilities = [T.Text] type Rules = [T.Text] type ContactPhones = [T.Text] type ProfileName = T.Text type PropertyAPI = "property" :> Capture "propertyId" PropertyId :> Get '[JSON] PropertyWithImgIds :<|> "property" :> Header "Authorization" UserToken :> ReqBody '[JSON] BasicPropData :> PostCreated '[JSON] Property :<|> "property" :> "location" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Region :> Put '[JSON] () :<|> "property" :> "name" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Name :> Put '[JSON] () :<|> "property" :> "type" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] PropType :> Put '[JSON] () :<|> "property" :> "descriptionES" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Description :> Put '[JSON] () :<|> "property" :> "descriptionEN" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Description :> Put '[JSON] () :<|> "property" :> "facilities" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Facilities :> Put '[JSON] () :<|> "property" :> "rules" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] Rules :> Put '[JSON] () :<|> "property" :> "contactPhones" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JSON] ContactPhones :> Put '[JSON] () :<|> "property" :> "mainImg" :> Capture "propertyId" PropertyId :> Capture "imgId" ImageId :> Header "Authorization" UserToken :> Put '[JSON] () :<|> "property" :> "postImg" :> Capture "propertyId" PropertyId :> Header "Authorization" UserToken :> ReqBody '[JPEG 100] DynamicImage :> PostCreated '[JSON] ImageId :<|> "property" :> "deleteImg" :> Capture "propertyId" PropertyId :> Capture "imgId" ImageId :> Header "Authorization" UserToken :> Delete '[JSON] () :<|> "property" :> "imageIds" :> Capture "propertyId" PropertyId :> Get '[JSON] [ImageId] :<|> "properties" :> QueryParam "from" Int :> QueryParam "size" Int :> Get '[JSON] [Property] :<|> "properties" :> "admin" :> Header "Authorization" UserToken :> Get '[JSON] [Property] :<|> "properties" :> "search" :> Capture "countryCode" T.Text :> QueryParam "queryString" T.Text :> QueryParam "from" Int :> QueryParam "size" Int :> Get '[JSON] [Property]
eff91b80a720f64a248efc44fda42e9892582161a12c20f186eabf13154c726d
weldr/bdcs
DepsolveSpec.hs
Copyright ( C ) 2017 Red Hat , Inc. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, see </>. module BDCS.DepsolveSpec(spec) where import Control.Monad.Except(runExceptT) import qualified Data.Map as Map import qualified Data.Set as Set import Test.Hspec import BDCS.Depsolve # ANN module ( " HLint : ignore Reduce duplication " : : String ) # spec :: Spec spec = do describe "BDCS.Depsolve.formulaToCNF tests" $ do it "atom" $ formulaToCNF (Atom '1') `shouldBe` [[CNFAtom (CNFOriginal '1')]] it "not" $ formulaToCNF (Not '1') `shouldBe` [[CNFNot (CNFOriginal '1')]] it "and" $ formulaToCNF (And [Atom '1', Atom '2', Atom '3', Atom '4']) `shouldBe` [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '2')], [CNFAtom (CNFOriginal '3')], [CNFAtom (CNFOriginal '4')]] it "Or 0 items" $ formulaToCNF (Or [] :: Formula ()) `shouldBe` ([[]] :: CNFFormula ()) it "Or 1 item" $ formulaToCNF (Or [Atom '1']) `shouldBe` [[CNFAtom (CNFOriginal '1')]] See the comment in formulaToCNF for more detail . In short , for 1 OR 2 OR 3 : start with ( 1 ) OR ( 2 OR 3 ) = = > ( sub 0 - > 1 ) AND ( NOT(sub 0 ) - > ( 2 OR 3 ) ) the left half becomes ( NOT(sub0 ) OR 1 ) , which is the first part of the result the right half becomes ( sub0 OR ( 2 OR 3 ) ) recurse on ( 2 OR 3 ) , adding sub0 to the front of each result it "Or 2 items" $ formulaToCNF (Or [Atom '1', Atom '2']) `shouldBe` [[CNFNot (CNFSubstitute 0), CNFAtom (CNFOriginal '1')], [CNFAtom (CNFSubstitute 0), CNFAtom (CNFOriginal '2')]] it "Or 3 items" $ formulaToCNF (Or [Atom '1', Atom '2', Atom '3']) `shouldBe` [[CNFNot (CNFSubstitute 0), CNFAtom (CNFOriginal '1')], [CNFAtom (CNFSubstitute 0), CNFNot (CNFSubstitute 1), CNFAtom (CNFOriginal '2')], [CNFAtom (CNFSubstitute 0), CNFAtom (CNFSubstitute 1), CNFAtom (CNFOriginal '3')]] describe "BDCS.Depsolve.pureLiteralEliminate tests" $ do it "pureLiteralEliminate, empty list" $ pureLiteralEliminate Set.empty Map.empty ([] :: CNFFormula Char) `shouldBe` Map.empty it "already assigned, matches" $ do let assignments = Map.singleton (CNFOriginal '1') True let formula = [[CNFAtom (CNFOriginal '1')]] let solution = assignments pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "already assigned, does not match" $ do let assignments = Map.singleton (CNFOriginal '1') True let formula = [[CNFNot (CNFOriginal '1')]] let solution = Map.empty pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "pureLiteralEliminate, pure, appears once" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')]] let solution = Map.singleton (CNFOriginal '1') True pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "pure, appears once negative" $ do let assignments = Map.empty let formula = [[CNFNot (CNFOriginal '1')]] let solution = Map.singleton (CNFOriginal '1') False pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "pure, appears multiple times" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '1'), CNFAtom (CNFOriginal '2')], [CNFNot (CNFOriginal '2')]] let solution = Map.singleton (CNFOriginal '1') True pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "pure, appears multiple times negative" $ do let assignments = Map.empty let formula = [[CNFNot (CNFOriginal '1')], [CNFNot (CNFOriginal '1'), CNFAtom (CNFOriginal '2')], [CNFNot (CNFOriginal '2')]] let solution = Map.singleton (CNFOriginal '1') False pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "unpure" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFNot (CNFOriginal '1')]] let solution = Map.empty pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "unpure 2" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1'), CNFNot (CNFOriginal '1')], [CNFNot (CNFOriginal '1')]] let solution = Map.empty pureLiteralEliminate Set.empty assignments formula `shouldBe` solution describe "BDCS.Depsolve.unitPropagate tests" $ do it "empty list" $ runExceptT (unitPropagate Map.empty ([] :: CNFFormula Char)) >>= (`shouldBe` Right (Map.empty, [])) it "one thing" $ runExceptT (unitPropagate Map.empty [[CNFAtom (CNFOriginal '1')]]) >>= (`shouldBe` Right (Map.singleton (CNFOriginal '1') True, [])) it "unit then elimate clause" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '1'), CNFNot (CNFOriginal '2')]] let assignments' = Map.singleton (CNFOriginal '1') True let formula' = [] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Right (assignments', formula')) it "unit then elimate impossible" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '2'), CNFNot (CNFOriginal '1')]] let assignments' = Map.singleton (CNFOriginal '1') True let formula' = [[CNFAtom (CNFOriginal '2')]] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Right (assignments', formula')) it "unit then repeated" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '1')]] let assignments' = Map.singleton (CNFOriginal '1') True let formula' = [] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Right (assignments', formula')) it "unit then unsolvable unit" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFNot (CNFOriginal '1')]] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Left "Unable to solve expression") it "units then unsolvable clause" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '2')], [CNFNot (CNFOriginal '1'), CNFNot (CNFOriginal '2')]] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Left "Unable to solve expression") describe "BDCS.Depsolve.solveCNF tests" $ do it "empty formula" $ do let formula = [] :: (CNFFormula Char) let solution = [] :: [DepAssignment Char] runExceptT (solveCNF formula) >>= (`shouldBe` Right solution) it "singleton" $ do let formula = [[CNFAtom (CNFOriginal '1')]] let solution = [('1', True)] runExceptT (solveCNF formula) >>= (`shouldBe` Right solution)
null
https://raw.githubusercontent.com/weldr/bdcs/cf360c3240644b4847336b9d58b2067f3aa1ec50/src/tests/BDCS/DepsolveSpec.hs
haskell
This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. License along with this library; if not, see </>.
Copyright ( C ) 2017 Red Hat , Inc. License as published by the Free Software Foundation ; either version 2.1 of the License , or ( at your option ) any later version . You should have received a copy of the GNU Lesser General Public module BDCS.DepsolveSpec(spec) where import Control.Monad.Except(runExceptT) import qualified Data.Map as Map import qualified Data.Set as Set import Test.Hspec import BDCS.Depsolve # ANN module ( " HLint : ignore Reduce duplication " : : String ) # spec :: Spec spec = do describe "BDCS.Depsolve.formulaToCNF tests" $ do it "atom" $ formulaToCNF (Atom '1') `shouldBe` [[CNFAtom (CNFOriginal '1')]] it "not" $ formulaToCNF (Not '1') `shouldBe` [[CNFNot (CNFOriginal '1')]] it "and" $ formulaToCNF (And [Atom '1', Atom '2', Atom '3', Atom '4']) `shouldBe` [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '2')], [CNFAtom (CNFOriginal '3')], [CNFAtom (CNFOriginal '4')]] it "Or 0 items" $ formulaToCNF (Or [] :: Formula ()) `shouldBe` ([[]] :: CNFFormula ()) it "Or 1 item" $ formulaToCNF (Or [Atom '1']) `shouldBe` [[CNFAtom (CNFOriginal '1')]] See the comment in formulaToCNF for more detail . In short , for 1 OR 2 OR 3 : start with ( 1 ) OR ( 2 OR 3 ) = = > ( sub 0 - > 1 ) AND ( NOT(sub 0 ) - > ( 2 OR 3 ) ) the left half becomes ( NOT(sub0 ) OR 1 ) , which is the first part of the result the right half becomes ( sub0 OR ( 2 OR 3 ) ) recurse on ( 2 OR 3 ) , adding sub0 to the front of each result it "Or 2 items" $ formulaToCNF (Or [Atom '1', Atom '2']) `shouldBe` [[CNFNot (CNFSubstitute 0), CNFAtom (CNFOriginal '1')], [CNFAtom (CNFSubstitute 0), CNFAtom (CNFOriginal '2')]] it "Or 3 items" $ formulaToCNF (Or [Atom '1', Atom '2', Atom '3']) `shouldBe` [[CNFNot (CNFSubstitute 0), CNFAtom (CNFOriginal '1')], [CNFAtom (CNFSubstitute 0), CNFNot (CNFSubstitute 1), CNFAtom (CNFOriginal '2')], [CNFAtom (CNFSubstitute 0), CNFAtom (CNFSubstitute 1), CNFAtom (CNFOriginal '3')]] describe "BDCS.Depsolve.pureLiteralEliminate tests" $ do it "pureLiteralEliminate, empty list" $ pureLiteralEliminate Set.empty Map.empty ([] :: CNFFormula Char) `shouldBe` Map.empty it "already assigned, matches" $ do let assignments = Map.singleton (CNFOriginal '1') True let formula = [[CNFAtom (CNFOriginal '1')]] let solution = assignments pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "already assigned, does not match" $ do let assignments = Map.singleton (CNFOriginal '1') True let formula = [[CNFNot (CNFOriginal '1')]] let solution = Map.empty pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "pureLiteralEliminate, pure, appears once" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')]] let solution = Map.singleton (CNFOriginal '1') True pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "pure, appears once negative" $ do let assignments = Map.empty let formula = [[CNFNot (CNFOriginal '1')]] let solution = Map.singleton (CNFOriginal '1') False pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "pure, appears multiple times" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '1'), CNFAtom (CNFOriginal '2')], [CNFNot (CNFOriginal '2')]] let solution = Map.singleton (CNFOriginal '1') True pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "pure, appears multiple times negative" $ do let assignments = Map.empty let formula = [[CNFNot (CNFOriginal '1')], [CNFNot (CNFOriginal '1'), CNFAtom (CNFOriginal '2')], [CNFNot (CNFOriginal '2')]] let solution = Map.singleton (CNFOriginal '1') False pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "unpure" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFNot (CNFOriginal '1')]] let solution = Map.empty pureLiteralEliminate Set.empty assignments formula `shouldBe` solution it "unpure 2" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1'), CNFNot (CNFOriginal '1')], [CNFNot (CNFOriginal '1')]] let solution = Map.empty pureLiteralEliminate Set.empty assignments formula `shouldBe` solution describe "BDCS.Depsolve.unitPropagate tests" $ do it "empty list" $ runExceptT (unitPropagate Map.empty ([] :: CNFFormula Char)) >>= (`shouldBe` Right (Map.empty, [])) it "one thing" $ runExceptT (unitPropagate Map.empty [[CNFAtom (CNFOriginal '1')]]) >>= (`shouldBe` Right (Map.singleton (CNFOriginal '1') True, [])) it "unit then elimate clause" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '1'), CNFNot (CNFOriginal '2')]] let assignments' = Map.singleton (CNFOriginal '1') True let formula' = [] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Right (assignments', formula')) it "unit then elimate impossible" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '2'), CNFNot (CNFOriginal '1')]] let assignments' = Map.singleton (CNFOriginal '1') True let formula' = [[CNFAtom (CNFOriginal '2')]] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Right (assignments', formula')) it "unit then repeated" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '1')]] let assignments' = Map.singleton (CNFOriginal '1') True let formula' = [] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Right (assignments', formula')) it "unit then unsolvable unit" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFNot (CNFOriginal '1')]] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Left "Unable to solve expression") it "units then unsolvable clause" $ do let assignments = Map.empty let formula = [[CNFAtom (CNFOriginal '1')], [CNFAtom (CNFOriginal '2')], [CNFNot (CNFOriginal '1'), CNFNot (CNFOriginal '2')]] runExceptT (unitPropagate assignments formula) >>= (`shouldBe` Left "Unable to solve expression") describe "BDCS.Depsolve.solveCNF tests" $ do it "empty formula" $ do let formula = [] :: (CNFFormula Char) let solution = [] :: [DepAssignment Char] runExceptT (solveCNF formula) >>= (`shouldBe` Right solution) it "singleton" $ do let formula = [[CNFAtom (CNFOriginal '1')]] let solution = [('1', True)] runExceptT (solveCNF formula) >>= (`shouldBe` Right solution)
c1a468be1c50603a99b9c9896a1f5b9be3b3cc8bdc6ca4c8026256598c6a8a92
bsansouci/bsb-native
exec.mli
(***********************************************************************) (* *) (* OCaml *) (* *) , projet Cristal , INRIA Rocquencourt OCaml port by and (* *) Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . (* *) (***********************************************************************) (* Handling of keyboard interrupts *) val protect : (unit -> unit) -> unit val unprotect : (unit -> unit) -> unit
null
https://raw.githubusercontent.com/bsansouci/bsb-native/9a89457783d6e80deb0fba9ca7372c10a768a9ea/vendor/ocaml/debugger/exec.mli
ocaml
********************************************************************* OCaml ********************************************************************* Handling of keyboard interrupts
, projet Cristal , INRIA Rocquencourt OCaml port by and Copyright 1996 Institut National de Recherche en Informatique et en Automatique . All rights reserved . This file is distributed under the terms of the Q Public License version 1.0 . val protect : (unit -> unit) -> unit val unprotect : (unit -> unit) -> unit
3eb313c78070f6365e21ce28717356c857dd53b9c5970eb45672dc74a7a0f365
snewman/lein-gentags
core.clj
(ns update-tags.test.core (:use [update-tags.core]) (:use [clojure.test])) (deftest replace-me ;; FIXME: write (is false "No tests have been written."))
null
https://raw.githubusercontent.com/snewman/lein-gentags/8514012ac0b5eab8bc8befce15ee0db3680d7a8f/test/update_tags/test/core.clj
clojure
FIXME: write
(ns update-tags.test.core (:use [update-tags.core]) (:use [clojure.test])) (is false "No tests have been written."))
a826b68dc747af4ed128a59cdf3805ca13961244724928980ce01c8826040ae7
clojure-interop/java-jdk
XPathConstants.clj
(ns javax.xml.xpath.XPathConstants "XPath constants." (:refer-clojure :only [require comment defn ->]) (:import [javax.xml.xpath XPathConstants])) (def *-number "Static Constant. The XPath 1.0 number data type. Maps to Java Double. type: javax.xml.namespace.QName" XPathConstants/NUMBER) (def *-string "Static Constant. The XPath 1.0 string data type. Maps to Java String. type: javax.xml.namespace.QName" XPathConstants/STRING) (def *-boolean "Static Constant. The XPath 1.0 boolean data type. Maps to Java Boolean. type: javax.xml.namespace.QName" XPathConstants/BOOLEAN) (def *-nodeset "Static Constant. The XPath 1.0 NodeSet data type. Maps to Java NodeList. type: javax.xml.namespace.QName" XPathConstants/NODESET) (def *-node "Static Constant. The XPath 1.0 NodeSet data type. Maps to Java Node. type: javax.xml.namespace.QName" XPathConstants/NODE) (def *-dom-object-model "Static Constant. The URI for the DOM object model, \"\". type: java.lang.String" XPathConstants/DOM_OBJECT_MODEL)
null
https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.xml/src/javax/xml/xpath/XPathConstants.clj
clojure
(ns javax.xml.xpath.XPathConstants "XPath constants." (:refer-clojure :only [require comment defn ->]) (:import [javax.xml.xpath XPathConstants])) (def *-number "Static Constant. The XPath 1.0 number data type. Maps to Java Double. type: javax.xml.namespace.QName" XPathConstants/NUMBER) (def *-string "Static Constant. The XPath 1.0 string data type. Maps to Java String. type: javax.xml.namespace.QName" XPathConstants/STRING) (def *-boolean "Static Constant. The XPath 1.0 boolean data type. Maps to Java Boolean. type: javax.xml.namespace.QName" XPathConstants/BOOLEAN) (def *-nodeset "Static Constant. The XPath 1.0 NodeSet data type. Maps to Java NodeList. type: javax.xml.namespace.QName" XPathConstants/NODESET) (def *-node "Static Constant. The XPath 1.0 NodeSet data type. Maps to Java Node. type: javax.xml.namespace.QName" XPathConstants/NODE) (def *-dom-object-model "Static Constant. The URI for the DOM object model, \"\". type: java.lang.String" XPathConstants/DOM_OBJECT_MODEL)
3422ed2a8df23920dc12bbd5d78abc5cc4b5ed9ee374933b5e83df2132bdb978
SimulaVR/godot-haskell
CheckButton.hs
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.CheckButton () where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Button()
null
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/CheckButton.hs
haskell
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving , TypeFamilies , TypeOperators , FlexibleContexts , DataKinds , MultiParamTypeClasses # TypeFamilies, TypeOperators, FlexibleContexts, DataKinds, MultiParamTypeClasses #-} module Godot.Core.CheckButton () where import Data.Coerce import Foreign.C import Godot.Internal.Dispatch import qualified Data.Vector as V import Linear(V2(..),V3(..),M22) import Data.Colour(withOpacity) import Data.Colour.SRGB(sRGB) import System.IO.Unsafe import Godot.Gdnative.Internal import Godot.Api.Types import Godot.Core.Button()
3022f91d7e9eef85bbbd10142c959f243eb80b124df0e3a83c5bd08d7fb4ef0d
jordwalke/rehp
mutable_closure.ml
Js_of_ocaml compiler * / * Copyright ( C ) 2017 Hugo Heuzard * Copyright ( C ) 2019 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2017 Hugo Heuzard * Copyright (C) 2019 Ty Overby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) let%expect_test _ = Util.compile_and_run {| let log_success () = print_endline "Success!" let log_failure = Printf.printf "Failure! %s" let direct = ref [] let indirect = ref [] let () = for i = 0 to 3 do let rec f = function | 0 -> i | -1 -> g (-2) (* deadcode or infinite loop *) | n -> g (pred n) and g = function | 0 -> i | -1 -> f (-2) (* deadcode or infinite loop *) | n -> f (pred n) in direct := f i :: !direct; indirect := (fun () -> f i) :: !indirect done; let indirect = List.map (fun f -> f ()) !indirect in let direct = !direct in assert (indirect = direct) let () = let delayed = ref (fun () -> ()) in for i = 1 to 2 do let rec f n = function | 0 -> assert (i = n) | j -> delayed := let prev = !delayed in fun () -> prev (); f (succ n + i - i) (pred j) in f 0 i done; !delayed () let _ = let l_fun = ref [] in let l_var = ref [] in let l_base = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10] in for i = 0 to 10 do l_fun := (fun () -> i) :: !l_fun; l_var := i :: !l_var done; let sum l = List.fold_left ( + ) 0 l in let sum_base = sum l_base in if sum !l_var <> sum_base then log_failure "l_var" else if sum (List.map (fun f -> f ()) !l_fun) <> sum_base then log_failure "l_fun" else log_success () |}; [%expect "Success!"]
null
https://raw.githubusercontent.com/jordwalke/rehp/f122b94f0a3f06410ddba59e3c9c603b33aadabf/compiler/tests/mutable_closure.ml
ocaml
deadcode or infinite loop deadcode or infinite loop
Js_of_ocaml compiler * / * Copyright ( C ) 2017 Hugo Heuzard * Copyright ( C ) 2019 * * This program is free software ; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation , with linking exception ; * either version 2.1 of the License , or ( at your option ) any later version . * * This program is distributed in the hope that it will be useful , * but WITHOUT ANY WARRANTY ; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the * GNU Lesser General Public License for more details . * * You should have received a copy of the GNU Lesser General Public License * along with this program ; if not , write to the Free Software * Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA . * / * Copyright (C) 2017 Hugo Heuzard * Copyright (C) 2019 Ty Overby * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, with linking exception; * either version 2.1 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *) let%expect_test _ = Util.compile_and_run {| let log_success () = print_endline "Success!" let log_failure = Printf.printf "Failure! %s" let direct = ref [] let indirect = ref [] let () = for i = 0 to 3 do let rec f = function | 0 -> i | n -> g (pred n) and g = function | 0 -> i | n -> f (pred n) in direct := f i :: !direct; indirect := (fun () -> f i) :: !indirect done; let indirect = List.map (fun f -> f ()) !indirect in let direct = !direct in assert (indirect = direct) let () = let delayed = ref (fun () -> ()) in for i = 1 to 2 do let rec f n = function | 0 -> assert (i = n) | j -> delayed := let prev = !delayed in fun () -> prev (); f (succ n + i - i) (pred j) in f 0 i done; !delayed () let _ = let l_fun = ref [] in let l_var = ref [] in let l_base = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10] in for i = 0 to 10 do l_fun := (fun () -> i) :: !l_fun; l_var := i :: !l_var done; let sum l = List.fold_left ( + ) 0 l in let sum_base = sum l_base in if sum !l_var <> sum_base then log_failure "l_var" else if sum (List.map (fun f -> f ()) !l_fun) <> sum_base then log_failure "l_fun" else log_success () |}; [%expect "Success!"]
bb9a7fed0162c06147b6d4f81c1de5e48de81c07ba6578f3f8a95efe011a6856
AHartNtkn/SICAM
Setup.hs
import Prelude import Distribution.Extra.Doctest (defaultMainWithDoctests) main :: IO () main = defaultMainWithDoctests "doctests"
null
https://raw.githubusercontent.com/AHartNtkn/SICAM/126d8eb90452af9f535c838fa953be05a9ddf282/clash%20files/Setup.hs
haskell
import Prelude import Distribution.Extra.Doctest (defaultMainWithDoctests) main :: IO () main = defaultMainWithDoctests "doctests"
63d0e57c439893d968aa0a77cac390f9d94041f5ca360ca8da72e14e79378dc0
VisionsGlobalEmpowerment/webchange
icon_caret_right.cljs
(ns webchange.ui.components.icon.system.icon-caret-right) (def data [:svg {:xmlns "" :width "24" :height "24" :viewBox "0 0 24 24" :class-name "stroke-colored" :fill "none" :stroke "#3453A1" :stroke-width "2" :stroke-linecap "round" :stroke-linejoin "round"} [:g {:clip-path "url(#clip0_1179_94879)"} [:path {:d "M10 7L15 12L10 17"}]] [:defs [:clipPath#clip0_1179_94879 [:rect {:width "24" :height "24" :fill "white"}]]]])
null
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/e5747e187937d85e9c92c728d52a704f323f00ef/src/cljs/webchange/ui/components/icon/system/icon_caret_right.cljs
clojure
(ns webchange.ui.components.icon.system.icon-caret-right) (def data [:svg {:xmlns "" :width "24" :height "24" :viewBox "0 0 24 24" :class-name "stroke-colored" :fill "none" :stroke "#3453A1" :stroke-width "2" :stroke-linecap "round" :stroke-linejoin "round"} [:g {:clip-path "url(#clip0_1179_94879)"} [:path {:d "M10 7L15 12L10 17"}]] [:defs [:clipPath#clip0_1179_94879 [:rect {:width "24" :height "24" :fill "white"}]]]])
a4f60ceef5a3fc8bfe72e806f3957954f9d88310ffe86d7304bfe383f0fea9b6
hstreamdb/hstreamdb_erl
hstreamdb_SUITE.erl
-module(hstreamdb_SUITE). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -define(DAY, (24 * 60 * 60)). all() -> hstreamdb_test_helpers:test_cases(?MODULE). init_per_suite(Config) -> _ = application:ensure_all_started(hstreamdb_erl), Client = hstreamdb_test_helpers:client(test_c), [{client, Client} | Config]. end_per_suite(Config) -> Client = ?config(client, Config), _ = hstreamdb:stop_client(Client), _ = application:stop(hstreamdb_erl), ok. t_stop_client_by_name(_Config) -> _ = hstreamdb_test_helpers:client(test_c1), ?assertEqual( ok, hstreamdb:stop_client(test_c1)). t_start_client_error(_Config) -> ClientOptions = hstreamdb_test_helpers:default_options(), ?assertMatch( {error, _}, hstreamdb:start_client(test_c2, lists:keyreplace(url, 1, ClientOptions, {url, "#badurl#"}))), ?assertMatch( {error, _}, hstreamdb:start_client(test_c2, lists:keyreplace(url, 1, ClientOptions, {url, "http://#badurl#"}))). t_echo(Config) -> Client = ?config(client, Config), ?assertEqual( {ok, echo}, hstreamdb:echo(Client)). t_create_delete_stream(Config) -> Client = ?config(client, Config), _ = hstreamdb:delete_stream(Client, "stream1"), ?assertEqual( ok, hstreamdb:create_stream(Client, "stream1", 2, ?DAY, 5)), ?assertMatch( {error, {already_exists, _}}, hstreamdb:create_stream(Client, "stream1", 2, ?DAY, 5)), _ = hstreamdb:delete_stream(Client, "stream1"), ?assertEqual( ok, hstreamdb:create_stream(Client, "stream1", 2, ?DAY, 5)), _ = hstreamdb:delete_stream(Client, "stream1"). t_start_stop_producer(Config) -> Client = ?config(client, Config), _ = hstreamdb:create_stream(Client, "stream2", 2, ?DAY, 5), ProducerOptions = [ {pool_size, 4}, {stream, "stream2"}, {callback, fun(_) -> ok end}, {max_records, 1000}, {interval, 1000} ], {ok, Producer} = hstreamdb:start_producer(Client, test_producer, ProducerOptions), ?assertEqual( ok, hstreamdb:stop_producer(Producer)), ok = hstreamdb:delete_stream(Client, "stream2"). no op t_start_stop_consumer(Config) -> Client = ?config(client, Config), {ok, Consumer} = hstreamdb:start_consumer(Client, test_consumer, []), ?assertEqual( ok, hstreamdb:stop_consumer(Consumer)).
null
https://raw.githubusercontent.com/hstreamdb/hstreamdb_erl/7ba26bbcde321930052b5fdff724b187edcd1c8a/test/hstreamdb_SUITE.erl
erlang
-module(hstreamdb_SUITE). -compile(export_all). -compile(nowarn_export_all). -include_lib("eunit/include/eunit.hrl"). -include_lib("common_test/include/ct.hrl"). -define(DAY, (24 * 60 * 60)). all() -> hstreamdb_test_helpers:test_cases(?MODULE). init_per_suite(Config) -> _ = application:ensure_all_started(hstreamdb_erl), Client = hstreamdb_test_helpers:client(test_c), [{client, Client} | Config]. end_per_suite(Config) -> Client = ?config(client, Config), _ = hstreamdb:stop_client(Client), _ = application:stop(hstreamdb_erl), ok. t_stop_client_by_name(_Config) -> _ = hstreamdb_test_helpers:client(test_c1), ?assertEqual( ok, hstreamdb:stop_client(test_c1)). t_start_client_error(_Config) -> ClientOptions = hstreamdb_test_helpers:default_options(), ?assertMatch( {error, _}, hstreamdb:start_client(test_c2, lists:keyreplace(url, 1, ClientOptions, {url, "#badurl#"}))), ?assertMatch( {error, _}, hstreamdb:start_client(test_c2, lists:keyreplace(url, 1, ClientOptions, {url, "http://#badurl#"}))). t_echo(Config) -> Client = ?config(client, Config), ?assertEqual( {ok, echo}, hstreamdb:echo(Client)). t_create_delete_stream(Config) -> Client = ?config(client, Config), _ = hstreamdb:delete_stream(Client, "stream1"), ?assertEqual( ok, hstreamdb:create_stream(Client, "stream1", 2, ?DAY, 5)), ?assertMatch( {error, {already_exists, _}}, hstreamdb:create_stream(Client, "stream1", 2, ?DAY, 5)), _ = hstreamdb:delete_stream(Client, "stream1"), ?assertEqual( ok, hstreamdb:create_stream(Client, "stream1", 2, ?DAY, 5)), _ = hstreamdb:delete_stream(Client, "stream1"). t_start_stop_producer(Config) -> Client = ?config(client, Config), _ = hstreamdb:create_stream(Client, "stream2", 2, ?DAY, 5), ProducerOptions = [ {pool_size, 4}, {stream, "stream2"}, {callback, fun(_) -> ok end}, {max_records, 1000}, {interval, 1000} ], {ok, Producer} = hstreamdb:start_producer(Client, test_producer, ProducerOptions), ?assertEqual( ok, hstreamdb:stop_producer(Producer)), ok = hstreamdb:delete_stream(Client, "stream2"). no op t_start_stop_consumer(Config) -> Client = ?config(client, Config), {ok, Consumer} = hstreamdb:start_consumer(Client, test_consumer, []), ?assertEqual( ok, hstreamdb:stop_consumer(Consumer)).