_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 |
|---|---|---|---|---|---|---|---|---|
b44f8990dee6a65619c1500ba5ff7b965f7b0799c99fba8794661f3634a7f65a | ejlilley/AbstractMusic | Examples.hs | module Examples where
import Music (Name(..), Accidental(..), Scale(..), Tuning(..), Timing(..), Metronome(..),
AbstractInt1(..), AbstractPitch1(..), AbstractDur1(..),
AbstractInt2(..), AbstractPitch2(..), AbstractDur2(..),
AbstractInt3(..), AbstractPitch3(..), AbstractDur3(..),
Name(..), Number(..), Accidental(..), Quality(..),
Pitch(..), Interval(..),
Transpose(..),
AbstractNote(..), Note1, Note2, Note3,
AbstractPhrase(..),
Degree(..), Ficta(..), noteToSound,
apPitch, chord,
mapPhrase, absolute, normalise, faInt, faPitch, Music(..), mapMusic)
import Tuning
import FiveLimit (JustTuning(..), JustPitch(..), JustInt(..), ForceJustTuning(..))
import Scales (minor, major, HarmonicMinor(..), Minor, Major,
harmonicminor, infiniteScale, chromaticScale)
import Util (allPairs, interleave)
import Shortcuts
import LilyPrint
import Output
-- example notes:
fsharp = pitch F (Sh Na)
gsharp = pitch G (Sh Na)
gsharp' = pitch (Up G) (Sh Na)
n1 :: Note2
n1 = AbstractPitch fsharp quaver
n2 :: Note2
n2 = AbstractInt d5 quaver
n3 :: Note2
n3 = Rest quaver
somefreq = AbstractPitch3 4.52
somelength = AbstractDur3 4.56
n4 :: Note3
n4 = AbstractPitch somefreq somelength
-- example scales:
cmajor = major (pitch C Na)
bflatmajor = major (pitch B (Fl Na))
dminor = minor (pitch D Na)
csharpminor = minor (pitch C (Sh Na))
dsharpminor = harmonicminor (pitch D (Sh Na))
longquavercmajscale = phrase $ zipWith note (take 22 $ infiniteScale cmajor) (repeat quaver)
play_longquavercmajscale = playCsound $ mapPhrase (noteToSound et me) longquavercmajscale
-- example tuning systems:
p = pythagorean (pitch A Na, AbstractPitch3 440.0)
et = equal (pitch A Na, AbstractPitch3 440.0)
qc = qcmeantone (pitch A Na, AbstractPitch3 440.0)
me = Metronome 240
-- tuning some scales:
frequencies = map (tune et) (scale cmajor)
frequencies' = map (tune qc) (scale csharpminor)
-- Construct a tune from scale degrees ( this is pretty unwieldy )
notes = [AbstractPitch1 TO Neutral,
AbstractPitch1 DO Neutral,
AbstractPitch1 ME Neutral,
AbstractPitch1 TO Neutral,
AbstractPitch1 (DDown LN) Neutral,
AbstractPitch1 TO Neutral,
AbstractPitch1 ST Neutral,
AbstractPitch1 ME Neutral,
AbstractPitch1 SD Neutral,
AbstractPitch1 ME Neutral,
AbstractPitch1 ST Neutral,
AbstractPitch1 TO Neutral]
durs = [minim, minim, minim, minim, minim, crotchet, crotchet, tie minim quaver, quaver, quaver, quaver, crotchet]
notes1 = AbstractPhrase $ zipWith AbstractPitch (map (applyScale cmajor) notes) durs
notes2 = AbstractPhrase $ zipWith AbstractPitch (map (applyScale (harmonicminor (pitch D Na))) notes) durs
---- Some simple polyphony
cnotes1 = [g, a, b, c, c, c, b, c]
cnotes2 = [e, f, d, e, d, e, d, e]
cnotes3 = map (.-^ _P8) [c, f, gis, a, fis, g, g, c]
chords = Voices $ map (\p -> phrase $ zipWith note p (repeat minim)) [cnotes1, cnotes2, cnotes3]
note the arguments to noteToSound : ' et ' is a tuning system , ' me ' is a timing .
chordsounds = mapMusic (mapPhrase (noteToSound et me)) chords
-- and now to hear it through your speakers
playchordsounds = playCsounds chordsounds
----------------
pos = [0..]
neg = map (*(-1)) [1..]
ints = interleave pos neg
pairs = allPairs ints ints
intervals = map (\(a,d) -> a *^ _A1 ^+^ d *^ d2) pairs
| null | https://raw.githubusercontent.com/ejlilley/AbstractMusic/815ab33ee204dd3ebf29076bde330bfdf6938677/Examples.hs | haskell | example notes:
example scales:
example tuning systems:
tuning some scales:
Construct a tune from scale degrees ( this is pretty unwieldy )
-- Some simple polyphony
and now to hear it through your speakers
-------------- | module Examples where
import Music (Name(..), Accidental(..), Scale(..), Tuning(..), Timing(..), Metronome(..),
AbstractInt1(..), AbstractPitch1(..), AbstractDur1(..),
AbstractInt2(..), AbstractPitch2(..), AbstractDur2(..),
AbstractInt3(..), AbstractPitch3(..), AbstractDur3(..),
Name(..), Number(..), Accidental(..), Quality(..),
Pitch(..), Interval(..),
Transpose(..),
AbstractNote(..), Note1, Note2, Note3,
AbstractPhrase(..),
Degree(..), Ficta(..), noteToSound,
apPitch, chord,
mapPhrase, absolute, normalise, faInt, faPitch, Music(..), mapMusic)
import Tuning
import FiveLimit (JustTuning(..), JustPitch(..), JustInt(..), ForceJustTuning(..))
import Scales (minor, major, HarmonicMinor(..), Minor, Major,
harmonicminor, infiniteScale, chromaticScale)
import Util (allPairs, interleave)
import Shortcuts
import LilyPrint
import Output
fsharp = pitch F (Sh Na)
gsharp = pitch G (Sh Na)
gsharp' = pitch (Up G) (Sh Na)
n1 :: Note2
n1 = AbstractPitch fsharp quaver
n2 :: Note2
n2 = AbstractInt d5 quaver
n3 :: Note2
n3 = Rest quaver
somefreq = AbstractPitch3 4.52
somelength = AbstractDur3 4.56
n4 :: Note3
n4 = AbstractPitch somefreq somelength
cmajor = major (pitch C Na)
bflatmajor = major (pitch B (Fl Na))
dminor = minor (pitch D Na)
csharpminor = minor (pitch C (Sh Na))
dsharpminor = harmonicminor (pitch D (Sh Na))
longquavercmajscale = phrase $ zipWith note (take 22 $ infiniteScale cmajor) (repeat quaver)
play_longquavercmajscale = playCsound $ mapPhrase (noteToSound et me) longquavercmajscale
p = pythagorean (pitch A Na, AbstractPitch3 440.0)
et = equal (pitch A Na, AbstractPitch3 440.0)
qc = qcmeantone (pitch A Na, AbstractPitch3 440.0)
me = Metronome 240
frequencies = map (tune et) (scale cmajor)
frequencies' = map (tune qc) (scale csharpminor)
notes = [AbstractPitch1 TO Neutral,
AbstractPitch1 DO Neutral,
AbstractPitch1 ME Neutral,
AbstractPitch1 TO Neutral,
AbstractPitch1 (DDown LN) Neutral,
AbstractPitch1 TO Neutral,
AbstractPitch1 ST Neutral,
AbstractPitch1 ME Neutral,
AbstractPitch1 SD Neutral,
AbstractPitch1 ME Neutral,
AbstractPitch1 ST Neutral,
AbstractPitch1 TO Neutral]
durs = [minim, minim, minim, minim, minim, crotchet, crotchet, tie minim quaver, quaver, quaver, quaver, crotchet]
notes1 = AbstractPhrase $ zipWith AbstractPitch (map (applyScale cmajor) notes) durs
notes2 = AbstractPhrase $ zipWith AbstractPitch (map (applyScale (harmonicminor (pitch D Na))) notes) durs
cnotes1 = [g, a, b, c, c, c, b, c]
cnotes2 = [e, f, d, e, d, e, d, e]
cnotes3 = map (.-^ _P8) [c, f, gis, a, fis, g, g, c]
chords = Voices $ map (\p -> phrase $ zipWith note p (repeat minim)) [cnotes1, cnotes2, cnotes3]
note the arguments to noteToSound : ' et ' is a tuning system , ' me ' is a timing .
chordsounds = mapMusic (mapPhrase (noteToSound et me)) chords
playchordsounds = playCsounds chordsounds
pos = [0..]
neg = map (*(-1)) [1..]
ints = interleave pos neg
pairs = allPairs ints ints
intervals = map (\(a,d) -> a *^ _A1 ^+^ d *^ d2) pairs
|
98e4f736ff55ac63a17a3cef1048a509a8850a0701fa751fb4e6b2d9f2e803ae | arcfide/chez-srfi | tables-test.ikarus.sps | Copyright ( C ) 2015 . All Rights Reserved .
;;;
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without restriction ,
;;; including without limitation the rights to use, copy, modify, merge,
publish , distribute , sublicense , and/or sell copies of the Software ,
and to permit persons to whom the Software is furnished to do so ,
;;; subject to the following conditions:
;;;
;;; The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
;;;
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT .
;;; IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT ,
;;; TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
;;; SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
;;; This is a very shallow sanity test for hash tables.
;;;
;;; Tests marked by a "FIXME: glass-box" comment test behavior of the
;;; reference implementation that is not required by the specification.
(import (rnrs)
(srfi :128)
(srfi :125))
(define (writeln . xs)
(for-each write xs)
(newline))
(define (displayln . xs)
(for-each display xs)
(newline))
(define (exact-integer? x)
(and (integer? x) (exact? x)))
(define (bytevector . args)
(u8-list->bytevector args))
(define (fail token . more)
(displayln "Error: test failed: ")
(writeln token)
(if (not (null? more))
(for-each writeln more))
(newline)
#f)
(define (success token)
( " Test succeded : " )
( token )
#f)
;;; FIXME: when debugging catastrophic failures, printing every expression
;;; before it's executed may help.
(define-syntax test
(syntax-rules ()
((_ expr expected)
(let ()
;; (write 'expr) (newline)
(let ((actual expr))
(if (equal? actual expected)
(success 'expr)
(fail 'expr actual expected)))))))
(define-syntax test-assert
(syntax-rules ()
((_ expr)
(or expr (fail 'expr)))))
(define-syntax test-deny
(syntax-rules ()
((_ expr)
(or (not expr) (fail 'expr)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Transition from SRFI 114 to SRFI 128 .
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define default-comparator (make-default-comparator))
SRFI 128 says the following definition will work , but that 's
an error in SRFI 128 ; the hash function produce non - integers .
#;
(define number-comparator
(make-comparator real? = < (lambda (x) (exact (abs x)))))
(define number-comparator
(make-comparator real? = < (lambda (x) (exact (abs (round x))))))
(define string-comparator
(make-comparator string? string=? string<? string-hash))
(define string-ci-comparator
(make-comparator string? string-ci=? string-ci<? string-ci-hash))
(define eq-comparator (make-eq-comparator))
(define eqv-comparator (make-eqv-comparator))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Transition from earlier draft of SRFI 125 to this draft .
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Returns an immutable hash table.
(define (hash-table-tabulate comparator n proc)
(let ((ht (make-hash-table comparator)))
(do ((i 0 (+ i 1)))
((= i n)
(hash-table-copy ht))
(call-with-values
(lambda ()
(proc i))
(lambda (key val)
(hash-table-set! ht key val))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Constructors.
(define ht-default (make-hash-table default-comparator))
(define ht-eq (make-hash-table eq-comparator 'random-argument "another"))
(define ht-eqv (make-hash-table eqv-comparator))
(define ht-eq2 (make-hash-table eq?))
(define ht-eqv2 (make-hash-table eqv?))
(define ht-equal (make-hash-table default-comparator))
(define ht-string (make-hash-table string=?))
(define ht-string-ci (make-hash-table string-ci=?))
(define ht-symbol (make-hash-table symbol=?)) ; FIXME: glass-box
(define ht-fixnum (make-hash-table = abs))
(define ht-default2
(hash-table default-comparator 'foo 'bar 101.3 "fever" '(x y z) '#()))
(define ht-fixnum2
(hash-table-tabulate number-comparator
10
(lambda (i) (values (* i i) i))))
(define ht-string2
(hash-table-unfold (lambda (s) (= 0 (string-length s)))
(lambda (s) (values s (string-length s)))
(lambda (s) (substring s 0 (- (string-length s) 1)))
"prefixes"
string-comparator
'ignored1 'ignored2 "ignored3" '#(ignored 4 5)))
(define ht-string-ci2
(alist->hash-table '(("" . 0) ("Mary" . 4) ("Paul" . 4) ("Peter" . 5))
string-ci-comparator
"ignored1" 'ignored2))
(define ht-symbol2
(alist->hash-table '((mary . travers) (noel . stookey) (peter . yarrow))
eq?))
(define ht-equal2
(alist->hash-table '(((edward) . abbey)
((dashiell) . hammett)
((edward) . teach)
((mark) . twain))
equal?
(comparator-hash-function default-comparator)))
(define test-tables
initial keys : foo , 101.3 , ( x y z )
ht-eq ht-eq2 ; initially empty
ht-eqv ht-eqv2 ; initially empty
initial keys : ( ) , ( dashiell ) , ( mark )
ht-string ht-string2 ; initial keys: "p, "pr", ..., "prefixes"
initial keys : " " , " " , " " , " "
initial keys : ,
initial keys : 0 , 1 , 4 , 9 , ... , 81
;;; Predicates
(test (map hash-table?
(cons '#()
(cons default-comparator
test-tables)))
(append '(#f #f) (map (lambda (x) #t) test-tables)))
(test (map hash-table-contains?
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(#f #t #f #f #f #f #f #t #f #t #f #t #f #t #f #t))
(test (map hash-table-contains?
test-tables
`(,(bytevector) 47.9
'#() '()
foo bar
19 (henry)
"p" "perp"
"mike" "Noel"
jane paul
0 5))
(map (lambda (x) #f) test-tables))
(test (map hash-table-empty? test-tables)
'(#t #f #t #t #t #t #t #f #t #f #t #f #t #f #t #f))
(test (map (lambda (ht1 ht2) (hash-table=? default-comparator ht1 ht2))
test-tables
test-tables)
(map (lambda (x) #t) test-tables))
(test (map (lambda (ht1 ht2) (hash-table=? default-comparator ht1 ht2))
test-tables
(do ((tables (reverse test-tables) (cddr tables))
(rev '() (cons (car tables) (cons (cadr tables) rev))))
((null? tables)
rev)))
'(#f #f #t #t #t #t #f #f #f #f #f #f #f #f #f #f))
(test (map hash-table-mutable? test-tables)
'(#t #t #t #t #t #t #t #t #t #t #t #t #t #t #t #f))
;;; FIXME: glass-box
(test (map hash-table-mutable? (map hash-table-copy test-tables))
(map (lambda (x) #f) test-tables))
(test (hash-table-mutable? (hash-table-copy ht-fixnum2 #t))
#t)
;;; Accessors.
;;; FIXME: glass-box (implementations not required to raise an exception here)
(test (map (lambda (ht)
(guard (exn
(else 'err))
(hash-table-ref ht 'not-a-key)))
test-tables)
(map (lambda (ht) 'err) test-tables))
;;; FIXME: glass-box (implementations not required to raise an exception here)
(test (map (lambda (ht)
(guard (exn
(else 'err))
(hash-table-ref ht 'not-a-key (lambda () 'err))))
test-tables)
(map (lambda (ht) 'err) test-tables))
;;; FIXME: glass-box (implementations not required to raise an exception here)
(test (map (lambda (ht)
(guard (exn
(else 'err))
(hash-table-ref ht 'not-a-key (lambda () 'err) values)))
test-tables)
(map (lambda (ht) 'err) test-tables))
(test (map (lambda (ht key)
(guard (exn
(else 'err))
(hash-table-ref ht key)))
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(err "fever" err err err err err twain err 4 err 4 err stookey err 2))
(test (map (lambda (ht key)
(guard (exn
(else 'err))
(hash-table-ref ht key (lambda () 'eh))))
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(eh "fever" eh eh eh eh eh twain eh 4 eh 4 eh stookey eh 2))
(test (map (lambda (ht key)
(guard (exn
(else 'err))
(hash-table-ref ht key (lambda () 'eh) list)))
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(eh ("fever") eh eh eh eh eh (twain) eh (4) eh (4) eh (stookey) eh (2)))
;;; FIXME: glass-box (implementations not required to raise an exception here)
(test (map (lambda (ht)
(guard (exn
(else 'eh))
(hash-table-ref/default ht 'not-a-key 'eh)))
test-tables)
(map (lambda (ht) 'eh) test-tables))
(test (map (lambda (ht key)
(guard (exn
(else 'err))
(hash-table-ref/default ht key 'eh)))
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(eh "fever" eh eh eh eh eh twain eh 4 eh 4 eh stookey eh 2))
(test (begin (hash-table-set! ht-fixnum)
(list-sort < (hash-table-keys ht-fixnum)))
'())
(test (begin (hash-table-set! ht-fixnum 121 11 144 12 169 13)
(list-sort < (hash-table-keys ht-fixnum)))
'(121 144 169))
(test (begin (hash-table-set! ht-fixnum
0 0 1 1 4 2 9 3 16 4 25 5 36 6 49 7 64 8 81 9)
(list-sort < (hash-table-keys ht-fixnum)))
'(0 1 4 9 16 25 36 49 64 81 121 144 169))
(test (map (lambda (i) (hash-table-ref/default ht-fixnum i 'error))
'(169 144 121 0 1 4 9 16 25 36 49 64 81))
'(13 12 11 0 1 2 3 4 5 6 7 8 9))
(test (begin (hash-table-delete! ht-fixnum)
(map (lambda (i) (hash-table-ref/default ht-fixnum i 'error))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 5 6 7 8 9))
(test (begin (hash-table-delete! ht-fixnum 1 9 25 49 81 200 121 169 81 1)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(-1 12 -1 0 -1 2 -1 4 -1 6 -1 8 -1))
(test (begin (hash-table-delete! ht-fixnum 200 100 0 81 36)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(-1 12 -1 -1 -1 2 -1 4 -1 -1 -1 8 -1))
(test (begin (hash-table-intern! ht-fixnum 169 (lambda () 13))
(hash-table-intern! ht-fixnum 121 (lambda () 11))
(hash-table-intern! ht-fixnum 0 (lambda () 0))
(hash-table-intern! ht-fixnum 1 (lambda () 1))
(hash-table-intern! ht-fixnum 1 (lambda () 99))
(hash-table-intern! ht-fixnum 121 (lambda () 66))
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 -1 4 -1 -1 -1 8 -1))
(test (list-sort (lambda (v1 v2) (< (vector-ref v1 0) (vector-ref v2 0)))
(hash-table-map->list vector ht-fixnum))
'(#(0 0) #(1 1) #(4 2) #(16 4) #(64 8) #(121 11) #(144 12) #(169 13)))
(test (begin (hash-table-prune! (lambda (key val)
(and (odd? key) (> val 10)))
ht-fixnum)
(list-sort (lambda (l1 l2)
(< (car l1) (car l2)))
(hash-table-map->list list ht-fixnum)))
( 121 11 ) ( 144 12 ) # ; ( 169 13 ) ) )
(test (begin (hash-table-intern! ht-fixnum 169 (lambda () 13))
(hash-table-intern! ht-fixnum 144 (lambda () 9999))
(hash-table-intern! ht-fixnum 121 (lambda () 11))
(list-sort (lambda (l1 l2)
(< (car l1) (car l2)))
(hash-table-map->list list ht-fixnum)))
'((0 0) (1 1) (4 2) (16 4) (64 8) (121 11) (144 12) (169 13)))
(test (begin (hash-table-update! ht-fixnum 9 length (lambda () '(a b c)))
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 -1 -1 -1 8 -1))
(test (begin (hash-table-update! ht-fixnum 16 -)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 -4 -1 -1 -1 8 -1))
(test (begin (hash-table-update! ht-fixnum 16 - abs)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 -1 -1 -1 8 -1))
(test (begin (hash-table-update!/default ht-fixnum 25 - 5)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 -5 -1 -1 8 -1))
(test (begin (hash-table-update!/default ht-fixnum 25 - 999)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 5 -1 -1 8 -1))
(test (let* ((n0 (hash-table-size ht-fixnum))
(ht (hash-table-copy ht-fixnum #t)))
(call-with-values
(lambda () (hash-table-pop! ht))
(lambda (key val)
(list (= key (* val val))
(= (- n0 1) (hash-table-size ht))))))
'(#t #t))
(test (begin (hash-table-delete! ht-fixnum 75)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 75 81)))
'(13 12 11 0 1 2 3 4 5 -1 -1 8 -1 -1))
(let ((ht-eg (hash-table number-comparator 1 1 4 2 9 3 16 4 25 5 64 8)))
(test (hash-table-delete! ht-eg)
0)
(test (hash-table-delete! ht-eg 2 7 2000)
0)
(test (hash-table-delete! ht-eg 1 2 4 7 64 2000)
3)
(test-assert (= 3 (length (hash-table-keys ht-eg)))))
(test (map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81))
'(13 12 11 0 1 2 3 4 5 -1 -1 8 -1))
(test (begin (hash-table-set! ht-fixnum 36 6)
(hash-table-set! ht-fixnum 81 9)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 5 6 -1 8 9))
(test (begin (hash-table-clear! ht-eq)
(hash-table-size ht-eq))
0)
;;; The whole hash table.
(test (begin (hash-table-set! ht-eq 'foo 13 'bar 14 'baz 18)
(hash-table-size ht-eq))
3)
(test (let* ((ht (hash-table-empty-copy ht-eq))
(n0 (hash-table-size ht))
(ignored (hash-table-set! ht 'foo 13 'bar 14 'baz 18))
(n1 (hash-table-size ht)))
(list n0 n1 (hash-table=? default-comparator ht ht-eq)))
'(0 3 #t))
(test (begin (hash-table-clear! ht-eq)
(hash-table-size ht-eq))
0)
(test (hash-table-find (lambda (key val)
(if (= 144 key (* val val))
(list key val)
#f))
ht-fixnum
(lambda () 99))
'(144 12))
(test (hash-table-find (lambda (key val)
(if (= 144 key val)
(list key val)
#f))
ht-fixnum
(lambda () 99))
99)
(test (hash-table-count <= ht-fixnum)
2)
;;; Mapping and folding.
(test (map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(0 1 4 9 16 25 36 49 64 81 100 121 144 169 196))
'(0 1 2 3 4 5 6 -1 8 9 -1 11 12 13 -1))
(test (let ((ht (hash-table-map (lambda (val) (* val val))
eqv-comparator
ht-fixnum)))
(map (lambda (i) (hash-table-ref/default ht i -1))
'(0 1 4 9 16 25 36 49 64 81 100 121 144 169 196)))
'(0 1 4 9 16 25 36 -1 64 81 -1 121 144 169 -1))
(test (let ((keys (make-vector 15 -1))
(vals (make-vector 15 -1)))
(hash-table-for-each (lambda (key val)
(vector-set! keys val key)
(vector-set! vals val val))
ht-fixnum)
(list keys vals))
'(#(0 1 4 9 16 25 36 -1 64 81 -1 121 144 169 -1)
#(0 1 2 3 4 5 6 -1 8 9 -1 11 12 13 -1)))
(test (begin (hash-table-map! (lambda (key val)
(if (<= 10 key)
(- val)
val))
ht-fixnum)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(0 1 4 9 16 25 36 49 64 81 100 121 144 169 196)))
'(0 1 2 3 -4 -5 -6 -1 -8 -9 -1 -11 -12 -13 -1))
(test (hash-table-fold (lambda (key val acc)
(+ val acc))
0
ht-string-ci2)
13)
(test (list-sort < (hash-table-fold (lambda (key val acc)
(cons key acc))
'()
ht-fixnum))
'(0 1 4 9 16 25 36 64 81 121 144 169))
;;; Copying and conversion.
(test (hash-table=? number-comparator ht-fixnum (hash-table-copy ht-fixnum))
#t)
(test (hash-table=? number-comparator ht-fixnum (hash-table-copy ht-fixnum #f))
#t)
(test (hash-table=? number-comparator ht-fixnum (hash-table-copy ht-fixnum #t))
#t)
(test (hash-table-mutable? (hash-table-copy ht-fixnum))
#f)
(test (hash-table-mutable? (hash-table-copy ht-fixnum #f))
#f)
(test (hash-table-mutable? (hash-table-copy ht-fixnum #t))
#t)
(test (hash-table->alist ht-eq)
'())
(test (list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht-fixnum))
'((0 . 0)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . -4)
(25 . -5)
(36 . -6)
(64 . -8)
(81 . -9)
(121 . -11)
(144 . -12)
(169 . -13)))
;;; Hash tables as sets.
(test (begin (hash-table-union! ht-fixnum ht-fixnum2)
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht-fixnum)))
'((0 . 0)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . -4)
(25 . -5)
(36 . -6)
(49 . 7)
(64 . -8)
(81 . -9)
(121 . -11)
(144 . -12)
(169 . -13)))
(test (let ((ht (hash-table-copy ht-fixnum2 #t)))
(hash-table-union! ht ht-fixnum)
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht)))
'((0 . 0)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . 4)
(25 . 5)
(36 . 6)
(49 . 7)
(64 . 8)
(81 . 9)
(121 . -11)
(144 . -12)
(169 . -13)))
(test (begin (hash-table-union! ht-eqv2 ht-fixnum)
(hash-table=? default-comparator ht-eqv2 ht-fixnum))
#t)
(test (begin (hash-table-intersection! ht-eqv2 ht-fixnum)
(hash-table=? default-comparator ht-eqv2 ht-fixnum))
#t)
(test (begin (hash-table-intersection! ht-eqv2 ht-eqv)
(hash-table-empty? ht-eqv2))
#t)
(test (begin (hash-table-intersection! ht-fixnum ht-fixnum2)
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht-fixnum)))
'((0 . 0)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . -4)
(25 . -5)
(36 . -6)
(49 . 7)
(64 . -8)
(81 . -9)))
(test (begin (hash-table-intersection!
ht-fixnum
(alist->hash-table '((-1 . -1) (4 . 202) (25 . 205) (100 . 10))
number-comparator))
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht-fixnum)))
'((4 . 2)
(25 . -5)))
(test (let ((ht (hash-table-copy ht-fixnum2 #t)))
(hash-table-difference!
ht
(alist->hash-table '((-1 . -1) (4 . 202) (25 . 205) (100 . 10))
number-comparator))
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht)))
'((0 . 0)
(1 . 1)
(9 . 3)
(16 . 4)
(36 . 6)
(49 . 7)
(64 . 8)
(81 . 9)))
(test (let ((ht (hash-table-copy ht-fixnum2 #t)))
(hash-table-xor!
ht
(alist->hash-table '((-1 . -1) (4 . 202) (25 . 205) (100 . 10))
number-comparator))
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht)))
'((-1 . -1)
(0 . 0)
(1 . 1)
(9 . 3)
(16 . 4)
(36 . 6)
(49 . 7)
(64 . 8)
(81 . 9)
(100 . 10)))
(test (guard (exn
(else 'key-not-found))
(hash-table-ref ht-default "this key won't be present"))
'key-not-found)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;
Desultory tests of deprecated procedures and usages .
;;; Deprecated usage of make-hash-table and alist->hash-table
;;; has already been tested above.
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(test (let* ((x (list 1 2 3))
(y (cons 1 (cdr x)))
(h1 (deprecated:hash x))
(h2 (deprecated:hash y)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x "abcd")
(y (string-append "ab" "cd"))
(h1 (deprecated:string-hash x))
(h2 (deprecated:string-hash y)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x "Hello There!")
(y "hello THERE!")
(h1 (deprecated:string-ci-hash x))
(h2 (deprecated:string-ci-hash y)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x (vector 'a "bcD" #\c '(d 2.718) -42 (bytevector) '#() (bytevector 9 20)))
(y x)
(h1 (deprecated:hash-by-identity x))
(h2 (deprecated:hash-by-identity y)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x (list 1 2 3))
(y (cons 1 (cdr x)))
(h1 (deprecated:hash x 60))
(h2 (deprecated:hash y 60)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x "abcd")
(y (string-append "ab" "cd"))
(h1 (deprecated:string-hash x 97))
(h2 (deprecated:string-hash y 97)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x "Hello There!")
(y "hello THERE!")
(h1 (deprecated:string-ci-hash x 101))
(h2 (deprecated:string-ci-hash y 101)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x (vector 'a "bcD" #\c '(d 2.718) -42 (bytevector) '#() (bytevector 19 20)))
(y x)
(h1 (deprecated:hash-by-identity x 102))
(h2 (deprecated:hash-by-identity y 102)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let ((f (deprecated:hash-table-equivalence-function ht-fixnum)))
(if (procedure? f)
(f 34 34)
#t))
#t)
(test (let ((f (deprecated:hash-table-hash-function ht-fixnum)))
(if (procedure? f)
(= (f 34) (f 34))
#t))
#t)
(test (map (lambda (key) (deprecated:hash-table-exists? ht-fixnum2 key))
'(0 1 2 3 4 5 6 7 8 9 10))
'(#t #t #f #f #t #f #f #f #f #t #f))
(test (let ((n 0))
(deprecated:hash-table-walk ht-fixnum2
(lambda (key val) (set! n (+ n key))))
n)
(apply +
(map (lambda (x) (* x x))
'(0 1 2 3 4 5 6 7 8 9))))
(test (list-sort < (hash-table-fold ht-fixnum2
(lambda (key val acc)
(cons key acc))
'()))
'(0 1 4 9 16 25 36 49 64 81))
(test (let ((ht (hash-table-copy ht-fixnum2 #t))
(ht2 (hash-table number-comparator
.25 .5 64 9999 81 9998 121 -11 144 -12)))
(deprecated:hash-table-merge! ht ht2)
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht)))
'((0 . 0)
(.25 . .5)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . 4)
(25 . 5)
(36 . 6)
(49 . 7)
(64 . 8)
(81 . 9)
(121 . -11)
(144 . -12)))
(displayln "Done.")
eof
| null | https://raw.githubusercontent.com/arcfide/chez-srfi/96fb553b6ba0834747d5ccfc08c181aa8fd5f612/tests/tables-test.ikarus.sps | scheme |
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
including without limitation the rights to use, copy, modify, merge,
subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
This is a very shallow sanity test for hash tables.
Tests marked by a "FIXME: glass-box" comment test behavior of the
reference implementation that is not required by the specification.
FIXME: when debugging catastrophic failures, printing every expression
before it's executed may help.
(write 'expr) (newline)
the hash function produce non - integers .
Returns an immutable hash table.
Constructors.
FIXME: glass-box
initially empty
initially empty
initial keys: "p, "pr", ..., "prefixes"
Predicates
FIXME: glass-box
Accessors.
FIXME: glass-box (implementations not required to raise an exception here)
FIXME: glass-box (implementations not required to raise an exception here)
FIXME: glass-box (implementations not required to raise an exception here)
FIXME: glass-box (implementations not required to raise an exception here)
( 169 13 ) ) )
The whole hash table.
Mapping and folding.
Copying and conversion.
Hash tables as sets.
Deprecated usage of make-hash-table and alist->hash-table
has already been tested above.
| Copyright ( C ) 2015 . All Rights Reserved .
files ( the " Software " ) , to deal in the Software without restriction ,
publish , distribute , sublicense , and/or sell copies of the Software ,
and to permit persons to whom the Software is furnished to do so ,
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
MERCHANTABILITY , FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT .
CLAIM , DAMAGES OR OTHER LIABILITY , WHETHER IN AN ACTION OF CONTRACT ,
(import (rnrs)
(srfi :128)
(srfi :125))
(define (writeln . xs)
(for-each write xs)
(newline))
(define (displayln . xs)
(for-each display xs)
(newline))
(define (exact-integer? x)
(and (integer? x) (exact? x)))
(define (bytevector . args)
(u8-list->bytevector args))
(define (fail token . more)
(displayln "Error: test failed: ")
(writeln token)
(if (not (null? more))
(for-each writeln more))
(newline)
#f)
(define (success token)
( " Test succeded : " )
( token )
#f)
(define-syntax test
(syntax-rules ()
((_ expr expected)
(let ()
(let ((actual expr))
(if (equal? actual expected)
(success 'expr)
(fail 'expr actual expected)))))))
(define-syntax test-assert
(syntax-rules ()
((_ expr)
(or expr (fail 'expr)))))
(define-syntax test-deny
(syntax-rules ()
((_ expr)
(or (not expr) (fail 'expr)))))
Transition from SRFI 114 to SRFI 128 .
(define default-comparator (make-default-comparator))
SRFI 128 says the following definition will work , but that 's
(define number-comparator
(make-comparator real? = < (lambda (x) (exact (abs x)))))
(define number-comparator
(make-comparator real? = < (lambda (x) (exact (abs (round x))))))
(define string-comparator
(make-comparator string? string=? string<? string-hash))
(define string-ci-comparator
(make-comparator string? string-ci=? string-ci<? string-ci-hash))
(define eq-comparator (make-eq-comparator))
(define eqv-comparator (make-eqv-comparator))
Transition from earlier draft of SRFI 125 to this draft .
(define (hash-table-tabulate comparator n proc)
(let ((ht (make-hash-table comparator)))
(do ((i 0 (+ i 1)))
((= i n)
(hash-table-copy ht))
(call-with-values
(lambda ()
(proc i))
(lambda (key val)
(hash-table-set! ht key val))))))
(define ht-default (make-hash-table default-comparator))
(define ht-eq (make-hash-table eq-comparator 'random-argument "another"))
(define ht-eqv (make-hash-table eqv-comparator))
(define ht-eq2 (make-hash-table eq?))
(define ht-eqv2 (make-hash-table eqv?))
(define ht-equal (make-hash-table default-comparator))
(define ht-string (make-hash-table string=?))
(define ht-string-ci (make-hash-table string-ci=?))
(define ht-fixnum (make-hash-table = abs))
(define ht-default2
(hash-table default-comparator 'foo 'bar 101.3 "fever" '(x y z) '#()))
(define ht-fixnum2
(hash-table-tabulate number-comparator
10
(lambda (i) (values (* i i) i))))
(define ht-string2
(hash-table-unfold (lambda (s) (= 0 (string-length s)))
(lambda (s) (values s (string-length s)))
(lambda (s) (substring s 0 (- (string-length s) 1)))
"prefixes"
string-comparator
'ignored1 'ignored2 "ignored3" '#(ignored 4 5)))
(define ht-string-ci2
(alist->hash-table '(("" . 0) ("Mary" . 4) ("Paul" . 4) ("Peter" . 5))
string-ci-comparator
"ignored1" 'ignored2))
(define ht-symbol2
(alist->hash-table '((mary . travers) (noel . stookey) (peter . yarrow))
eq?))
(define ht-equal2
(alist->hash-table '(((edward) . abbey)
((dashiell) . hammett)
((edward) . teach)
((mark) . twain))
equal?
(comparator-hash-function default-comparator)))
(define test-tables
initial keys : foo , 101.3 , ( x y z )
initial keys : ( ) , ( dashiell ) , ( mark )
initial keys : " " , " " , " " , " "
initial keys : ,
initial keys : 0 , 1 , 4 , 9 , ... , 81
(test (map hash-table?
(cons '#()
(cons default-comparator
test-tables)))
(append '(#f #f) (map (lambda (x) #t) test-tables)))
(test (map hash-table-contains?
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(#f #t #f #f #f #f #f #t #f #t #f #t #f #t #f #t))
(test (map hash-table-contains?
test-tables
`(,(bytevector) 47.9
'#() '()
foo bar
19 (henry)
"p" "perp"
"mike" "Noel"
jane paul
0 5))
(map (lambda (x) #f) test-tables))
(test (map hash-table-empty? test-tables)
'(#t #f #t #t #t #t #t #f #t #f #t #f #t #f #t #f))
(test (map (lambda (ht1 ht2) (hash-table=? default-comparator ht1 ht2))
test-tables
test-tables)
(map (lambda (x) #t) test-tables))
(test (map (lambda (ht1 ht2) (hash-table=? default-comparator ht1 ht2))
test-tables
(do ((tables (reverse test-tables) (cddr tables))
(rev '() (cons (car tables) (cons (cadr tables) rev))))
((null? tables)
rev)))
'(#f #f #t #t #t #t #f #f #f #f #f #f #f #f #f #f))
(test (map hash-table-mutable? test-tables)
'(#t #t #t #t #t #t #t #t #t #t #t #t #t #t #t #f))
(test (map hash-table-mutable? (map hash-table-copy test-tables))
(map (lambda (x) #f) test-tables))
(test (hash-table-mutable? (hash-table-copy ht-fixnum2 #t))
#t)
(test (map (lambda (ht)
(guard (exn
(else 'err))
(hash-table-ref ht 'not-a-key)))
test-tables)
(map (lambda (ht) 'err) test-tables))
(test (map (lambda (ht)
(guard (exn
(else 'err))
(hash-table-ref ht 'not-a-key (lambda () 'err))))
test-tables)
(map (lambda (ht) 'err) test-tables))
(test (map (lambda (ht)
(guard (exn
(else 'err))
(hash-table-ref ht 'not-a-key (lambda () 'err) values)))
test-tables)
(map (lambda (ht) 'err) test-tables))
(test (map (lambda (ht key)
(guard (exn
(else 'err))
(hash-table-ref ht key)))
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(err "fever" err err err err err twain err 4 err 4 err stookey err 2))
(test (map (lambda (ht key)
(guard (exn
(else 'err))
(hash-table-ref ht key (lambda () 'eh))))
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(eh "fever" eh eh eh eh eh twain eh 4 eh 4 eh stookey eh 2))
(test (map (lambda (ht key)
(guard (exn
(else 'err))
(hash-table-ref ht key (lambda () 'eh) list)))
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(eh ("fever") eh eh eh eh eh (twain) eh (4) eh (4) eh (stookey) eh (2)))
(test (map (lambda (ht)
(guard (exn
(else 'eh))
(hash-table-ref/default ht 'not-a-key 'eh)))
test-tables)
(map (lambda (ht) 'eh) test-tables))
(test (map (lambda (ht key)
(guard (exn
(else 'err))
(hash-table-ref/default ht key 'eh)))
test-tables
'(foo 101.3
x "y"
(14 15) #\newline
(edward) (mark)
"p" "pref"
"mike" "PAUL"
jane noel
0 4))
'(eh "fever" eh eh eh eh eh twain eh 4 eh 4 eh stookey eh 2))
(test (begin (hash-table-set! ht-fixnum)
(list-sort < (hash-table-keys ht-fixnum)))
'())
(test (begin (hash-table-set! ht-fixnum 121 11 144 12 169 13)
(list-sort < (hash-table-keys ht-fixnum)))
'(121 144 169))
(test (begin (hash-table-set! ht-fixnum
0 0 1 1 4 2 9 3 16 4 25 5 36 6 49 7 64 8 81 9)
(list-sort < (hash-table-keys ht-fixnum)))
'(0 1 4 9 16 25 36 49 64 81 121 144 169))
(test (map (lambda (i) (hash-table-ref/default ht-fixnum i 'error))
'(169 144 121 0 1 4 9 16 25 36 49 64 81))
'(13 12 11 0 1 2 3 4 5 6 7 8 9))
(test (begin (hash-table-delete! ht-fixnum)
(map (lambda (i) (hash-table-ref/default ht-fixnum i 'error))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 5 6 7 8 9))
(test (begin (hash-table-delete! ht-fixnum 1 9 25 49 81 200 121 169 81 1)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(-1 12 -1 0 -1 2 -1 4 -1 6 -1 8 -1))
(test (begin (hash-table-delete! ht-fixnum 200 100 0 81 36)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(-1 12 -1 -1 -1 2 -1 4 -1 -1 -1 8 -1))
(test (begin (hash-table-intern! ht-fixnum 169 (lambda () 13))
(hash-table-intern! ht-fixnum 121 (lambda () 11))
(hash-table-intern! ht-fixnum 0 (lambda () 0))
(hash-table-intern! ht-fixnum 1 (lambda () 1))
(hash-table-intern! ht-fixnum 1 (lambda () 99))
(hash-table-intern! ht-fixnum 121 (lambda () 66))
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 -1 4 -1 -1 -1 8 -1))
(test (list-sort (lambda (v1 v2) (< (vector-ref v1 0) (vector-ref v2 0)))
(hash-table-map->list vector ht-fixnum))
'(#(0 0) #(1 1) #(4 2) #(16 4) #(64 8) #(121 11) #(144 12) #(169 13)))
(test (begin (hash-table-prune! (lambda (key val)
(and (odd? key) (> val 10)))
ht-fixnum)
(list-sort (lambda (l1 l2)
(< (car l1) (car l2)))
(hash-table-map->list list ht-fixnum)))
(test (begin (hash-table-intern! ht-fixnum 169 (lambda () 13))
(hash-table-intern! ht-fixnum 144 (lambda () 9999))
(hash-table-intern! ht-fixnum 121 (lambda () 11))
(list-sort (lambda (l1 l2)
(< (car l1) (car l2)))
(hash-table-map->list list ht-fixnum)))
'((0 0) (1 1) (4 2) (16 4) (64 8) (121 11) (144 12) (169 13)))
(test (begin (hash-table-update! ht-fixnum 9 length (lambda () '(a b c)))
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 -1 -1 -1 8 -1))
(test (begin (hash-table-update! ht-fixnum 16 -)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 -4 -1 -1 -1 8 -1))
(test (begin (hash-table-update! ht-fixnum 16 - abs)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 -1 -1 -1 8 -1))
(test (begin (hash-table-update!/default ht-fixnum 25 - 5)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 -5 -1 -1 8 -1))
(test (begin (hash-table-update!/default ht-fixnum 25 - 999)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 5 -1 -1 8 -1))
(test (let* ((n0 (hash-table-size ht-fixnum))
(ht (hash-table-copy ht-fixnum #t)))
(call-with-values
(lambda () (hash-table-pop! ht))
(lambda (key val)
(list (= key (* val val))
(= (- n0 1) (hash-table-size ht))))))
'(#t #t))
(test (begin (hash-table-delete! ht-fixnum 75)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 75 81)))
'(13 12 11 0 1 2 3 4 5 -1 -1 8 -1 -1))
(let ((ht-eg (hash-table number-comparator 1 1 4 2 9 3 16 4 25 5 64 8)))
(test (hash-table-delete! ht-eg)
0)
(test (hash-table-delete! ht-eg 2 7 2000)
0)
(test (hash-table-delete! ht-eg 1 2 4 7 64 2000)
3)
(test-assert (= 3 (length (hash-table-keys ht-eg)))))
(test (map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81))
'(13 12 11 0 1 2 3 4 5 -1 -1 8 -1))
(test (begin (hash-table-set! ht-fixnum 36 6)
(hash-table-set! ht-fixnum 81 9)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(169 144 121 0 1 4 9 16 25 36 49 64 81)))
'(13 12 11 0 1 2 3 4 5 6 -1 8 9))
(test (begin (hash-table-clear! ht-eq)
(hash-table-size ht-eq))
0)
(test (begin (hash-table-set! ht-eq 'foo 13 'bar 14 'baz 18)
(hash-table-size ht-eq))
3)
(test (let* ((ht (hash-table-empty-copy ht-eq))
(n0 (hash-table-size ht))
(ignored (hash-table-set! ht 'foo 13 'bar 14 'baz 18))
(n1 (hash-table-size ht)))
(list n0 n1 (hash-table=? default-comparator ht ht-eq)))
'(0 3 #t))
(test (begin (hash-table-clear! ht-eq)
(hash-table-size ht-eq))
0)
(test (hash-table-find (lambda (key val)
(if (= 144 key (* val val))
(list key val)
#f))
ht-fixnum
(lambda () 99))
'(144 12))
(test (hash-table-find (lambda (key val)
(if (= 144 key val)
(list key val)
#f))
ht-fixnum
(lambda () 99))
99)
(test (hash-table-count <= ht-fixnum)
2)
(test (map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(0 1 4 9 16 25 36 49 64 81 100 121 144 169 196))
'(0 1 2 3 4 5 6 -1 8 9 -1 11 12 13 -1))
(test (let ((ht (hash-table-map (lambda (val) (* val val))
eqv-comparator
ht-fixnum)))
(map (lambda (i) (hash-table-ref/default ht i -1))
'(0 1 4 9 16 25 36 49 64 81 100 121 144 169 196)))
'(0 1 4 9 16 25 36 -1 64 81 -1 121 144 169 -1))
(test (let ((keys (make-vector 15 -1))
(vals (make-vector 15 -1)))
(hash-table-for-each (lambda (key val)
(vector-set! keys val key)
(vector-set! vals val val))
ht-fixnum)
(list keys vals))
'(#(0 1 4 9 16 25 36 -1 64 81 -1 121 144 169 -1)
#(0 1 2 3 4 5 6 -1 8 9 -1 11 12 13 -1)))
(test (begin (hash-table-map! (lambda (key val)
(if (<= 10 key)
(- val)
val))
ht-fixnum)
(map (lambda (i) (hash-table-ref/default ht-fixnum i -1))
'(0 1 4 9 16 25 36 49 64 81 100 121 144 169 196)))
'(0 1 2 3 -4 -5 -6 -1 -8 -9 -1 -11 -12 -13 -1))
(test (hash-table-fold (lambda (key val acc)
(+ val acc))
0
ht-string-ci2)
13)
(test (list-sort < (hash-table-fold (lambda (key val acc)
(cons key acc))
'()
ht-fixnum))
'(0 1 4 9 16 25 36 64 81 121 144 169))
(test (hash-table=? number-comparator ht-fixnum (hash-table-copy ht-fixnum))
#t)
(test (hash-table=? number-comparator ht-fixnum (hash-table-copy ht-fixnum #f))
#t)
(test (hash-table=? number-comparator ht-fixnum (hash-table-copy ht-fixnum #t))
#t)
(test (hash-table-mutable? (hash-table-copy ht-fixnum))
#f)
(test (hash-table-mutable? (hash-table-copy ht-fixnum #f))
#f)
(test (hash-table-mutable? (hash-table-copy ht-fixnum #t))
#t)
(test (hash-table->alist ht-eq)
'())
(test (list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht-fixnum))
'((0 . 0)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . -4)
(25 . -5)
(36 . -6)
(64 . -8)
(81 . -9)
(121 . -11)
(144 . -12)
(169 . -13)))
(test (begin (hash-table-union! ht-fixnum ht-fixnum2)
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht-fixnum)))
'((0 . 0)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . -4)
(25 . -5)
(36 . -6)
(49 . 7)
(64 . -8)
(81 . -9)
(121 . -11)
(144 . -12)
(169 . -13)))
(test (let ((ht (hash-table-copy ht-fixnum2 #t)))
(hash-table-union! ht ht-fixnum)
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht)))
'((0 . 0)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . 4)
(25 . 5)
(36 . 6)
(49 . 7)
(64 . 8)
(81 . 9)
(121 . -11)
(144 . -12)
(169 . -13)))
(test (begin (hash-table-union! ht-eqv2 ht-fixnum)
(hash-table=? default-comparator ht-eqv2 ht-fixnum))
#t)
(test (begin (hash-table-intersection! ht-eqv2 ht-fixnum)
(hash-table=? default-comparator ht-eqv2 ht-fixnum))
#t)
(test (begin (hash-table-intersection! ht-eqv2 ht-eqv)
(hash-table-empty? ht-eqv2))
#t)
(test (begin (hash-table-intersection! ht-fixnum ht-fixnum2)
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht-fixnum)))
'((0 . 0)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . -4)
(25 . -5)
(36 . -6)
(49 . 7)
(64 . -8)
(81 . -9)))
(test (begin (hash-table-intersection!
ht-fixnum
(alist->hash-table '((-1 . -1) (4 . 202) (25 . 205) (100 . 10))
number-comparator))
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht-fixnum)))
'((4 . 2)
(25 . -5)))
(test (let ((ht (hash-table-copy ht-fixnum2 #t)))
(hash-table-difference!
ht
(alist->hash-table '((-1 . -1) (4 . 202) (25 . 205) (100 . 10))
number-comparator))
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht)))
'((0 . 0)
(1 . 1)
(9 . 3)
(16 . 4)
(36 . 6)
(49 . 7)
(64 . 8)
(81 . 9)))
(test (let ((ht (hash-table-copy ht-fixnum2 #t)))
(hash-table-xor!
ht
(alist->hash-table '((-1 . -1) (4 . 202) (25 . 205) (100 . 10))
number-comparator))
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht)))
'((-1 . -1)
(0 . 0)
(1 . 1)
(9 . 3)
(16 . 4)
(36 . 6)
(49 . 7)
(64 . 8)
(81 . 9)
(100 . 10)))
(test (guard (exn
(else 'key-not-found))
(hash-table-ref ht-default "this key won't be present"))
'key-not-found)
Desultory tests of deprecated procedures and usages .
(test (let* ((x (list 1 2 3))
(y (cons 1 (cdr x)))
(h1 (deprecated:hash x))
(h2 (deprecated:hash y)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x "abcd")
(y (string-append "ab" "cd"))
(h1 (deprecated:string-hash x))
(h2 (deprecated:string-hash y)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x "Hello There!")
(y "hello THERE!")
(h1 (deprecated:string-ci-hash x))
(h2 (deprecated:string-ci-hash y)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x (vector 'a "bcD" #\c '(d 2.718) -42 (bytevector) '#() (bytevector 9 20)))
(y x)
(h1 (deprecated:hash-by-identity x))
(h2 (deprecated:hash-by-identity y)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x (list 1 2 3))
(y (cons 1 (cdr x)))
(h1 (deprecated:hash x 60))
(h2 (deprecated:hash y 60)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x "abcd")
(y (string-append "ab" "cd"))
(h1 (deprecated:string-hash x 97))
(h2 (deprecated:string-hash y 97)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x "Hello There!")
(y "hello THERE!")
(h1 (deprecated:string-ci-hash x 101))
(h2 (deprecated:string-ci-hash y 101)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let* ((x (vector 'a "bcD" #\c '(d 2.718) -42 (bytevector) '#() (bytevector 19 20)))
(y x)
(h1 (deprecated:hash-by-identity x 102))
(h2 (deprecated:hash-by-identity y 102)))
(list (exact-integer? h1)
(exact-integer? h2)
(= h1 h2)))
'(#t #t #t))
(test (let ((f (deprecated:hash-table-equivalence-function ht-fixnum)))
(if (procedure? f)
(f 34 34)
#t))
#t)
(test (let ((f (deprecated:hash-table-hash-function ht-fixnum)))
(if (procedure? f)
(= (f 34) (f 34))
#t))
#t)
(test (map (lambda (key) (deprecated:hash-table-exists? ht-fixnum2 key))
'(0 1 2 3 4 5 6 7 8 9 10))
'(#t #t #f #f #t #f #f #f #f #t #f))
(test (let ((n 0))
(deprecated:hash-table-walk ht-fixnum2
(lambda (key val) (set! n (+ n key))))
n)
(apply +
(map (lambda (x) (* x x))
'(0 1 2 3 4 5 6 7 8 9))))
(test (list-sort < (hash-table-fold ht-fixnum2
(lambda (key val acc)
(cons key acc))
'()))
'(0 1 4 9 16 25 36 49 64 81))
(test (let ((ht (hash-table-copy ht-fixnum2 #t))
(ht2 (hash-table number-comparator
.25 .5 64 9999 81 9998 121 -11 144 -12)))
(deprecated:hash-table-merge! ht ht2)
(list-sort (lambda (x y) (< (car x) (car y)))
(hash-table->alist ht)))
'((0 . 0)
(.25 . .5)
(1 . 1)
(4 . 2)
(9 . 3)
(16 . 4)
(25 . 5)
(36 . 6)
(49 . 7)
(64 . 8)
(81 . 9)
(121 . -11)
(144 . -12)))
(displayln "Done.")
eof
|
32a67e98978d9a16af374525aafd020193f6ed43bb54bb948ee923e83c94a5b4 | lidcore/bs-async-monad | bsAsyncMonad.ml | module type Async_t = sig
type 'a t
val return : 'a -> 'a t
val fail : exn -> 'a t
val compose : ?noStack:bool -> 'a t -> ('a -> 'b t) -> 'b t
val (>>) : 'a t -> ('a -> 'b t) -> 'b t
val catch : ?noStack:bool -> 'a t -> (exn -> 'a t) -> 'a t
val (||>) : 'a t -> (exn -> 'a t) -> 'a t
val pipe : ?noStack:bool -> 'a t -> ('a -> 'b) -> 'b t
val (>|) : 'a t -> ('a -> 'b) -> 'b t
val ensure : ?noStack:bool -> 'a t -> (unit -> unit t) -> 'a t
val (&>) : 'a t -> (unit -> unit t) -> 'a t
val ensure_pipe : ?noStack:bool -> 'a t -> (unit -> unit) -> 'a t
val (|&>) : 'a t -> (unit -> unit) -> 'a t
val discard : 'a t -> unit t
val repeat : (unit -> bool t) -> (unit -> unit t) -> unit t
val repeat_unless : (unit -> bool t) -> (unit -> unit t) -> unit t
val async_if : bool t -> (unit -> unit t) -> unit t
val async_unless : bool t -> (unit -> unit t) -> unit t
val fold_lefta : ?concurrency:int -> ('a -> 'b -> 'a t) -> 'a t -> 'b array -> 'a t
val fold_left : ?concurrency:int -> ('a -> 'b -> 'a t) -> 'a t -> 'b list -> 'a t
val fold_lefti : ?concurrency:int -> ('a -> int -> 'b -> 'a t) -> 'a t -> 'b list -> 'a t
val itera : ?concurrency:int -> ('a -> unit t) -> 'a array -> unit t
val iter : ?concurrency:int -> ('a -> unit t) -> 'a list -> unit t
val iteri : ?concurrency:int -> (int -> 'a -> unit t) -> 'a list -> unit t
val mapa : ?concurrency:int -> ('a -> 'b t) -> 'a array -> 'b array t
val map : ?concurrency:int -> ('a -> 'b t) -> 'a list -> 'b list t
val mapi : ?concurrency:int -> (int -> 'a -> 'b t) -> 'a list -> 'b list t
val seqa : ?concurrency:int -> unit t array -> unit t
val seq : ?concurrency:int -> unit t list -> unit t
val resolvea : ?resolver:('a -> unit t) -> concurrency:int -> 'a t array -> 'a t array
val resolve : ?resolver:('a -> unit t) -> concurrency:int -> 'a t list -> 'a t list
val execute : ?exceptionHandler:(exn->unit) -> 'a t -> ('a -> unit) -> unit
val finish : ?exceptionHandler:(exn->unit) -> unit t -> unit
end
module Callback = struct
type error = exn Js.nullable
type 'a callback = error -> 'a -> unit [@bs]
(* A computation takes a callback and executes it
either with an error or with a result of type 'a. *)
type 'a t = 'a callback -> unit
(* Computation that returns x as a value. *)
let return x cb =
cb Js.Nullable.null x [@bs]
(* Computation that returns an error. *)
let fail exn cb =
cb (Js.Nullable.return exn) (Obj.magic Js.Nullable.null) [@bs]
external setTimeout : (unit -> unit [@bs]) -> float -> unit = "" [@@bs.val]
exception Error of exn
(* Pipe current's result into next. *)
let compose ?(noStack=false) current next cb =
let fn = fun [@bs] err ret ->
match Js.toOption err with
| Some exn -> fail exn cb
| None ->
let next = fun [@bs] () ->
try
let next =
try
next ret
with exn -> raise (Error exn)
in
next cb
with Error exn -> fail exn cb
in
if noStack then
setTimeout next 0.
else
next () [@bs]
in
current fn
let (>>) = fun a b ->
compose a b
let on_next ~noStack next =
if noStack then
setTimeout next 0.
else
next () [@bs]
(* Catch exception. *)
let catch ?(noStack=false) current catcher cb =
let cb = fun [@bs] err ret ->
match Js.toOption err with
| Some exn ->
on_next ~noStack (fun [@bs] () ->
catcher exn cb)
| None ->
on_next ~noStack (fun [@bs] () ->
cb err ret [@bs])
in
current cb
let (||>) = fun a b ->
catch a b
let pipe ?(noStack=false) current fn cb =
current (fun [@bs] err ret ->
match Js.toOption err with
| Some exn ->
on_next ~noStack (fun [@bs] () ->
fail exn cb)
| None ->
on_next ~noStack (fun [@bs] () ->
try
let ret =
try
fn ret
with exn -> raise (Error exn)
in
return ret cb
with Error exn ->
fail exn cb))
let (>|) = fun a b ->
pipe a b
let ensure ?(noStack=false) current ensure cb =
current (fun [@bs] err ret ->
on_next ~noStack (fun [@bs] () ->
ensure () (fun [@bs] _ _ ->
cb err ret [@bs])))
let (&>) = fun a b ->
ensure a b
let ensure_pipe ?(noStack=false) current ensure cb =
current (fun [@bs] err ret ->
on_next ~noStack (fun [@bs] () ->
begin
try
ensure ()
with _ -> ()
end;
cb err ret [@bs]))
let (|&>) current ensure cb =
ensure_pipe current ensure cb
let discard fn cb =
fn (fun [@bs] err _ ->
cb err () [@bs])
let repeat condition computation cb =
let rec exec () =
condition () (fun [@bs] err ret ->
match Js.Nullable.isNullable err, ret with
| true, true ->
computation () (fun [@bs] err ret ->
if Js.Nullable.isNullable err then
cb err ret [@bs]
else
setTimeout (fun [@bs] () ->
exec ()) 0.)
| _ -> cb err () [@bs])
in
setTimeout (fun [@bs] () ->
exec ()) 0.
let repeat_unless condition computation =
let condition () cb =
condition () (fun [@bs] err ret ->
cb err (not ret) [@bs])
in
repeat condition computation
let async_if cond computation cb =
cond (fun [@bs] err ret ->
match Js.Nullable.isNullable err, ret with
| false, _
| _, false -> cb err () [@bs]
| _ -> computation () cb)
let async_unless cond computation cb =
let cond cb =
cond (fun [@bs] err ret ->
cb err (not ret) [@bs])
in
async_if cond computation cb
let itera ?(concurrency=1) fn a cb =
let total = Array.length a in
let executed = ref 0 in
let failed = ref false in
let rec process () =
let on_done () =
incr executed;
match !failed, !executed with
| true, _ -> ()
| false, n when n = total ->
return () cb
| _ ->
setTimeout (fun [@bs] () -> process ()) 0.
in
match Js.Array.shift a with
| Some v ->
fn v (fun [@bs] err () ->
match Js.toOption err with
| Some exn ->
if not !failed then
fail exn cb;
failed := true
| None -> on_done ())
| None -> ()
in
if total = 0 then
return () cb
else
for _ = 1 to min total concurrency do
setTimeout (fun [@bs] () -> process ()) 0.
done
let iter ?concurrency fn l =
itera ?concurrency fn (Array.of_list l)
let fold_lefta ?concurrency fn a ba =
let cur = ref a in
let fn b =
!cur >> fun a ->
cur := fn a b;
return ()
in
itera ?concurrency fn ba >> fun () ->
!cur
let fold_left ?concurrency fn cur l =
fold_lefta ?concurrency fn cur (Array.of_list l)
let fold_lefti ?concurrency fn cur l =
let l =
List.mapi (fun idx el ->
(idx,el)) l
in
let fn cur (idx,el) =
fn cur idx el
in
fold_left ?concurrency fn cur l
let iteri ?concurrency fn l =
let l =
List.mapi (fun idx el ->
(idx,el)) l
in
let fn (idx,el) =
fn idx el
in
iter ?concurrency fn l
let mapa ?concurrency fn a =
let ret = [||] in
let map v =
fn v >> fun res ->
ignore(Js.Array.push res ret);
return ()
in
itera ?concurrency map a >> fun () ->
return ret
let map ?concurrency fn l =
mapa ?concurrency fn (Array.of_list l) >> fun ret ->
return (Array.to_list ret)
let mapi ?concurrency fn l =
let l =
List.mapi (fun idx el ->
(idx,el)) l
in
let fn (idx,el) =
fn idx el
in
map ?concurrency fn l
let seqa ?concurrency a =
itera ?concurrency (fun v -> v >> return) a
let seq ?concurrency l =
seqa ?concurrency (Array.of_list l)
let resolvea ?(resolver=fun _ -> return ()) ~concurrency a =
let resolving = ref [] in
let pop_resolving () =
match !resolving with
| el::tl ->
resolving := tl;
el ()
| _ -> ()
in
let wrap fn =
let can_resolve = ref false in
let callback = ref None in
let wrap cb = fun [@bs] err ret ->
cb err ret [@bs];
if Js.Nullable.isNullable err then
resolver ret (fun [@bs] _ _ ->
pop_resolving ())
in
let resolve () =
match !callback with
| None ->
can_resolve := true
| Some cb ->
fn cb
in
let fn cb =
if !can_resolve then
fn (wrap cb)
else
callback := Some (wrap cb)
in
can_resolve, resolve, fn
in
if Array.length a <= concurrency then
a
else
let mapped = Array.map wrap a in
let can_resolve =
Array.map (fun (can_resolve, _, fn) ->
can_resolve := true;
fn) (Js.Array.slice ~start:0 ~end_:concurrency mapped)
in
let pending =
Array.map (fun (_, resolve, fn) ->
resolving := resolve::!resolving;
fn) (Js.Array.sliceFrom concurrency mapped)
in
Array.append can_resolve pending
let resolve ?resolver ~concurrency l =
Array.to_list
(resolvea ?resolver ~concurrency (Array.of_list l))
let execute ?(exceptionHandler=fun exn -> raise exn) t cb =
t (fun [@bs] err ret ->
match Js.toOption err with
| None -> cb ret
| Some exn -> exceptionHandler exn)
let finish ?exceptionHandler t =
execute ?exceptionHandler t (fun _ -> ())
end
let from_promise p = fun cb ->
let on_success ret =
Callback.return ret cb;
Js.Promise.resolve ret
in
There 's an inherent conflict here between dynamically typed JS world
* and statically typed BS / OCaml world . The promise API says that the
* value returned by the onError handler determines the value or error
* with which the promise gets resolved .
* In JS world , that means that you can just do console.log and the promise
* gets resolved with null / unit whatever .
* But in statically typed world the promise is of type ' a and needs a
* type ' a to resolve and since this code is generic , we have no idea how
* to produce a value of type ' a. Also , if we return the original promise ,
* the runtime thinks that we 're not handling errors and complains about it .
* Thus : Obj.magic . 😳
* and statically typed BS/OCaml world. The promise API says that the
* value returned by the onError handler determines the value or error
* with which the promise gets resolved.
* In JS world, that means that you can just do console.log and the promise
* gets resolved with null/unit whatever.
* But in statically typed world the promise is of type 'a and needs a
* type 'a to resolve and since this code is generic, we have no idea how
* to produce a value of type 'a. Also, if we return the original promise,
* the runtime thinks that we're not handling errors and complains about it.
* Thus: Obj.magic. 😳 *)
let on_error err =
Callback.fail (Obj.magic err) cb;
Js.Promise.reject (Obj.magic err)
in
ignore(Js.Promise.then_ on_success p |> Js.Promise.catch on_error)
let to_promise fn =
Js.Promise.make (fun ~resolve ~reject ->
fn (fun [@bs] err ret ->
match Js.toOption err with
| Some exn -> reject exn [@bs]
| None -> resolve ret [@bs]))
module type Wrapper_t = sig
type 'a t
val return : 'a -> 'a t
val fail : exn -> 'a t
val to_callback : 'a t -> 'a Callback.t
val from_callback : 'a Callback.t -> 'a t
end
module Make(Wrapper:Wrapper_t) = struct
type 'a t = 'a Wrapper.t
let return = Wrapper.return
let fail = Wrapper.fail
let compose ?noStack p fn =
let c =
Wrapper.to_callback p
in
let fn v =
Wrapper.to_callback (fn v)
in
Wrapper.from_callback
(Callback.compose ?noStack c fn)
let (>>) = fun p fn -> compose p fn
let catch ?noStack p fn =
let c =
Wrapper.to_callback p
in
let fn v =
Wrapper.to_callback (fn v)
in
Wrapper.from_callback
(Callback.catch ?noStack c fn)
let (||>) = fun p fn -> catch p fn
let pipe ?noStack p fn =
let c =
Wrapper.to_callback p
in
Wrapper.from_callback
(Callback.pipe ?noStack c fn)
let (>|) = fun p fn -> pipe p fn
let ensure ?noStack p fn =
let c =
Wrapper.to_callback p
in
let c =
Callback.ensure ?noStack c (fun () ->
Wrapper.to_callback (fn ()))
in
Wrapper.from_callback c
let (&>) = fun p fn ->
ensure p fn
let ensure_pipe ?noStack p fn =
let c =
Wrapper.to_callback p
in
let c =
Callback.ensure_pipe ?noStack c fn
in
Wrapper.from_callback c
let (|&>) = fun p fn ->
ensure_pipe p fn
let discard p =
p >> (fun _ -> return ())
let repeat cond body =
let cond () =
Wrapper.to_callback (cond ())
in
let body () =
Wrapper.to_callback (body ())
in
let c =
Callback.repeat cond body
in
Wrapper.from_callback c
let repeat_unless cond body =
let cond () =
Wrapper.to_callback (cond ())
in
let body () =
Wrapper.to_callback (body ())
in
let c =
Callback.repeat_unless cond body
in
Wrapper.from_callback c
let async_if cond computation =
let cond =
Wrapper.to_callback cond
in
let computation () =
Wrapper.to_callback (computation ())
in
let c =
Callback.async_if cond computation
in
Wrapper.from_callback c
let async_unless cond computation =
let cond =
Wrapper.to_callback cond
in
let computation () =
Wrapper.to_callback (computation ())
in
let c =
Callback.async_unless cond computation
in
Wrapper.from_callback c
let fold_lefta ?concurrency fn p a =
let fn x y =
Wrapper.to_callback (fn x y)
in
let c =
Wrapper.to_callback p
in
Wrapper.from_callback
(Callback.fold_lefta ?concurrency fn c a)
let fold_left ?concurrency fn p l =
fold_lefta ?concurrency fn p (Array.of_list l)
let fold_lefti ?concurrency fn p l =
let fn x pos y =
Wrapper.to_callback (fn x pos y)
in
let c =
Wrapper.to_callback p
in
Wrapper.from_callback
(Callback.fold_lefti ?concurrency fn c l)
let itera ?concurrency fn a =
let fn x =
Wrapper.to_callback (fn x)
in
Wrapper.from_callback
(Callback.itera ?concurrency fn a)
let iter ?concurrency fn l =
itera ?concurrency fn (Array.of_list l)
let iteri ?concurrency fn l =
let fn pos x =
Wrapper.to_callback (fn pos x)
in
Wrapper.from_callback
(Callback.iteri ?concurrency fn l)
let mapa ?concurrency fn a =
let fn x =
Wrapper.to_callback (fn x)
in
Wrapper.from_callback
(Callback.mapa ?concurrency fn a)
let map ?concurrency fn l =
mapa ?concurrency fn (Array.of_list l) >> fun a ->
return (Array.to_list a)
let mapi ?concurrency fn l =
let fn pos x =
Wrapper.to_callback (fn pos x)
in
Wrapper.from_callback
(Callback.mapi ?concurrency fn l)
let seqa ?concurrency a =
let a =
Array.map Wrapper.to_callback a
in
Wrapper.from_callback
(Callback.seqa ?concurrency a)
let seq ?concurrency l =
seqa ?concurrency (Array.of_list l)
let resolvea ?resolver ~concurrency a =
let resolver =
match resolver with
| None ->
None
| Some fn ->
Some (fun x ->
Wrapper.to_callback (fn x))
in
let a =
Array.map Wrapper.to_callback a
in
Array.map Wrapper.from_callback
(Callback.resolvea ?resolver ~concurrency a)
let resolve ?resolver ~concurrency l =
Array.to_list
(resolvea ?resolver ~concurrency (Array.of_list l))
let execute ?exceptionHandler p cb =
Callback.execute ?exceptionHandler
(Wrapper.to_callback p) cb
let finish ?exceptionHandler p =
execute ?exceptionHandler p (fun () -> ())
end
module PromiseWrapper = struct
type 'a t = 'a Js.Promise.t
let return = Js.Promise.resolve
let fail = Js.Promise.reject
let to_callback = from_promise
let from_callback = to_promise
end
module Promise = struct
include Make(PromiseWrapper)
(* Use native functions when available. *)
let compose ?noStack:_ p fn =
Js.Promise.then_ fn p
let (>>) = fun p fn ->
compose p fn
let catch ?noStack:_ p fn =
Js.Promise.catch (fun exn ->
fn (Obj.magic exn)) p
let (||>) = fun p fn ->
catch p fn
let pipe ?noStack:_ p fn =
compose p (fun v ->
return (fn v))
let (>|) = fun p fn ->
pipe p fn
(* Default to noStack:true for ensure for consistency: *)
let ensure ?noStack:_ p fn =
ensure ~noStack:true p fn
let (&>) p fn =
ensure p fn
end
| null | https://raw.githubusercontent.com/lidcore/bs-async-monad/7b4a2791684c74e0e61d7bfb6c84d319a7e6f5e5/src/bsAsyncMonad.ml | ocaml | A computation takes a callback and executes it
either with an error or with a result of type 'a.
Computation that returns x as a value.
Computation that returns an error.
Pipe current's result into next.
Catch exception.
Use native functions when available.
Default to noStack:true for ensure for consistency: | module type Async_t = sig
type 'a t
val return : 'a -> 'a t
val fail : exn -> 'a t
val compose : ?noStack:bool -> 'a t -> ('a -> 'b t) -> 'b t
val (>>) : 'a t -> ('a -> 'b t) -> 'b t
val catch : ?noStack:bool -> 'a t -> (exn -> 'a t) -> 'a t
val (||>) : 'a t -> (exn -> 'a t) -> 'a t
val pipe : ?noStack:bool -> 'a t -> ('a -> 'b) -> 'b t
val (>|) : 'a t -> ('a -> 'b) -> 'b t
val ensure : ?noStack:bool -> 'a t -> (unit -> unit t) -> 'a t
val (&>) : 'a t -> (unit -> unit t) -> 'a t
val ensure_pipe : ?noStack:bool -> 'a t -> (unit -> unit) -> 'a t
val (|&>) : 'a t -> (unit -> unit) -> 'a t
val discard : 'a t -> unit t
val repeat : (unit -> bool t) -> (unit -> unit t) -> unit t
val repeat_unless : (unit -> bool t) -> (unit -> unit t) -> unit t
val async_if : bool t -> (unit -> unit t) -> unit t
val async_unless : bool t -> (unit -> unit t) -> unit t
val fold_lefta : ?concurrency:int -> ('a -> 'b -> 'a t) -> 'a t -> 'b array -> 'a t
val fold_left : ?concurrency:int -> ('a -> 'b -> 'a t) -> 'a t -> 'b list -> 'a t
val fold_lefti : ?concurrency:int -> ('a -> int -> 'b -> 'a t) -> 'a t -> 'b list -> 'a t
val itera : ?concurrency:int -> ('a -> unit t) -> 'a array -> unit t
val iter : ?concurrency:int -> ('a -> unit t) -> 'a list -> unit t
val iteri : ?concurrency:int -> (int -> 'a -> unit t) -> 'a list -> unit t
val mapa : ?concurrency:int -> ('a -> 'b t) -> 'a array -> 'b array t
val map : ?concurrency:int -> ('a -> 'b t) -> 'a list -> 'b list t
val mapi : ?concurrency:int -> (int -> 'a -> 'b t) -> 'a list -> 'b list t
val seqa : ?concurrency:int -> unit t array -> unit t
val seq : ?concurrency:int -> unit t list -> unit t
val resolvea : ?resolver:('a -> unit t) -> concurrency:int -> 'a t array -> 'a t array
val resolve : ?resolver:('a -> unit t) -> concurrency:int -> 'a t list -> 'a t list
val execute : ?exceptionHandler:(exn->unit) -> 'a t -> ('a -> unit) -> unit
val finish : ?exceptionHandler:(exn->unit) -> unit t -> unit
end
module Callback = struct
type error = exn Js.nullable
type 'a callback = error -> 'a -> unit [@bs]
type 'a t = 'a callback -> unit
let return x cb =
cb Js.Nullable.null x [@bs]
let fail exn cb =
cb (Js.Nullable.return exn) (Obj.magic Js.Nullable.null) [@bs]
external setTimeout : (unit -> unit [@bs]) -> float -> unit = "" [@@bs.val]
exception Error of exn
let compose ?(noStack=false) current next cb =
let fn = fun [@bs] err ret ->
match Js.toOption err with
| Some exn -> fail exn cb
| None ->
let next = fun [@bs] () ->
try
let next =
try
next ret
with exn -> raise (Error exn)
in
next cb
with Error exn -> fail exn cb
in
if noStack then
setTimeout next 0.
else
next () [@bs]
in
current fn
let (>>) = fun a b ->
compose a b
let on_next ~noStack next =
if noStack then
setTimeout next 0.
else
next () [@bs]
let catch ?(noStack=false) current catcher cb =
let cb = fun [@bs] err ret ->
match Js.toOption err with
| Some exn ->
on_next ~noStack (fun [@bs] () ->
catcher exn cb)
| None ->
on_next ~noStack (fun [@bs] () ->
cb err ret [@bs])
in
current cb
let (||>) = fun a b ->
catch a b
let pipe ?(noStack=false) current fn cb =
current (fun [@bs] err ret ->
match Js.toOption err with
| Some exn ->
on_next ~noStack (fun [@bs] () ->
fail exn cb)
| None ->
on_next ~noStack (fun [@bs] () ->
try
let ret =
try
fn ret
with exn -> raise (Error exn)
in
return ret cb
with Error exn ->
fail exn cb))
let (>|) = fun a b ->
pipe a b
let ensure ?(noStack=false) current ensure cb =
current (fun [@bs] err ret ->
on_next ~noStack (fun [@bs] () ->
ensure () (fun [@bs] _ _ ->
cb err ret [@bs])))
let (&>) = fun a b ->
ensure a b
let ensure_pipe ?(noStack=false) current ensure cb =
current (fun [@bs] err ret ->
on_next ~noStack (fun [@bs] () ->
begin
try
ensure ()
with _ -> ()
end;
cb err ret [@bs]))
let (|&>) current ensure cb =
ensure_pipe current ensure cb
let discard fn cb =
fn (fun [@bs] err _ ->
cb err () [@bs])
let repeat condition computation cb =
let rec exec () =
condition () (fun [@bs] err ret ->
match Js.Nullable.isNullable err, ret with
| true, true ->
computation () (fun [@bs] err ret ->
if Js.Nullable.isNullable err then
cb err ret [@bs]
else
setTimeout (fun [@bs] () ->
exec ()) 0.)
| _ -> cb err () [@bs])
in
setTimeout (fun [@bs] () ->
exec ()) 0.
let repeat_unless condition computation =
let condition () cb =
condition () (fun [@bs] err ret ->
cb err (not ret) [@bs])
in
repeat condition computation
let async_if cond computation cb =
cond (fun [@bs] err ret ->
match Js.Nullable.isNullable err, ret with
| false, _
| _, false -> cb err () [@bs]
| _ -> computation () cb)
let async_unless cond computation cb =
let cond cb =
cond (fun [@bs] err ret ->
cb err (not ret) [@bs])
in
async_if cond computation cb
let itera ?(concurrency=1) fn a cb =
let total = Array.length a in
let executed = ref 0 in
let failed = ref false in
let rec process () =
let on_done () =
incr executed;
match !failed, !executed with
| true, _ -> ()
| false, n when n = total ->
return () cb
| _ ->
setTimeout (fun [@bs] () -> process ()) 0.
in
match Js.Array.shift a with
| Some v ->
fn v (fun [@bs] err () ->
match Js.toOption err with
| Some exn ->
if not !failed then
fail exn cb;
failed := true
| None -> on_done ())
| None -> ()
in
if total = 0 then
return () cb
else
for _ = 1 to min total concurrency do
setTimeout (fun [@bs] () -> process ()) 0.
done
let iter ?concurrency fn l =
itera ?concurrency fn (Array.of_list l)
let fold_lefta ?concurrency fn a ba =
let cur = ref a in
let fn b =
!cur >> fun a ->
cur := fn a b;
return ()
in
itera ?concurrency fn ba >> fun () ->
!cur
let fold_left ?concurrency fn cur l =
fold_lefta ?concurrency fn cur (Array.of_list l)
let fold_lefti ?concurrency fn cur l =
let l =
List.mapi (fun idx el ->
(idx,el)) l
in
let fn cur (idx,el) =
fn cur idx el
in
fold_left ?concurrency fn cur l
let iteri ?concurrency fn l =
let l =
List.mapi (fun idx el ->
(idx,el)) l
in
let fn (idx,el) =
fn idx el
in
iter ?concurrency fn l
let mapa ?concurrency fn a =
let ret = [||] in
let map v =
fn v >> fun res ->
ignore(Js.Array.push res ret);
return ()
in
itera ?concurrency map a >> fun () ->
return ret
let map ?concurrency fn l =
mapa ?concurrency fn (Array.of_list l) >> fun ret ->
return (Array.to_list ret)
let mapi ?concurrency fn l =
let l =
List.mapi (fun idx el ->
(idx,el)) l
in
let fn (idx,el) =
fn idx el
in
map ?concurrency fn l
let seqa ?concurrency a =
itera ?concurrency (fun v -> v >> return) a
let seq ?concurrency l =
seqa ?concurrency (Array.of_list l)
let resolvea ?(resolver=fun _ -> return ()) ~concurrency a =
let resolving = ref [] in
let pop_resolving () =
match !resolving with
| el::tl ->
resolving := tl;
el ()
| _ -> ()
in
let wrap fn =
let can_resolve = ref false in
let callback = ref None in
let wrap cb = fun [@bs] err ret ->
cb err ret [@bs];
if Js.Nullable.isNullable err then
resolver ret (fun [@bs] _ _ ->
pop_resolving ())
in
let resolve () =
match !callback with
| None ->
can_resolve := true
| Some cb ->
fn cb
in
let fn cb =
if !can_resolve then
fn (wrap cb)
else
callback := Some (wrap cb)
in
can_resolve, resolve, fn
in
if Array.length a <= concurrency then
a
else
let mapped = Array.map wrap a in
let can_resolve =
Array.map (fun (can_resolve, _, fn) ->
can_resolve := true;
fn) (Js.Array.slice ~start:0 ~end_:concurrency mapped)
in
let pending =
Array.map (fun (_, resolve, fn) ->
resolving := resolve::!resolving;
fn) (Js.Array.sliceFrom concurrency mapped)
in
Array.append can_resolve pending
let resolve ?resolver ~concurrency l =
Array.to_list
(resolvea ?resolver ~concurrency (Array.of_list l))
let execute ?(exceptionHandler=fun exn -> raise exn) t cb =
t (fun [@bs] err ret ->
match Js.toOption err with
| None -> cb ret
| Some exn -> exceptionHandler exn)
let finish ?exceptionHandler t =
execute ?exceptionHandler t (fun _ -> ())
end
let from_promise p = fun cb ->
let on_success ret =
Callback.return ret cb;
Js.Promise.resolve ret
in
There 's an inherent conflict here between dynamically typed JS world
* and statically typed BS / OCaml world . The promise API says that the
* value returned by the onError handler determines the value or error
* with which the promise gets resolved .
* In JS world , that means that you can just do console.log and the promise
* gets resolved with null / unit whatever .
* But in statically typed world the promise is of type ' a and needs a
* type ' a to resolve and since this code is generic , we have no idea how
* to produce a value of type ' a. Also , if we return the original promise ,
* the runtime thinks that we 're not handling errors and complains about it .
* Thus : Obj.magic . 😳
* and statically typed BS/OCaml world. The promise API says that the
* value returned by the onError handler determines the value or error
* with which the promise gets resolved.
* In JS world, that means that you can just do console.log and the promise
* gets resolved with null/unit whatever.
* But in statically typed world the promise is of type 'a and needs a
* type 'a to resolve and since this code is generic, we have no idea how
* to produce a value of type 'a. Also, if we return the original promise,
* the runtime thinks that we're not handling errors and complains about it.
* Thus: Obj.magic. 😳 *)
let on_error err =
Callback.fail (Obj.magic err) cb;
Js.Promise.reject (Obj.magic err)
in
ignore(Js.Promise.then_ on_success p |> Js.Promise.catch on_error)
let to_promise fn =
Js.Promise.make (fun ~resolve ~reject ->
fn (fun [@bs] err ret ->
match Js.toOption err with
| Some exn -> reject exn [@bs]
| None -> resolve ret [@bs]))
module type Wrapper_t = sig
type 'a t
val return : 'a -> 'a t
val fail : exn -> 'a t
val to_callback : 'a t -> 'a Callback.t
val from_callback : 'a Callback.t -> 'a t
end
module Make(Wrapper:Wrapper_t) = struct
type 'a t = 'a Wrapper.t
let return = Wrapper.return
let fail = Wrapper.fail
let compose ?noStack p fn =
let c =
Wrapper.to_callback p
in
let fn v =
Wrapper.to_callback (fn v)
in
Wrapper.from_callback
(Callback.compose ?noStack c fn)
let (>>) = fun p fn -> compose p fn
let catch ?noStack p fn =
let c =
Wrapper.to_callback p
in
let fn v =
Wrapper.to_callback (fn v)
in
Wrapper.from_callback
(Callback.catch ?noStack c fn)
let (||>) = fun p fn -> catch p fn
let pipe ?noStack p fn =
let c =
Wrapper.to_callback p
in
Wrapper.from_callback
(Callback.pipe ?noStack c fn)
let (>|) = fun p fn -> pipe p fn
let ensure ?noStack p fn =
let c =
Wrapper.to_callback p
in
let c =
Callback.ensure ?noStack c (fun () ->
Wrapper.to_callback (fn ()))
in
Wrapper.from_callback c
let (&>) = fun p fn ->
ensure p fn
let ensure_pipe ?noStack p fn =
let c =
Wrapper.to_callback p
in
let c =
Callback.ensure_pipe ?noStack c fn
in
Wrapper.from_callback c
let (|&>) = fun p fn ->
ensure_pipe p fn
let discard p =
p >> (fun _ -> return ())
let repeat cond body =
let cond () =
Wrapper.to_callback (cond ())
in
let body () =
Wrapper.to_callback (body ())
in
let c =
Callback.repeat cond body
in
Wrapper.from_callback c
let repeat_unless cond body =
let cond () =
Wrapper.to_callback (cond ())
in
let body () =
Wrapper.to_callback (body ())
in
let c =
Callback.repeat_unless cond body
in
Wrapper.from_callback c
let async_if cond computation =
let cond =
Wrapper.to_callback cond
in
let computation () =
Wrapper.to_callback (computation ())
in
let c =
Callback.async_if cond computation
in
Wrapper.from_callback c
let async_unless cond computation =
let cond =
Wrapper.to_callback cond
in
let computation () =
Wrapper.to_callback (computation ())
in
let c =
Callback.async_unless cond computation
in
Wrapper.from_callback c
let fold_lefta ?concurrency fn p a =
let fn x y =
Wrapper.to_callback (fn x y)
in
let c =
Wrapper.to_callback p
in
Wrapper.from_callback
(Callback.fold_lefta ?concurrency fn c a)
let fold_left ?concurrency fn p l =
fold_lefta ?concurrency fn p (Array.of_list l)
let fold_lefti ?concurrency fn p l =
let fn x pos y =
Wrapper.to_callback (fn x pos y)
in
let c =
Wrapper.to_callback p
in
Wrapper.from_callback
(Callback.fold_lefti ?concurrency fn c l)
let itera ?concurrency fn a =
let fn x =
Wrapper.to_callback (fn x)
in
Wrapper.from_callback
(Callback.itera ?concurrency fn a)
let iter ?concurrency fn l =
itera ?concurrency fn (Array.of_list l)
let iteri ?concurrency fn l =
let fn pos x =
Wrapper.to_callback (fn pos x)
in
Wrapper.from_callback
(Callback.iteri ?concurrency fn l)
let mapa ?concurrency fn a =
let fn x =
Wrapper.to_callback (fn x)
in
Wrapper.from_callback
(Callback.mapa ?concurrency fn a)
let map ?concurrency fn l =
mapa ?concurrency fn (Array.of_list l) >> fun a ->
return (Array.to_list a)
let mapi ?concurrency fn l =
let fn pos x =
Wrapper.to_callback (fn pos x)
in
Wrapper.from_callback
(Callback.mapi ?concurrency fn l)
let seqa ?concurrency a =
let a =
Array.map Wrapper.to_callback a
in
Wrapper.from_callback
(Callback.seqa ?concurrency a)
let seq ?concurrency l =
seqa ?concurrency (Array.of_list l)
let resolvea ?resolver ~concurrency a =
let resolver =
match resolver with
| None ->
None
| Some fn ->
Some (fun x ->
Wrapper.to_callback (fn x))
in
let a =
Array.map Wrapper.to_callback a
in
Array.map Wrapper.from_callback
(Callback.resolvea ?resolver ~concurrency a)
let resolve ?resolver ~concurrency l =
Array.to_list
(resolvea ?resolver ~concurrency (Array.of_list l))
let execute ?exceptionHandler p cb =
Callback.execute ?exceptionHandler
(Wrapper.to_callback p) cb
let finish ?exceptionHandler p =
execute ?exceptionHandler p (fun () -> ())
end
module PromiseWrapper = struct
type 'a t = 'a Js.Promise.t
let return = Js.Promise.resolve
let fail = Js.Promise.reject
let to_callback = from_promise
let from_callback = to_promise
end
module Promise = struct
include Make(PromiseWrapper)
let compose ?noStack:_ p fn =
Js.Promise.then_ fn p
let (>>) = fun p fn ->
compose p fn
let catch ?noStack:_ p fn =
Js.Promise.catch (fun exn ->
fn (Obj.magic exn)) p
let (||>) = fun p fn ->
catch p fn
let pipe ?noStack:_ p fn =
compose p (fun v ->
return (fn v))
let (>|) = fun p fn ->
pipe p fn
let ensure ?noStack:_ p fn =
ensure ~noStack:true p fn
let (&>) p fn =
ensure p fn
end
|
ee02c258e803146a4e5ebbd3032a06ea1e59d9a6a906132ed6b1a177af91dff4 | adamschoenemann/clofrp | Interop.hs |
|
Module : CloFRP.Interop
Description : Reflecting CloFRP - Types into the type - system
Module : CloFRP.Interop
Description : Reflecting CloFRP-Types into the Haskell type-system
-}
# LANGUAGE AutoDeriveTypeable #
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
{-# LANGUAGE KindSignatures #-}
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
{-# LANGUAGE StandaloneDeriving #-}
# LANGUAGE TemplateHaskell #
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE QuasiQuotes #-}
# LANGUAGE TypeApplications #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
# LANGUAGE UndecidableInstances #
{-# LANGUAGE OverloadedStrings #-}
module CloFRP.Interop where
import GHC.TypeLits
import Language.Haskell.TH ( Exp (..), ExpQ, Lit (..), Pat (..), Q
, DecQ, mkName, runQ)
import qualified Language.Haskell.TH.Syntax as S
import qualified Language.Haskell.TH as T
import Data.Data
import Debug.Trace
import qualified CloFRP.AST as P
import CloFRP.AST (PolyType, TySort(..))
import CloFRP.Annotated
import CloFRP.AST.Helpers
import CloFRP.Eval
import CloFRP.Pretty
-- -----------------------------------------------------------------------------
CloTy
-- -----------------------------------------------------------------------------
infixr 0 :->:
infixl 9 :@:
-- | The type of CloFRP-types that can be reflected
data CloTy
= CTFree Symbol
| CTTuple [CloTy]
| CloTy :->: CloTy
| CloTy :@: CloTy
deriving ( Show , Eq , Typeable , Data )
-- -----------------------------------------------------------------------------
-- Sing
-- -----------------------------------------------------------------------------
-- |Singleton representation to lift Ty into types
-- using kind-promotion
data Sing :: CloTy -> * where
SFree :: KnownSymbol s => Proxy s -> Sing ('CTFree s)
SPair :: Sing t1 -> Sing t2 -> Sing ('CTTuple '[t1, t2])
STup :: Sing t -> Sing ('CTTuple ts) -> Sing ('CTTuple (t ': ts))
SApp :: Sing t1 -> Sing t2 -> Sing (t1 ':@: t2)
SArr :: Sing t1 -> Sing t2 -> Sing (t1 ':->: t2)
instance Show (Sing ct) where
show sng = case sng of
SFree px -> symbolVal px
t1 `SArr` t2 -> show t1 ++ " -> " ++ show t2
t1 `SApp` t2 -> "(" ++ show t1 ++ " " ++ show t2 ++ ")"
t1 `SPair` t2 -> "(" ++ show t1 ++ ", " ++ show t2 ++ ")"
STup t ts ->
"(" ++ show t ++ ", " ++ tupShow ts
where
tupShow :: Sing ('CTTuple ts') -> String
tupShow (SPair x y) = show x ++ ", " ++ show y ++ ")"
tupShow (STup t' ts') = show t' ++ ", " ++ tupShow ts'
deriving instance Eq (Sing a)
-- deriving instance Show (Sing a)
deriving instance Typeable (Sing a)
-- |Reify a singleton back into an CloFRP type. Not used presently
reifySing :: Sing t -> PolyType ()
reifySing = \case
SFree px -> A () $ P.TFree (P.UName $ symbolVal px)
t1 `SArr` t2 -> A () $ reifySing t1 P.:->: reifySing t2
t1 `SApp` t2 -> A () $ reifySing t1 `P.TApp` reifySing t2
t1 `SPair` t2 -> A () $ P.TTuple [reifySing t1, reifySing t2]
STup t ts ->
A () $ P.TTuple (reifySing t : tupleSing ts)
where
tupleSing :: Sing (CTTuple ts') -> [PolyType ()]
tupleSing (SPair x y) = [reifySing x, reifySing y]
tupleSing (STup t' ts') = reifySing t' : tupleSing ts'
infixr 0 `SArr`
infixl 9 `SApp`
infixr 8 `STup`
-- -----------------------------------------------------------------------------
-- CloFRP
-- -----------------------------------------------------------------------------
-- |An FRP program of a type, executed in an environment
data CloFRP :: CloTy -> * -> * where
CloFRP :: EvalRead a -> EvalState a -> P.Expr a -> Sing t -> CloFRP t a
deriving instance Typeable a => Typeable (CloFRP t a)
instance Show (CloFRP t a) where
show (CloFRP er es expr sing) = pps expr
-- |Use template haskell to generate a singleton value that represents
-- a CloFRP type
typeToSingExp :: PolyType a -> ExpQ
typeToSingExp (A _ typ') = case typ' of
P.TFree (P.UName nm) ->
let nmQ = pure (S.LitT (S.StrTyLit nm))
in [| SFree (Proxy :: (Proxy $(nmQ))) |]
t1 P.:->: t2 ->
let s1 = typeToSingExp t1
s2 = typeToSingExp t2
in [| $(s1) `SArr` $(s2) |]
t1 `P.TApp` t2 ->
let s1 = typeToSingExp t1
s2 = typeToSingExp t2
in [| $(s1) `SApp` $(s2) |]
P.TTuple ts ->
case ts of
(x1 : x2 : xs) -> do
let s1 = typeToSingExp x1
s2 = typeToSingExp x2
base = [| $(s1) `SPair` $(s2) |]
foldr (\x acc -> [| STup $(typeToSingExp x) $(acc) |]) base xs
_ -> fail $ "Cannot convert tuples of " ++ show (length ts) ++ " elements"
_ -> fail "Can only convert free types, tuples, and arrow types atm"
class ToHask (t :: CloTy) (r :: *) | t -> r where
toHask :: Sing t -> Value a -> r
class ToCloFRP (r :: *) (t :: CloTy) | t -> r where
toCloFRP :: Sing t -> r -> Value a
instance ToHask ('CTFree "Int") Integer where
toHask _ (Prim (IntVal i)) = i
toHask _ v = error $ "expected int but got " ++ pps v
instance ToCloFRP Integer ('CTFree "Int") where
toCloFRP _ i = Prim (IntVal i)
instance (ToCloFRP h1 c1, ToCloFRP h2 c2) => ToCloFRP (h1, h2) ('CTTuple [c1, c2]) where
toCloFRP (SPair s1 s2) (x1, x2) = Tuple [toCloFRP s1 x1, toCloFRP s2 x2]
toCloFRP (STup ss s) (x1, x2) = error "impossible" -- Tuple [toCloFRP s1 x1, toCloFRP s2 x2]
instance (ToHask c1 h1, ToHask c2 h2) => ToHask ('CTTuple [c1, c2]) (h1, h2) where
toHask (SPair s1 s2) (Tuple [x1, x2]) = (toHask s1 x1, toHask s2 x2)
toHask _ v = error $ show $ "Expected tuple but got" <+> pretty v
ca nt make this inductive , since tuples are not inductive in .
alternatively , one could marshall to HList instead which would allow it
instance (ToHask c1 h1, ToHask c2 h2, ToHask c3 h3) => ToHask ('CTTuple '[c1,c2,c3]) (h1,h2,h3) where
toHask (s1 `STup` (s2 `SPair` s3)) (Tuple [x1,x2,x3]) = (toHask s1 x1, toHask s2 x2, toHask s3 x3)
toHask _ v = error $ show $ "Expected tuple but got" <+> pretty v
execute :: (Pretty a, ToHask t r) => CloFRP t a -> r
execute (CloFRP er st expr sing) = toHask sing $ runEvalMState (evalExprCorec expr) er st
runCloFRP :: (Pretty a) => CloFRP t a -> Value a
runCloFRP (CloFRP er st expr sing) = runEvalMState (evalExprCorec expr) er st
stepCloFRP :: (Pretty a) => CloFRP t a -> Value a
stepCloFRP (CloFRP er st expr sing) = runEvalMState (evalExprStep expr) er st
transform :: (Pretty a, ToCloFRP hask1 clott1, ToHask clott2 hask2)
=> CloFRP (clott1 :->: clott2) a -> hask1 -> hask2
transform (CloFRP er st expr (SArr s1 s2)) input = toHask s2 $ runEvalMState (evl expr) er st where
evl e = do
Closure cenv nm ne <- evalExprStep e
let inv = toCloFRP s1 input
let cenv' = extendEnv nm inv cenv
withEnv (combine cenv') $ evalExprCorec ne
-- TODO: Generalizing these things is not easy
evalExprOver :: forall a. Pretty a => [(Value a)] -> P.Expr a -> EvalM a (Value a)
evalExprOver f = foldr mapping (const $ pure $ runtimeErr "End of input") f where
mapping :: Value a -> (P.Expr a -> EvalM a (Value a)) -> (P.Expr a -> EvalM a (Value a))
mapping x accfn expr = do
v <- withInput x $ evalExprStep expr
case v of
Fold (Constr "Cons" [y, TickClosure cenv nm e]) -> do
cont <- withEnv (const $ extendEnv nm (Prim Tick) cenv) $ accfn e
pure $ Fold $ Constr "Cons" [y, cont]
_ -> error (pps v)
streamTrans :: (Pretty a, ToCloFRP hask1 clott1, ToHask clott2 hask2, KnownSymbol k)
=> CloFRP ('CTFree "Stream" ':@: 'CTFree k ':@: clott1
':->:
'CTFree "Stream" ':@: 'CTFree k ':@: clott2) a
-> [hask1] -> [hask2]
streamTrans (CloFRP er st expr ((s1 `SApp` _ `SApp` s2) `SArr` (s3 `SApp` s4 `SApp` s5))) input = do
fromCloFRPStream $ runEvalMState (begin input) er st
where
begin xs = do
Closure env nm e@(A ann _) <- evalExprStep expr
let e' = P.substExpr (P.Prim P.Input) nm e
let inputs = map (makeInput ann) xs
withEnv (const env) $ evalExprOver inputs e'
makeInput ann z = Fold $ Constr "Cons" [toCloFRP s2 z, TickClosure mempty "_" $ A ann $ P.Prim P.Input]
fromCloFRPStream (Fold (Constr "Cons" [v, c])) = toHask s5 v : fromCloFRPStream c
fromCloFRPStream v = error $ "fromCloFRPStream:" ++ pps v | null | https://raw.githubusercontent.com/adamschoenemann/clofrp/c26f86aec2cdb8fa7fd317acd13f7d77af984bd3/library/CloFRP/Interop.hs | haskell | # LANGUAGE DataKinds #
# LANGUAGE DeriveDataTypeable #
# LANGUAGE KindSignatures #
# LANGUAGE RankNTypes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeOperators #
# LANGUAGE QuasiQuotes #
# LANGUAGE OverloadedStrings #
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
| The type of CloFRP-types that can be reflected
-----------------------------------------------------------------------------
Sing
-----------------------------------------------------------------------------
|Singleton representation to lift Ty into types
using kind-promotion
deriving instance Show (Sing a)
|Reify a singleton back into an CloFRP type. Not used presently
-----------------------------------------------------------------------------
CloFRP
-----------------------------------------------------------------------------
|An FRP program of a type, executed in an environment
|Use template haskell to generate a singleton value that represents
a CloFRP type
Tuple [toCloFRP s1 x1, toCloFRP s2 x2]
TODO: Generalizing these things is not easy |
|
Module : CloFRP.Interop
Description : Reflecting CloFRP - Types into the type - system
Module : CloFRP.Interop
Description : Reflecting CloFRP-Types into the Haskell type-system
-}
# LANGUAGE AutoDeriveTypeable #
# LANGUAGE FlexibleInstances #
# LANGUAGE GADTs #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeApplications #
# LANGUAGE LambdaCase #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE FunctionalDependencies #
# LANGUAGE UndecidableInstances #
module CloFRP.Interop where
import GHC.TypeLits
import Language.Haskell.TH ( Exp (..), ExpQ, Lit (..), Pat (..), Q
, DecQ, mkName, runQ)
import qualified Language.Haskell.TH.Syntax as S
import qualified Language.Haskell.TH as T
import Data.Data
import Debug.Trace
import qualified CloFRP.AST as P
import CloFRP.AST (PolyType, TySort(..))
import CloFRP.Annotated
import CloFRP.AST.Helpers
import CloFRP.Eval
import CloFRP.Pretty
CloTy
infixr 0 :->:
infixl 9 :@:
data CloTy
= CTFree Symbol
| CTTuple [CloTy]
| CloTy :->: CloTy
| CloTy :@: CloTy
deriving ( Show , Eq , Typeable , Data )
data Sing :: CloTy -> * where
SFree :: KnownSymbol s => Proxy s -> Sing ('CTFree s)
SPair :: Sing t1 -> Sing t2 -> Sing ('CTTuple '[t1, t2])
STup :: Sing t -> Sing ('CTTuple ts) -> Sing ('CTTuple (t ': ts))
SApp :: Sing t1 -> Sing t2 -> Sing (t1 ':@: t2)
SArr :: Sing t1 -> Sing t2 -> Sing (t1 ':->: t2)
instance Show (Sing ct) where
show sng = case sng of
SFree px -> symbolVal px
t1 `SArr` t2 -> show t1 ++ " -> " ++ show t2
t1 `SApp` t2 -> "(" ++ show t1 ++ " " ++ show t2 ++ ")"
t1 `SPair` t2 -> "(" ++ show t1 ++ ", " ++ show t2 ++ ")"
STup t ts ->
"(" ++ show t ++ ", " ++ tupShow ts
where
tupShow :: Sing ('CTTuple ts') -> String
tupShow (SPair x y) = show x ++ ", " ++ show y ++ ")"
tupShow (STup t' ts') = show t' ++ ", " ++ tupShow ts'
deriving instance Eq (Sing a)
deriving instance Typeable (Sing a)
reifySing :: Sing t -> PolyType ()
reifySing = \case
SFree px -> A () $ P.TFree (P.UName $ symbolVal px)
t1 `SArr` t2 -> A () $ reifySing t1 P.:->: reifySing t2
t1 `SApp` t2 -> A () $ reifySing t1 `P.TApp` reifySing t2
t1 `SPair` t2 -> A () $ P.TTuple [reifySing t1, reifySing t2]
STup t ts ->
A () $ P.TTuple (reifySing t : tupleSing ts)
where
tupleSing :: Sing (CTTuple ts') -> [PolyType ()]
tupleSing (SPair x y) = [reifySing x, reifySing y]
tupleSing (STup t' ts') = reifySing t' : tupleSing ts'
infixr 0 `SArr`
infixl 9 `SApp`
infixr 8 `STup`
data CloFRP :: CloTy -> * -> * where
CloFRP :: EvalRead a -> EvalState a -> P.Expr a -> Sing t -> CloFRP t a
deriving instance Typeable a => Typeable (CloFRP t a)
instance Show (CloFRP t a) where
show (CloFRP er es expr sing) = pps expr
typeToSingExp :: PolyType a -> ExpQ
typeToSingExp (A _ typ') = case typ' of
P.TFree (P.UName nm) ->
let nmQ = pure (S.LitT (S.StrTyLit nm))
in [| SFree (Proxy :: (Proxy $(nmQ))) |]
t1 P.:->: t2 ->
let s1 = typeToSingExp t1
s2 = typeToSingExp t2
in [| $(s1) `SArr` $(s2) |]
t1 `P.TApp` t2 ->
let s1 = typeToSingExp t1
s2 = typeToSingExp t2
in [| $(s1) `SApp` $(s2) |]
P.TTuple ts ->
case ts of
(x1 : x2 : xs) -> do
let s1 = typeToSingExp x1
s2 = typeToSingExp x2
base = [| $(s1) `SPair` $(s2) |]
foldr (\x acc -> [| STup $(typeToSingExp x) $(acc) |]) base xs
_ -> fail $ "Cannot convert tuples of " ++ show (length ts) ++ " elements"
_ -> fail "Can only convert free types, tuples, and arrow types atm"
class ToHask (t :: CloTy) (r :: *) | t -> r where
toHask :: Sing t -> Value a -> r
class ToCloFRP (r :: *) (t :: CloTy) | t -> r where
toCloFRP :: Sing t -> r -> Value a
instance ToHask ('CTFree "Int") Integer where
toHask _ (Prim (IntVal i)) = i
toHask _ v = error $ "expected int but got " ++ pps v
instance ToCloFRP Integer ('CTFree "Int") where
toCloFRP _ i = Prim (IntVal i)
instance (ToCloFRP h1 c1, ToCloFRP h2 c2) => ToCloFRP (h1, h2) ('CTTuple [c1, c2]) where
toCloFRP (SPair s1 s2) (x1, x2) = Tuple [toCloFRP s1 x1, toCloFRP s2 x2]
instance (ToHask c1 h1, ToHask c2 h2) => ToHask ('CTTuple [c1, c2]) (h1, h2) where
toHask (SPair s1 s2) (Tuple [x1, x2]) = (toHask s1 x1, toHask s2 x2)
toHask _ v = error $ show $ "Expected tuple but got" <+> pretty v
ca nt make this inductive , since tuples are not inductive in .
alternatively , one could marshall to HList instead which would allow it
instance (ToHask c1 h1, ToHask c2 h2, ToHask c3 h3) => ToHask ('CTTuple '[c1,c2,c3]) (h1,h2,h3) where
toHask (s1 `STup` (s2 `SPair` s3)) (Tuple [x1,x2,x3]) = (toHask s1 x1, toHask s2 x2, toHask s3 x3)
toHask _ v = error $ show $ "Expected tuple but got" <+> pretty v
execute :: (Pretty a, ToHask t r) => CloFRP t a -> r
execute (CloFRP er st expr sing) = toHask sing $ runEvalMState (evalExprCorec expr) er st
runCloFRP :: (Pretty a) => CloFRP t a -> Value a
runCloFRP (CloFRP er st expr sing) = runEvalMState (evalExprCorec expr) er st
stepCloFRP :: (Pretty a) => CloFRP t a -> Value a
stepCloFRP (CloFRP er st expr sing) = runEvalMState (evalExprStep expr) er st
transform :: (Pretty a, ToCloFRP hask1 clott1, ToHask clott2 hask2)
=> CloFRP (clott1 :->: clott2) a -> hask1 -> hask2
transform (CloFRP er st expr (SArr s1 s2)) input = toHask s2 $ runEvalMState (evl expr) er st where
evl e = do
Closure cenv nm ne <- evalExprStep e
let inv = toCloFRP s1 input
let cenv' = extendEnv nm inv cenv
withEnv (combine cenv') $ evalExprCorec ne
evalExprOver :: forall a. Pretty a => [(Value a)] -> P.Expr a -> EvalM a (Value a)
evalExprOver f = foldr mapping (const $ pure $ runtimeErr "End of input") f where
mapping :: Value a -> (P.Expr a -> EvalM a (Value a)) -> (P.Expr a -> EvalM a (Value a))
mapping x accfn expr = do
v <- withInput x $ evalExprStep expr
case v of
Fold (Constr "Cons" [y, TickClosure cenv nm e]) -> do
cont <- withEnv (const $ extendEnv nm (Prim Tick) cenv) $ accfn e
pure $ Fold $ Constr "Cons" [y, cont]
_ -> error (pps v)
streamTrans :: (Pretty a, ToCloFRP hask1 clott1, ToHask clott2 hask2, KnownSymbol k)
=> CloFRP ('CTFree "Stream" ':@: 'CTFree k ':@: clott1
':->:
'CTFree "Stream" ':@: 'CTFree k ':@: clott2) a
-> [hask1] -> [hask2]
streamTrans (CloFRP er st expr ((s1 `SApp` _ `SApp` s2) `SArr` (s3 `SApp` s4 `SApp` s5))) input = do
fromCloFRPStream $ runEvalMState (begin input) er st
where
begin xs = do
Closure env nm e@(A ann _) <- evalExprStep expr
let e' = P.substExpr (P.Prim P.Input) nm e
let inputs = map (makeInput ann) xs
withEnv (const env) $ evalExprOver inputs e'
makeInput ann z = Fold $ Constr "Cons" [toCloFRP s2 z, TickClosure mempty "_" $ A ann $ P.Prim P.Input]
fromCloFRPStream (Fold (Constr "Cons" [v, c])) = toHask s5 v : fromCloFRPStream c
fromCloFRPStream v = error $ "fromCloFRPStream:" ++ pps v |
c4ca10f996f94245ccd3190e6566518487f6e6e7fbeafde56dc750bbb2dd133d | RDTK/generator | package.lisp | ;;;; package.lisp --- Package for tests of the model.variables module.
;;;;
Copyright ( C ) 2018 , 2019 Jan Moringen
;;;;
Author : < >
(cl:defpackage #:build-generator.model.variables.test
(:use
#:cl
#:alexandria
#:let-plus
#:fiveam
#:build-generator.model.variables)
(:import-from #:build-generator.model.variables
#:merge-alists))
(cl:in-package #:build-generator.model.variables.test)
(def-suite :build-generator.model.variables
:in :build-generator)
| null | https://raw.githubusercontent.com/RDTK/generator/8d9e6e47776f2ccb7b5ed934337d2db50ecbe2f5/test/model/variables/package.lisp | lisp | package.lisp --- Package for tests of the model.variables module.
| Copyright ( C ) 2018 , 2019 Jan Moringen
Author : < >
(cl:defpackage #:build-generator.model.variables.test
(:use
#:cl
#:alexandria
#:let-plus
#:fiveam
#:build-generator.model.variables)
(:import-from #:build-generator.model.variables
#:merge-alists))
(cl:in-package #:build-generator.model.variables.test)
(def-suite :build-generator.model.variables
:in :build-generator)
|
cd4e0989ebba90423f5947e9cdbf75ce76e3c075a610f31dc9688abd3a48776a | singleheart/programming-in-haskell | ex3.hs | type Board = [Int]
initial :: Board
initial = [5, 4, 3, 2, 1]
putRow :: Int -> Int -> IO ()
putRow row num = do
putStr (show row)
putStr ": "
putStrLn (concat (replicate num "* "))
putBoard :: Board -> IO ()
putBoard board = sequence_ [putRow idx row | (idx, row) <- zip [1 ..] board]
| null | https://raw.githubusercontent.com/singleheart/programming-in-haskell/80c7efc0425babea3cd982e47e121f19bec0aba9/ch10/ex3.hs | haskell | type Board = [Int]
initial :: Board
initial = [5, 4, 3, 2, 1]
putRow :: Int -> Int -> IO ()
putRow row num = do
putStr (show row)
putStr ": "
putStrLn (concat (replicate num "* "))
putBoard :: Board -> IO ()
putBoard board = sequence_ [putRow idx row | (idx, row) <- zip [1 ..] board]
| |
59143b2387f00ddbc8571db55f00ef1dea4399a4d99e7790718e8c88779cb35f | reasonml/reason | reason_omp.ml | (**************************************************************************)
(* *)
(* OCaml Migrate Parsetree *)
(* *)
, Jane Street Europe
(* *)
Copyright 2017 Institut National de Recherche en Informatique et
(* en Automatique (INRIA). *)
(* *)
(* 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. *)
(* *)
(**************************************************************************)
(*$ #use "src/cinaps_helpers" $*)
(* Shared definitions.
Mostly errors about features missing in older versions. *)
module Def = Migrate_parsetree_def
Copy of
$ foreach_version ( fun suffix _ - >
printf " module " suffix suffix
)
printf "module Ast_%s = Ast_%s\n" suffix suffix
)*)
module Ast_402 = Ast_402
module Ast_403 = Ast_403
module Ast_404 = Ast_404
module Ast_405 = Ast_405
module Ast_406 = Ast_406
module Ast_407 = Ast_407
module Ast_408 = Ast_408
module Ast_409 = Ast_409
module Ast_410 = Ast_410
module Ast_411 = Ast_411
module Ast_412 = Ast_412
module Ast_413 = Ast_413
module Ast_414 = Ast_414
module Ast_500 = Ast_500
(*$*)
A module for marshalling / unmarshalling arbitrary versions of Asts
module Ast_io = Migrate_parsetree_ast_io
(* Manual migration between versions *)
$ foreach_version_pair ( fun x y - >
printf " module " x y x y ;
printf " module " y x y x ;
)
printf "module Migrate_%s_%s = Migrate_parsetree_%s_%s\n" x y x y;
printf "module Migrate_%s_%s = Migrate_parsetree_%s_%s\n" y x y x;
)*)
module Migrate_402_403 = Migrate_parsetree_402_403
module Migrate_403_402 = Migrate_parsetree_403_402
module Migrate_403_404 = Migrate_parsetree_403_404
module Migrate_404_403 = Migrate_parsetree_404_403
module Migrate_404_405 = Migrate_parsetree_404_405
module Migrate_405_404 = Migrate_parsetree_405_404
module Migrate_405_406 = Migrate_parsetree_405_406
module Migrate_406_405 = Migrate_parsetree_406_405
module Migrate_406_407 = Migrate_parsetree_406_407
module Migrate_407_406 = Migrate_parsetree_407_406
module Migrate_407_408 = Migrate_parsetree_407_408
module Migrate_408_407 = Migrate_parsetree_408_407
module Migrate_408_409 = Migrate_parsetree_408_409
module Migrate_409_408 = Migrate_parsetree_409_408
module Migrate_409_410 = Migrate_parsetree_409_410
module Migrate_410_409 = Migrate_parsetree_410_409
module Migrate_410_411 = Migrate_parsetree_410_411
module Migrate_411_410 = Migrate_parsetree_411_410
module Migrate_411_412 = Migrate_parsetree_411_412
module Migrate_412_411 = Migrate_parsetree_412_411
module Migrate_412_413 = Migrate_parsetree_412_413
module Migrate_413_412 = Migrate_parsetree_413_412
module Migrate_413_414 = Migrate_parsetree_413_414
module Migrate_414_413 = Migrate_parsetree_414_413
module Migrate_414_500 = Migrate_parsetree_414_500
module Migrate_500_414 = Migrate_parsetree_500_414
(*$*)
(* An abstraction of OCaml compiler versions *)
module Versions = Migrate_parsetree_versions
(* All versions are compatible with this signature *)
module type OCaml_version = Versions.OCaml_version
(*$foreach_version (fun suffix _ ->
printf "module OCaml_%s = Versions.OCaml_%s\n" suffix suffix
)*)
module OCaml_402 = Versions.OCaml_402
module OCaml_403 = Versions.OCaml_403
module OCaml_404 = Versions.OCaml_404
module OCaml_405 = Versions.OCaml_405
module OCaml_406 = Versions.OCaml_406
module OCaml_407 = Versions.OCaml_407
module OCaml_408 = Versions.OCaml_408
module OCaml_409 = Versions.OCaml_409
module OCaml_410 = Versions.OCaml_410
module OCaml_411 = Versions.OCaml_411
module OCaml_412 = Versions.OCaml_412
module OCaml_413 = Versions.OCaml_413
module OCaml_414 = Versions.OCaml_414
module OCaml_500 = Versions.OCaml_500
(*$*)
module OCaml_current = Versions.OCaml_current
A Functor taking two OCaml versions and producing a module of functions
migrating from one to the other .
migrating from one to the other. *)
module Convert = Versions.Convert
(* A [Parse] module that migrate ASTs to the desired version of an AST *)
module Parse = Migrate_parsetree_parse
(* Entrypoints for registering rewriters and making a ppx binary *)
module Driver = Migrate_parsetree_driver
(* Aliases for compiler-libs modules that might be shadowed *)
module Compiler_libs = struct
module Location = Location
module Longident = Longident
module type Asttypes = module type of struct include Asttypes end
module rec Asttypes : Asttypes = Asttypes
module type Parsetree = module type of struct include Parsetree end
module rec Parsetree : Parsetree = Parsetree
module Docstrings = Docstrings
module Ast_helper = Ast_helper
module Ast_mapper = Ast_mapper
end
| null | https://raw.githubusercontent.com/reasonml/reason/3f433821d93bdc8f85677d4ee5d276ff6551c777/src/vendored-omp/src/reason_omp.ml | ocaml | ************************************************************************
OCaml Migrate Parsetree
en Automatique (INRIA).
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
$ #use "src/cinaps_helpers" $
Shared definitions.
Mostly errors about features missing in older versions.
$
Manual migration between versions
$
An abstraction of OCaml compiler versions
All versions are compatible with this signature
$foreach_version (fun suffix _ ->
printf "module OCaml_%s = Versions.OCaml_%s\n" suffix suffix
)
$
A [Parse] module that migrate ASTs to the desired version of an AST
Entrypoints for registering rewriters and making a ppx binary
Aliases for compiler-libs modules that might be shadowed |
, Jane Street Europe
Copyright 2017 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
module Def = Migrate_parsetree_def
Copy of
$ foreach_version ( fun suffix _ - >
printf " module " suffix suffix
)
printf "module Ast_%s = Ast_%s\n" suffix suffix
)*)
module Ast_402 = Ast_402
module Ast_403 = Ast_403
module Ast_404 = Ast_404
module Ast_405 = Ast_405
module Ast_406 = Ast_406
module Ast_407 = Ast_407
module Ast_408 = Ast_408
module Ast_409 = Ast_409
module Ast_410 = Ast_410
module Ast_411 = Ast_411
module Ast_412 = Ast_412
module Ast_413 = Ast_413
module Ast_414 = Ast_414
module Ast_500 = Ast_500
A module for marshalling / unmarshalling arbitrary versions of Asts
module Ast_io = Migrate_parsetree_ast_io
$ foreach_version_pair ( fun x y - >
printf " module " x y x y ;
printf " module " y x y x ;
)
printf "module Migrate_%s_%s = Migrate_parsetree_%s_%s\n" x y x y;
printf "module Migrate_%s_%s = Migrate_parsetree_%s_%s\n" y x y x;
)*)
module Migrate_402_403 = Migrate_parsetree_402_403
module Migrate_403_402 = Migrate_parsetree_403_402
module Migrate_403_404 = Migrate_parsetree_403_404
module Migrate_404_403 = Migrate_parsetree_404_403
module Migrate_404_405 = Migrate_parsetree_404_405
module Migrate_405_404 = Migrate_parsetree_405_404
module Migrate_405_406 = Migrate_parsetree_405_406
module Migrate_406_405 = Migrate_parsetree_406_405
module Migrate_406_407 = Migrate_parsetree_406_407
module Migrate_407_406 = Migrate_parsetree_407_406
module Migrate_407_408 = Migrate_parsetree_407_408
module Migrate_408_407 = Migrate_parsetree_408_407
module Migrate_408_409 = Migrate_parsetree_408_409
module Migrate_409_408 = Migrate_parsetree_409_408
module Migrate_409_410 = Migrate_parsetree_409_410
module Migrate_410_409 = Migrate_parsetree_410_409
module Migrate_410_411 = Migrate_parsetree_410_411
module Migrate_411_410 = Migrate_parsetree_411_410
module Migrate_411_412 = Migrate_parsetree_411_412
module Migrate_412_411 = Migrate_parsetree_412_411
module Migrate_412_413 = Migrate_parsetree_412_413
module Migrate_413_412 = Migrate_parsetree_413_412
module Migrate_413_414 = Migrate_parsetree_413_414
module Migrate_414_413 = Migrate_parsetree_414_413
module Migrate_414_500 = Migrate_parsetree_414_500
module Migrate_500_414 = Migrate_parsetree_500_414
module Versions = Migrate_parsetree_versions
module type OCaml_version = Versions.OCaml_version
module OCaml_402 = Versions.OCaml_402
module OCaml_403 = Versions.OCaml_403
module OCaml_404 = Versions.OCaml_404
module OCaml_405 = Versions.OCaml_405
module OCaml_406 = Versions.OCaml_406
module OCaml_407 = Versions.OCaml_407
module OCaml_408 = Versions.OCaml_408
module OCaml_409 = Versions.OCaml_409
module OCaml_410 = Versions.OCaml_410
module OCaml_411 = Versions.OCaml_411
module OCaml_412 = Versions.OCaml_412
module OCaml_413 = Versions.OCaml_413
module OCaml_414 = Versions.OCaml_414
module OCaml_500 = Versions.OCaml_500
module OCaml_current = Versions.OCaml_current
A Functor taking two OCaml versions and producing a module of functions
migrating from one to the other .
migrating from one to the other. *)
module Convert = Versions.Convert
module Parse = Migrate_parsetree_parse
module Driver = Migrate_parsetree_driver
module Compiler_libs = struct
module Location = Location
module Longident = Longident
module type Asttypes = module type of struct include Asttypes end
module rec Asttypes : Asttypes = Asttypes
module type Parsetree = module type of struct include Parsetree end
module rec Parsetree : Parsetree = Parsetree
module Docstrings = Docstrings
module Ast_helper = Ast_helper
module Ast_mapper = Ast_mapper
end
|
ea4f5aa7dd6a5928eb9163bd0ba86ab5c87beec7ebe5039550ac164cc097d195 | alex-hhh/ActivityLog2 | info.rkt | #lang info
;; info.rkt -- package definition for the the-application package
;;
;; This file is part of ActivityLog2 -- -hhh/ActivityLog2
Copyright ( c ) 2020 < >
;;
;; This program is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option )
;; any later version.
;;
;; This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
;; FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
;; more details.
;;
You should have received a copy of the GNU General Public License along
;; with this program. If not, see </>.
(define collection "the-application")
(define deps '("base"))
(define build-deps '())
(define scribblings '())
(define pkg-desc "provides basic application functions")
(define version "0.0")
(define pkg-authors '(aharsanyi))
| null | https://raw.githubusercontent.com/alex-hhh/ActivityLog2/36a4bb8af45db19cea02e982e22379acb18d0c49/pkgs/the-application/info.rkt | racket | info.rkt -- package definition for the the-application package
This file is part of ActivityLog2 -- -hhh/ActivityLog2
This program is free software: you can redistribute it and/or modify it
any later version.
This program is distributed in the hope that it will be useful, but WITHOUT
without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
with this program. If not, see </>. | #lang info
Copyright ( c ) 2020 < >
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 )
You should have received a copy of the GNU General Public License along
(define collection "the-application")
(define deps '("base"))
(define build-deps '())
(define scribblings '())
(define pkg-desc "provides basic application functions")
(define version "0.0")
(define pkg-authors '(aharsanyi))
|
721b2ab09259f2aee2489d8d4b4c903dd313b12dd72176590a5bc7208e01da18 | froggey/Mezzano | mass-storage.lisp | Copyright ( c ) 2019 ( )
This code is licensed under the MIT license .
;;======================================================================
;; Mass Storage Class Driver
;;======================================================================
(defpackage :mezzano.driver.usb.mass
(:use :cl :mezzano.driver.usb :mezzano.disk)
(:local-nicknames (:sup :mezzano.supervisor)
(:sync :mezzano.sync)
(:sys.int :mezzano.internals)))
(in-package :mezzano.driver.usb.mass)
(defvar *mass-storage* nil) ;; for debug
(defvar *trace-stream* sys.int::*cold-stream*)
(defvar *trace* 0)
(defmacro with-trace-level ((trace-level) &body body)
`(when (>= *trace* ,trace-level)
,@body))
(declaim (inline enter-function))
(defun enter-function (name)
(with-trace-level (1)
(sup:debug-print-line name)))
;;======================================================================
From USB Mass Storage Class Specification Overview Rev 1.4 Feb. 19 , 2020
;;======================================================================
(defconstant +mass-subclass-de-faco-scsi 0)
(defconstant +mass-subclass-rbc+ 1)
(defconstant +mass-subclass-atapi+ 2)
(defconstant +mass-subclass-obsolete-3+ 3)
(defconstant +mass-subclass-ufi+ 4)
(defconstant +mass-subclass-obsolete-5+ 5)
(defconstant +mass-subclass-scsi+ 6)
(defconstant +mass-subclass-lsd-fs+ 7)
(defconstant +mass-subclass-ieee-1667+ 8)
;;======================================================================
;; Command Block Wrapper Definitions
from USB Mass Storage Class Bulk - Only Transport Rev 1.0 Sept. 31 1999
;;======================================================================
(defconstant +cbw-signature+ 0)
(defconstant +cbw-tag+ 4)
(defconstant +cbw-transfer-length+ 8)
(defconstant +cbw-flags+ 12)
(defconstant +cbw-lun+ 13)
(defconstant +cbw-cb-length+ 14)
(defconstant +cbw-control-block+ 15)
CBWs are always 31 bytes , but only bytes 0 - ( 14 + + cbw - cb - length+ ) are valid
(defconstant +cbw-buffer-size+ 31)
(defconstant +cbw-signature-value+ #x43425355)
Only the MSB ( bit 7 ) of the flags is used , so just define the two values
(defconstant +cbw-flags-data-out+ #x00)
(defconstant +cbw-flags-data-in+ #x80)
;;======================================================================
;; Command Status Wrapper Definitions
from USB Mass Storage Class Bulk - Only Transport Rev 1.0 Sept. 31 1999
;;======================================================================
(defconstant +csw-signature+ 0)
(defconstant +csw-tag+ 4)
(defconstant +csw-data-residue+ 8)
(defconstant +cs2-status+ 12)
CSWs are always 13 bytes
(defconstant +csw-buffer-size+ 13)
(defconstant +csw-signature-value+ #x53425355)
(defconstant +csw-status-success+ 0)
(defconstant +csw-status-cmd-failed+ 1)
(defconstant +csw-phase-error+ 2)
3 - 4 Reserved - obsolete
5 - # xFF Reserved
#+nil
(define-constant +scsi-operation-code+ 0)
#+nil
(define-constant +scsi-flags+ 1)
(defconstant +scsi-code-inquiry+ #x12)
(defconstant +scsi-code-read/10+ #x28)
(defconstant +scsi-code-write/10+ #x2A)
(defconstant +scsi-code-read/16+ #x88)
(defconstant +scsi-code-write/16+ #x8A)
(defconstant +scsi-service-action+ #x9E)
(defconstant +scsi-code-read-capacity+ #x10)
;;======================================================================
Notes
;; Reset Recovery section 5.3.4
1 . A bulk - only mass storage reset
2 . A Clear Feature HALT to bulk - in endpoint
3 . A Clear Feature HALT to bulk - out endpont
I think these are all control endpoint messages first one is a class message ?
;;======================================================================
;;======================================================================
(defstruct mass-storage
usbd
device
interface
event
bulk-in-endpt-num
bulk-out-endpt-num
lock
cbw-tag
status
;; info from the inquiry command
vendor
product
revision
;; info from read capacity command
num-blocks
block-size
;;
disk
partitions
)
(defun next-cbw-tag (driver)
(sup:with-mutex ((mass-storage-lock driver))
(incf (mass-storage-cbw-tag driver))))
(defun timed-wait (event timeout)
(sup:with-timer (timer :relative timeout :name "Mass Storage timed wait")
(sync:wait-for-objects timer event)
(if (and (not (sup:event-state event)) (sup:timer-expired-p timer))
:timeout
:complete)))
;;======================================================================
;;======================================================================
(define-condition timeout-retry ()
((%endpoint :initarg :endpoint :reader timeout-endpoint)
(%enqueued-buf :initarg :enqueued-buf :reader timeout-enqueued-buf)))
(defun retry-operation (c)
(invoke-restart 'retry-operation
(timeout-endpoint c)
(timeout-enqueued-buf c)))
;;======================================================================
;;======================================================================
(defclass usb-ms-partition (disk-partition-mixin)
((%mass-storage :initarg :mass-storage :accessor dp-mass-storage)))
(defmethod block-device-sector-size ((partition usb-ms-partition))
(mass-storage-block-size (dp-mass-storage partition)))
(defmethod block-device-n-sectors ((partition usb-ms-partition))
(mass-storage-num-blocks (dp-mass-storage partition)))
(defclass usb-ms-disk (disk-mixin disk-pt-mixin)
((%mass-storage :initarg :mass-storage :accessor disk-mass-storage)))
(defmethod block-device-sector-size ((disk usb-ms-disk))
(mass-storage-block-size (disk-mass-storage disk)))
(defmethod block-device-n-sectors ((disk usb-ms-disk))
(mass-storage-num-blocks (disk-mass-storage disk)))
;;======================================================================
;;======================================================================
(defun encode-cbw (driver buf offset length in-p logical-unit)
(setf (get-unsigned-word/32 buf (+ offset +cbw-signature+))
+cbw-signature-value+
(get-unsigned-word/32 buf (+ offset +cbw-tag+))
(next-cbw-tag driver)
(get-unsigned-word/32 buf (+ offset +cbw-transfer-length+))
length
(aref buf (+ offset +cbw-flags+))
(if in-p +cbw-flags-data-in+ +cbw-flags-data-out+)
(aref buf (+ offset +cbw-lun+))
logical-unit))
(defun encode-scsi-inquiry (buf offset vital-p page length)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 6
(aref buf cbw-offset) +scsi-code-inquiry+
(aref buf (+ cbw-offset 1)) (if vital-p 1 0)
(aref buf (+ cbw-offset 2)) page
(get-unsigned-word/16 buf (+ cbw-offset 3)) length
TODO what about the NACA bit
(defun encode-scsi-read-capacity/10 (buf offset)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 10
(aref buf cbw-offset) #x25)
(dotimes (i 9)
(setf (aref buf (+ cbw-offset i 1)) 0))))
(defun encode-scsi-read-capacity/16 (buf offset length)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 16
(aref buf cbw-offset) +scsi-service-action+
(aref buf (+ cbw-offset 1)) +scsi-code-read-capacity+
(get-unsigned-word/32 buf (+ cbw-offset 2)) 0
(get-unsigned-word/32 buf (+ cbw-offset 6)) 0
(get-be-unsigned-word/32 buf (+ cbw-offset 10)) length
(aref buf (+ cbw-offset 14)) 0
(aref buf (+ cbw-offset 15)) 0)))
(defun encode-scsi-read/10 (buf offset lba n-blocks)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 10
(aref buf cbw-offset) +scsi-code-read/10+
(aref buf (+ cbw-offset 1)) 0
(get-be-unsigned-word/32 buf (+ cbw-offset 2)) lba
(aref buf (+ cbw-offset 6)) 0
(get-be-unsigned-word/16 buf (+ cbw-offset 7)) n-blocks
(aref buf (+ cbw-offset 9)) 0)))
(defun encode-scsi-write/10 (buf offset lba n-blocks)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 10
(aref buf cbw-offset) +scsi-code-write/10+
(aref buf (+ cbw-offset 1)) 0
(get-be-unsigned-word/32 buf (+ cbw-offset 2)) lba
(aref buf (+ cbw-offset 6)) 0
(get-be-unsigned-word/16 buf (+ cbw-offset 7)) n-blocks
(aref buf (+ cbw-offset 9)) 0)))
;;======================================================================
;;======================================================================
(defun send-buf (usbd device mass-storage endpoint buf length)
(let((event (mass-storage-event mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd device endpoint buf length)
(when (eq (timed-wait event 0.500) :timeout)
(sup:debug-print-line "send-buf timeout")
(signal 'timeout-retry :endpoint endpoint :enqueued-buf buf))))
(defun %read-sector (usbd device mass-storage lba buf offset)
(enter-function "%read-sector")
(let ((data-length (mass-storage-block-size mass-storage))
(out-endpoint (mass-storage-bulk-out-endpt-num mass-storage))
(in-endpoint (mass-storage-bulk-in-endpt-num mass-storage)))
(with-buffers ((buf-pool usbd) ((cmd-buf /8 31)
(data-buf /8 data-length)
(status-buf /8 13)))
(encode-cbw mass-storage cmd-buf 0 data-length T 0)
(encode-scsi-read/10 cmd-buf 0 lba 1)
(send-buf usbd device mass-storage out-endpoint cmd-buf 31)
(with-trace-level (4)
(sup:debug-print-line "%read-sector command status "
(mass-storage-status mass-storage)))
(send-buf usbd device mass-storage in-endpoint data-buf data-length)
(with-trace-level (3)
(sup:debug-print-line "read sector data buffer:")
(print-buffer sys.int::*cold-stream* data-buf :indent " ")
(sup:debug-print-line "read sector data status "
(mass-storage-status mass-storage)))
(send-buf usbd device mass-storage in-endpoint status-buf 13)
(with-trace-level (4)
(sup:debug-print-line "%read-sector status buffer:")
(print-buffer sys.int::*cold-stream* status-buf :indent " ")
(sup:debug-print-line "%read-sector status status "
(mass-storage-status mass-storage)))
(cond ((= (aref status-buf 12) 0)
;; Copy buffer
(dotimes (i data-length)
(setf (aref buf (+ offset i)) (aref data-buf i))))
((= (aref status-buf 12) 1)
;; Command failed
(error "%read-sector failed"))
((= (aref status-buf 12) 2)
(error "%read-sector failed with phase error"))
(T
(error "%read-sector failed with unknown error ~D"
(aref status-buf 12)))))))
(defun %block-device-read (mass-storage lba n-sectors buf offset)
(enter-function "%block-device-read")
(handler-bind
((timeout-retry #'retry-operation))
(loop
with usbd = (mass-storage-usbd mass-storage)
with device = (mass-storage-device mass-storage)
with sector-size = (mass-storage-block-size mass-storage)
with retry-count = 0
do
(restart-case
(progn
(when (<= n-sectors 0)
(return))
(%read-sector usbd device mass-storage lba buf offset)
(incf lba)
(incf offset sector-size)
(decf n-sectors))
(retry-operation (endpoint enqueued-buf)
(sup:debug-print-line "timeout on read lba: " lba)
;; clean up
(bulk-dequeue-buf usbd device endpoint enqueued-buf)
(reset-recovery usbd device mass-storage)
;; if too many retries, give up
(incf retry-count)
(when (= retry-count 5)
(error "Mass storage timeout on read")))))))
(defmethod block-device-read
((disk usb-ms-disk) lba n-sectors buf &key (offset 0))
(enter-function "block-device-read (mass-storage)")
(%block-device-read (disk-mass-storage disk) lba n-sectors buf offset))
(defmethod block-device-read
((partition usb-ms-partition) lba n-sectors buf &key (offset 0))
(enter-function "block-device-read (partition)")
(when (> (+ lba n-sectors) (dp-size partition))
(error "Attempt to read past end of partition, ~
LBA: ~D, read size ~D, partition size ~D"
lba n-sectors (dp-size partition)))
(%block-device-read (dp-mass-storage partition)
(+ lba (dp-start-lba partition))
n-sectors
buf
offset))
;;======================================================================
;;======================================================================
(defun %write-sector (usbd device mass-storage lba buf offset)
(enter-function "%write-sector")
(let ((data-length (mass-storage-block-size mass-storage))
(out-endpoint (mass-storage-bulk-out-endpt-num mass-storage))
(in-endpoint (mass-storage-bulk-in-endpt-num mass-storage)))
(with-buffers ((buf-pool usbd) ((cmd-buf /8 31)
(data-buf /8 data-length)
(status-buf /8 13)))
(encode-cbw mass-storage cmd-buf 0 data-length NIL 0)
(encode-scsi-write/10 cmd-buf 0 lba 1)
(send-buf usbd device mass-storage out-endpoint cmd-buf 31)
;; Copy buffer
(dotimes (i data-length)
(setf (aref data-buf i) (aref buf (+ offset i))))
(with-trace-level (4)
(sup:debug-print-line "%write-sector command status "
(mass-storage-status mass-storage)))
(send-buf usbd device mass-storage out-endpoint data-buf data-length)
(with-trace-level (3)
(sup:debug-print-line "write sector data buffer:")
(print-buffer sys.int::*cold-stream* data-buf :indent " ")
(sup:debug-print-line "write sector data status "
(mass-storage-status mass-storage)))
(send-buf usbd device mass-storage in-endpoint status-buf 13)
(with-trace-level (4)
(sup:debug-print-line "%write-sector status buffer:")
(print-buffer sys.int::*cold-stream* status-buf :indent " ")
(sup:debug-print-line "%write-sector status status "
(mass-storage-status mass-storage)))
(cond ((= (aref status-buf 12) 0)
Success - nothing else to do
)
((= (aref status-buf 12) 1)
;; Command failed
(error "%read-sector failed"))
((= (aref status-buf 12) 2)
(error "%write-sector failed with phase error"))
(T
(error "%write-sector failed with unknown error ~D"
(aref status-buf 12)))))))
(defun %block-device-write (mass-storage lba n-sectors buf offset)
(enter-function "block-device-write")
(handler-bind
((timeout-retry #'retry-operation))
(loop
with usbd = (mass-storage-usbd mass-storage)
with device = (mass-storage-device mass-storage)
with sector-size = (mass-storage-block-size mass-storage)
with retry-count = 0
do
(restart-case
(progn
(when (<= n-sectors 0)
(return))
(%write-sector usbd device mass-storage lba buf offset)
(incf lba)
(incf offset sector-size)
(decf n-sectors))
(retry-operation (endpoint enqueued-buf)
(sup:debug-print-line "timeout on write lba: " lba)
;; clean up
(bulk-dequeue-buf usbd device endpoint enqueued-buf)
(reset-recovery usbd device mass-storage)
;; if too many retries, give up
(incf retry-count)
(when (= retry-count 5)
(error "Mass storage timeout on write")))))))
(defmethod block-device-write
((disk usb-ms-disk) lba n-sectors buf &key (offset 0))
(enter-function "block-device-write (disk)")
(%block-device-write (disk-mass-storage disk) lba n-sectors buf offset))
(defmethod block-device-write
((partition usb-ms-partition) lba n-sectors buf &key (offset 0))
(enter-function "block-device-write (partition)")
(when (> (+ lba n-sectors) (dp-size partition))
(error "Attempt to write past end of partition, ~
LBA: ~D, write size ~D, partition size ~D"
lba n-sectors (dp-size partition)))
(%block-device-write (dp-mass-storage partition)
(+ lba (dp-start-lba partition))
n-sectors
buf
offset))
;;======================================================================
;;======================================================================
(defmethod block-device-flush ((mass-storage mass-storage))
(enter-function "block-device-flush")
)
;;======================================================================
;;======================================================================
(defun parse-endpt-descriptor (usbd device mass-storage endpt-desc)
(let* ((address (aref endpt-desc +ed-address+))
(endpt-in (ldb-test +ed-direction-field+ address))
(endpt-num (ldb +ed-endpt-num-field+ address)))
(when (/= (aref endpt-desc +ed-attributes+) +ed-attr-bulk+)
(sup:debug-print-line "Mass Storage Probe failed because "
"endpoint type is "
(aref endpt-desc +ed-attributes+)
" instead of a bulk endpoint")
(throw :probe-failed nil))
(create-bulk-endpt usbd
device
mass-storage
endpt-num
endpt-in
'mass-storage-int-callback)
(if endpt-in
(setf (mass-storage-bulk-in-endpt-num mass-storage) endpt-num)
(setf (mass-storage-bulk-out-endpt-num mass-storage) endpt-num))))
(defmethod delete-device ((mass-storage mass-storage) device)
;; Device has disconnected - clean up
;; terminate and transfers in progress
;; unmount device - deregister-disk? It's already gone so no operations allowed
(unregister-block-device (mass-storage-disk mass-storage))
(dolist (part (mass-storage-partitions mass-storage))
(unregister-block-device part)))
(defun parse-inquiry (usbd device mass-storage)
(enter-function "parse-inquiry")
(let ((data-length 36)
(event (mass-storage-event mass-storage)))
(with-buffers ((buf-pool usbd) ((cmd-buf /8 31)
(data-buf /8 data-length)
(status-buf /8 13)))
;; send inquiry command
(encode-cbw mass-storage cmd-buf 0 data-length T 0)
(encode-scsi-inquiry cmd-buf 0 NIL 0 data-length)
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-out-endpt-num mass-storage)
cmd-buf
31)
(with-trace-level (4)
(sup:debug-print-line "inquiry command buffer:")
(print-buffer sys.int::*cold-stream* cmd-buf :indent " "))
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage inquiry command timeout"))
(with-trace-level (4)
(sup:debug-print-line "inquiry command status"
(mass-storage-status mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-in-endpt-num mass-storage)
data-buf
data-length)
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage inquiry data timeout"))
(with-trace-level (3)
(sup:debug-print-line "inquiry data buffer:")
(print-buffer sys.int::*cold-stream* data-buf :indent " ")
(sup:debug-print-line "inquiry data status "
(mass-storage-status mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-in-endpt-num mass-storage)
status-buf
13)
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage inquiry status timeout"))
(with-trace-level (4)
(sup:debug-print-line "inquiry status buffer:")
(print-buffer sys.int::*cold-stream* status-buf :indent " ")
(sup:debug-print-line "inquiry status status "
(mass-storage-status mass-storage)))
(cond ((= (aref status-buf 12) 0)
;; success - process data-buffer
(setf (mass-storage-vendor mass-storage)
(string-right-trim " " (get-ascii-string data-buf 8 8))
(mass-storage-product mass-storage)
(string-right-trim " " (get-ascii-string data-buf 16 16))
(mass-storage-revision mass-storage)
(string-right-trim " " (get-ascii-string data-buf 32 4))))
((= (aref status-buf 12) 1)
;;command failed
(sup:debug-print-line "Mass Storage Probe failed because "
"Inquiry command failed")
(throw :probe-failed nil))
((= (aref status-buf 12) 2)
(sup:debug-print-line "Mass Storage Probe failed because "
"Inquiry command got phase error")
(throw :probe-failed nil))
(T
(sup:debug-print-line "Mass Storage Probe failed because "
"Inquiry failed with unkown error "
(aref status-buf 12))
(throw :probe-failed nil))))))
(defun parse-read-capacity (usbd device mass-storage cap/10-p)
(enter-function "parse-read-capacity")
(let ((data-length (if cap/10-p 8 32))
(event (mass-storage-event mass-storage)))
(with-buffers ((buf-pool usbd) ((cmd-buf /8 31)
(data-buf /8 data-length)
(status-buf /8 13)))
;; send read capacity command
(encode-cbw mass-storage cmd-buf 0 data-length T 0)
(if cap/10-p
(encode-scsi-read-capacity/10 cmd-buf 0)
(encode-scsi-read-capacity/16 cmd-buf 0 data-length))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-out-endpt-num mass-storage)
cmd-buf
31)
(with-trace-level (4)
(sup:debug-print-line "read capacity command buffer:")
(print-buffer sys.int::*cold-stream* cmd-buf :indent " "))
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage read capacity command timeout"))
(with-trace-level (4)
(sup:debug-print-line "read capacity command status "
(mass-storage-status mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-in-endpt-num mass-storage)
data-buf
data-length)
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage read capacity data timeout"))
(with-trace-level (3)
(sup:debug-print-line "read capacity data buffer:")
(print-buffer sys.int::*cold-stream* data-buf :indent " ")
(sup:debug-print-line "read capacity data status "
(mass-storage-status mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-in-endpt-num mass-storage)
status-buf
13)
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage read capacity status timeout"))
(with-trace-level (4)
(sup:debug-print-line "read capacity status buffer:")
(print-buffer sys.int::*cold-stream* status-buf :indent " ")
(sup:debug-print-line "read capacity status status "
(mass-storage-status mass-storage)))
(cond ((= (aref status-buf 12) 0)
;; success - process data-buffer
(if cap/10-p
(let ((block-addr (get-be-unsigned-word/32 data-buf 0)))
(cond ((= block-addr #xFFFFFFFF)
(parse-read-capacity usbd device mass-storage NIL))
(T
(setf (mass-storage-num-blocks mass-storage)
block-addr
(mass-storage-block-size mass-storage)
(get-be-unsigned-word/32 data-buf 4)))))
(setf (mass-storage-num-blocks mass-storage)
(get-be-unsigned-word/64 data-buf 0)
(mass-storage-block-size mass-storage)
(get-be-unsigned-word/32 data-buf 8))))
((= (aref status-buf 12) 1)
;;command failed
(sup:debug-print-line "Mass Storage Probe failed because "
"read capacity command failed")
(throw :probe-failed nil))
((= (aref status-buf 12) 2)
(sup:debug-print-line "Mass Storage Probe failed because "
"read capacity command got phase error")
(throw :probe-failed nil))
(T
(sup:debug-print-line "Mass Storage Probe failed because "
"read capacity failed with unkown error "
(aref status-buf 12))
(throw :probe-failed nil))))))
(defun probe-mass-storage-scsi (usbd device iface-desc configs)
(when (/= (aref iface-desc +id-num-endpoints+) 2)
(sup:debug-print-line "Mass Storage Probe failed because "
"interface descriptor has "
(aref iface-desc +id-num-endpoints+)
" endpoints, Only exactly 2 supported.")
(throw :probe-failed nil))
(let ((mass-storage (make-mass-storage
:usbd usbd
:device device
:interface (aref iface-desc +id-number+)
:event (sup:make-event
:name "Mass Storage Event")
:bulk-in-endpt-num nil
:bulk-out-endpt-num nil
:lock (sup:make-mutex "USB Mass Storage Lock")
:cbw-tag #x100)))
(dotimes (i 2)
(let ((endpt-desc (pop configs)))
(when (or (null endpt-desc)
(/= (aref endpt-desc +ed-type+) +desc-type-endpoint+))
(sup:debug-print-line "Mass Storage probe failed because "
"found descriptor type "
(aref endpt-desc +ed-type+)
" instead of endpoint descriptor.")
(throw :probe-failed nil))
(parse-endpt-descriptor usbd device mass-storage endpt-desc)))
(when (or (null (mass-storage-bulk-in-endpt-num mass-storage))
(null (mass-storage-bulk-out-endpt-num mass-storage)))
(sup:debug-print-line "Mass Storage probe failed because "
"did not have both in and out bulk endpoints")
(throw :probe-failed nil))
(parse-inquiry usbd device mass-storage)
(parse-read-capacity usbd device mass-storage T)
(with-trace-level (2)
(sup:debug-print-line "vendor: \""
(mass-storage-vendor mass-storage)
"\", product: \""
(mass-storage-product mass-storage)
"\", revision: \""
(mass-storage-revision mass-storage)
"\"")
(sup:debug-print-line "num blocks: #x"
(mass-storage-num-blocks mass-storage)
", block size: #x"
(mass-storage-block-size mass-storage)))
(setf (mass-storage-disk mass-storage)
(make-instance 'usb-ms-disk
:mass-storage mass-storage
;; TODO really determine writable
:writable-p T
:n-sectors (mass-storage-num-blocks mass-storage)
:sector-size (mass-storage-block-size mass-storage))
(mass-storage-partitions mass-storage)
(mapcar #'(lambda (part-info)
(apply #'make-instance 'usb-ms-partition
:mass-storage mass-storage
part-info))
(parse-partition-table (mass-storage-disk mass-storage))))
(register-block-device (mass-storage-disk mass-storage))
(dolist (part (mass-storage-partitions mass-storage))
(register-block-device part))
(setf *mass-storage* mass-storage)
(values configs mass-storage)))
(define-usb-class-driver "Mass Storage" 'probe-mass-storage-scsi
'((#.+id-class-mass-storage+ #.+mass-subclass-scsi+ #.+id-protocol-bulk-only+)))
(defun mass-storage-int-callback (mass-storage endpoint-num status length buf)
(setf (mass-storage-status mass-storage) status
(sup:event-state (mass-storage-event mass-storage)) T))
(defun reset-recovery (usbd device mass-storage)
(with-trace-level (0)
(sup:debug-print-line "reset-recovery"))
do n't want 0 length buf
(control-receive-data usbd
device
#b00100001 ;; Class, Interface, host to device
#xFF
0
(mass-storage-interface mass-storage)
0
buf)
(control-receive-data usbd
device
(encode-request-type +rt-dir-host-to-device+
+rt-type-standard+
+rt-rec-endpoint+)
+dev-req-clear-feature+
+feature-endpoint-halt+
(mass-storage-bulk-in-endpt-num mass-storage)
0
buf)
(control-receive-data usbd
device
(encode-request-type +rt-dir-host-to-device+
+rt-type-standard+
+rt-rec-endpoint+)
+dev-req-clear-feature+
+feature-endpoint-halt+
(mass-storage-bulk-out-endpt-num mass-storage)
0
buf)))
| null | https://raw.githubusercontent.com/froggey/Mezzano/f0eeb2a3f032098b394e31e3dfd32800f8a51122/drivers/usb/mass-storage.lisp | lisp | ======================================================================
Mass Storage Class Driver
======================================================================
for debug
======================================================================
======================================================================
======================================================================
Command Block Wrapper Definitions
======================================================================
======================================================================
Command Status Wrapper Definitions
======================================================================
======================================================================
Reset Recovery section 5.3.4
======================================================================
======================================================================
info from the inquiry command
info from read capacity command
======================================================================
======================================================================
======================================================================
======================================================================
======================================================================
======================================================================
======================================================================
======================================================================
Copy buffer
Command failed
clean up
if too many retries, give up
======================================================================
======================================================================
Copy buffer
Command failed
clean up
if too many retries, give up
======================================================================
======================================================================
======================================================================
======================================================================
Device has disconnected - clean up
terminate and transfers in progress
unmount device - deregister-disk? It's already gone so no operations allowed
send inquiry command
success - process data-buffer
command failed
send read capacity command
success - process data-buffer
command failed
TODO really determine writable
Class, Interface, host to device | Copyright ( c ) 2019 ( )
This code is licensed under the MIT license .
(defpackage :mezzano.driver.usb.mass
(:use :cl :mezzano.driver.usb :mezzano.disk)
(:local-nicknames (:sup :mezzano.supervisor)
(:sync :mezzano.sync)
(:sys.int :mezzano.internals)))
(in-package :mezzano.driver.usb.mass)
(defvar *trace-stream* sys.int::*cold-stream*)
(defvar *trace* 0)
(defmacro with-trace-level ((trace-level) &body body)
`(when (>= *trace* ,trace-level)
,@body))
(declaim (inline enter-function))
(defun enter-function (name)
(with-trace-level (1)
(sup:debug-print-line name)))
From USB Mass Storage Class Specification Overview Rev 1.4 Feb. 19 , 2020
(defconstant +mass-subclass-de-faco-scsi 0)
(defconstant +mass-subclass-rbc+ 1)
(defconstant +mass-subclass-atapi+ 2)
(defconstant +mass-subclass-obsolete-3+ 3)
(defconstant +mass-subclass-ufi+ 4)
(defconstant +mass-subclass-obsolete-5+ 5)
(defconstant +mass-subclass-scsi+ 6)
(defconstant +mass-subclass-lsd-fs+ 7)
(defconstant +mass-subclass-ieee-1667+ 8)
from USB Mass Storage Class Bulk - Only Transport Rev 1.0 Sept. 31 1999
(defconstant +cbw-signature+ 0)
(defconstant +cbw-tag+ 4)
(defconstant +cbw-transfer-length+ 8)
(defconstant +cbw-flags+ 12)
(defconstant +cbw-lun+ 13)
(defconstant +cbw-cb-length+ 14)
(defconstant +cbw-control-block+ 15)
CBWs are always 31 bytes , but only bytes 0 - ( 14 + + cbw - cb - length+ ) are valid
(defconstant +cbw-buffer-size+ 31)
(defconstant +cbw-signature-value+ #x43425355)
Only the MSB ( bit 7 ) of the flags is used , so just define the two values
(defconstant +cbw-flags-data-out+ #x00)
(defconstant +cbw-flags-data-in+ #x80)
from USB Mass Storage Class Bulk - Only Transport Rev 1.0 Sept. 31 1999
(defconstant +csw-signature+ 0)
(defconstant +csw-tag+ 4)
(defconstant +csw-data-residue+ 8)
(defconstant +cs2-status+ 12)
CSWs are always 13 bytes
(defconstant +csw-buffer-size+ 13)
(defconstant +csw-signature-value+ #x53425355)
(defconstant +csw-status-success+ 0)
(defconstant +csw-status-cmd-failed+ 1)
(defconstant +csw-phase-error+ 2)
3 - 4 Reserved - obsolete
5 - # xFF Reserved
#+nil
(define-constant +scsi-operation-code+ 0)
#+nil
(define-constant +scsi-flags+ 1)
(defconstant +scsi-code-inquiry+ #x12)
(defconstant +scsi-code-read/10+ #x28)
(defconstant +scsi-code-write/10+ #x2A)
(defconstant +scsi-code-read/16+ #x88)
(defconstant +scsi-code-write/16+ #x8A)
(defconstant +scsi-service-action+ #x9E)
(defconstant +scsi-code-read-capacity+ #x10)
Notes
1 . A bulk - only mass storage reset
2 . A Clear Feature HALT to bulk - in endpoint
3 . A Clear Feature HALT to bulk - out endpont
I think these are all control endpoint messages first one is a class message ?
(defstruct mass-storage
usbd
device
interface
event
bulk-in-endpt-num
bulk-out-endpt-num
lock
cbw-tag
status
vendor
product
revision
num-blocks
block-size
disk
partitions
)
(defun next-cbw-tag (driver)
(sup:with-mutex ((mass-storage-lock driver))
(incf (mass-storage-cbw-tag driver))))
(defun timed-wait (event timeout)
(sup:with-timer (timer :relative timeout :name "Mass Storage timed wait")
(sync:wait-for-objects timer event)
(if (and (not (sup:event-state event)) (sup:timer-expired-p timer))
:timeout
:complete)))
(define-condition timeout-retry ()
((%endpoint :initarg :endpoint :reader timeout-endpoint)
(%enqueued-buf :initarg :enqueued-buf :reader timeout-enqueued-buf)))
(defun retry-operation (c)
(invoke-restart 'retry-operation
(timeout-endpoint c)
(timeout-enqueued-buf c)))
(defclass usb-ms-partition (disk-partition-mixin)
((%mass-storage :initarg :mass-storage :accessor dp-mass-storage)))
(defmethod block-device-sector-size ((partition usb-ms-partition))
(mass-storage-block-size (dp-mass-storage partition)))
(defmethod block-device-n-sectors ((partition usb-ms-partition))
(mass-storage-num-blocks (dp-mass-storage partition)))
(defclass usb-ms-disk (disk-mixin disk-pt-mixin)
((%mass-storage :initarg :mass-storage :accessor disk-mass-storage)))
(defmethod block-device-sector-size ((disk usb-ms-disk))
(mass-storage-block-size (disk-mass-storage disk)))
(defmethod block-device-n-sectors ((disk usb-ms-disk))
(mass-storage-num-blocks (disk-mass-storage disk)))
(defun encode-cbw (driver buf offset length in-p logical-unit)
(setf (get-unsigned-word/32 buf (+ offset +cbw-signature+))
+cbw-signature-value+
(get-unsigned-word/32 buf (+ offset +cbw-tag+))
(next-cbw-tag driver)
(get-unsigned-word/32 buf (+ offset +cbw-transfer-length+))
length
(aref buf (+ offset +cbw-flags+))
(if in-p +cbw-flags-data-in+ +cbw-flags-data-out+)
(aref buf (+ offset +cbw-lun+))
logical-unit))
(defun encode-scsi-inquiry (buf offset vital-p page length)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 6
(aref buf cbw-offset) +scsi-code-inquiry+
(aref buf (+ cbw-offset 1)) (if vital-p 1 0)
(aref buf (+ cbw-offset 2)) page
(get-unsigned-word/16 buf (+ cbw-offset 3)) length
TODO what about the NACA bit
(defun encode-scsi-read-capacity/10 (buf offset)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 10
(aref buf cbw-offset) #x25)
(dotimes (i 9)
(setf (aref buf (+ cbw-offset i 1)) 0))))
(defun encode-scsi-read-capacity/16 (buf offset length)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 16
(aref buf cbw-offset) +scsi-service-action+
(aref buf (+ cbw-offset 1)) +scsi-code-read-capacity+
(get-unsigned-word/32 buf (+ cbw-offset 2)) 0
(get-unsigned-word/32 buf (+ cbw-offset 6)) 0
(get-be-unsigned-word/32 buf (+ cbw-offset 10)) length
(aref buf (+ cbw-offset 14)) 0
(aref buf (+ cbw-offset 15)) 0)))
(defun encode-scsi-read/10 (buf offset lba n-blocks)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 10
(aref buf cbw-offset) +scsi-code-read/10+
(aref buf (+ cbw-offset 1)) 0
(get-be-unsigned-word/32 buf (+ cbw-offset 2)) lba
(aref buf (+ cbw-offset 6)) 0
(get-be-unsigned-word/16 buf (+ cbw-offset 7)) n-blocks
(aref buf (+ cbw-offset 9)) 0)))
(defun encode-scsi-write/10 (buf offset lba n-blocks)
(let ((cbw-offset (+ offset +cbw-control-block+)))
(setf (aref buf (+ offset +cbw-cb-length+)) 10
(aref buf cbw-offset) +scsi-code-write/10+
(aref buf (+ cbw-offset 1)) 0
(get-be-unsigned-word/32 buf (+ cbw-offset 2)) lba
(aref buf (+ cbw-offset 6)) 0
(get-be-unsigned-word/16 buf (+ cbw-offset 7)) n-blocks
(aref buf (+ cbw-offset 9)) 0)))
(defun send-buf (usbd device mass-storage endpoint buf length)
(let((event (mass-storage-event mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd device endpoint buf length)
(when (eq (timed-wait event 0.500) :timeout)
(sup:debug-print-line "send-buf timeout")
(signal 'timeout-retry :endpoint endpoint :enqueued-buf buf))))
(defun %read-sector (usbd device mass-storage lba buf offset)
(enter-function "%read-sector")
(let ((data-length (mass-storage-block-size mass-storage))
(out-endpoint (mass-storage-bulk-out-endpt-num mass-storage))
(in-endpoint (mass-storage-bulk-in-endpt-num mass-storage)))
(with-buffers ((buf-pool usbd) ((cmd-buf /8 31)
(data-buf /8 data-length)
(status-buf /8 13)))
(encode-cbw mass-storage cmd-buf 0 data-length T 0)
(encode-scsi-read/10 cmd-buf 0 lba 1)
(send-buf usbd device mass-storage out-endpoint cmd-buf 31)
(with-trace-level (4)
(sup:debug-print-line "%read-sector command status "
(mass-storage-status mass-storage)))
(send-buf usbd device mass-storage in-endpoint data-buf data-length)
(with-trace-level (3)
(sup:debug-print-line "read sector data buffer:")
(print-buffer sys.int::*cold-stream* data-buf :indent " ")
(sup:debug-print-line "read sector data status "
(mass-storage-status mass-storage)))
(send-buf usbd device mass-storage in-endpoint status-buf 13)
(with-trace-level (4)
(sup:debug-print-line "%read-sector status buffer:")
(print-buffer sys.int::*cold-stream* status-buf :indent " ")
(sup:debug-print-line "%read-sector status status "
(mass-storage-status mass-storage)))
(cond ((= (aref status-buf 12) 0)
(dotimes (i data-length)
(setf (aref buf (+ offset i)) (aref data-buf i))))
((= (aref status-buf 12) 1)
(error "%read-sector failed"))
((= (aref status-buf 12) 2)
(error "%read-sector failed with phase error"))
(T
(error "%read-sector failed with unknown error ~D"
(aref status-buf 12)))))))
(defun %block-device-read (mass-storage lba n-sectors buf offset)
(enter-function "%block-device-read")
(handler-bind
((timeout-retry #'retry-operation))
(loop
with usbd = (mass-storage-usbd mass-storage)
with device = (mass-storage-device mass-storage)
with sector-size = (mass-storage-block-size mass-storage)
with retry-count = 0
do
(restart-case
(progn
(when (<= n-sectors 0)
(return))
(%read-sector usbd device mass-storage lba buf offset)
(incf lba)
(incf offset sector-size)
(decf n-sectors))
(retry-operation (endpoint enqueued-buf)
(sup:debug-print-line "timeout on read lba: " lba)
(bulk-dequeue-buf usbd device endpoint enqueued-buf)
(reset-recovery usbd device mass-storage)
(incf retry-count)
(when (= retry-count 5)
(error "Mass storage timeout on read")))))))
(defmethod block-device-read
((disk usb-ms-disk) lba n-sectors buf &key (offset 0))
(enter-function "block-device-read (mass-storage)")
(%block-device-read (disk-mass-storage disk) lba n-sectors buf offset))
(defmethod block-device-read
((partition usb-ms-partition) lba n-sectors buf &key (offset 0))
(enter-function "block-device-read (partition)")
(when (> (+ lba n-sectors) (dp-size partition))
(error "Attempt to read past end of partition, ~
LBA: ~D, read size ~D, partition size ~D"
lba n-sectors (dp-size partition)))
(%block-device-read (dp-mass-storage partition)
(+ lba (dp-start-lba partition))
n-sectors
buf
offset))
(defun %write-sector (usbd device mass-storage lba buf offset)
(enter-function "%write-sector")
(let ((data-length (mass-storage-block-size mass-storage))
(out-endpoint (mass-storage-bulk-out-endpt-num mass-storage))
(in-endpoint (mass-storage-bulk-in-endpt-num mass-storage)))
(with-buffers ((buf-pool usbd) ((cmd-buf /8 31)
(data-buf /8 data-length)
(status-buf /8 13)))
(encode-cbw mass-storage cmd-buf 0 data-length NIL 0)
(encode-scsi-write/10 cmd-buf 0 lba 1)
(send-buf usbd device mass-storage out-endpoint cmd-buf 31)
(dotimes (i data-length)
(setf (aref data-buf i) (aref buf (+ offset i))))
(with-trace-level (4)
(sup:debug-print-line "%write-sector command status "
(mass-storage-status mass-storage)))
(send-buf usbd device mass-storage out-endpoint data-buf data-length)
(with-trace-level (3)
(sup:debug-print-line "write sector data buffer:")
(print-buffer sys.int::*cold-stream* data-buf :indent " ")
(sup:debug-print-line "write sector data status "
(mass-storage-status mass-storage)))
(send-buf usbd device mass-storage in-endpoint status-buf 13)
(with-trace-level (4)
(sup:debug-print-line "%write-sector status buffer:")
(print-buffer sys.int::*cold-stream* status-buf :indent " ")
(sup:debug-print-line "%write-sector status status "
(mass-storage-status mass-storage)))
(cond ((= (aref status-buf 12) 0)
Success - nothing else to do
)
((= (aref status-buf 12) 1)
(error "%read-sector failed"))
((= (aref status-buf 12) 2)
(error "%write-sector failed with phase error"))
(T
(error "%write-sector failed with unknown error ~D"
(aref status-buf 12)))))))
(defun %block-device-write (mass-storage lba n-sectors buf offset)
(enter-function "block-device-write")
(handler-bind
((timeout-retry #'retry-operation))
(loop
with usbd = (mass-storage-usbd mass-storage)
with device = (mass-storage-device mass-storage)
with sector-size = (mass-storage-block-size mass-storage)
with retry-count = 0
do
(restart-case
(progn
(when (<= n-sectors 0)
(return))
(%write-sector usbd device mass-storage lba buf offset)
(incf lba)
(incf offset sector-size)
(decf n-sectors))
(retry-operation (endpoint enqueued-buf)
(sup:debug-print-line "timeout on write lba: " lba)
(bulk-dequeue-buf usbd device endpoint enqueued-buf)
(reset-recovery usbd device mass-storage)
(incf retry-count)
(when (= retry-count 5)
(error "Mass storage timeout on write")))))))
(defmethod block-device-write
((disk usb-ms-disk) lba n-sectors buf &key (offset 0))
(enter-function "block-device-write (disk)")
(%block-device-write (disk-mass-storage disk) lba n-sectors buf offset))
(defmethod block-device-write
((partition usb-ms-partition) lba n-sectors buf &key (offset 0))
(enter-function "block-device-write (partition)")
(when (> (+ lba n-sectors) (dp-size partition))
(error "Attempt to write past end of partition, ~
LBA: ~D, write size ~D, partition size ~D"
lba n-sectors (dp-size partition)))
(%block-device-write (dp-mass-storage partition)
(+ lba (dp-start-lba partition))
n-sectors
buf
offset))
(defmethod block-device-flush ((mass-storage mass-storage))
(enter-function "block-device-flush")
)
(defun parse-endpt-descriptor (usbd device mass-storage endpt-desc)
(let* ((address (aref endpt-desc +ed-address+))
(endpt-in (ldb-test +ed-direction-field+ address))
(endpt-num (ldb +ed-endpt-num-field+ address)))
(when (/= (aref endpt-desc +ed-attributes+) +ed-attr-bulk+)
(sup:debug-print-line "Mass Storage Probe failed because "
"endpoint type is "
(aref endpt-desc +ed-attributes+)
" instead of a bulk endpoint")
(throw :probe-failed nil))
(create-bulk-endpt usbd
device
mass-storage
endpt-num
endpt-in
'mass-storage-int-callback)
(if endpt-in
(setf (mass-storage-bulk-in-endpt-num mass-storage) endpt-num)
(setf (mass-storage-bulk-out-endpt-num mass-storage) endpt-num))))
(defmethod delete-device ((mass-storage mass-storage) device)
(unregister-block-device (mass-storage-disk mass-storage))
(dolist (part (mass-storage-partitions mass-storage))
(unregister-block-device part)))
(defun parse-inquiry (usbd device mass-storage)
(enter-function "parse-inquiry")
(let ((data-length 36)
(event (mass-storage-event mass-storage)))
(with-buffers ((buf-pool usbd) ((cmd-buf /8 31)
(data-buf /8 data-length)
(status-buf /8 13)))
(encode-cbw mass-storage cmd-buf 0 data-length T 0)
(encode-scsi-inquiry cmd-buf 0 NIL 0 data-length)
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-out-endpt-num mass-storage)
cmd-buf
31)
(with-trace-level (4)
(sup:debug-print-line "inquiry command buffer:")
(print-buffer sys.int::*cold-stream* cmd-buf :indent " "))
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage inquiry command timeout"))
(with-trace-level (4)
(sup:debug-print-line "inquiry command status"
(mass-storage-status mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-in-endpt-num mass-storage)
data-buf
data-length)
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage inquiry data timeout"))
(with-trace-level (3)
(sup:debug-print-line "inquiry data buffer:")
(print-buffer sys.int::*cold-stream* data-buf :indent " ")
(sup:debug-print-line "inquiry data status "
(mass-storage-status mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-in-endpt-num mass-storage)
status-buf
13)
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage inquiry status timeout"))
(with-trace-level (4)
(sup:debug-print-line "inquiry status buffer:")
(print-buffer sys.int::*cold-stream* status-buf :indent " ")
(sup:debug-print-line "inquiry status status "
(mass-storage-status mass-storage)))
(cond ((= (aref status-buf 12) 0)
(setf (mass-storage-vendor mass-storage)
(string-right-trim " " (get-ascii-string data-buf 8 8))
(mass-storage-product mass-storage)
(string-right-trim " " (get-ascii-string data-buf 16 16))
(mass-storage-revision mass-storage)
(string-right-trim " " (get-ascii-string data-buf 32 4))))
((= (aref status-buf 12) 1)
(sup:debug-print-line "Mass Storage Probe failed because "
"Inquiry command failed")
(throw :probe-failed nil))
((= (aref status-buf 12) 2)
(sup:debug-print-line "Mass Storage Probe failed because "
"Inquiry command got phase error")
(throw :probe-failed nil))
(T
(sup:debug-print-line "Mass Storage Probe failed because "
"Inquiry failed with unkown error "
(aref status-buf 12))
(throw :probe-failed nil))))))
(defun parse-read-capacity (usbd device mass-storage cap/10-p)
(enter-function "parse-read-capacity")
(let ((data-length (if cap/10-p 8 32))
(event (mass-storage-event mass-storage)))
(with-buffers ((buf-pool usbd) ((cmd-buf /8 31)
(data-buf /8 data-length)
(status-buf /8 13)))
(encode-cbw mass-storage cmd-buf 0 data-length T 0)
(if cap/10-p
(encode-scsi-read-capacity/10 cmd-buf 0)
(encode-scsi-read-capacity/16 cmd-buf 0 data-length))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-out-endpt-num mass-storage)
cmd-buf
31)
(with-trace-level (4)
(sup:debug-print-line "read capacity command buffer:")
(print-buffer sys.int::*cold-stream* cmd-buf :indent " "))
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage read capacity command timeout"))
(with-trace-level (4)
(sup:debug-print-line "read capacity command status "
(mass-storage-status mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-in-endpt-num mass-storage)
data-buf
data-length)
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage read capacity data timeout"))
(with-trace-level (3)
(sup:debug-print-line "read capacity data buffer:")
(print-buffer sys.int::*cold-stream* data-buf :indent " ")
(sup:debug-print-line "read capacity data status "
(mass-storage-status mass-storage)))
(setf (sup:event-state event) nil)
(bulk-enqueue-buf usbd
device
(mass-storage-bulk-in-endpt-num mass-storage)
status-buf
13)
(when (eq (timed-wait event 1.0) :timeout)
TODO need better error message here
(error "Mass storage read capacity status timeout"))
(with-trace-level (4)
(sup:debug-print-line "read capacity status buffer:")
(print-buffer sys.int::*cold-stream* status-buf :indent " ")
(sup:debug-print-line "read capacity status status "
(mass-storage-status mass-storage)))
(cond ((= (aref status-buf 12) 0)
(if cap/10-p
(let ((block-addr (get-be-unsigned-word/32 data-buf 0)))
(cond ((= block-addr #xFFFFFFFF)
(parse-read-capacity usbd device mass-storage NIL))
(T
(setf (mass-storage-num-blocks mass-storage)
block-addr
(mass-storage-block-size mass-storage)
(get-be-unsigned-word/32 data-buf 4)))))
(setf (mass-storage-num-blocks mass-storage)
(get-be-unsigned-word/64 data-buf 0)
(mass-storage-block-size mass-storage)
(get-be-unsigned-word/32 data-buf 8))))
((= (aref status-buf 12) 1)
(sup:debug-print-line "Mass Storage Probe failed because "
"read capacity command failed")
(throw :probe-failed nil))
((= (aref status-buf 12) 2)
(sup:debug-print-line "Mass Storage Probe failed because "
"read capacity command got phase error")
(throw :probe-failed nil))
(T
(sup:debug-print-line "Mass Storage Probe failed because "
"read capacity failed with unkown error "
(aref status-buf 12))
(throw :probe-failed nil))))))
(defun probe-mass-storage-scsi (usbd device iface-desc configs)
(when (/= (aref iface-desc +id-num-endpoints+) 2)
(sup:debug-print-line "Mass Storage Probe failed because "
"interface descriptor has "
(aref iface-desc +id-num-endpoints+)
" endpoints, Only exactly 2 supported.")
(throw :probe-failed nil))
(let ((mass-storage (make-mass-storage
:usbd usbd
:device device
:interface (aref iface-desc +id-number+)
:event (sup:make-event
:name "Mass Storage Event")
:bulk-in-endpt-num nil
:bulk-out-endpt-num nil
:lock (sup:make-mutex "USB Mass Storage Lock")
:cbw-tag #x100)))
(dotimes (i 2)
(let ((endpt-desc (pop configs)))
(when (or (null endpt-desc)
(/= (aref endpt-desc +ed-type+) +desc-type-endpoint+))
(sup:debug-print-line "Mass Storage probe failed because "
"found descriptor type "
(aref endpt-desc +ed-type+)
" instead of endpoint descriptor.")
(throw :probe-failed nil))
(parse-endpt-descriptor usbd device mass-storage endpt-desc)))
(when (or (null (mass-storage-bulk-in-endpt-num mass-storage))
(null (mass-storage-bulk-out-endpt-num mass-storage)))
(sup:debug-print-line "Mass Storage probe failed because "
"did not have both in and out bulk endpoints")
(throw :probe-failed nil))
(parse-inquiry usbd device mass-storage)
(parse-read-capacity usbd device mass-storage T)
(with-trace-level (2)
(sup:debug-print-line "vendor: \""
(mass-storage-vendor mass-storage)
"\", product: \""
(mass-storage-product mass-storage)
"\", revision: \""
(mass-storage-revision mass-storage)
"\"")
(sup:debug-print-line "num blocks: #x"
(mass-storage-num-blocks mass-storage)
", block size: #x"
(mass-storage-block-size mass-storage)))
(setf (mass-storage-disk mass-storage)
(make-instance 'usb-ms-disk
:mass-storage mass-storage
:writable-p T
:n-sectors (mass-storage-num-blocks mass-storage)
:sector-size (mass-storage-block-size mass-storage))
(mass-storage-partitions mass-storage)
(mapcar #'(lambda (part-info)
(apply #'make-instance 'usb-ms-partition
:mass-storage mass-storage
part-info))
(parse-partition-table (mass-storage-disk mass-storage))))
(register-block-device (mass-storage-disk mass-storage))
(dolist (part (mass-storage-partitions mass-storage))
(register-block-device part))
(setf *mass-storage* mass-storage)
(values configs mass-storage)))
(define-usb-class-driver "Mass Storage" 'probe-mass-storage-scsi
'((#.+id-class-mass-storage+ #.+mass-subclass-scsi+ #.+id-protocol-bulk-only+)))
(defun mass-storage-int-callback (mass-storage endpoint-num status length buf)
(setf (mass-storage-status mass-storage) status
(sup:event-state (mass-storage-event mass-storage)) T))
(defun reset-recovery (usbd device mass-storage)
(with-trace-level (0)
(sup:debug-print-line "reset-recovery"))
do n't want 0 length buf
(control-receive-data usbd
device
#xFF
0
(mass-storage-interface mass-storage)
0
buf)
(control-receive-data usbd
device
(encode-request-type +rt-dir-host-to-device+
+rt-type-standard+
+rt-rec-endpoint+)
+dev-req-clear-feature+
+feature-endpoint-halt+
(mass-storage-bulk-in-endpt-num mass-storage)
0
buf)
(control-receive-data usbd
device
(encode-request-type +rt-dir-host-to-device+
+rt-type-standard+
+rt-rec-endpoint+)
+dev-req-clear-feature+
+feature-endpoint-halt+
(mass-storage-bulk-out-endpt-num mass-storage)
0
buf)))
|
ab956f76d6e268fba34e49cc73fff9188978168e543945706e4be9e4189ab796 | helium/erlang-tc | key_SUITE.erl | -module(key_SUITE).
-include_lib("common_test/include/ct.hrl").
-export([all/0, init_per_testcase/2, end_per_testcase/2]).
-export(
[
pk_size_test/1,
pk_serde_test/1,
signature_test/1,
pk_set_test/1,
pk_set_serde_test/1,
pk_set_combine_test/1,
pk_share_combine_test/1,
pk_share_serde_test/1,
sk_set_test/1,
random_sk_set_test/1,
verify_sig_test/1,
verify_ciphertext_test/1,
ciphertext_serde_test/1,
sk_share_combine_test/1,
fr_serde_test/1,
sk_share_serde_test/1,
signature_serde_test/1
]
).
all() ->
[
pk_size_test,
pk_serde_test,
signature_test,
pk_set_test,
pk_set_serde_test,
pk_set_combine_test,
pk_share_combine_test,
pk_share_serde_test,
sk_set_test,
random_sk_set_test,
verify_sig_test,
verify_ciphertext_test,
ciphertext_serde_test,
sk_share_combine_test,
fr_serde_test,
sk_share_serde_test,
signature_serde_test
].
init_per_testcase(_, Config) ->
[{pk_size, 48}, {sig_size, 96}, {degree, 5} | Config].
end_per_testcase(_, Config) ->
Config.
-include_lib("eunit/include/eunit.hrl").
pk_size_test(Config) ->
PKSize = ?config(pk_size, Config),
SK = tc_secret_key:random(),
PK = tc_secret_key:public_key(SK),
PKSize = byte_size(tc_pubkey:serialize(PK)),
ok.
pk_serde_test(_Config) ->
SK = tc_secret_key:random(),
PK = tc_secret_key:public_key(SK),
SPK = tc_pubkey:serialize(PK),
DPK = tc_pubkey:deserialize(SPK),
?assert(tc_pubkey:cmp(PK, DPK)),
ok.
signature_test(Config) ->
SigSize = ?config(sig_size, Config),
SK = tc_secret_key:random(),
Signature = tc_secret_key:sign(SK, <<"resistance is futile">>),
%% Parity = tc_signature:parity(Signature),
%% ?debugFmt("Parity: ~p~n", [Parity]),
SigSize = byte_size(tc_signature:serialize(Signature)),
ok.
pk_set_test(Config) ->
PKSize = ?config(pk_size, Config),
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
PK = tc_public_key_set:public_key(PKSet),
PKSize = byte_size(tc_pubkey:serialize(PK)),
Degree = tc_public_key_set:threshold(PKSet),
ok.
pk_set_serde_test(Config) ->
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
SerPKSet = tc_public_key_set:serialize(PKSet),
DeserPKSet = tc_public_key_set:deserialize(SerPKSet),
?assert(tc_public_key_set:cmp(PKSet, DeserPKSet)),
ok.
pk_set_combine_test(Config) ->
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
RandomPoly2 = tc_poly:random(Degree),
Commitment2 = tc_poly:commitment(RandomPoly2),
PKSet2 = tc_public_key_set:from_commitment(Commitment2),
PKSC = tc_public_key_set:combine(PKSet, PKSet2),
ct:pal("PKS1: ~p", [tc_public_key_set:serialize(PKSet)]),
ct:pal("PKS2: ~p", [tc_public_key_set:serialize(PKSet2)]),
ct:pal("PKSC: ~p", [tc_public_key_set:serialize(PKSC)]),
ok.
pk_share_combine_test(Config) ->
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
PKS1 = tc_public_key_set:public_key_share(PKSet, 1),
PKS2 = tc_public_key_set:public_key_share(PKSet, 2),
PKSC = tc_public_key_share:combine(PKS1, PKS2),
ct:pal("PKS1: ~p", [tc_public_key_share:reveal(PKS1)]),
ct:pal("PKS2: ~p", [tc_public_key_share:reveal(PKS2)]),
ct:pal("PKSC: ~p", [tc_public_key_share:reveal(PKSC)]),
ok.
pk_share_serde_test(Config) ->
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
PKShare = tc_public_key_set:public_key_share(PKSet, 1),
SerPKShare = tc_public_key_share:serialize(PKShare),
DeserPKShare = tc_public_key_share:deserialize(SerPKShare),
?assert(tc_public_key_share:cmp(PKShare, DeserPKShare)),
ok.
sk_set_test(Config) ->
PKSize = ?config(pk_size, Config),
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
SKSet = tc_secret_key_set:from_poly(RandomPoly),
PKSet = tc_secret_key_set:public_keys(SKSet),
PK = tc_public_key_set:public_key(PKSet),
PKSize = byte_size(tc_pubkey:serialize(PK)),
Degree = tc_secret_key_set:threshold(SKSet),
ok.
random_sk_set_test(Config) ->
PKSize = ?config(pk_size, Config),
Degree = ?config(degree, Config),
SKSet = tc_secret_key_set:random(Degree),
PKSet = tc_secret_key_set:public_keys(SKSet),
PK = tc_public_key_set:public_key(PKSet),
PKSize = byte_size(tc_pubkey:serialize(PK)),
Degree = tc_secret_key_set:threshold(SKSet),
ok.
verify_sig_test(_Config) ->
SK = tc_secret_key:random(),
Msg = <<"Say hello to my little friend">>,
Sig = tc_secret_key:sign(SK, Msg),
PK = tc_secret_key:public_key(SK),
true = tc_pubkey:verify(PK, Sig, Msg),
ok.
sk_share_combine_test(_Config) ->
Fr1 = tc_fr:into(42),
Fr2 = tc_fr:into(666),
SKS1 = tc_secret_key_share:from_fr(Fr1),
SKS2 = tc_secret_key_share:from_fr(Fr2),
SKSC = tc_secret_key_share:combine(SKS1, SKS2),
ct:pal("SKS1: ~p", [tc_secret_key_share:reveal(SKS1)]),
ct:pal("SKS2: ~p", [tc_secret_key_share:reveal(SKS2)]),
ct:pal("SKSC: ~p", [tc_secret_key_share:reveal(SKSC)]),
ok.
verify_ciphertext_test(_Config) ->
SK = tc_secret_key:random(),
Msg = <<"His name is Robert Paulson">>,
PK = tc_secret_key:public_key(SK),
Cipher = tc_pubkey:encrypt(PK, Msg),
true = tc_ciphertext:verify(Cipher),
ok.
ciphertext_serde_test(_Config) ->
SK = tc_secret_key:random(),
Msg = <<"His name is Robert Paulson">>,
PK = tc_secret_key:public_key(SK),
Cipher = tc_pubkey:encrypt(PK, Msg),
true = tc_ciphertext:verify(Cipher),
SerCipher = tc_ciphertext:serialize(Cipher),
DeserCipher = tc_ciphertext:deserialize(SerCipher),
true = tc_ciphertext:verify(DeserCipher),
?assert(tc_ciphertext:cmp(Cipher, DeserCipher)),
ok.
fr_serde_test(_Config) ->
true = tc_fr:cmp(tc_fr:deserialize(tc_fr:serialize(tc_fr:into(0))), tc_fr:into(0)),
true = tc_fr:cmp(tc_fr:deserialize(tc_fr:serialize(tc_fr:into(42))), tc_fr:into(42)),
true = tc_fr:cmp(tc_fr:deserialize(tc_fr:serialize(tc_fr:into(-8))), tc_fr:into(-8)),
true = tc_fr:cmp(tc_fr:deserialize(tc_fr:serialize(tc_fr:zero())), tc_fr:zero()),
ok.
sk_share_serde_test(_Config) ->
Fr1 = tc_fr:into(42),
SKS = tc_secret_key_share:from_fr(Fr1),
SerSKS = tc_secret_key_share:serialize(SKS),
DeserSKS = tc_secret_key_share:deserialize(SerSKS),
?assert(tc_secret_key_share:cmp(SKS, DeserSKS)),
ok.
signature_serde_test(_Config) ->
SK = tc_secret_key:random(),
Signature = tc_secret_key:sign(SK, <<"resistance is futile">>),
SerSig = tc_signature:serialize(Signature),
DeserSig = tc_signature:deserialize(SerSig),
?assert(tc_signature:cmp(Signature, DeserSig)),
ok.
| null | https://raw.githubusercontent.com/helium/erlang-tc/b3ef1d5541586f5c85b6d231345a921d57be32a3/test/key_SUITE.erl | erlang | Parity = tc_signature:parity(Signature),
?debugFmt("Parity: ~p~n", [Parity]), | -module(key_SUITE).
-include_lib("common_test/include/ct.hrl").
-export([all/0, init_per_testcase/2, end_per_testcase/2]).
-export(
[
pk_size_test/1,
pk_serde_test/1,
signature_test/1,
pk_set_test/1,
pk_set_serde_test/1,
pk_set_combine_test/1,
pk_share_combine_test/1,
pk_share_serde_test/1,
sk_set_test/1,
random_sk_set_test/1,
verify_sig_test/1,
verify_ciphertext_test/1,
ciphertext_serde_test/1,
sk_share_combine_test/1,
fr_serde_test/1,
sk_share_serde_test/1,
signature_serde_test/1
]
).
all() ->
[
pk_size_test,
pk_serde_test,
signature_test,
pk_set_test,
pk_set_serde_test,
pk_set_combine_test,
pk_share_combine_test,
pk_share_serde_test,
sk_set_test,
random_sk_set_test,
verify_sig_test,
verify_ciphertext_test,
ciphertext_serde_test,
sk_share_combine_test,
fr_serde_test,
sk_share_serde_test,
signature_serde_test
].
init_per_testcase(_, Config) ->
[{pk_size, 48}, {sig_size, 96}, {degree, 5} | Config].
end_per_testcase(_, Config) ->
Config.
-include_lib("eunit/include/eunit.hrl").
pk_size_test(Config) ->
PKSize = ?config(pk_size, Config),
SK = tc_secret_key:random(),
PK = tc_secret_key:public_key(SK),
PKSize = byte_size(tc_pubkey:serialize(PK)),
ok.
pk_serde_test(_Config) ->
SK = tc_secret_key:random(),
PK = tc_secret_key:public_key(SK),
SPK = tc_pubkey:serialize(PK),
DPK = tc_pubkey:deserialize(SPK),
?assert(tc_pubkey:cmp(PK, DPK)),
ok.
signature_test(Config) ->
SigSize = ?config(sig_size, Config),
SK = tc_secret_key:random(),
Signature = tc_secret_key:sign(SK, <<"resistance is futile">>),
SigSize = byte_size(tc_signature:serialize(Signature)),
ok.
pk_set_test(Config) ->
PKSize = ?config(pk_size, Config),
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
PK = tc_public_key_set:public_key(PKSet),
PKSize = byte_size(tc_pubkey:serialize(PK)),
Degree = tc_public_key_set:threshold(PKSet),
ok.
pk_set_serde_test(Config) ->
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
SerPKSet = tc_public_key_set:serialize(PKSet),
DeserPKSet = tc_public_key_set:deserialize(SerPKSet),
?assert(tc_public_key_set:cmp(PKSet, DeserPKSet)),
ok.
pk_set_combine_test(Config) ->
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
RandomPoly2 = tc_poly:random(Degree),
Commitment2 = tc_poly:commitment(RandomPoly2),
PKSet2 = tc_public_key_set:from_commitment(Commitment2),
PKSC = tc_public_key_set:combine(PKSet, PKSet2),
ct:pal("PKS1: ~p", [tc_public_key_set:serialize(PKSet)]),
ct:pal("PKS2: ~p", [tc_public_key_set:serialize(PKSet2)]),
ct:pal("PKSC: ~p", [tc_public_key_set:serialize(PKSC)]),
ok.
pk_share_combine_test(Config) ->
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
PKS1 = tc_public_key_set:public_key_share(PKSet, 1),
PKS2 = tc_public_key_set:public_key_share(PKSet, 2),
PKSC = tc_public_key_share:combine(PKS1, PKS2),
ct:pal("PKS1: ~p", [tc_public_key_share:reveal(PKS1)]),
ct:pal("PKS2: ~p", [tc_public_key_share:reveal(PKS2)]),
ct:pal("PKSC: ~p", [tc_public_key_share:reveal(PKSC)]),
ok.
pk_share_serde_test(Config) ->
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
Commitment = tc_poly:commitment(RandomPoly),
PKSet = tc_public_key_set:from_commitment(Commitment),
PKShare = tc_public_key_set:public_key_share(PKSet, 1),
SerPKShare = tc_public_key_share:serialize(PKShare),
DeserPKShare = tc_public_key_share:deserialize(SerPKShare),
?assert(tc_public_key_share:cmp(PKShare, DeserPKShare)),
ok.
sk_set_test(Config) ->
PKSize = ?config(pk_size, Config),
Degree = ?config(degree, Config),
RandomPoly = tc_poly:random(Degree),
SKSet = tc_secret_key_set:from_poly(RandomPoly),
PKSet = tc_secret_key_set:public_keys(SKSet),
PK = tc_public_key_set:public_key(PKSet),
PKSize = byte_size(tc_pubkey:serialize(PK)),
Degree = tc_secret_key_set:threshold(SKSet),
ok.
random_sk_set_test(Config) ->
PKSize = ?config(pk_size, Config),
Degree = ?config(degree, Config),
SKSet = tc_secret_key_set:random(Degree),
PKSet = tc_secret_key_set:public_keys(SKSet),
PK = tc_public_key_set:public_key(PKSet),
PKSize = byte_size(tc_pubkey:serialize(PK)),
Degree = tc_secret_key_set:threshold(SKSet),
ok.
verify_sig_test(_Config) ->
SK = tc_secret_key:random(),
Msg = <<"Say hello to my little friend">>,
Sig = tc_secret_key:sign(SK, Msg),
PK = tc_secret_key:public_key(SK),
true = tc_pubkey:verify(PK, Sig, Msg),
ok.
sk_share_combine_test(_Config) ->
Fr1 = tc_fr:into(42),
Fr2 = tc_fr:into(666),
SKS1 = tc_secret_key_share:from_fr(Fr1),
SKS2 = tc_secret_key_share:from_fr(Fr2),
SKSC = tc_secret_key_share:combine(SKS1, SKS2),
ct:pal("SKS1: ~p", [tc_secret_key_share:reveal(SKS1)]),
ct:pal("SKS2: ~p", [tc_secret_key_share:reveal(SKS2)]),
ct:pal("SKSC: ~p", [tc_secret_key_share:reveal(SKSC)]),
ok.
verify_ciphertext_test(_Config) ->
SK = tc_secret_key:random(),
Msg = <<"His name is Robert Paulson">>,
PK = tc_secret_key:public_key(SK),
Cipher = tc_pubkey:encrypt(PK, Msg),
true = tc_ciphertext:verify(Cipher),
ok.
ciphertext_serde_test(_Config) ->
SK = tc_secret_key:random(),
Msg = <<"His name is Robert Paulson">>,
PK = tc_secret_key:public_key(SK),
Cipher = tc_pubkey:encrypt(PK, Msg),
true = tc_ciphertext:verify(Cipher),
SerCipher = tc_ciphertext:serialize(Cipher),
DeserCipher = tc_ciphertext:deserialize(SerCipher),
true = tc_ciphertext:verify(DeserCipher),
?assert(tc_ciphertext:cmp(Cipher, DeserCipher)),
ok.
fr_serde_test(_Config) ->
true = tc_fr:cmp(tc_fr:deserialize(tc_fr:serialize(tc_fr:into(0))), tc_fr:into(0)),
true = tc_fr:cmp(tc_fr:deserialize(tc_fr:serialize(tc_fr:into(42))), tc_fr:into(42)),
true = tc_fr:cmp(tc_fr:deserialize(tc_fr:serialize(tc_fr:into(-8))), tc_fr:into(-8)),
true = tc_fr:cmp(tc_fr:deserialize(tc_fr:serialize(tc_fr:zero())), tc_fr:zero()),
ok.
sk_share_serde_test(_Config) ->
Fr1 = tc_fr:into(42),
SKS = tc_secret_key_share:from_fr(Fr1),
SerSKS = tc_secret_key_share:serialize(SKS),
DeserSKS = tc_secret_key_share:deserialize(SerSKS),
?assert(tc_secret_key_share:cmp(SKS, DeserSKS)),
ok.
signature_serde_test(_Config) ->
SK = tc_secret_key:random(),
Signature = tc_secret_key:sign(SK, <<"resistance is futile">>),
SerSig = tc_signature:serialize(Signature),
DeserSig = tc_signature:deserialize(SerSig),
?assert(tc_signature:cmp(Signature, DeserSig)),
ok.
|
e0fcec6577b2e2f1445a56ecb3dab53f15b8be31e6e7f000d2e3294ad0c05e82 | viercc/kitchen-sink-hs | LogRwd.hs | # LANGUAGE DerivingVia #
module LogRwd where
import Prelude hiding (log)
import Data.Bifunctor
import Control.Monad.State
module LogRwdTransf(M : MONAD ) = struct
type ( ' a , ' b ) log = ( ' a , ' b ) argFunPair list
and ( ' a , ' b ) mon = ( ' a , ' b ) log - > ( ' a * ( ' a , ' b ) log ) M.mon
and ( ' a , ' b ) argFunPair = ( ' a * ( ' a - > ( ' a , ' b ) mon ) )
type ( ' a , ' b ) result = ( ' a * ( ' a , ' b ) log ) let ret x = fun l - > M.ret ( x , l )
let bind m f = fun l - > M.bind ( m l ) ( fun ( x , s ' ) - > f x s ' )
let ( > > =) = bind
let lift m = fun l - > M.bind m ( fun x - > M.ret ( x , l ) )
let run ( m : ( ' a , ' b ) mon ) : ( ' a , ' b ) result =
M.run ( M.bind ( m [ ] ) ( fun ( x , l ) - > M.ret ( x , List.rev l ) ) )
let log ( p : ( ' a , ' b ) argFunPair ) = fun l - > M.ret ( ( ) , p : : l )
let sizeOfLog ( s : ( ' a , ' b ) result ) = match s with _ , l - > List.length l
let ( s : ( ' a , ' b ) result ) ( n : int ) = match s with _ , l - >
if n < 0 || n > = sizeOfLog s then List.nth l 0 else List.nth l n
let navigate ( s : ( ' a , ' b ) result ) ( n : int ) =
match nthFunPair s n with x , f - >
match run ( f x ) with r , _ - > s , r , n
let ( s : ( ' a , ' b ) result ) ( n : int ) =
let k = sizeOfLog s
in navigate s ( if n < 0 || n > k then k - 1 else n - 1 )
let forward ( s : ( ' a , ' b ) result ) ( n : int ) =
let k = sizeOfLog s
in navigate s ( if n < 0 || n > k then 0 else n + 1 )
module LogRwdTransf(M : MONAD) = struct
type ('a, 'b) log = ('a, 'b) argFunPair list
and ('a, 'b) mon = ('a, 'b) log -> ('a * ('a, 'b) log) M.mon
and ('a, 'b) argFunPair = ('a * ('a -> ('a, 'b) mon))
type ('a, 'b) result = ('a * ('a, 'b) log) M.result
let ret x = fun l -> M.ret (x, l)
let bind m f = fun l -> M.bind (m l) (fun (x, s') -> f x s')
let (>>=) = bind
let lift m = fun l -> M.bind m (fun x -> M.ret (x, l))
let run (m: ('a, 'b) mon) : ('a, 'b) result =
M.run (M.bind (m []) (fun (x, l) -> M.ret (x, List.rev l)))
let log (p : ('a, 'b) argFunPair) = fun l -> M.ret ((), p :: l)
let sizeOfLog (s : ('a, 'b) result) = match s with _, l -> List.length l
let nthFunPair (s : ('a, 'b) result) (n : int) = match s with _, l ->
if n < 0 || n >= sizeOfLog s then List.nth l 0 else List.nth l n
let navigate (s : ('a, 'b) result) (n : int) =
match nthFunPair s n with x, f ->
match run (f x) with r, _ -> s, r, n
let bakward (s : ('a, 'b) result) (n : int) =
let k = sizeOfLog s
in navigate s (if n < 0 || n > k then k - 1 else n - 1)
let forward (s : ('a, 'b) result) (n : int) =
let k = sizeOfLog s
in navigate s (if n < 0 || n > k then 0 else n + 1)
-}
newtype Mon m a b c = Mon { runMon :: StateT (Log m a b) m c }
deriving (Functor, Applicative, Monad) via (StateT (Log m a b) m)
type Log m a b = [ArgFunPair m a b]
type ArgFunPair m a b = (a, a -> Mon m a b a)
The parameter ` b ` is actually never used .
Nothing is lost by changing them to more simpler
newtype Mon m a b = Mon { runMon : : StateT ( Log m a ) m b }
type Log m a = [ ArgFunPair m a ]
type ArgFunPair m a = ( a , a - > Mon m a a )
The parameter `b` is actually never used.
Nothing is lost by changing them to more simpler
newtype Mon m a b = Mon { runMon :: StateT (Log m a) m b }
type Log m a = [ArgFunPair m a]
type ArgFunPair m a = (a, a -> Mon m a a)
-}
------------------------------------
log :: (Monad m) => ArgFunPair m a b -> Mon m a b ()
log p = Mon (modify (p:))
run :: (Functor m) => Mon m a b c -> m (c, Log m a b)
run (Mon m) = fmap (second reverse) (runStateT m [])
navigate :: (Functor m) => (c, Log m a b) -> Int -> m a
navigate (_, l) n = let (x, f) = l !! n in fst <$> run (f x)
------------------------------------
log_fibCps :: (Monad m)
=> Int
-> (Int -> Mon m Int b Int)
-> m (Int, Log m Int b)
log_fibCps x f = run (fib x f)
where
fib n k =
do log (n, k)
if n <= 1
then k 1
else fib (n-1) $ \n1 -> fib (n-2) $ \n2 -> k (n1 + n2)
| null | https://raw.githubusercontent.com/viercc/kitchen-sink-hs/391efc1a30f02a65bbcc37a4391bd5cb0d3eee8c/snippets/src/LogRwd.hs | haskell | ----------------------------------
---------------------------------- | # LANGUAGE DerivingVia #
module LogRwd where
import Prelude hiding (log)
import Data.Bifunctor
import Control.Monad.State
module LogRwdTransf(M : MONAD ) = struct
type ( ' a , ' b ) log = ( ' a , ' b ) argFunPair list
and ( ' a , ' b ) mon = ( ' a , ' b ) log - > ( ' a * ( ' a , ' b ) log ) M.mon
and ( ' a , ' b ) argFunPair = ( ' a * ( ' a - > ( ' a , ' b ) mon ) )
type ( ' a , ' b ) result = ( ' a * ( ' a , ' b ) log ) let ret x = fun l - > M.ret ( x , l )
let bind m f = fun l - > M.bind ( m l ) ( fun ( x , s ' ) - > f x s ' )
let ( > > =) = bind
let lift m = fun l - > M.bind m ( fun x - > M.ret ( x , l ) )
let run ( m : ( ' a , ' b ) mon ) : ( ' a , ' b ) result =
M.run ( M.bind ( m [ ] ) ( fun ( x , l ) - > M.ret ( x , List.rev l ) ) )
let log ( p : ( ' a , ' b ) argFunPair ) = fun l - > M.ret ( ( ) , p : : l )
let sizeOfLog ( s : ( ' a , ' b ) result ) = match s with _ , l - > List.length l
let ( s : ( ' a , ' b ) result ) ( n : int ) = match s with _ , l - >
if n < 0 || n > = sizeOfLog s then List.nth l 0 else List.nth l n
let navigate ( s : ( ' a , ' b ) result ) ( n : int ) =
match nthFunPair s n with x , f - >
match run ( f x ) with r , _ - > s , r , n
let ( s : ( ' a , ' b ) result ) ( n : int ) =
let k = sizeOfLog s
in navigate s ( if n < 0 || n > k then k - 1 else n - 1 )
let forward ( s : ( ' a , ' b ) result ) ( n : int ) =
let k = sizeOfLog s
in navigate s ( if n < 0 || n > k then 0 else n + 1 )
module LogRwdTransf(M : MONAD) = struct
type ('a, 'b) log = ('a, 'b) argFunPair list
and ('a, 'b) mon = ('a, 'b) log -> ('a * ('a, 'b) log) M.mon
and ('a, 'b) argFunPair = ('a * ('a -> ('a, 'b) mon))
type ('a, 'b) result = ('a * ('a, 'b) log) M.result
let ret x = fun l -> M.ret (x, l)
let bind m f = fun l -> M.bind (m l) (fun (x, s') -> f x s')
let (>>=) = bind
let lift m = fun l -> M.bind m (fun x -> M.ret (x, l))
let run (m: ('a, 'b) mon) : ('a, 'b) result =
M.run (M.bind (m []) (fun (x, l) -> M.ret (x, List.rev l)))
let log (p : ('a, 'b) argFunPair) = fun l -> M.ret ((), p :: l)
let sizeOfLog (s : ('a, 'b) result) = match s with _, l -> List.length l
let nthFunPair (s : ('a, 'b) result) (n : int) = match s with _, l ->
if n < 0 || n >= sizeOfLog s then List.nth l 0 else List.nth l n
let navigate (s : ('a, 'b) result) (n : int) =
match nthFunPair s n with x, f ->
match run (f x) with r, _ -> s, r, n
let bakward (s : ('a, 'b) result) (n : int) =
let k = sizeOfLog s
in navigate s (if n < 0 || n > k then k - 1 else n - 1)
let forward (s : ('a, 'b) result) (n : int) =
let k = sizeOfLog s
in navigate s (if n < 0 || n > k then 0 else n + 1)
-}
newtype Mon m a b c = Mon { runMon :: StateT (Log m a b) m c }
deriving (Functor, Applicative, Monad) via (StateT (Log m a b) m)
type Log m a b = [ArgFunPair m a b]
type ArgFunPair m a b = (a, a -> Mon m a b a)
The parameter ` b ` is actually never used .
Nothing is lost by changing them to more simpler
newtype Mon m a b = Mon { runMon : : StateT ( Log m a ) m b }
type Log m a = [ ArgFunPair m a ]
type ArgFunPair m a = ( a , a - > Mon m a a )
The parameter `b` is actually never used.
Nothing is lost by changing them to more simpler
newtype Mon m a b = Mon { runMon :: StateT (Log m a) m b }
type Log m a = [ArgFunPair m a]
type ArgFunPair m a = (a, a -> Mon m a a)
-}
log :: (Monad m) => ArgFunPair m a b -> Mon m a b ()
log p = Mon (modify (p:))
run :: (Functor m) => Mon m a b c -> m (c, Log m a b)
run (Mon m) = fmap (second reverse) (runStateT m [])
navigate :: (Functor m) => (c, Log m a b) -> Int -> m a
navigate (_, l) n = let (x, f) = l !! n in fst <$> run (f x)
log_fibCps :: (Monad m)
=> Int
-> (Int -> Mon m Int b Int)
-> m (Int, Log m Int b)
log_fibCps x f = run (fib x f)
where
fib n k =
do log (n, k)
if n <= 1
then k 1
else fib (n-1) $ \n1 -> fib (n-2) $ \n2 -> k (n1 + n2)
|
c7d1736edacf6bcf8fed841af56ebe6c699add1971c8ee39cbee9b93f2783ea8 | vitorenesduarte/tricks | tricks_config.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2018 . All Rights Reserved .
%%
This file is provided to you under the Apache License ,
%% Version 2.0 (the "License"); you may not use this file
except in compliance with the License . You may obtain
%% a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
%% KIND, either express or implied. See the License for the
%% specific language governing permissions and limitations
%% under the License.
%%
%% -------------------------------------------------------------------
-module(tricks_config).
-author("Vitor Enes <>").
-include("tricks.hrl").
%% API
-export([get/1,
get/2,
set/2]).
-spec get(atom()) -> term().
get(Property) ->
{ok, Value} = application:get_env(?APP, Property),
Value.
-spec get(atom(), term()) -> term().
get(Property, Default) ->
application:get_env(?APP, Property, Default).
-spec set(atom(), term()) -> ok.
set(Property, Value) ->
application:set_env(?APP, Property, Value).
| null | https://raw.githubusercontent.com/vitorenesduarte/tricks/9ba11252be128be481b4d4a00fe162ccdbdac501/src/tricks_config.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
API | Copyright ( c ) 2018 . All Rights Reserved .
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(tricks_config).
-author("Vitor Enes <>").
-include("tricks.hrl").
-export([get/1,
get/2,
set/2]).
-spec get(atom()) -> term().
get(Property) ->
{ok, Value} = application:get_env(?APP, Property),
Value.
-spec get(atom(), term()) -> term().
get(Property, Default) ->
application:get_env(?APP, Property, Default).
-spec set(atom(), term()) -> ok.
set(Property, Value) ->
application:set_env(?APP, Property, Value).
|
cf2cfc43d5772ddb7f9a58678e327e8109b9d5d980bd1e7182b11845445c1369 | hjcapple/reading-sicp | exercise_1_12.scm | #lang racket
P27 - [ 练习 1.12 ]
(define (pascal-row n)
(define (next-row lst)
(if (= (length lst) 1)
(list (car lst) (car lst))
(let ((ret (next-row (cdr lst)))
(first (car lst)))
(cons first (cons (+ first (car ret)) (cdr ret))))))
(if (<= n 1)
(list 1)
(next-row (pascal-row (- n 1)))))
;;;;;;;;;;;;;;;;;;;
(define (for-loop n last op)
(cond ((<= n last)
(op n)
(for-loop (+ n 1) last op))))
(define (print-pascal-triangle n)
(define (print-pascal-row x)
(displayln (pascal-row x)))
(for-loop 1 n print-pascal-row))
(print-pascal-triangle 13)
;输出
( 1 )
( 1 1 )
; (1 2 1)
( 1 3 3 1 )
; (1 4 6 4 1)
; (1 5 10 10 5 1)
; (1 6 15 20 15 6 1)
; (1 7 21 35 35 21 7 1)
; (1 8 28 56 70 56 28 8 1)
( 1 9 36 84 126 126 84 36 9 1 )
( 1 10 45 120 210 252 210 120 45 10 1 )
( 1 11 55 165 330 462 462 330 165 55 11 1 )
( 1 12 66 220 495 792 924 792 495 220 66 12 1 )
| null | https://raw.githubusercontent.com/hjcapple/reading-sicp/7051d55dde841c06cf9326dc865d33d656702ecc/chapter_1/exercise_1_12.scm | scheme |
输出
(1 2 1)
(1 4 6 4 1)
(1 5 10 10 5 1)
(1 6 15 20 15 6 1)
(1 7 21 35 35 21 7 1)
(1 8 28 56 70 56 28 8 1) | #lang racket
P27 - [ 练习 1.12 ]
(define (pascal-row n)
(define (next-row lst)
(if (= (length lst) 1)
(list (car lst) (car lst))
(let ((ret (next-row (cdr lst)))
(first (car lst)))
(cons first (cons (+ first (car ret)) (cdr ret))))))
(if (<= n 1)
(list 1)
(next-row (pascal-row (- n 1)))))
(define (for-loop n last op)
(cond ((<= n last)
(op n)
(for-loop (+ n 1) last op))))
(define (print-pascal-triangle n)
(define (print-pascal-row x)
(displayln (pascal-row x)))
(for-loop 1 n print-pascal-row))
(print-pascal-triangle 13)
( 1 )
( 1 1 )
( 1 3 3 1 )
( 1 9 36 84 126 126 84 36 9 1 )
( 1 10 45 120 210 252 210 120 45 10 1 )
( 1 11 55 165 330 462 462 330 165 55 11 1 )
( 1 12 66 220 495 792 924 792 495 220 66 12 1 )
|
49931f0d1268eb09eff9c92b6c47ef71693ee8f8fad3d85eb905661401cf44e5 | LdBeth/keim | symbolics.lisp | ;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
;; ;;
Copyright ( C ) 1993 by AG Siekmann , , ; ;
Universitaet des Saarlandes , Saarbruecken , Germany . ; ;
;; All rights reserved. ;;
;; For information about this program, write to: ;;
;; KEIM Project ;;
AG Siekmann / FB Informatik ; ;
Universitaet des Saarlandes ; ;
1150 ; ;
; ;
Germany ; ;
;; electronic mail: ;;
;; ;;
;; The author makes no representations about the suitability of this ;;
software for any purpose . It is provided " AS IS " without express or ; ;
;; implied warranty. In particular, it must be understood that this ;;
;; software is an experimental version, and is not suitable for use in ;;
;; any safety-critical application, and the author denies a license for ;;
;; such use. ;;
;; ;;
;; You may use, copy, modify and distribute this software for any ;;
;; noncommercial and non-safety-critical purpose. Use of this software ;;
;; in a commercial product is not included under this license. You must ;;
;; maintain this copyright statement in all copies of this software that ;;
;; you modify or distribute. ;;
;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
(in-package "AGS")
#+(or symbolics explorer)
(defun emacs-time (&optional symbolp)
(multiple-value-bind (second minute hour day month year day.of.week daylight.saving.time.p time.zone)
(get-decoded-time)
(declare (ignore second day.of.week daylight.saving.time.p time.zone))
(let ((res (format nil "~@2,1,0,'0a-~a-~a ~@2,1,0,'0a:~@2,1,0,'0a"
day
(case month
(1 "JAN")
(2 "FEB")
(3 "MAR")
(4 "APR")
(5 "MAY")
(6 "JUN")
(7 "JUL")
(8 "AUG")
(9 "SEP")
(10 "OCT")
(11 "NOV")
(12 "DEC"))
year
hour
minute)))
(if symbolp (intern res) res))))
#+(or symbolics explorer)
(defvar emacs*author8)
#+(or symbolics explorer)
(defun emacs-authors ()
(intern (string-upcase (format nil "~a" (let ((user (global:send si:*user* :name)))
(if (stringp user)
user
(global:send user :string)))))))
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
'(#\h-r zwei:com-evaluate-and-replace-into-buffer))
#+(or symbolics explorer)
(zwei:DEFCOM COM-update-authors "" ()
(let ((position (zwei:search (zwei:point) "declare")))
(cond (position (zwei:move-point position)
(let ((ed.position (zwei:search (zwei:point) "(authors")))
(cond (ed.position (zwei:move-point ed.position)
(unless (search (symbol-name (emacs-authors)) (car ed.position))
(zwei:insert (list (car ed.position) (1+ (cadr ed.position)))
(format nil "~a " (emacs-authors))))))))))
zwei:DIS-TEXT)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
`(#\h-s com-update-authors))
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-declare (nil)
#\return "(ags::emacs-time)" #\c-space #\c-m-b #\h-r #\c-a #\tab "(declare (edited " #\c-e ")"
#\return "(ags::emacs-authors)" #\c-space #\c-m-b #\h-r #\c-a #\tab "(authors " #\c-e ")"
#\return #\tab "(input )"
#\return #\tab "(effect )"
#\return #\tab "(value ))")
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-declare)
#\h-d zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-update-current-declare (nil)
#\c-m-a #\h-s
#\c-m-a #\c-s "(declare (edited" #\end " " #\c-space #\c-e #\c-w
"(ags::emacs-time)" #\c-space #\c-m-b #\h-r #\c-e ")")
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-update-current-declare)
#\h-shift-s zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-kkl-evaluate (nil)
;; Evaluation of definitions with update of KKL declarations.
#\h-shift-s #\c-shift-e)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-kkl-compile (nil)
;; Evaluation of definitions with update of KKL declarations.
#\h-shift-s #\c-shift-c)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-kkl-evaluate)
#\h-shift-e zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-kkl-compile)
#\h-shift-c zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(ZWEI::READ-MAJOR-MODE-DEFAULTED-PATHNAME "Extract documentation for file:" (ZWEI::DEFAULT-PATHNAME)); ':NEWEST)
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(RETURN (VALUES)))) ;Saving failed, so quit early
(ZWEI::TYPEIN-LINE "Extract documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract Documentation" . com-EXTRACT-DOCUMENTATION)))
;;; extract tex documentation
;;; -------------------------
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-tex-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(ZWEI::READ-MAJOR-MODE-DEFAULTED-PATHNAME "Extract tex documentation for file:" (ZWEI::DEFAULT-PATHNAME)); ':NEWEST)
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract tex documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(RETURN (VALUES)))) ;Saving failed, so quit early
(ZWEI::TYPEIN-LINE "Extract tex documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH :interface-tex)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract tex Documentation" . com-EXTRACT-tex-DOCUMENTATION)))
;;; extract manual documentation
;;; -------------------------
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-manual-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(ZWEI::READ-MAJOR-MODE-DEFAULTED-PATHNAME "Extract manual documentation for file:" (ZWEI::DEFAULT-PATHNAME)); ':NEWEST)
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract manual documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(RETURN (VALUES)))) ;Saving failed, so quit early
(ZWEI::TYPEIN-LINE "Extract manual documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH :simple-tex)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract manual Documentation" . com-EXTRACT-manual-DOCUMENTATION)))
;;; extract complete documentation
;;; ------------------------------
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-complete-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(ZWEI::READ-MAJOR-MODE-DEFAULTED-PATHNAME "Extract complete documentation for file:" (ZWEI::DEFAULT-PATHNAME)); ':NEWEST)
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract complete documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(RETURN (VALUES)))) ;Saving failed, so quit early
(ZWEI::TYPEIN-LINE "Extract complete documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH :complete)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract complete Documentation" . com-EXTRACT-COMPLETE-DOCUMENTATION)))
;;; extract complete tex documentation
;;; ------------------------------
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-complete-tex-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(ZWEI::READ-MAJOR-MODE-DEFAULTED-PATHNAME "Extract complete tex-documentation for file:"
(ZWEI::DEFAULT-PATHNAME)); ':NEWEST)
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract complete tex documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(RETURN (VALUES)))) ;Saving failed, so quit early
(ZWEI::TYPEIN-LINE "Extract complete tex documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH :complete-tex)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract complete tex Documentation" . com-EXTRACT-COMPLETE-tex-DOCUMENTATION)))
;;; Same with semicolon comments
;;; ----------------------------
#+(or symbolics explorer)
(zwei:DEFCOM COM-update-authors-my "" ()
(let ((position (zwei:search (zwei:point) "")))
(cond (position (zwei:move-point position)
(let ((ed.position (zwei:search (zwei:point) "; Authors:")))
(cond (ed.position (zwei:move-point ed.position)
(unless (search (symbol-name (emacs-authors)) (car ed.position))
(zwei:insert (list (car ed.position) (1+ (cadr ed.position)))
(format nil "~a " (emacs-authors))))))))))
zwei:DIS-TEXT)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
`(#\s-s com-update-authors-my))
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-declare-my (nil)
#\return "(ags::emacs-time t)" #\c-space #\c-m-b #\h-r #\c-a #\tab
"; Edited: " #\c-space #\c-e #\c-% #\| #\return #\return #\c-e
#\return "(ags::emacs-authors)" #\c-space #\c-m-b #\h-r #\c-a #\tab "; Authors: " #\c-e
#\return #\tab "; Input: "
#\return #\tab "; Effect: "
#\return #\tab "; Value: " #\m-b #\m-b #\m-b #\m-f #\c-f #\c-f #\c-f #\c-f)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-declare-my)
#\s-d zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-update-current-declare-my (nil)
#\c-m-a #\s-s
#\c-m-a #\c-s "; Edited:" #\end " " #\c-space #\c-e #\c-w
"(ags::emacs-time t)" #\c-space #\c-m-b #\h-r #\c-a #\c-s "|" #\c-b #\c-d #\c-s "|" #\c-b #\c-d)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-update-current-declare-my)
#\s-shift-s zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-kkl-evaluate-my (nil)
;; Evaluation of definitions with update of KKL declarations.
#\s-shift-s #\c-shift-e)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-kkl-compile-my (nil)
;; Evaluation of definitions with update of KKL declarations.
#\s-shift-s #\c-shift-c)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-kkl-evaluate-my)
#\s-shift-e zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-kkl-compile-my)
#\s-shift-c zwei:*zmacs-comtab*)
| null | https://raw.githubusercontent.com/LdBeth/keim/ed2665d3b0d9a78eaa88b5a2940a4541f0750926/ags/prog/emacs/symbolics.lisp | lisp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
;;
;
;
All rights reserved. ;;
For information about this program, write to: ;;
KEIM Project ;;
;
;
;
;
;
electronic mail: ;;
;;
The author makes no representations about the suitability of this ;;
;
implied warranty. In particular, it must be understood that this ;;
software is an experimental version, and is not suitable for use in ;;
any safety-critical application, and the author denies a license for ;;
such use. ;;
;;
You may use, copy, modify and distribute this software for any ;;
noncommercial and non-safety-critical purpose. Use of this software ;;
in a commercial product is not included under this license. You must ;;
maintain this copyright statement in all copies of this software that ;;
you modify or distribute. ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;
Evaluation of definitions with update of KKL declarations.
Evaluation of definitions with update of KKL declarations.
':NEWEST)
Saving failed, so quit early
extract tex documentation
-------------------------
':NEWEST)
Saving failed, so quit early
extract manual documentation
-------------------------
':NEWEST)
Saving failed, so quit early
extract complete documentation
------------------------------
':NEWEST)
Saving failed, so quit early
extract complete tex documentation
------------------------------
':NEWEST)
Saving failed, so quit early
Same with semicolon comments
----------------------------
Evaluation of definitions with update of KKL declarations.
Evaluation of definitions with update of KKL declarations. |
(in-package "AGS")
#+(or symbolics explorer)
(defun emacs-time (&optional symbolp)
(multiple-value-bind (second minute hour day month year day.of.week daylight.saving.time.p time.zone)
(get-decoded-time)
(declare (ignore second day.of.week daylight.saving.time.p time.zone))
(let ((res (format nil "~@2,1,0,'0a-~a-~a ~@2,1,0,'0a:~@2,1,0,'0a"
day
(case month
(1 "JAN")
(2 "FEB")
(3 "MAR")
(4 "APR")
(5 "MAY")
(6 "JUN")
(7 "JUL")
(8 "AUG")
(9 "SEP")
(10 "OCT")
(11 "NOV")
(12 "DEC"))
year
hour
minute)))
(if symbolp (intern res) res))))
#+(or symbolics explorer)
(defvar emacs*author8)
#+(or symbolics explorer)
(defun emacs-authors ()
(intern (string-upcase (format nil "~a" (let ((user (global:send si:*user* :name)))
(if (stringp user)
user
(global:send user :string)))))))
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
'(#\h-r zwei:com-evaluate-and-replace-into-buffer))
#+(or symbolics explorer)
(zwei:DEFCOM COM-update-authors "" ()
(let ((position (zwei:search (zwei:point) "declare")))
(cond (position (zwei:move-point position)
(let ((ed.position (zwei:search (zwei:point) "(authors")))
(cond (ed.position (zwei:move-point ed.position)
(unless (search (symbol-name (emacs-authors)) (car ed.position))
(zwei:insert (list (car ed.position) (1+ (cadr ed.position)))
(format nil "~a " (emacs-authors))))))))))
zwei:DIS-TEXT)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
`(#\h-s com-update-authors))
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-declare (nil)
#\return "(ags::emacs-time)" #\c-space #\c-m-b #\h-r #\c-a #\tab "(declare (edited " #\c-e ")"
#\return "(ags::emacs-authors)" #\c-space #\c-m-b #\h-r #\c-a #\tab "(authors " #\c-e ")"
#\return #\tab "(input )"
#\return #\tab "(effect )"
#\return #\tab "(value ))")
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-declare)
#\h-d zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-update-current-declare (nil)
#\c-m-a #\h-s
#\c-m-a #\c-s "(declare (edited" #\end " " #\c-space #\c-e #\c-w
"(ags::emacs-time)" #\c-space #\c-m-b #\h-r #\c-e ")")
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-update-current-declare)
#\h-shift-s zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-kkl-evaluate (nil)
#\h-shift-s #\c-shift-e)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-kkl-compile (nil)
#\h-shift-s #\c-shift-c)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-kkl-evaluate)
#\h-shift-e zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-kkl-compile)
#\h-shift-c zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(ZWEI::TYPEIN-LINE "Extract documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract Documentation" . com-EXTRACT-DOCUMENTATION)))
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-tex-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract tex documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(ZWEI::TYPEIN-LINE "Extract tex documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH :interface-tex)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract tex Documentation" . com-EXTRACT-tex-DOCUMENTATION)))
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-manual-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract manual documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(ZWEI::TYPEIN-LINE "Extract manual documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH :simple-tex)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract manual Documentation" . com-EXTRACT-manual-DOCUMENTATION)))
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-complete-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract complete documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(ZWEI::TYPEIN-LINE "Extract complete documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH :complete)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract complete Documentation" . com-EXTRACT-COMPLETE-DOCUMENTATION)))
#+(or symbolics explorer)
(zwei:DEFCOM COM-extract-complete-tex-docUmentation "" ()
(MULTIPLE-VALUE-BIND (PATH MAJOR-MODE)
(ZWEI::READ-MAJOR-MODE-DEFAULTED-PATHNAME "Extract complete tex-documentation for file:"
(LET* ((OUT-PATH (AND ZWEI::*NUMERIC-ARG-P*
(kkb-default-pathname
(FORMAT NIL "Extract complete tex documentation ~A into file:" PATH)
PATH (GLOBAL:SEND MAJOR-MODE ':DEFAULT-COMPILER-OBJECT-FILE-TYPE)
':NEWEST ':WRITE)))
(BUFFER (ZWEI::FIND-BUFFER-NAMED PATH)))
(PROG ()
(WHEN (AND BUFFER
(GLOBAL:SEND BUFFER ':MODIFIED-P)
(ZWEI::FQUERY '(:SELECT T) "Save buffer ~A first? " (GLOBAL:SEND BUFFER ':NAME)))
(OR (ZWEI::SAVE-BUFFER BUFFER)
(ZWEI::TYPEIN-LINE "Extract complete tex documentation ~A~@[ into ~A~] ... " PATH OUT-PATH)
(DOC-EXTRACT PATH :complete-tex)
(ZWEI::TYPEIN-LINE-MORE "Done."))))
ZWEI::DIS-NONE)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
nil `(("Extract complete tex Documentation" . com-EXTRACT-COMPLETE-tex-DOCUMENTATION)))
#+(or symbolics explorer)
(zwei:DEFCOM COM-update-authors-my "" ()
(let ((position (zwei:search (zwei:point) "")))
(cond (position (zwei:move-point position)
(let ((ed.position (zwei:search (zwei:point) "; Authors:")))
(cond (ed.position (zwei:move-point ed.position)
(unless (search (symbol-name (emacs-authors)) (car ed.position))
(zwei:insert (list (car ed.position) (1+ (cadr ed.position)))
(format nil "~a " (emacs-authors))))))))))
zwei:DIS-TEXT)
#+(or symbolics explorer)
(zwei:set-comtab zwei:*zmacs-comtab*
`(#\s-s com-update-authors-my))
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-declare-my (nil)
#\return "(ags::emacs-time t)" #\c-space #\c-m-b #\h-r #\c-a #\tab
"; Edited: " #\c-space #\c-e #\c-% #\| #\return #\return #\c-e
#\return "(ags::emacs-authors)" #\c-space #\c-m-b #\h-r #\c-a #\tab "; Authors: " #\c-e
#\return #\tab "; Input: "
#\return #\tab "; Effect: "
#\return #\tab "; Value: " #\m-b #\m-b #\m-b #\m-f #\c-f #\c-f #\c-f #\c-f)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-declare-my)
#\s-d zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-update-current-declare-my (nil)
#\c-m-a #\s-s
#\c-m-a #\c-s "; Edited:" #\end " " #\c-space #\c-e #\c-w
"(ags::emacs-time t)" #\c-space #\c-m-b #\h-r #\c-a #\c-s "|" #\c-b #\c-d #\c-s "|" #\c-b #\c-d)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-update-current-declare-my)
#\s-shift-s zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-kkl-evaluate-my (nil)
#\s-shift-s #\c-shift-e)
#+(or symbolics explorer)
(zwei:define-keyboard-macro emacs-kkl-compile-my (nil)
#\s-shift-s #\c-shift-c)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-kkl-evaluate-my)
#\s-shift-e zwei:*zmacs-comtab*)
#+(or symbolics explorer)
(zwei:command-store (zwei:make-macro-command :emacs-kkl-compile-my)
#\s-shift-c zwei:*zmacs-comtab*)
|
cb0f2114d6c1d549a181b4489e77839bae1e6ce1b3181c6c7b787363a9ed41aa | metaocaml/ber-metaocaml | subst.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. *)
(* *)
(**************************************************************************)
(* Substitutions *)
open Misc
open Path
open Types
open Btype
type type_replacement =
| Path of Path.t
| Type_function of { params : type_expr list; body : type_expr }
type t =
{ types: type_replacement Path.Map.t;
modules: Path.t Path.Map.t;
modtypes: module_type Ident.Map.t;
for_saving: bool;
}
let identity =
{ types = Path.Map.empty;
modules = Path.Map.empty;
modtypes = Ident.Map.empty;
for_saving = false;
}
let add_type_path id p s = { s with types = Path.Map.add id (Path p) s.types }
let add_type id p s = add_type_path (Pident id) p s
let add_type_function id ~params ~body s =
{ s with types = Path.Map.add id (Type_function { params; body }) s.types }
let add_module_path id p s = { s with modules = Path.Map.add id p s.modules }
let add_module id p s = add_module_path (Pident id) p s
let add_modtype id ty s = { s with modtypes = Ident.Map.add id ty s.modtypes }
let for_saving s = { s with for_saving = true }
let loc s x =
if s.for_saving && not !Clflags.keep_locs then Location.none else x
let remove_loc =
let open Ast_mapper in
{default_mapper with location = (fun _this _loc -> Location.none)}
let is_not_doc = function
| {Parsetree.attr_name = {Location.txt = "ocaml.doc"}; _} -> false
| {Parsetree.attr_name = {Location.txt = "ocaml.text"}; _} -> false
| {Parsetree.attr_name = {Location.txt = "doc"}; _} -> false
| {Parsetree.attr_name = {Location.txt = "text"}; _} -> false
| _ -> true
let attrs s x =
let x =
if s.for_saving && not !Clflags.keep_docs then
List.filter is_not_doc x
else x
in
if s.for_saving && not !Clflags.keep_locs
then remove_loc.Ast_mapper.attributes remove_loc x
else x
let rec module_path s path =
try Path.Map.find path s.modules
with Not_found ->
match path with
| Pident _ -> path
| Pdot(p, n) ->
Pdot(module_path s p, n)
| Papply(p1, p2) ->
Papply(module_path s p1, module_path s p2)
let modtype_path s = function
Pident id as p ->
begin try
match Ident.Map.find id s.modtypes with
| Mty_ident p -> p
| _ -> fatal_error "Subst.modtype_path"
with Not_found -> p end
| Pdot(p, n) ->
Pdot(module_path s p, n)
| Papply _ ->
fatal_error "Subst.modtype_path"
let type_path s path =
match Path.Map.find path s.types with
| Path p -> p
| Type_function _ -> assert false
| exception Not_found ->
match path with
| Pident _ -> path
| Pdot(p, n) ->
Pdot(module_path s p, n)
| Papply _ ->
fatal_error "Subst.type_path"
let type_path s p =
match Path.constructor_typath p with
| Regular p -> type_path s p
| Cstr (ty_path, cstr) -> Pdot(type_path s ty_path, cstr)
| LocalExt _ -> type_path s p
| Ext (p, cstr) -> Pdot(module_path s p, cstr)
let to_subst_by_type_function s p =
match Path.Map.find p s.types with
| Path _ -> false
| Type_function _ -> true
| exception Not_found -> false
(* Special type ids for saved signatures *)
let new_id = ref (-1)
let reset_for_saving () = new_id := -1
let newpersty desc =
decr new_id;
{ desc; level = generic_level; scope = Btype.lowest_level; id = !new_id }
(* ensure that all occurrences of 'Tvar None' are physically shared *)
let tvar_none = Tvar None
let tunivar_none = Tunivar None
let norm = function
| Tvar None -> tvar_none
| Tunivar None -> tunivar_none
| d -> d
let ctype_apply_env_empty = ref (fun _ -> assert false)
(* Similar to [Ctype.nondep_type_rec]. *)
let rec typexp copy_scope s ty =
let ty = repr ty in
match ty.desc with
Tvar _ | Tunivar _ as desc ->
if s.for_saving || ty.id < 0 then
let ty' =
if s.for_saving then newpersty (norm desc)
else newty2 ty.level desc
in
For_copy.save_desc copy_scope ty desc;
ty.desc <- Tsubst ty';
ty'
else ty
| Tsubst ty ->
ty
| Tfield (m, k, _t1, _t2) when not s.for_saving && m = dummy_method
&& field_kind_repr k <> Fabsent && (repr ty).level < generic_level ->
(* do not copy the type of self when it is not generalized *)
ty
can not do it , since it would omit substitution
| Tvariant row when not ( static_row row ) - >
ty
| Tvariant row when not (static_row row) ->
ty
*)
| _ ->
let desc = ty.desc in
For_copy.save_desc copy_scope ty desc;
let tm = row_of_type ty in
let has_fixed_row =
not (is_Tconstr ty) && is_constr_row ~allow_ident:false tm in
(* Make a stub *)
let ty' = if s.for_saving then newpersty (Tvar None) else newgenvar () in
ty'.scope <- ty.scope;
ty.desc <- Tsubst ty';
ty'.desc <-
begin if has_fixed_row then
match tm.desc with (* PR#7348 *)
Tconstr (Pdot(m,i), tl, _abbrev) ->
let i' = String.sub i 0 (String.length i - 4) in
Tconstr(type_path s (Pdot(m,i')), tl, ref Mnil)
| _ -> assert false
else match desc with
| Tconstr (p, args, _abbrev) ->
let args = List.map (typexp copy_scope s) args in
begin match Path.Map.find p s.types with
| exception Not_found -> Tconstr(type_path s p, args, ref Mnil)
| Path _ -> Tconstr(type_path s p, args, ref Mnil)
| Type_function { params; body } ->
Tlink (!ctype_apply_env_empty params body args)
end
| Tpackage(p, n, tl) ->
Tpackage(modtype_path s p, n, List.map (typexp copy_scope s) tl)
| Tobject (t1, name) ->
let t1' = typexp copy_scope s t1 in
let name' =
match !name with
| None -> None
| Some (p, tl) ->
if to_subst_by_type_function s p
then None
else Some (type_path s p, List.map (typexp copy_scope s) tl)
in
Tobject (t1', ref name')
| Tvariant row ->
let row = row_repr row in
let more = repr row.row_more in
(* We must substitute in a subtle way *)
(* Tsubst takes a tuple containing the row var and the variant *)
begin match more.desc with
Tsubst {desc = Ttuple [_;ty2]} ->
(* This variant type has been already copied *)
avoid in the new type
Tlink ty2
| _ ->
let dup =
s.for_saving || more.level = generic_level || static_row row ||
match more.desc with Tconstr _ -> true | _ -> false in
(* Various cases for the row variable *)
let more' =
match more.desc with
Tsubst ty -> ty
| Tconstr _ | Tnil -> typexp copy_scope s more
| Tunivar _ | Tvar _ ->
For_copy.save_desc copy_scope more more.desc;
if s.for_saving then newpersty (norm more.desc) else
if dup && is_Tvar more then newgenty more.desc else more
| _ -> assert false
in
Register new type first for recursion
more.desc <- Tsubst(newgenty(Ttuple[more';ty']));
(* Return a new copy *)
let row =
copy_row (typexp copy_scope s) true row (not dup) more' in
match row.row_name with
| Some (p, tl) ->
Tvariant {row with row_name =
if to_subst_by_type_function s p
then None
else Some (type_path s p, tl)}
| None ->
Tvariant row
end
| Tfield(_label, kind, _t1, t2) when field_kind_repr kind = Fabsent ->
Tlink (typexp copy_scope s t2)
| _ -> copy_type_desc (typexp copy_scope s) desc
end;
ty'
(*
Always make a copy of the type. If this is not done, type levels
might not be correct.
*)
let type_expr s ty =
For_copy.with_scope (fun copy_scope -> typexp copy_scope s ty)
let label_declaration copy_scope s l =
{
ld_id = l.ld_id;
ld_mutable = l.ld_mutable;
ld_type = typexp copy_scope s l.ld_type;
ld_loc = loc s l.ld_loc;
ld_attributes = attrs s l.ld_attributes;
ld_uid = l.ld_uid;
}
let constructor_arguments copy_scope s = function
| Cstr_tuple l ->
Cstr_tuple (List.map (typexp copy_scope s) l)
| Cstr_record l ->
Cstr_record (List.map (label_declaration copy_scope s) l)
let constructor_declaration copy_scope s c =
{
cd_id = c.cd_id;
cd_args = constructor_arguments copy_scope s c.cd_args;
cd_res = Option.map (typexp copy_scope s) c.cd_res;
cd_loc = loc s c.cd_loc;
cd_attributes = attrs s c.cd_attributes;
cd_uid = c.cd_uid;
}
let type_declaration' copy_scope s decl =
{ type_params = List.map (typexp copy_scope s) decl.type_params;
type_arity = decl.type_arity;
type_kind =
begin match decl.type_kind with
Type_abstract -> Type_abstract
| Type_variant cstrs ->
Type_variant (List.map (constructor_declaration copy_scope s) cstrs)
| Type_record(lbls, rep) ->
Type_record (List.map (label_declaration copy_scope s) lbls, rep)
| Type_open -> Type_open
end;
type_manifest =
begin
match decl.type_manifest with
None -> None
| Some ty -> Some(typexp copy_scope s ty)
end;
type_private = decl.type_private;
type_variance = decl.type_variance;
type_separability = decl.type_separability;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = loc s decl.type_loc;
type_attributes = attrs s decl.type_attributes;
type_immediate = decl.type_immediate;
type_unboxed = decl.type_unboxed;
type_uid = decl.type_uid;
}
let type_declaration s decl =
For_copy.with_scope (fun copy_scope -> type_declaration' copy_scope s decl)
let class_signature copy_scope s sign =
{ csig_self = typexp copy_scope s sign.csig_self;
csig_vars =
Vars.map
(function (m, v, t) -> (m, v, typexp copy_scope s t)) sign.csig_vars;
csig_concr = sign.csig_concr;
csig_inher =
List.map
(fun (p, tl) -> (type_path s p, List.map (typexp copy_scope s) tl))
sign.csig_inher;
}
let rec class_type copy_scope s = function
| Cty_constr (p, tyl, cty) ->
let p' = type_path s p in
let tyl' = List.map (typexp copy_scope s) tyl in
let cty' = class_type copy_scope s cty in
Cty_constr (p', tyl', cty')
| Cty_signature sign ->
Cty_signature (class_signature copy_scope s sign)
| Cty_arrow (l, ty, cty) ->
Cty_arrow (l, typexp copy_scope s ty, class_type copy_scope s cty)
let class_declaration' copy_scope s decl =
{ cty_params = List.map (typexp copy_scope s) decl.cty_params;
cty_variance = decl.cty_variance;
cty_type = class_type copy_scope s decl.cty_type;
cty_path = type_path s decl.cty_path;
cty_new =
begin match decl.cty_new with
| None -> None
| Some ty -> Some (typexp copy_scope s ty)
end;
cty_loc = loc s decl.cty_loc;
cty_attributes = attrs s decl.cty_attributes;
cty_uid = decl.cty_uid;
}
let class_declaration s decl =
For_copy.with_scope (fun copy_scope -> class_declaration' copy_scope s decl)
let cltype_declaration' copy_scope s decl =
{ clty_params = List.map (typexp copy_scope s) decl.clty_params;
clty_variance = decl.clty_variance;
clty_type = class_type copy_scope s decl.clty_type;
clty_path = type_path s decl.clty_path;
clty_loc = loc s decl.clty_loc;
clty_attributes = attrs s decl.clty_attributes;
clty_uid = decl.clty_uid;
}
let cltype_declaration s decl =
For_copy.with_scope (fun copy_scope -> cltype_declaration' copy_scope s decl)
let class_type s cty =
For_copy.with_scope (fun copy_scope -> class_type copy_scope s cty)
let value_description' copy_scope s descr =
{ val_type = typexp copy_scope s descr.val_type;
val_kind = descr.val_kind;
val_loc = loc s descr.val_loc;
val_attributes = attrs s descr.val_attributes;
val_uid = descr.val_uid;
}
let value_description s descr =
For_copy.with_scope (fun copy_scope -> value_description' copy_scope s descr)
let extension_constructor' copy_scope s ext =
{ ext_type_path = type_path s ext.ext_type_path;
ext_type_params = List.map (typexp copy_scope s) ext.ext_type_params;
ext_args = constructor_arguments copy_scope s ext.ext_args;
ext_ret_type = Option.map (typexp copy_scope s) ext.ext_ret_type;
ext_private = ext.ext_private;
ext_attributes = attrs s ext.ext_attributes;
ext_loc = if s.for_saving then Location.none else ext.ext_loc;
ext_uid = ext.ext_uid;
}
let extension_constructor s ext =
For_copy.with_scope
(fun copy_scope -> extension_constructor' copy_scope s ext)
type scoping =
| Keep
| Make_local
| Rescope of int
let rename_bound_idents scoping s sg =
let rename =
let open Ident in
match scoping with
| Keep -> (fun id -> create_scoped ~scope:(scope id) (name id))
| Make_local -> Ident.rename
| Rescope scope -> (fun id -> create_scoped ~scope (name id))
in
let rec rename_bound_idents s sg = function
| [] -> sg, s
| Sig_type(id, td, rs, vis) :: rest ->
let id' = rename id in
rename_bound_idents
(add_type id (Pident id') s)
(Sig_type(id', td, rs, vis) :: sg)
rest
| Sig_module(id, pres, md, rs, vis) :: rest ->
let id' = rename id in
rename_bound_idents
(add_module id (Pident id') s)
(Sig_module (id', pres, md, rs, vis) :: sg)
rest
| Sig_modtype(id, mtd, vis) :: rest ->
let id' = rename id in
rename_bound_idents
(add_modtype id (Mty_ident(Pident id')) s)
(Sig_modtype(id', mtd, vis) :: sg)
rest
| Sig_class(id, cd, rs, vis) :: rest ->
(* cheat and pretend they are types cf. PR#6650 *)
let id' = rename id in
rename_bound_idents
(add_type id (Pident id') s)
(Sig_class(id', cd, rs, vis) :: sg)
rest
| Sig_class_type(id, ctd, rs, vis) :: rest ->
(* cheat and pretend they are types cf. PR#6650 *)
let id' = rename id in
rename_bound_idents
(add_type id (Pident id') s)
(Sig_class_type(id', ctd, rs, vis) :: sg)
rest
| Sig_value(id, vd, vis) :: rest ->
(* scope doesn't matter for value identifiers. *)
let id' = Ident.rename id in
rename_bound_idents s (Sig_value(id', vd, vis) :: sg) rest
| Sig_typext(id, ec, es, vis) :: rest ->
let id' = rename id in
rename_bound_idents s (Sig_typext(id',ec,es,vis) :: sg) rest
in
rename_bound_idents s [] sg
let rec modtype scoping s = function
Mty_ident p as mty ->
begin match p with
Pident id ->
begin try Ident.Map.find id s.modtypes with Not_found -> mty end
| Pdot(p, n) ->
Mty_ident(Pdot(module_path s p, n))
| Papply _ ->
fatal_error "Subst.modtype"
end
| Mty_signature sg ->
Mty_signature(signature scoping s sg)
| Mty_functor(Unit, res) ->
Mty_functor(Unit, modtype scoping s res)
| Mty_functor(Named (None, arg), res) ->
Mty_functor(Named (None, (modtype scoping s) arg), modtype scoping s res)
| Mty_functor(Named (Some id, arg), res) ->
let id' = Ident.rename id in
Mty_functor(Named (Some id', (modtype scoping s) arg),
modtype scoping (add_module id (Pident id') s) res)
| Mty_alias p ->
Mty_alias (module_path s p)
and signature scoping s sg =
Components of signature may be mutually recursive ( e.g. type declarations
or class and type declarations ) , so first build global renaming
substitution ...
or class and type declarations), so first build global renaming
substitution... *)
let (sg', s') = rename_bound_idents scoping s sg in
(* ... then apply it to each signature component in turn *)
For_copy.with_scope (fun copy_scope ->
List.rev_map (signature_item' copy_scope scoping s') sg'
)
and signature_item' copy_scope scoping s comp =
match comp with
Sig_value(id, d, vis) ->
Sig_value(id, value_description' copy_scope s d, vis)
| Sig_type(id, d, rs, vis) ->
Sig_type(id, type_declaration' copy_scope s d, rs, vis)
| Sig_typext(id, ext, es, vis) ->
Sig_typext(id, extension_constructor' copy_scope s ext, es, vis)
| Sig_module(id, pres, d, rs, vis) ->
Sig_module(id, pres, module_declaration scoping s d, rs, vis)
| Sig_modtype(id, d, vis) ->
Sig_modtype(id, modtype_declaration scoping s d, vis)
| Sig_class(id, d, rs, vis) ->
Sig_class(id, class_declaration' copy_scope s d, rs, vis)
| Sig_class_type(id, d, rs, vis) ->
Sig_class_type(id, cltype_declaration' copy_scope s d, rs, vis)
and signature_item scoping s comp =
For_copy.with_scope
(fun copy_scope -> signature_item' copy_scope scoping s comp)
and module_declaration scoping s decl =
{
md_type = modtype scoping s decl.md_type;
md_attributes = attrs s decl.md_attributes;
md_loc = loc s decl.md_loc;
md_uid = decl.md_uid;
}
and modtype_declaration scoping s decl =
{
mtd_type = Option.map (modtype scoping s) decl.mtd_type;
mtd_attributes = attrs s decl.mtd_attributes;
mtd_loc = loc s decl.mtd_loc;
mtd_uid = decl.mtd_uid;
}
(* For every binding k |-> d of m1, add k |-> f d to m2
and return resulting merged map. *)
let merge_tbls f m1 m2 =
Ident.Map.fold (fun k d accu -> Ident.Map.add k (f d) accu) m1 m2
let merge_path_maps f m1 m2 =
Path.Map.fold (fun k d accu -> Path.Map.add k (f d) accu) m1 m2
let type_replacement s = function
| Path p -> Path (type_path s p)
| Type_function { params; body } ->
For_copy.with_scope (fun copy_scope ->
let params = List.map (typexp copy_scope s) params in
let body = typexp copy_scope s body in
Type_function { params; body })
(* Composition of substitutions:
apply (compose s1 s2) x = apply s2 (apply s1 x) *)
let compose s1 s2 =
{ types = merge_path_maps (type_replacement s2) s1.types s2.types;
modules = merge_path_maps (module_path s2) s1.modules s2.modules;
modtypes = merge_tbls (modtype Keep s2) s1.modtypes s2.modtypes;
for_saving = s1.for_saving || s2.for_saving;
}
| null | https://raw.githubusercontent.com/metaocaml/ber-metaocaml/4992d1f87fc08ccb958817926cf9d1d739caf3a2/typing/subst.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.
************************************************************************
Substitutions
Special type ids for saved signatures
ensure that all occurrences of 'Tvar None' are physically shared
Similar to [Ctype.nondep_type_rec].
do not copy the type of self when it is not generalized
Make a stub
PR#7348
We must substitute in a subtle way
Tsubst takes a tuple containing the row var and the variant
This variant type has been already copied
Various cases for the row variable
Return a new copy
Always make a copy of the type. If this is not done, type levels
might not be correct.
cheat and pretend they are types cf. PR#6650
cheat and pretend they are types cf. PR#6650
scope doesn't matter for value identifiers.
... then apply it to each signature component in turn
For every binding k |-> d of m1, add k |-> f d to m2
and return resulting merged map.
Composition of substitutions:
apply (compose s1 s2) x = apply s2 (apply s1 x) | , 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 Misc
open Path
open Types
open Btype
type type_replacement =
| Path of Path.t
| Type_function of { params : type_expr list; body : type_expr }
type t =
{ types: type_replacement Path.Map.t;
modules: Path.t Path.Map.t;
modtypes: module_type Ident.Map.t;
for_saving: bool;
}
let identity =
{ types = Path.Map.empty;
modules = Path.Map.empty;
modtypes = Ident.Map.empty;
for_saving = false;
}
let add_type_path id p s = { s with types = Path.Map.add id (Path p) s.types }
let add_type id p s = add_type_path (Pident id) p s
let add_type_function id ~params ~body s =
{ s with types = Path.Map.add id (Type_function { params; body }) s.types }
let add_module_path id p s = { s with modules = Path.Map.add id p s.modules }
let add_module id p s = add_module_path (Pident id) p s
let add_modtype id ty s = { s with modtypes = Ident.Map.add id ty s.modtypes }
let for_saving s = { s with for_saving = true }
let loc s x =
if s.for_saving && not !Clflags.keep_locs then Location.none else x
let remove_loc =
let open Ast_mapper in
{default_mapper with location = (fun _this _loc -> Location.none)}
let is_not_doc = function
| {Parsetree.attr_name = {Location.txt = "ocaml.doc"}; _} -> false
| {Parsetree.attr_name = {Location.txt = "ocaml.text"}; _} -> false
| {Parsetree.attr_name = {Location.txt = "doc"}; _} -> false
| {Parsetree.attr_name = {Location.txt = "text"}; _} -> false
| _ -> true
let attrs s x =
let x =
if s.for_saving && not !Clflags.keep_docs then
List.filter is_not_doc x
else x
in
if s.for_saving && not !Clflags.keep_locs
then remove_loc.Ast_mapper.attributes remove_loc x
else x
let rec module_path s path =
try Path.Map.find path s.modules
with Not_found ->
match path with
| Pident _ -> path
| Pdot(p, n) ->
Pdot(module_path s p, n)
| Papply(p1, p2) ->
Papply(module_path s p1, module_path s p2)
let modtype_path s = function
Pident id as p ->
begin try
match Ident.Map.find id s.modtypes with
| Mty_ident p -> p
| _ -> fatal_error "Subst.modtype_path"
with Not_found -> p end
| Pdot(p, n) ->
Pdot(module_path s p, n)
| Papply _ ->
fatal_error "Subst.modtype_path"
let type_path s path =
match Path.Map.find path s.types with
| Path p -> p
| Type_function _ -> assert false
| exception Not_found ->
match path with
| Pident _ -> path
| Pdot(p, n) ->
Pdot(module_path s p, n)
| Papply _ ->
fatal_error "Subst.type_path"
let type_path s p =
match Path.constructor_typath p with
| Regular p -> type_path s p
| Cstr (ty_path, cstr) -> Pdot(type_path s ty_path, cstr)
| LocalExt _ -> type_path s p
| Ext (p, cstr) -> Pdot(module_path s p, cstr)
let to_subst_by_type_function s p =
match Path.Map.find p s.types with
| Path _ -> false
| Type_function _ -> true
| exception Not_found -> false
let new_id = ref (-1)
let reset_for_saving () = new_id := -1
let newpersty desc =
decr new_id;
{ desc; level = generic_level; scope = Btype.lowest_level; id = !new_id }
let tvar_none = Tvar None
let tunivar_none = Tunivar None
let norm = function
| Tvar None -> tvar_none
| Tunivar None -> tunivar_none
| d -> d
let ctype_apply_env_empty = ref (fun _ -> assert false)
let rec typexp copy_scope s ty =
let ty = repr ty in
match ty.desc with
Tvar _ | Tunivar _ as desc ->
if s.for_saving || ty.id < 0 then
let ty' =
if s.for_saving then newpersty (norm desc)
else newty2 ty.level desc
in
For_copy.save_desc copy_scope ty desc;
ty.desc <- Tsubst ty';
ty'
else ty
| Tsubst ty ->
ty
| Tfield (m, k, _t1, _t2) when not s.for_saving && m = dummy_method
&& field_kind_repr k <> Fabsent && (repr ty).level < generic_level ->
ty
can not do it , since it would omit substitution
| Tvariant row when not ( static_row row ) - >
ty
| Tvariant row when not (static_row row) ->
ty
*)
| _ ->
let desc = ty.desc in
For_copy.save_desc copy_scope ty desc;
let tm = row_of_type ty in
let has_fixed_row =
not (is_Tconstr ty) && is_constr_row ~allow_ident:false tm in
let ty' = if s.for_saving then newpersty (Tvar None) else newgenvar () in
ty'.scope <- ty.scope;
ty.desc <- Tsubst ty';
ty'.desc <-
begin if has_fixed_row then
Tconstr (Pdot(m,i), tl, _abbrev) ->
let i' = String.sub i 0 (String.length i - 4) in
Tconstr(type_path s (Pdot(m,i')), tl, ref Mnil)
| _ -> assert false
else match desc with
| Tconstr (p, args, _abbrev) ->
let args = List.map (typexp copy_scope s) args in
begin match Path.Map.find p s.types with
| exception Not_found -> Tconstr(type_path s p, args, ref Mnil)
| Path _ -> Tconstr(type_path s p, args, ref Mnil)
| Type_function { params; body } ->
Tlink (!ctype_apply_env_empty params body args)
end
| Tpackage(p, n, tl) ->
Tpackage(modtype_path s p, n, List.map (typexp copy_scope s) tl)
| Tobject (t1, name) ->
let t1' = typexp copy_scope s t1 in
let name' =
match !name with
| None -> None
| Some (p, tl) ->
if to_subst_by_type_function s p
then None
else Some (type_path s p, List.map (typexp copy_scope s) tl)
in
Tobject (t1', ref name')
| Tvariant row ->
let row = row_repr row in
let more = repr row.row_more in
begin match more.desc with
Tsubst {desc = Ttuple [_;ty2]} ->
avoid in the new type
Tlink ty2
| _ ->
let dup =
s.for_saving || more.level = generic_level || static_row row ||
match more.desc with Tconstr _ -> true | _ -> false in
let more' =
match more.desc with
Tsubst ty -> ty
| Tconstr _ | Tnil -> typexp copy_scope s more
| Tunivar _ | Tvar _ ->
For_copy.save_desc copy_scope more more.desc;
if s.for_saving then newpersty (norm more.desc) else
if dup && is_Tvar more then newgenty more.desc else more
| _ -> assert false
in
Register new type first for recursion
more.desc <- Tsubst(newgenty(Ttuple[more';ty']));
let row =
copy_row (typexp copy_scope s) true row (not dup) more' in
match row.row_name with
| Some (p, tl) ->
Tvariant {row with row_name =
if to_subst_by_type_function s p
then None
else Some (type_path s p, tl)}
| None ->
Tvariant row
end
| Tfield(_label, kind, _t1, t2) when field_kind_repr kind = Fabsent ->
Tlink (typexp copy_scope s t2)
| _ -> copy_type_desc (typexp copy_scope s) desc
end;
ty'
let type_expr s ty =
For_copy.with_scope (fun copy_scope -> typexp copy_scope s ty)
let label_declaration copy_scope s l =
{
ld_id = l.ld_id;
ld_mutable = l.ld_mutable;
ld_type = typexp copy_scope s l.ld_type;
ld_loc = loc s l.ld_loc;
ld_attributes = attrs s l.ld_attributes;
ld_uid = l.ld_uid;
}
let constructor_arguments copy_scope s = function
| Cstr_tuple l ->
Cstr_tuple (List.map (typexp copy_scope s) l)
| Cstr_record l ->
Cstr_record (List.map (label_declaration copy_scope s) l)
let constructor_declaration copy_scope s c =
{
cd_id = c.cd_id;
cd_args = constructor_arguments copy_scope s c.cd_args;
cd_res = Option.map (typexp copy_scope s) c.cd_res;
cd_loc = loc s c.cd_loc;
cd_attributes = attrs s c.cd_attributes;
cd_uid = c.cd_uid;
}
let type_declaration' copy_scope s decl =
{ type_params = List.map (typexp copy_scope s) decl.type_params;
type_arity = decl.type_arity;
type_kind =
begin match decl.type_kind with
Type_abstract -> Type_abstract
| Type_variant cstrs ->
Type_variant (List.map (constructor_declaration copy_scope s) cstrs)
| Type_record(lbls, rep) ->
Type_record (List.map (label_declaration copy_scope s) lbls, rep)
| Type_open -> Type_open
end;
type_manifest =
begin
match decl.type_manifest with
None -> None
| Some ty -> Some(typexp copy_scope s ty)
end;
type_private = decl.type_private;
type_variance = decl.type_variance;
type_separability = decl.type_separability;
type_is_newtype = false;
type_expansion_scope = Btype.lowest_level;
type_loc = loc s decl.type_loc;
type_attributes = attrs s decl.type_attributes;
type_immediate = decl.type_immediate;
type_unboxed = decl.type_unboxed;
type_uid = decl.type_uid;
}
let type_declaration s decl =
For_copy.with_scope (fun copy_scope -> type_declaration' copy_scope s decl)
let class_signature copy_scope s sign =
{ csig_self = typexp copy_scope s sign.csig_self;
csig_vars =
Vars.map
(function (m, v, t) -> (m, v, typexp copy_scope s t)) sign.csig_vars;
csig_concr = sign.csig_concr;
csig_inher =
List.map
(fun (p, tl) -> (type_path s p, List.map (typexp copy_scope s) tl))
sign.csig_inher;
}
let rec class_type copy_scope s = function
| Cty_constr (p, tyl, cty) ->
let p' = type_path s p in
let tyl' = List.map (typexp copy_scope s) tyl in
let cty' = class_type copy_scope s cty in
Cty_constr (p', tyl', cty')
| Cty_signature sign ->
Cty_signature (class_signature copy_scope s sign)
| Cty_arrow (l, ty, cty) ->
Cty_arrow (l, typexp copy_scope s ty, class_type copy_scope s cty)
let class_declaration' copy_scope s decl =
{ cty_params = List.map (typexp copy_scope s) decl.cty_params;
cty_variance = decl.cty_variance;
cty_type = class_type copy_scope s decl.cty_type;
cty_path = type_path s decl.cty_path;
cty_new =
begin match decl.cty_new with
| None -> None
| Some ty -> Some (typexp copy_scope s ty)
end;
cty_loc = loc s decl.cty_loc;
cty_attributes = attrs s decl.cty_attributes;
cty_uid = decl.cty_uid;
}
let class_declaration s decl =
For_copy.with_scope (fun copy_scope -> class_declaration' copy_scope s decl)
let cltype_declaration' copy_scope s decl =
{ clty_params = List.map (typexp copy_scope s) decl.clty_params;
clty_variance = decl.clty_variance;
clty_type = class_type copy_scope s decl.clty_type;
clty_path = type_path s decl.clty_path;
clty_loc = loc s decl.clty_loc;
clty_attributes = attrs s decl.clty_attributes;
clty_uid = decl.clty_uid;
}
let cltype_declaration s decl =
For_copy.with_scope (fun copy_scope -> cltype_declaration' copy_scope s decl)
let class_type s cty =
For_copy.with_scope (fun copy_scope -> class_type copy_scope s cty)
let value_description' copy_scope s descr =
{ val_type = typexp copy_scope s descr.val_type;
val_kind = descr.val_kind;
val_loc = loc s descr.val_loc;
val_attributes = attrs s descr.val_attributes;
val_uid = descr.val_uid;
}
let value_description s descr =
For_copy.with_scope (fun copy_scope -> value_description' copy_scope s descr)
let extension_constructor' copy_scope s ext =
{ ext_type_path = type_path s ext.ext_type_path;
ext_type_params = List.map (typexp copy_scope s) ext.ext_type_params;
ext_args = constructor_arguments copy_scope s ext.ext_args;
ext_ret_type = Option.map (typexp copy_scope s) ext.ext_ret_type;
ext_private = ext.ext_private;
ext_attributes = attrs s ext.ext_attributes;
ext_loc = if s.for_saving then Location.none else ext.ext_loc;
ext_uid = ext.ext_uid;
}
let extension_constructor s ext =
For_copy.with_scope
(fun copy_scope -> extension_constructor' copy_scope s ext)
type scoping =
| Keep
| Make_local
| Rescope of int
let rename_bound_idents scoping s sg =
let rename =
let open Ident in
match scoping with
| Keep -> (fun id -> create_scoped ~scope:(scope id) (name id))
| Make_local -> Ident.rename
| Rescope scope -> (fun id -> create_scoped ~scope (name id))
in
let rec rename_bound_idents s sg = function
| [] -> sg, s
| Sig_type(id, td, rs, vis) :: rest ->
let id' = rename id in
rename_bound_idents
(add_type id (Pident id') s)
(Sig_type(id', td, rs, vis) :: sg)
rest
| Sig_module(id, pres, md, rs, vis) :: rest ->
let id' = rename id in
rename_bound_idents
(add_module id (Pident id') s)
(Sig_module (id', pres, md, rs, vis) :: sg)
rest
| Sig_modtype(id, mtd, vis) :: rest ->
let id' = rename id in
rename_bound_idents
(add_modtype id (Mty_ident(Pident id')) s)
(Sig_modtype(id', mtd, vis) :: sg)
rest
| Sig_class(id, cd, rs, vis) :: rest ->
let id' = rename id in
rename_bound_idents
(add_type id (Pident id') s)
(Sig_class(id', cd, rs, vis) :: sg)
rest
| Sig_class_type(id, ctd, rs, vis) :: rest ->
let id' = rename id in
rename_bound_idents
(add_type id (Pident id') s)
(Sig_class_type(id', ctd, rs, vis) :: sg)
rest
| Sig_value(id, vd, vis) :: rest ->
let id' = Ident.rename id in
rename_bound_idents s (Sig_value(id', vd, vis) :: sg) rest
| Sig_typext(id, ec, es, vis) :: rest ->
let id' = rename id in
rename_bound_idents s (Sig_typext(id',ec,es,vis) :: sg) rest
in
rename_bound_idents s [] sg
let rec modtype scoping s = function
Mty_ident p as mty ->
begin match p with
Pident id ->
begin try Ident.Map.find id s.modtypes with Not_found -> mty end
| Pdot(p, n) ->
Mty_ident(Pdot(module_path s p, n))
| Papply _ ->
fatal_error "Subst.modtype"
end
| Mty_signature sg ->
Mty_signature(signature scoping s sg)
| Mty_functor(Unit, res) ->
Mty_functor(Unit, modtype scoping s res)
| Mty_functor(Named (None, arg), res) ->
Mty_functor(Named (None, (modtype scoping s) arg), modtype scoping s res)
| Mty_functor(Named (Some id, arg), res) ->
let id' = Ident.rename id in
Mty_functor(Named (Some id', (modtype scoping s) arg),
modtype scoping (add_module id (Pident id') s) res)
| Mty_alias p ->
Mty_alias (module_path s p)
and signature scoping s sg =
Components of signature may be mutually recursive ( e.g. type declarations
or class and type declarations ) , so first build global renaming
substitution ...
or class and type declarations), so first build global renaming
substitution... *)
let (sg', s') = rename_bound_idents scoping s sg in
For_copy.with_scope (fun copy_scope ->
List.rev_map (signature_item' copy_scope scoping s') sg'
)
and signature_item' copy_scope scoping s comp =
match comp with
Sig_value(id, d, vis) ->
Sig_value(id, value_description' copy_scope s d, vis)
| Sig_type(id, d, rs, vis) ->
Sig_type(id, type_declaration' copy_scope s d, rs, vis)
| Sig_typext(id, ext, es, vis) ->
Sig_typext(id, extension_constructor' copy_scope s ext, es, vis)
| Sig_module(id, pres, d, rs, vis) ->
Sig_module(id, pres, module_declaration scoping s d, rs, vis)
| Sig_modtype(id, d, vis) ->
Sig_modtype(id, modtype_declaration scoping s d, vis)
| Sig_class(id, d, rs, vis) ->
Sig_class(id, class_declaration' copy_scope s d, rs, vis)
| Sig_class_type(id, d, rs, vis) ->
Sig_class_type(id, cltype_declaration' copy_scope s d, rs, vis)
and signature_item scoping s comp =
For_copy.with_scope
(fun copy_scope -> signature_item' copy_scope scoping s comp)
and module_declaration scoping s decl =
{
md_type = modtype scoping s decl.md_type;
md_attributes = attrs s decl.md_attributes;
md_loc = loc s decl.md_loc;
md_uid = decl.md_uid;
}
and modtype_declaration scoping s decl =
{
mtd_type = Option.map (modtype scoping s) decl.mtd_type;
mtd_attributes = attrs s decl.mtd_attributes;
mtd_loc = loc s decl.mtd_loc;
mtd_uid = decl.mtd_uid;
}
let merge_tbls f m1 m2 =
Ident.Map.fold (fun k d accu -> Ident.Map.add k (f d) accu) m1 m2
let merge_path_maps f m1 m2 =
Path.Map.fold (fun k d accu -> Path.Map.add k (f d) accu) m1 m2
let type_replacement s = function
| Path p -> Path (type_path s p)
| Type_function { params; body } ->
For_copy.with_scope (fun copy_scope ->
let params = List.map (typexp copy_scope s) params in
let body = typexp copy_scope s body in
Type_function { params; body })
let compose s1 s2 =
{ types = merge_path_maps (type_replacement s2) s1.types s2.types;
modules = merge_path_maps (module_path s2) s1.modules s2.modules;
modtypes = merge_tbls (modtype Keep s2) s1.modtypes s2.modtypes;
for_saving = s1.for_saving || s2.for_saving;
}
|
df20ce2d2b310d2202db144806ffff9de7bed55eceeef0bb6abfc553ce559cd4 | lnostdal/SymbolicWeb | container_model.clj | (in-ns 'symbolicweb.core)
TODO ( ? )
: Why you should avoid Linked Lists
;;; -vgmo
(defmacro cm-iterate "Iterate over CMNs in CONTAINER-MODEL executing BODY for each iteration with CMN-DATA-SYMBOL bound to the CMN-DATA of each
CMN respectively.
Iteration will end whenever BODY returns a True value, or when the tail of CONTAINER-MODEL was reached."
[container-model cmn-symbol cmn-data-symbol & body]
`(loop [~cmn-symbol (cm-head-node ~container-model)]
(when ~cmn-symbol
(let [~cmn-data-symbol (cmn-data ~cmn-symbol)]
(if-let [ret-value# (do ~@body)]
ret-value#
(when-let [right-node# (cmn-right-node ~cmn-symbol)]
(recur right-node#)))))))
;; Doubly linked list node.
(defprotocol IContainerModelNode
(cmn-left-node [node])
(cmn-set-left-node [node new-left-node])
(cmn-right-node [node])
(cmn-set-right-node [node new-right-node])
(cmn-container-model [node])
(cmn-set-container-model [node new-container-model])
(cmn-data [node]))
(deftype ContainerModelNode [%container-model
^Lifetime lifetime
^Ref left
^Ref right
data]
IContainerModelNode
(cmn-left-node [_]
(ensure left))
(cmn-set-left-node [_ new-left-node]
(ref-set left new-left-node))
(cmn-right-node [_]
(ensure right))
(cmn-set-right-node [_ new-right-node]
(ref-set right new-right-node))
(cmn-container-model [_]
(ensure %container-model))
(cmn-set-container-model [_ new-container-model]
(ref-set %container-model new-container-model))
(cmn-data [_]
data))
;; Doubly linked list.
(defprotocol IContainerModel
(cm-tail-node [cm])
(cm-set-tail-node [cm new-tail-node])
(cm-head-node [cm])
(cm-set-head-node [cm new-head-node])
(cm-set-count [cm new-count]))
(deftype ContainerModel [^Lifetime lifetime
^Ref head-node
^Ref tail-node
^Ref %count
^Observable observable]
clojure.lang.Counted
(count [_]
(dosync (ensure %count)))
IContainerModel
(cm-tail-node [_]
(ensure tail-node))
(cm-set-tail-node [_ new-tail-node]
(ref-set tail-node new-tail-node))
(cm-head-node [_]
(ensure head-node))
(cm-set-head-node [_ new-head-node]
(ref-set head-node new-head-node))
;; The getter is `count' from `clojure.lang.Count'.
(cm-set-count [_ new-count]
(ref-set %count new-count)))
(defn ^ContainerModel mk-ContainerModel []
LIFETIME
(ref nil) ;; HEAD-NODE
(ref nil) ;; TAIL-NODE
(ref 0) ;; %COUNT
OBSERVABLE
(mk-Observable (fn [^Observable observable & event-args]
(doseq [^Fn observer-fn (ensure (.observers observable))]
(observer-fn event-args))))))
(defn ^ContainerModel cm []
(mk-ContainerModel))
(declare cm-prepend cmn-after)
(defn cm-append "Add NEW-NODE to end of the contained nodes in CM.
This mirrors the jQuery `append' function:
/"
[^ContainerModel cm ^ContainerModelNode new-node]
;; -linked_list#Inserting_a_node
;;
;; function insertEnd(List list, Node newNode)
(if (not (cm-tail-node cm)) ;; if list.lastNode == null
(cm-prepend cm new-node) ;; insertBeginning(list, newNode)
;; else
(cmn-after (cm-tail-node cm) new-node)) ;; insertAfter(list, list.lastNode, newNode)
cm)
(declare cmn-before)
(defn cm-prepend "Add NEW-NODE to beginning of the contained nodes in CM.
This mirrors the jQuery `prepend' function:
/"
[^ContainerModel cm ^ContainerModelNode new-node]
;; -linked_list#Inserting_a_node
;;
function insertBeginning(List list , newNode )
;; if list.firstNode == null
(if (not (cm-head-node cm))
(do
(assert (not (cmn-container-model new-node)))
(cmn-set-container-model new-node cm)
(cm-set-count cm (inc (count cm)))
(attach-lifetime (.lifetime cm) (.lifetime new-node))
(cm-set-head-node cm new-node) ;; list.firstNode := newNode
(cm-set-tail-node cm new-node) ;; list.lastNode := newNode
(cmn-set-left-node new-node nil) ;; newNode.prev := null
(cmn-set-right-node new-node nil) ;; newNode.next := null
(notify-observers (.observable cm) 'cm-prepend new-node))
;; else
(cmn-before (cm-head-node cm) new-node)) ;; insertBefore(list, list.firstNode, newNode)
cm)
(defn cm-clear "Empty the ContainerModel; calls jqEmpty at the client (View) end."
[^ContainerModel cm]
(cm-set-count cm 0)
(cm-iterate cm node _
(detach-lifetime (.lifetime ^ContainerModelNode node))
nil)
(cm-set-head-node cm nil)
(cm-set-tail-node cm nil)
(notify-observers (.observable cm) 'cm-clear)
cm)
| null | https://raw.githubusercontent.com/lnostdal/SymbolicWeb/d9600b286f70f88570deda57b05ca240e4e06567/src/symbolicweb/container_model.clj | clojure | -vgmo
Doubly linked list node.
Doubly linked list.
The getter is `count' from `clojure.lang.Count'.
HEAD-NODE
TAIL-NODE
%COUNT
-linked_list#Inserting_a_node
function insertEnd(List list, Node newNode)
if list.lastNode == null
insertBeginning(list, newNode)
else
insertAfter(list, list.lastNode, newNode)
-linked_list#Inserting_a_node
if list.firstNode == null
list.firstNode := newNode
list.lastNode := newNode
newNode.prev := null
newNode.next := null
else
insertBefore(list, list.firstNode, newNode) | (in-ns 'symbolicweb.core)
TODO ( ? )
: Why you should avoid Linked Lists
(defmacro cm-iterate "Iterate over CMNs in CONTAINER-MODEL executing BODY for each iteration with CMN-DATA-SYMBOL bound to the CMN-DATA of each
CMN respectively.
Iteration will end whenever BODY returns a True value, or when the tail of CONTAINER-MODEL was reached."
[container-model cmn-symbol cmn-data-symbol & body]
`(loop [~cmn-symbol (cm-head-node ~container-model)]
(when ~cmn-symbol
(let [~cmn-data-symbol (cmn-data ~cmn-symbol)]
(if-let [ret-value# (do ~@body)]
ret-value#
(when-let [right-node# (cmn-right-node ~cmn-symbol)]
(recur right-node#)))))))
(defprotocol IContainerModelNode
(cmn-left-node [node])
(cmn-set-left-node [node new-left-node])
(cmn-right-node [node])
(cmn-set-right-node [node new-right-node])
(cmn-container-model [node])
(cmn-set-container-model [node new-container-model])
(cmn-data [node]))
(deftype ContainerModelNode [%container-model
^Lifetime lifetime
^Ref left
^Ref right
data]
IContainerModelNode
(cmn-left-node [_]
(ensure left))
(cmn-set-left-node [_ new-left-node]
(ref-set left new-left-node))
(cmn-right-node [_]
(ensure right))
(cmn-set-right-node [_ new-right-node]
(ref-set right new-right-node))
(cmn-container-model [_]
(ensure %container-model))
(cmn-set-container-model [_ new-container-model]
(ref-set %container-model new-container-model))
(cmn-data [_]
data))
(defprotocol IContainerModel
(cm-tail-node [cm])
(cm-set-tail-node [cm new-tail-node])
(cm-head-node [cm])
(cm-set-head-node [cm new-head-node])
(cm-set-count [cm new-count]))
(deftype ContainerModel [^Lifetime lifetime
^Ref head-node
^Ref tail-node
^Ref %count
^Observable observable]
clojure.lang.Counted
(count [_]
(dosync (ensure %count)))
IContainerModel
(cm-tail-node [_]
(ensure tail-node))
(cm-set-tail-node [_ new-tail-node]
(ref-set tail-node new-tail-node))
(cm-head-node [_]
(ensure head-node))
(cm-set-head-node [_ new-head-node]
(ref-set head-node new-head-node))
(cm-set-count [_ new-count]
(ref-set %count new-count)))
(defn ^ContainerModel mk-ContainerModel []
LIFETIME
OBSERVABLE
(mk-Observable (fn [^Observable observable & event-args]
(doseq [^Fn observer-fn (ensure (.observers observable))]
(observer-fn event-args))))))
(defn ^ContainerModel cm []
(mk-ContainerModel))
(declare cm-prepend cmn-after)
(defn cm-append "Add NEW-NODE to end of the contained nodes in CM.
This mirrors the jQuery `append' function:
/"
[^ContainerModel cm ^ContainerModelNode new-node]
cm)
(declare cmn-before)
(defn cm-prepend "Add NEW-NODE to beginning of the contained nodes in CM.
This mirrors the jQuery `prepend' function:
/"
[^ContainerModel cm ^ContainerModelNode new-node]
function insertBeginning(List list , newNode )
(if (not (cm-head-node cm))
(do
(assert (not (cmn-container-model new-node)))
(cmn-set-container-model new-node cm)
(cm-set-count cm (inc (count cm)))
(attach-lifetime (.lifetime cm) (.lifetime new-node))
(notify-observers (.observable cm) 'cm-prepend new-node))
cm)
(defn cm-clear "Empty the ContainerModel; calls jqEmpty at the client (View) end."
[^ContainerModel cm]
(cm-set-count cm 0)
(cm-iterate cm node _
(detach-lifetime (.lifetime ^ContainerModelNode node))
nil)
(cm-set-head-node cm nil)
(cm-set-tail-node cm nil)
(notify-observers (.observable cm) 'cm-clear)
cm)
|
c7bbd2eff5cca45bc651e8cf786a9239b53bfe7f077ad05567bca5083ceb3730 | KaroshiBee/weevil | service_cmdline.ml | module Defaults = Dapper.Dap.Defaults
let default_port = Defaults._DEFAULT_ADAPTER_PORT
(* NOTE type unparsing_mode = Optimized | Readable | Optimized_legacy, could we phantom this into the logger type? *)
let process port_arg () =
let p
?port_arg:(port:int=default_port)
() =
Server.svc ~port
in
p ?port_arg ()
module Term = struct
let listen_port_arg =
let open Cmdliner in
let doc =
Format.sprintf
"The port that the weevil DAP svc will use for IO. \
If not given defaults to %d" default_port
in
Arg.(
value & pos 0 (some int) None & info [] ~doc ~docv:"PORT"
)
let term setup_log =
Cmdliner.Term.(
ret
(const process $ listen_port_arg $ setup_log)
)
end
module Manpage = struct
let command_description =
"Run the Weevil DAP service locally"
let description = [`S "DESCRIPTION"; `P command_description]
let man = description
let info = Cmdliner.Cmd.info ~doc:command_description ~man "adapter"
end
let cmd setup_log = Cmdliner.Cmd.v Manpage.info @@ Term.term setup_log
| null | https://raw.githubusercontent.com/KaroshiBee/weevil/1b166ba053062498c1ec05c885e04fba4ae7d831/lib/adapter/service_cmdline.ml | ocaml | NOTE type unparsing_mode = Optimized | Readable | Optimized_legacy, could we phantom this into the logger type? | module Defaults = Dapper.Dap.Defaults
let default_port = Defaults._DEFAULT_ADAPTER_PORT
let process port_arg () =
let p
?port_arg:(port:int=default_port)
() =
Server.svc ~port
in
p ?port_arg ()
module Term = struct
let listen_port_arg =
let open Cmdliner in
let doc =
Format.sprintf
"The port that the weevil DAP svc will use for IO. \
If not given defaults to %d" default_port
in
Arg.(
value & pos 0 (some int) None & info [] ~doc ~docv:"PORT"
)
let term setup_log =
Cmdliner.Term.(
ret
(const process $ listen_port_arg $ setup_log)
)
end
module Manpage = struct
let command_description =
"Run the Weevil DAP service locally"
let description = [`S "DESCRIPTION"; `P command_description]
let man = description
let info = Cmdliner.Cmd.info ~doc:command_description ~man "adapter"
end
let cmd setup_log = Cmdliner.Cmd.v Manpage.info @@ Term.term setup_log
|
2b90bc0240bf400b1e74b4e204ca08eee823c41b9c4c5831110b9bbdbc9e1c45 | lspitzner/brittany | Test137.hs | module Main (Test(Test, a, b)) where
| null | https://raw.githubusercontent.com/lspitzner/brittany/a15eed5f3608bf1fa7084fcf008c6ecb79542562/data/Test137.hs | haskell | module Main (Test(Test, a, b)) where
| |
2e9ebcd265fddb254b6934f79fbc38aafcd6cbd6f5687675f1b4d63f81545d31 | losfair/Violet | IntAlu.hs | module Violet.Backend.IntAlu where
import Clash.Prelude
import qualified Violet.Config as Config
import qualified Violet.Types.Pipe as PipeT
import qualified Violet.Types.Gpr as GprT
import qualified Violet.Types.Issue as IssueT
intAlu' :: Maybe IssueT.IssuePort
-> (GprT.RegValue, GprT.RegValue)
-> PipeT.Commit
intAlu' Nothing _ = PipeT.Bubble
intAlu' (Just (pc, inst, _)) (rs1V, rs2V) = PipeT.Ok (pc, Just $ PipeT.GPR rd out, Nothing)
where
rd = GprT.decodeRd inst
arithFunct3 = slice d14 d12 inst
regSrc2 = testBit inst 5
arithSrc1 = rs1V
arithSrc2 = if regSrc2 then rs2V else signExtend (slice d31 d20 inst)
arithSub = testBit inst 30 && testBit inst 5
arithSra = testBit inst 30
arithOut = case arithFunct3 of
0b000 -> if arithSub then arithSrc1 - arithSrc2 else arithSrc1 + arithSrc2 -- add/sub
slt
0b011 -> extendBoolToReg (unsignedLt arithSrc1 arithSrc2) -- sltu
0b100 -> xor arithSrc1 arithSrc2 -- xor
0b110 -> arithSrc1 .|. arithSrc2 -- or
0b111 -> arithSrc1 .&. arithSrc2 -- and
sll
srl / sra
mulOut =
if Config.mulInAlu then
case arithFunct3 of
0b000 -> rs1V * rs2V
_ -> undefined
else undefined
miscIn = (slice d31 d12 inst ++# 0) :: GprT.RegValue
miscOut = case slice d5 d5 inst of
0b1 -> miscIn -- lui
auipc
out = case slice d2 d2 inst of
0b0 -> if slice d25 d25 inst == 0b1 && regSrc2 then mulOut else arithOut
0b1 -> miscOut
intAlu :: HiddenClockResetEnable dom
=> Signal dom (Maybe IssueT.IssuePort)
-> Signal dom (GprT.RegValue, GprT.RegValue)
-> Signal dom PipeT.Commit
intAlu a b = fmap (\(a, b) -> intAlu' a b) $ bundle (a, b)
extendBoolToReg :: Bool -> GprT.RegValue
extendBoolToReg False = 0
extendBoolToReg True = 1
unsignedLt :: GprT.RegValue -> GprT.RegValue -> Bool
unsignedLt a b = (unpack a :: Unsigned 32) < (unpack b :: Unsigned 32)
signedLt :: GprT.RegValue -> GprT.RegValue -> Bool
signedLt a b = (unpack a :: Signed 32) < (unpack b :: Signed 32)
genShiftL :: GprT.RegValue -> GprT.RegValue -> GprT.RegValue
genShiftL a b = shiftL a (shiftAmount b)
unsignedShiftR :: GprT.RegValue -> GprT.RegValue -> GprT.RegValue
unsignedShiftR a b = pack $ shiftR (unpack a :: Unsigned 32) (shiftAmount b)
signedShiftR :: GprT.RegValue -> GprT.RegValue -> GprT.RegValue
signedShiftR a b = pack $ shiftR (unpack a :: Signed 32) (shiftAmount b)
shiftAmount :: GprT.RegValue -> Int
shiftAmount x = fromIntegral (slice d4 d0 x) | null | https://raw.githubusercontent.com/losfair/Violet/dcdd05f8dc08a438a157347f424966da73ccc9b8/src/Violet/Backend/IntAlu.hs | haskell | add/sub
sltu
xor
or
and
lui | module Violet.Backend.IntAlu where
import Clash.Prelude
import qualified Violet.Config as Config
import qualified Violet.Types.Pipe as PipeT
import qualified Violet.Types.Gpr as GprT
import qualified Violet.Types.Issue as IssueT
intAlu' :: Maybe IssueT.IssuePort
-> (GprT.RegValue, GprT.RegValue)
-> PipeT.Commit
intAlu' Nothing _ = PipeT.Bubble
intAlu' (Just (pc, inst, _)) (rs1V, rs2V) = PipeT.Ok (pc, Just $ PipeT.GPR rd out, Nothing)
where
rd = GprT.decodeRd inst
arithFunct3 = slice d14 d12 inst
regSrc2 = testBit inst 5
arithSrc1 = rs1V
arithSrc2 = if regSrc2 then rs2V else signExtend (slice d31 d20 inst)
arithSub = testBit inst 30 && testBit inst 5
arithSra = testBit inst 30
arithOut = case arithFunct3 of
slt
sll
srl / sra
mulOut =
if Config.mulInAlu then
case arithFunct3 of
0b000 -> rs1V * rs2V
_ -> undefined
else undefined
miscIn = (slice d31 d12 inst ++# 0) :: GprT.RegValue
miscOut = case slice d5 d5 inst of
auipc
out = case slice d2 d2 inst of
0b0 -> if slice d25 d25 inst == 0b1 && regSrc2 then mulOut else arithOut
0b1 -> miscOut
intAlu :: HiddenClockResetEnable dom
=> Signal dom (Maybe IssueT.IssuePort)
-> Signal dom (GprT.RegValue, GprT.RegValue)
-> Signal dom PipeT.Commit
intAlu a b = fmap (\(a, b) -> intAlu' a b) $ bundle (a, b)
extendBoolToReg :: Bool -> GprT.RegValue
extendBoolToReg False = 0
extendBoolToReg True = 1
unsignedLt :: GprT.RegValue -> GprT.RegValue -> Bool
unsignedLt a b = (unpack a :: Unsigned 32) < (unpack b :: Unsigned 32)
signedLt :: GprT.RegValue -> GprT.RegValue -> Bool
signedLt a b = (unpack a :: Signed 32) < (unpack b :: Signed 32)
genShiftL :: GprT.RegValue -> GprT.RegValue -> GprT.RegValue
genShiftL a b = shiftL a (shiftAmount b)
unsignedShiftR :: GprT.RegValue -> GprT.RegValue -> GprT.RegValue
unsignedShiftR a b = pack $ shiftR (unpack a :: Unsigned 32) (shiftAmount b)
signedShiftR :: GprT.RegValue -> GprT.RegValue -> GprT.RegValue
signedShiftR a b = pack $ shiftR (unpack a :: Signed 32) (shiftAmount b)
shiftAmount :: GprT.RegValue -> Int
shiftAmount x = fromIntegral (slice d4 d0 x) |
fa3e8fefaa015ec3beb723e3fe7f63a4c46efd05e7be2dc419b2c73a6029f97e | xapi-project/xen-api-libs | xmlrpc.mli |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
val to_string : Rpc.t -> string
val of_string : ?callback:Rpc.callback -> string -> Rpc.t
val to_a : empty:(unit -> 'a) -> append:('a -> string -> unit) -> Rpc.t -> 'a
val of_a : ?callback:Rpc.callback -> next_char:('a -> char) -> 'a -> Rpc.t
val string_of_call: Rpc.call -> string
val call_of_string: ?callback:Rpc.callback -> string -> Rpc.call
val string_of_response: Rpc.response -> string
val a_of_response : empty:(unit -> 'a) -> append:('a -> string -> unit) -> Rpc.response -> 'a
val response_of_string: ?callback:Rpc.callback -> string -> Rpc.response
val response_of_in_channel: ?callback:Rpc.callback -> in_channel -> Rpc.response
| null | https://raw.githubusercontent.com/xapi-project/xen-api-libs/d603ee2b8456bc2aac99b0a4955f083e22f4f314/rpc-light/xmlrpc.mli | ocaml |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
val to_string : Rpc.t -> string
val of_string : ?callback:Rpc.callback -> string -> Rpc.t
val to_a : empty:(unit -> 'a) -> append:('a -> string -> unit) -> Rpc.t -> 'a
val of_a : ?callback:Rpc.callback -> next_char:('a -> char) -> 'a -> Rpc.t
val string_of_call: Rpc.call -> string
val call_of_string: ?callback:Rpc.callback -> string -> Rpc.call
val string_of_response: Rpc.response -> string
val a_of_response : empty:(unit -> 'a) -> append:('a -> string -> unit) -> Rpc.response -> 'a
val response_of_string: ?callback:Rpc.callback -> string -> Rpc.response
val response_of_in_channel: ?callback:Rpc.callback -> in_channel -> Rpc.response
| |
f691dae2ab913e0e1ec8ed6fc651692c94cf7e641335c1bb7d0ff440afbfc157 | ghc/packages-Cabal | ModuleShape.hs | {-# LANGUAGE DeriveDataTypeable #-}
# LANGUAGE DeriveGeneric #
-- | See <-proposals/blob/backpack/proposals/0000-backpack.rst>
module Distribution.Backpack.ModuleShape (
-- * Module shapes
ModuleShape(..),
emptyModuleShape,
shapeInstalledPackage,
) where
import Prelude ()
import Distribution.Compat.Prelude hiding (mod)
import Distribution.ModuleName
import Distribution.InstalledPackageInfo as IPI
import Distribution.Backpack.ModSubst
import Distribution.Backpack
import qualified Data.Map as Map
import qualified Data.Set as Set
-----------------------------------------------------------------------
-- Module shapes
| A ' ModuleShape ' describes the provisions and requirements of
a library . We can extract a ' ModuleShape ' from an
-- 'InstalledPackageInfo'.
data ModuleShape = ModuleShape {
modShapeProvides :: OpenModuleSubst,
modShapeRequires :: Set ModuleName
}
deriving (Eq, Show, Generic, Typeable)
instance Binary ModuleShape
instance Structured ModuleShape
instance ModSubst ModuleShape where
modSubst subst (ModuleShape provs reqs)
= ModuleShape (modSubst subst provs) (modSubst subst reqs)
-- | The default module shape, with no provisions and no requirements.
emptyModuleShape :: ModuleShape
emptyModuleShape = ModuleShape Map.empty Set.empty
Food for thought : suppose we apply the tree optimization .
-- Imagine this situation:
--
-- component p
-- signature H
-- module P
-- component h
-- module H
-- component a
-- signature P
-- module A
component q(P )
include p
-- include h
-- component r
-- include q (P)
-- include p (P) requires (H)
-- include h (H)
-- include a (A) requires (P)
--
-- Component r should not have any conflicts, since after mix-in linking
the two P imports will end up being the same , so we can properly
-- instantiate it. But to know that q's P is p:P instantiated with h:H,
-- we have to be able to expand its unit id. Maybe we can expand it
-- lazily but in some cases it will need to be expanded.
--
FWIW , the way that GHC handles this is by improving unit IDs as
-- soon as it sees an improved one in the package database. This
-- is a bit disgusting.
shapeInstalledPackage :: IPI.InstalledPackageInfo -> ModuleShape
shapeInstalledPackage ipi = ModuleShape (Map.fromList provs) reqs
where
uid = installedOpenUnitId ipi
provs = map shapeExposedModule (IPI.exposedModules ipi)
reqs = requiredSignatures ipi
shapeExposedModule (IPI.ExposedModule mod_name Nothing)
= (mod_name, OpenModule uid mod_name)
shapeExposedModule (IPI.ExposedModule mod_name (Just mod))
= (mod_name, mod)
| null | https://raw.githubusercontent.com/ghc/packages-Cabal/6f22f2a789fa23edb210a2591d74ea6a5f767872/Cabal/Distribution/Backpack/ModuleShape.hs | haskell | # LANGUAGE DeriveDataTypeable #
| See <-proposals/blob/backpack/proposals/0000-backpack.rst>
* Module shapes
---------------------------------------------------------------------
Module shapes
'InstalledPackageInfo'.
| The default module shape, with no provisions and no requirements.
Imagine this situation:
component p
signature H
module P
component h
module H
component a
signature P
module A
include h
component r
include q (P)
include p (P) requires (H)
include h (H)
include a (A) requires (P)
Component r should not have any conflicts, since after mix-in linking
instantiate it. But to know that q's P is p:P instantiated with h:H,
we have to be able to expand its unit id. Maybe we can expand it
lazily but in some cases it will need to be expanded.
soon as it sees an improved one in the package database. This
is a bit disgusting. | # LANGUAGE DeriveGeneric #
module Distribution.Backpack.ModuleShape (
ModuleShape(..),
emptyModuleShape,
shapeInstalledPackage,
) where
import Prelude ()
import Distribution.Compat.Prelude hiding (mod)
import Distribution.ModuleName
import Distribution.InstalledPackageInfo as IPI
import Distribution.Backpack.ModSubst
import Distribution.Backpack
import qualified Data.Map as Map
import qualified Data.Set as Set
| A ' ModuleShape ' describes the provisions and requirements of
a library . We can extract a ' ModuleShape ' from an
data ModuleShape = ModuleShape {
modShapeProvides :: OpenModuleSubst,
modShapeRequires :: Set ModuleName
}
deriving (Eq, Show, Generic, Typeable)
instance Binary ModuleShape
instance Structured ModuleShape
instance ModSubst ModuleShape where
modSubst subst (ModuleShape provs reqs)
= ModuleShape (modSubst subst provs) (modSubst subst reqs)
emptyModuleShape :: ModuleShape
emptyModuleShape = ModuleShape Map.empty Set.empty
Food for thought : suppose we apply the tree optimization .
component q(P )
include p
the two P imports will end up being the same , so we can properly
FWIW , the way that GHC handles this is by improving unit IDs as
shapeInstalledPackage :: IPI.InstalledPackageInfo -> ModuleShape
shapeInstalledPackage ipi = ModuleShape (Map.fromList provs) reqs
where
uid = installedOpenUnitId ipi
provs = map shapeExposedModule (IPI.exposedModules ipi)
reqs = requiredSignatures ipi
shapeExposedModule (IPI.ExposedModule mod_name Nothing)
= (mod_name, OpenModule uid mod_name)
shapeExposedModule (IPI.ExposedModule mod_name (Just mod))
= (mod_name, mod)
|
4e6e11ccf8108bd612827e798035bc09073f2b8ea5c93a4aba5674327e4828fc | clj-kafka/franzy | client.clj | (ns franzy.clients.mocks.consumer.client
(:require [franzy.clients.consumer.protocols :refer :all]
[franzy.clients.mocks.consumer.protocols :refer :all]
[franzy.clients.mocks.protocols :refer :all]
[franzy.clients.consumer.client :refer :all]
[franzy.clients.codec :as codec]
[franzy.clients.consumer.defaults :as defaults]
[schema.core :as s]
[franzy.clients.consumer.schema :as cs])
(:import (franzy.clients.consumer.client FranzConsumer)
(org.apache.kafka.clients.consumer MockConsumer)))
(extend-type FranzConsumer
KafkaRecordWriter
(add-record! [this consumer-record]
(->>
consumer-record
(codec/map->consumer-record)
(.addRecord ^MockConsumer (.consumer this))))
MockKafkaConsumerLifecycle
(closed? [this]
(.closed ^MockConsumer (.consumer this)))
KafkaPartitionRebalancer
(rebalance! [this topic-partitions]
"Simulate a rebalance event."
(->> topic-partitions
(map codec/map->topic-partition)
(.rebalance ^MockConsumer (.consumer this))))
KafkaPoller
(schedule-nop-poll [this]
(.scheduleNopPollTask ^MockConsumer (.consumer this)))
(schedule-poll [this task]
(.schedulePollTask ^MockConsumer (.consumer this) task))
KafkaOffsetWriter
(beginning-offsets! [this topic-partition-offset-map]
"Given a map of topic partitions to offset numbers,
sets the beginning offset for each topic partition key to the given offset value."
(->> topic-partition-offset-map
(codec/map->topic-partition-offset-number)
(.updateBeginningOffsets ^MockConsumer (.consumer this))))
(ending-offsets! [this topic-partition-offset-map]
"Given a map of topic partitions to offset numbers,
sets the beginning offset for each topic partition key to the given offset value."
(->> topic-partition-offset-map
(codec/map->topic-partition-offset-number)
(.updateEndOffsets ^MockConsumer (.consumer this))))
KafkaPartitionWriter
(update-partitions! [this topic partitions-info]
"Updates the partition info for a topic, given a list of topic partition info.
Example:
`(update-partitions! c topic {:topic topic :partition 0
:leader {:id 1234 :host \"127.0.0.1\" :port 2112}
:replicas [{:id 1234 :host \"127.0.0.1\" :port 2112}]
:in-sync-replicas [{:id 1234 :host \"127.0.0.1\" :port 2112}]})`"
(->> partitions-info
(map codec/map->partition-info)
(.updatePartitions ^MockConsumer (.consumer this) topic)))
KafkaExceptionWriter
(write-exception! [this e]
"Complete the earliest uncompleted call with the given error."
(.setException ^MockConsumer (.consumer this) e)))
(s/defn make-mock-consumer :- FranzConsumer
([offset-reset-strategy]
(make-mock-consumer offset-reset-strategy nil))
([offset-reset-strategy :- (s/either s/Keyword s/Str)
options :- (s/maybe cs/ConsumerOptions)]
(-> offset-reset-strategy
(codec/keyword->offset-reset-strategy)
(MockConsumer.)
(FranzConsumer. (defaults/make-default-consumer-options options)))))
| null | https://raw.githubusercontent.com/clj-kafka/franzy/6c2e2e65ad137d2bcbc04ff6e671f97ea8c0e380/mocks/src/franzy/clients/mocks/consumer/client.clj | clojure | (ns franzy.clients.mocks.consumer.client
(:require [franzy.clients.consumer.protocols :refer :all]
[franzy.clients.mocks.consumer.protocols :refer :all]
[franzy.clients.mocks.protocols :refer :all]
[franzy.clients.consumer.client :refer :all]
[franzy.clients.codec :as codec]
[franzy.clients.consumer.defaults :as defaults]
[schema.core :as s]
[franzy.clients.consumer.schema :as cs])
(:import (franzy.clients.consumer.client FranzConsumer)
(org.apache.kafka.clients.consumer MockConsumer)))
(extend-type FranzConsumer
KafkaRecordWriter
(add-record! [this consumer-record]
(->>
consumer-record
(codec/map->consumer-record)
(.addRecord ^MockConsumer (.consumer this))))
MockKafkaConsumerLifecycle
(closed? [this]
(.closed ^MockConsumer (.consumer this)))
KafkaPartitionRebalancer
(rebalance! [this topic-partitions]
"Simulate a rebalance event."
(->> topic-partitions
(map codec/map->topic-partition)
(.rebalance ^MockConsumer (.consumer this))))
KafkaPoller
(schedule-nop-poll [this]
(.scheduleNopPollTask ^MockConsumer (.consumer this)))
(schedule-poll [this task]
(.schedulePollTask ^MockConsumer (.consumer this) task))
KafkaOffsetWriter
(beginning-offsets! [this topic-partition-offset-map]
"Given a map of topic partitions to offset numbers,
sets the beginning offset for each topic partition key to the given offset value."
(->> topic-partition-offset-map
(codec/map->topic-partition-offset-number)
(.updateBeginningOffsets ^MockConsumer (.consumer this))))
(ending-offsets! [this topic-partition-offset-map]
"Given a map of topic partitions to offset numbers,
sets the beginning offset for each topic partition key to the given offset value."
(->> topic-partition-offset-map
(codec/map->topic-partition-offset-number)
(.updateEndOffsets ^MockConsumer (.consumer this))))
KafkaPartitionWriter
(update-partitions! [this topic partitions-info]
"Updates the partition info for a topic, given a list of topic partition info.
Example:
`(update-partitions! c topic {:topic topic :partition 0
:leader {:id 1234 :host \"127.0.0.1\" :port 2112}
:replicas [{:id 1234 :host \"127.0.0.1\" :port 2112}]
:in-sync-replicas [{:id 1234 :host \"127.0.0.1\" :port 2112}]})`"
(->> partitions-info
(map codec/map->partition-info)
(.updatePartitions ^MockConsumer (.consumer this) topic)))
KafkaExceptionWriter
(write-exception! [this e]
"Complete the earliest uncompleted call with the given error."
(.setException ^MockConsumer (.consumer this) e)))
(s/defn make-mock-consumer :- FranzConsumer
([offset-reset-strategy]
(make-mock-consumer offset-reset-strategy nil))
([offset-reset-strategy :- (s/either s/Keyword s/Str)
options :- (s/maybe cs/ConsumerOptions)]
(-> offset-reset-strategy
(codec/keyword->offset-reset-strategy)
(MockConsumer.)
(FranzConsumer. (defaults/make-default-consumer-options options)))))
| |
6207f25cf7c0ac9bdf539777aa535b695f934c16528da368dda9dc4618fc459b | samrushing/irken-compiler | t14.scm |
(include "lib/core.scm")
(include "lib/pair.scm")
(let ((l (cons 1 (cons 2 (cons 3 (list:nil))))))
(let ((t0 (member? 3 l =))
(t1 (length l))
(t2 (append l l))
(t3 (range 10))
(t4 (n-of 5 "five"))
(t5 (reverse t3))
)
{a=t0 b=t1 c=t2 d=t3 e=t4 f=t5}))
| null | https://raw.githubusercontent.com/samrushing/irken-compiler/690da48852d55497f873738df54f14e8e135d006/tests/t14.scm | scheme |
(include "lib/core.scm")
(include "lib/pair.scm")
(let ((l (cons 1 (cons 2 (cons 3 (list:nil))))))
(let ((t0 (member? 3 l =))
(t1 (length l))
(t2 (append l l))
(t3 (range 10))
(t4 (n-of 5 "five"))
(t5 (reverse t3))
)
{a=t0 b=t1 c=t2 d=t3 e=t4 f=t5}))
| |
0bf9fa4b67aae10ba19a3221542b505873b532f132339cb7eec5d25b378e363f | v-kolesnikov/sicp | constraints_test.clj | (ns sicp.chapter03.constraints-test
(:require [clojure.test :refer :all]
[sicp.chapter03.constraints :refer :all]))
(deftest test-celsius-fahrenheit-converter
(let [C (make-connector)
F (make-connector)]
(celsius-fahrenheit-converter C F)
(probe "Celcius temp" C)
(probe "Fahrenheit temp" F)
(is (= :done (set-value! C 25 :user)))
(is (= 25 (get-value C)))
(is (= 77 (get-value F)))
(is (thrown? Exception (set-value! F 212 :user)))
(is (= 25 (get-value C)))
(is (= 77 (get-value F)))
(is (= :done (forget-value! C :user)))
(is (= :done (set-value! F 212 :user)))
(is (= 100 (get-value C)))
(is (= 212 (get-value F)))))
| null | https://raw.githubusercontent.com/v-kolesnikov/sicp/4298de6083440a75898e97aad658025a8cecb631/test/sicp/chapter03/constraints_test.clj | clojure | (ns sicp.chapter03.constraints-test
(:require [clojure.test :refer :all]
[sicp.chapter03.constraints :refer :all]))
(deftest test-celsius-fahrenheit-converter
(let [C (make-connector)
F (make-connector)]
(celsius-fahrenheit-converter C F)
(probe "Celcius temp" C)
(probe "Fahrenheit temp" F)
(is (= :done (set-value! C 25 :user)))
(is (= 25 (get-value C)))
(is (= 77 (get-value F)))
(is (thrown? Exception (set-value! F 212 :user)))
(is (= 25 (get-value C)))
(is (= 77 (get-value F)))
(is (= :done (forget-value! C :user)))
(is (= :done (set-value! F 212 :user)))
(is (= 100 (get-value C)))
(is (= 212 (get-value F)))))
| |
d4a56570ea78355b2b742eb3b505e069a3eabb171f758b718103f8c4c7681328 | racket/racket7 | sandman.rkt | #lang racket/base
(require "check.rkt"
"tree.rkt"
"internal-error.rkt"
"sandman-struct.rkt")
;; A "sandman" manages the set of all sleeping threads that may need
;; to be awoken in response to an external event, and it implements
the process - wide ` sleep ` that waits for an external event . Timeouts
;; are the only external events recognized by the initial sandman,
;; and that is supported by the host system's `sleep` function.
;; When a thread is registered with a sandman, the sandman provides a
;; handle representing the registration. The handle can be any value
;; except #f, and it is provided back to the sandman to unregister a
;; thread. A sandman doesn't unregister threads on its own, even when
;; it detects that an external event has happened.
;; When `sync` determines that a thread should sleep, it accumulates
;; external-event specifications to provide to the sandman along with
;; the thread. For the initial sandman, this information is just a
;; maximum wake-up time, but a more sophisticated sandman might
;; support file-descriptor activity. Event implementations expect a
;; sandman that provides specific functionality, so all sandman
;; implementations need to support time.
;; All sandman functions are called in atomic mode.
;; See also "sandman-struct.rkt".
(provide sandman-merge-timeout
sandman-merge-exts
sandman-add-sleeping-thread!
sandman-remove-sleeping-thread!
sandman-poll
sandman-sleep
sandman-any-sleepers?
sandman-sleepers-external-events
sandman-condition-wait
sandman-condition-poll
sandman-any-waiters?
current-sandman)
;; in atomic mode
(define (sandman-merge-timeout exts timeout)
((sandman-do-merge-timeout the-sandman) exts timeout))
;; in atomic mode
(define (sandman-merge-exts a-exts b-exts)
((sandman-do-merge-external-event-sets the-sandman) a-exts b-exts))
;; in atomic mode
(define (sandman-add-sleeping-thread! th exts)
((sandman-do-add-thread! the-sandman) th exts))
;; in atomic mode
(define (sandman-remove-sleeping-thread! th h)
((sandman-do-remove-thread! the-sandman) th h))
;; in atomic mode
(define (sandman-poll mode thread-wakeup)
((sandman-do-poll the-sandman) mode thread-wakeup))
;; in atomic mode
(define (sandman-sleep exts)
((sandman-do-sleep the-sandman) exts))
;; in atomic mode
(define (sandman-any-sleepers?)
((sandman-do-any-sleepers? the-sandman)))
;; in atomic mode
(define (sandman-sleepers-external-events)
((sandman-do-sleepers-external-events the-sandman)))
;; in atomic mode
(define (sandman-condition-wait thread)
((sandman-do-condition-wait the-sandman) thread))
;; in atomic mode
(define (sandman-condition-poll mode thread-wakeup)
((sandman-do-condition-poll the-sandman) mode thread-wakeup))
;; in atomic mode
(define (sandman-any-waiters?)
((sandman-do-any-waiters? the-sandman)))
;; in atomic mode
(define/who current-sandman
(case-lambda
[() the-sandman]
[(sm)
(check who sandman? sm)
(set! the-sandman sm)]))
;; created simple lock here to avoid cycle in loading from using lock defined in future.rkt
(define (make-lock)
(box 0))
(define (lock-acquire box)
(let loop ()
(unless (and (= 0 (unbox box)) (box-cas! box 0 1))
(loop))))
(define (lock-release box)
(unless (box-cas! box 1 0)
(internal-error "Failed to release lock\n")))
(define waiting-threads '())
(define awoken-threads '())
;; ----------------------------------------
;; Default sandman implementation
;; A tree mapping times (in milliseconds) to a hash table of threads
;; to wake up at that time
(define sleeping-threads empty-tree)
(define (min* a-sleep-until b-sleep-until)
(if (and a-sleep-until b-sleep-until)
(min a-sleep-until b-sleep-until)
(or a-sleep-until b-sleep-until)))
(define the-sandman
(sandman
;; sleep
(lambda (timeout-at)
(sleep (/ (- (or timeout-at (distant-future)) (current-inexact-milliseconds)) 1000.0)))
;; poll
(lambda (mode wakeup)
;; This check is fast, so do it in all modes
(unless (tree-empty? sleeping-threads)
(define-values (timeout-at threads) (tree-min sleeping-threads))
(when (timeout-at . <= . (current-inexact-milliseconds))
(unless (null? threads)
(for ([t (in-hash-keys threads)])
(wakeup t))))))
;; any-sleepers?
(lambda ()
(not (tree-empty? sleeping-threads)))
;; sleepers-external-events
(lambda ()
(and (not (tree-empty? sleeping-threads))
(let-values ([(timeout-at threads) (tree-min sleeping-threads)])
timeout-at)))
;; add-thread!
(lambda (t sleep-until)
(set! sleeping-threads
(tree-set sleeping-threads
sleep-until
(hash-set (or (tree-ref sleeping-threads sleep-until <)
#hasheq())
t
#t)
<))
sleep-until)
;; remove-thread!
(lambda (t sleep-until)
(define threads (tree-ref sleeping-threads sleep-until <))
(unless threads (internal-error "thread not found among sleeping threads"))
(define new-threads (hash-remove threads t))
(set! sleeping-threads
(if (zero? (hash-count new-threads))
(tree-remove sleeping-threads sleep-until <)
(tree-set sleeping-threads sleep-until new-threads <))))
;; merge-exts
(lambda (a-sleep-until b-sleep-until)
(min* a-sleep-until b-sleep-until))
;; merge-timeout
(lambda (sleep-until timeout-at)
(if sleep-until
(min sleep-until timeout-at)
timeout-at))
;; extract-timeout
(lambda (sleep-until) sleep-until)
;; condition-wait
(lambda (t)
(lock-acquire (sandman-lock the-sandman))
(set! waiting-threads (cons t waiting-threads))
(lock-release (sandman-lock the-sandman))
;; awoken callback. for when thread is awoken
(lambda (root-thread)
(lock-acquire (sandman-lock the-sandman))
(if (memq t waiting-threads)
(begin
(set! waiting-threads (remove t waiting-threads eq?))
(set! awoken-threads (cons t awoken-threads)))
(internal-error "thread is not a member of waiting-threads\n"))
(lock-release (sandman-lock the-sandman))))
;; condition-poll
(lambda (mode wakeup)
(lock-acquire (sandman-lock the-sandman))
(define at awoken-threads)
(set! awoken-threads '())
(lock-release (sandman-lock the-sandman))
(for-each (lambda (t)
(wakeup t)) at))
;; any waiters?
(lambda ()
(or (not (null? waiting-threads)) (not (null? awoken-threads))))
(make-lock)))
;; Compute an approximation to infinity:
(define (distant-future)
(+ (current-inexact-milliseconds)
(* 1000.0 60 60 24 365)))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/thread/sandman.rkt | racket | A "sandman" manages the set of all sleeping threads that may need
to be awoken in response to an external event, and it implements
are the only external events recognized by the initial sandman,
and that is supported by the host system's `sleep` function.
When a thread is registered with a sandman, the sandman provides a
handle representing the registration. The handle can be any value
except #f, and it is provided back to the sandman to unregister a
thread. A sandman doesn't unregister threads on its own, even when
it detects that an external event has happened.
When `sync` determines that a thread should sleep, it accumulates
external-event specifications to provide to the sandman along with
the thread. For the initial sandman, this information is just a
maximum wake-up time, but a more sophisticated sandman might
support file-descriptor activity. Event implementations expect a
sandman that provides specific functionality, so all sandman
implementations need to support time.
All sandman functions are called in atomic mode.
See also "sandman-struct.rkt".
in atomic mode
in atomic mode
in atomic mode
in atomic mode
in atomic mode
in atomic mode
in atomic mode
in atomic mode
in atomic mode
in atomic mode
in atomic mode
in atomic mode
created simple lock here to avoid cycle in loading from using lock defined in future.rkt
----------------------------------------
Default sandman implementation
A tree mapping times (in milliseconds) to a hash table of threads
to wake up at that time
sleep
poll
This check is fast, so do it in all modes
any-sleepers?
sleepers-external-events
add-thread!
remove-thread!
merge-exts
merge-timeout
extract-timeout
condition-wait
awoken callback. for when thread is awoken
condition-poll
any waiters?
Compute an approximation to infinity: | #lang racket/base
(require "check.rkt"
"tree.rkt"
"internal-error.rkt"
"sandman-struct.rkt")
the process - wide ` sleep ` that waits for an external event . Timeouts
(provide sandman-merge-timeout
sandman-merge-exts
sandman-add-sleeping-thread!
sandman-remove-sleeping-thread!
sandman-poll
sandman-sleep
sandman-any-sleepers?
sandman-sleepers-external-events
sandman-condition-wait
sandman-condition-poll
sandman-any-waiters?
current-sandman)
(define (sandman-merge-timeout exts timeout)
((sandman-do-merge-timeout the-sandman) exts timeout))
(define (sandman-merge-exts a-exts b-exts)
((sandman-do-merge-external-event-sets the-sandman) a-exts b-exts))
(define (sandman-add-sleeping-thread! th exts)
((sandman-do-add-thread! the-sandman) th exts))
(define (sandman-remove-sleeping-thread! th h)
((sandman-do-remove-thread! the-sandman) th h))
(define (sandman-poll mode thread-wakeup)
((sandman-do-poll the-sandman) mode thread-wakeup))
(define (sandman-sleep exts)
((sandman-do-sleep the-sandman) exts))
(define (sandman-any-sleepers?)
((sandman-do-any-sleepers? the-sandman)))
(define (sandman-sleepers-external-events)
((sandman-do-sleepers-external-events the-sandman)))
(define (sandman-condition-wait thread)
((sandman-do-condition-wait the-sandman) thread))
(define (sandman-condition-poll mode thread-wakeup)
((sandman-do-condition-poll the-sandman) mode thread-wakeup))
(define (sandman-any-waiters?)
((sandman-do-any-waiters? the-sandman)))
(define/who current-sandman
(case-lambda
[() the-sandman]
[(sm)
(check who sandman? sm)
(set! the-sandman sm)]))
(define (make-lock)
(box 0))
(define (lock-acquire box)
(let loop ()
(unless (and (= 0 (unbox box)) (box-cas! box 0 1))
(loop))))
(define (lock-release box)
(unless (box-cas! box 1 0)
(internal-error "Failed to release lock\n")))
(define waiting-threads '())
(define awoken-threads '())
(define sleeping-threads empty-tree)
(define (min* a-sleep-until b-sleep-until)
(if (and a-sleep-until b-sleep-until)
(min a-sleep-until b-sleep-until)
(or a-sleep-until b-sleep-until)))
(define the-sandman
(sandman
(lambda (timeout-at)
(sleep (/ (- (or timeout-at (distant-future)) (current-inexact-milliseconds)) 1000.0)))
(lambda (mode wakeup)
(unless (tree-empty? sleeping-threads)
(define-values (timeout-at threads) (tree-min sleeping-threads))
(when (timeout-at . <= . (current-inexact-milliseconds))
(unless (null? threads)
(for ([t (in-hash-keys threads)])
(wakeup t))))))
(lambda ()
(not (tree-empty? sleeping-threads)))
(lambda ()
(and (not (tree-empty? sleeping-threads))
(let-values ([(timeout-at threads) (tree-min sleeping-threads)])
timeout-at)))
(lambda (t sleep-until)
(set! sleeping-threads
(tree-set sleeping-threads
sleep-until
(hash-set (or (tree-ref sleeping-threads sleep-until <)
#hasheq())
t
#t)
<))
sleep-until)
(lambda (t sleep-until)
(define threads (tree-ref sleeping-threads sleep-until <))
(unless threads (internal-error "thread not found among sleeping threads"))
(define new-threads (hash-remove threads t))
(set! sleeping-threads
(if (zero? (hash-count new-threads))
(tree-remove sleeping-threads sleep-until <)
(tree-set sleeping-threads sleep-until new-threads <))))
(lambda (a-sleep-until b-sleep-until)
(min* a-sleep-until b-sleep-until))
(lambda (sleep-until timeout-at)
(if sleep-until
(min sleep-until timeout-at)
timeout-at))
(lambda (sleep-until) sleep-until)
(lambda (t)
(lock-acquire (sandman-lock the-sandman))
(set! waiting-threads (cons t waiting-threads))
(lock-release (sandman-lock the-sandman))
(lambda (root-thread)
(lock-acquire (sandman-lock the-sandman))
(if (memq t waiting-threads)
(begin
(set! waiting-threads (remove t waiting-threads eq?))
(set! awoken-threads (cons t awoken-threads)))
(internal-error "thread is not a member of waiting-threads\n"))
(lock-release (sandman-lock the-sandman))))
(lambda (mode wakeup)
(lock-acquire (sandman-lock the-sandman))
(define at awoken-threads)
(set! awoken-threads '())
(lock-release (sandman-lock the-sandman))
(for-each (lambda (t)
(wakeup t)) at))
(lambda ()
(or (not (null? waiting-threads)) (not (null? awoken-threads))))
(make-lock)))
(define (distant-future)
(+ (current-inexact-milliseconds)
(* 1000.0 60 60 24 365)))
|
f96c526215ed44bf6dbd0c1c0745d23f26e9152db571c45220a25563e7031574 | RichiH/git-annex | Merger.hs | git - annex assistant git merge thread
-
- Copyright 2012 - 2017 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2012-2017 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Assistant.Threads.Merger where
import Assistant.Common
import Assistant.TransferQueue
import Assistant.BranchChange
import Assistant.Sync
import Utility.DirWatcher
import Utility.DirWatcher.Types
import qualified Annex.Branch
import qualified Git
import qualified Git.Branch
import qualified Git.Ref
import qualified Command.Sync
{- This thread watches for changes to .git/refs/, and handles incoming
- pushes. -}
mergeThread :: NamedThread
mergeThread = namedThread "Merger" $ do
g <- liftAnnex gitRepo
let dir = Git.localGitDir g </> "refs"
liftIO $ createDirectoryIfMissing True dir
let hook a = Just <$> asIO2 (runHandler a)
changehook <- hook onChange
errhook <- hook onErr
let hooks = mkWatchHooks
{ addHook = changehook
, modifyHook = changehook
, errHook = errhook
}
void $ liftIO $ watchDir dir (const False) True hooks id
debug ["watching", dir]
type Handler = FilePath -> Assistant ()
{- Runs an action handler.
-
- Exceptions are ignored, otherwise a whole thread could be crashed.
-}
runHandler :: Handler -> FilePath -> Maybe FileStatus -> Assistant ()
runHandler handler file _filestatus =
either (liftIO . print) (const noop) =<< tryIO <~> handler file
{- Called when there's an error with inotify. -}
onErr :: Handler
onErr = error
{- Called when a new branch ref is written, or a branch ref is modified.
-
- At startup, synthetic add events fire, causing this to run, but that's
- ok; it ensures that any changes pushed since the last time the assistant
- ran are merged in.
-}
onChange :: Handler
onChange file
| ".lock" `isSuffixOf` file = noop
| isAnnexBranch file = do
branchChanged
diverged <- liftAnnex Annex.Branch.forceUpdate
when diverged $ do
updateExportTreeFromLogAll
queueDeferredDownloads "retrying deferred download" Later
| otherwise = mergecurrent
where
changedbranch = fileToBranch file
mergecurrent =
mergecurrent' =<< liftAnnex (join Command.Sync.getCurrBranch)
mergecurrent' currbranch@(Just b, _)
| changedbranch `isRelatedTo` b =
whenM (liftAnnex $ inRepo $ Git.Branch.changed b changedbranch) $ do
debug
[ "merging", Git.fromRef changedbranch
, "into", Git.fromRef b
]
void $ liftAnnex $ Command.Sync.merge
currbranch Command.Sync.mergeConfig
def
Git.Branch.AutomaticCommit
changedbranch
mergecurrent' _ = noop
Is the first branch a synced branch or remote tracking branch related
- to the second branch , which should be merged into it ?
- to the second branch, which should be merged into it? -}
isRelatedTo :: Git.Ref -> Git.Ref -> Bool
isRelatedTo x y
| basex /= takeDirectory basex ++ "/" ++ basey = False
| "/synced/" `isInfixOf` Git.fromRef x = True
| "refs/remotes/" `isPrefixOf` Git.fromRef x = True
| otherwise = False
where
basex = Git.fromRef $ Git.Ref.base x
basey = Git.fromRef $ Git.Ref.base y
isAnnexBranch :: FilePath -> Bool
isAnnexBranch f = n `isSuffixOf` f
where
n = '/' : Git.fromRef Annex.Branch.name
fileToBranch :: FilePath -> Git.Ref
fileToBranch f = Git.Ref $ "refs" </> base
where
base = Prelude.last $ split "/refs/" f
| null | https://raw.githubusercontent.com/RichiH/git-annex/bbcad2b0af8cd9264d0cb86e6ca126ae626171f3/Assistant/Threads/Merger.hs | haskell | This thread watches for changes to .git/refs/, and handles incoming
- pushes.
Runs an action handler.
-
- Exceptions are ignored, otherwise a whole thread could be crashed.
Called when there's an error with inotify.
Called when a new branch ref is written, or a branch ref is modified.
-
- At startup, synthetic add events fire, causing this to run, but that's
- ok; it ensures that any changes pushed since the last time the assistant
- ran are merged in.
| git - annex assistant git merge thread
-
- Copyright 2012 - 2017 < >
-
- Licensed under the GNU GPL version 3 or higher .
-
- Copyright 2012-2017 Joey Hess <>
-
- Licensed under the GNU GPL version 3 or higher.
-}
module Assistant.Threads.Merger where
import Assistant.Common
import Assistant.TransferQueue
import Assistant.BranchChange
import Assistant.Sync
import Utility.DirWatcher
import Utility.DirWatcher.Types
import qualified Annex.Branch
import qualified Git
import qualified Git.Branch
import qualified Git.Ref
import qualified Command.Sync
mergeThread :: NamedThread
mergeThread = namedThread "Merger" $ do
g <- liftAnnex gitRepo
let dir = Git.localGitDir g </> "refs"
liftIO $ createDirectoryIfMissing True dir
let hook a = Just <$> asIO2 (runHandler a)
changehook <- hook onChange
errhook <- hook onErr
let hooks = mkWatchHooks
{ addHook = changehook
, modifyHook = changehook
, errHook = errhook
}
void $ liftIO $ watchDir dir (const False) True hooks id
debug ["watching", dir]
type Handler = FilePath -> Assistant ()
runHandler :: Handler -> FilePath -> Maybe FileStatus -> Assistant ()
runHandler handler file _filestatus =
either (liftIO . print) (const noop) =<< tryIO <~> handler file
onErr :: Handler
onErr = error
onChange :: Handler
onChange file
| ".lock" `isSuffixOf` file = noop
| isAnnexBranch file = do
branchChanged
diverged <- liftAnnex Annex.Branch.forceUpdate
when diverged $ do
updateExportTreeFromLogAll
queueDeferredDownloads "retrying deferred download" Later
| otherwise = mergecurrent
where
changedbranch = fileToBranch file
mergecurrent =
mergecurrent' =<< liftAnnex (join Command.Sync.getCurrBranch)
mergecurrent' currbranch@(Just b, _)
| changedbranch `isRelatedTo` b =
whenM (liftAnnex $ inRepo $ Git.Branch.changed b changedbranch) $ do
debug
[ "merging", Git.fromRef changedbranch
, "into", Git.fromRef b
]
void $ liftAnnex $ Command.Sync.merge
currbranch Command.Sync.mergeConfig
def
Git.Branch.AutomaticCommit
changedbranch
mergecurrent' _ = noop
Is the first branch a synced branch or remote tracking branch related
- to the second branch , which should be merged into it ?
- to the second branch, which should be merged into it? -}
isRelatedTo :: Git.Ref -> Git.Ref -> Bool
isRelatedTo x y
| basex /= takeDirectory basex ++ "/" ++ basey = False
| "/synced/" `isInfixOf` Git.fromRef x = True
| "refs/remotes/" `isPrefixOf` Git.fromRef x = True
| otherwise = False
where
basex = Git.fromRef $ Git.Ref.base x
basey = Git.fromRef $ Git.Ref.base y
isAnnexBranch :: FilePath -> Bool
isAnnexBranch f = n `isSuffixOf` f
where
n = '/' : Git.fromRef Annex.Branch.name
fileToBranch :: FilePath -> Git.Ref
fileToBranch f = Git.Ref $ "refs" </> base
where
base = Prelude.last $ split "/refs/" f
|
f2ab402be75292ac071a3ea7cb10547d5d1582d150da89d12873e96776742c55 | TrustInSoft/tis-interpreter | logic_const.ml | Modified by TrustInSoft
(**************************************************************************)
(* *)
This file is part of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
(* alternatives) *)
( Institut National de Recherche en Informatique et en
(* Automatique) *)
(* *)
(* 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 , version 2.1 .
(* *)
(* It 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. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
open Cil_types
(** Smart constructors for the logic.
@plugin development guide *)
* { 1 Identification Numbers }
module AnnotId =
State_builder.SharedCounter(struct let name = "annot_counter" end)
module PredicateId =
State_builder.SharedCounter(struct let name = "predicate_counter" end)
module TermId =
State_builder.SharedCounter(struct let name = "term_counter" end)
let new_code_annotation annot =
{ annot_content = annot ; annot_id = AnnotId.next () }
let fresh_code_annotation = AnnotId.next
let new_predicate p =
{ ip_id = PredicateId.next ();
ip_content = p.content; ip_loc = p.loc; ip_name = p.name }
let fresh_predicate_id = PredicateId.next
let pred_of_id_pred p =
{ name = p.ip_name; loc = p.ip_loc; content = p.ip_content }
let refresh_predicate p = { p with ip_id = PredicateId.next () }
let new_identified_term t =
{ it_id = TermId.next (); it_content = t }
let fresh_term_id = TermId.next
let refresh_identified_term d = new_identified_term d.it_content
let refresh_identified_term_list = List.map refresh_identified_term
let refresh_deps = function
| FromAny -> FromAny
| From l ->
From(refresh_identified_term_list l)
let refresh_from (a,d) = (new_identified_term a.it_content, refresh_deps d)
let refresh_allocation = function
| FreeAllocAny -> FreeAllocAny
| FreeAlloc(f,a) ->
FreeAlloc((refresh_identified_term_list f),refresh_identified_term_list a)
let refresh_assigns = function
| WritesAny -> WritesAny
| Writes l ->
Writes(List.map refresh_from l)
let refresh_behavior b =
{ b with
b_requires = List.map refresh_predicate b.b_requires;
b_assumes = List.map refresh_predicate b.b_assumes;
b_post_cond =
List.map (fun (k,p) -> (k, refresh_predicate p)) b.b_post_cond;
b_assigns = refresh_assigns b.b_assigns;
b_allocation = refresh_allocation b.b_allocation;
b_extended =
List.map (fun (s,n,p) -> (s,n,List.map refresh_predicate p)) b.b_extended
}
let refresh_spec s =
{ spec_behavior = List.map refresh_behavior s.spec_behavior;
spec_variant = s.spec_variant;
spec_terminates = Extlib.opt_map refresh_predicate s.spec_terminates;
spec_complete_behaviors = s.spec_complete_behaviors;
spec_disjoint_behaviors = s.spec_disjoint_behaviors;
}
let refresh_code_annotation annot =
let content =
match annot.annot_content with
| AAssert _ | AInvariant _ | AAllocation _ | AVariant _ | APragma _ as c -> c
| AStmtSpec(l,spec) -> AStmtSpec(l, refresh_spec spec)
| AAssigns(l,a) -> AAssigns(l, refresh_assigns a)
in
new_code_annotation content
* { 1 Smart constructors }
* { 2 pre - defined logic labels }
(* empty line for ocamldoc *)
let init_label = LogicLabel (None, "Init")
let pre_label = LogicLabel (None, "Pre")
let post_label = LogicLabel (None, "Post")
let here_label = LogicLabel (None, "Here")
let old_label = LogicLabel (None, "Old")
let loop_current_label = LogicLabel (None, "LoopCurrent")
let loop_entry_label = LogicLabel (None, "LoopEntry")
(** {2 Types} *)
let is_list_type = function
| Ltype ({lt_name = "\\list"},[_]) -> true
| _ -> false
(** returns the type of elements of a list type.
@raise Failure if the input type is not a list type. *)
let type_of_list_elem ty = match ty with
| Ltype ({lt_name = "\\list"},[t]) -> t
| _ -> failwith "not a list type"
(** build the type list of [ty]. *)
let make_type_list_of ty =
Ltype(Logic_env.find_logic_type "\\list",[ty])
let is_set_type = function
| Ltype ({lt_name = "set"},[_]) -> true
| _ -> false
* [ set_conversion ty1 ty2 ] returns a set type as soon as [ ] and/or [ ty2 ]
is a set . Elements have type [ ] , or the type of the elements of [ ] if
it is itself a set - type ( { i.e. } we do not build set of sets that way ) .
is a set. Elements have type [ty1], or the type of the elements of [ty1] if
it is itself a set-type ({i.e.} we do not build set of sets that way).*)
let set_conversion ty1 ty2 =
match ty1,ty2 with
| Ltype ({lt_name = "set"},[_]),_ -> ty1
| ty1, Ltype({lt_name = "set"} as lt,[_]) -> Ltype(lt,[ty1])
| _ -> ty1
(** converts a type into the corresponding set type if needed. *)
let make_set_type ty =
if is_set_type ty then ty
else Ltype(Logic_env.find_logic_type "set",[ty])
(** returns the type of elements of a set type.
@raise Failure if the input type is not a set type. *)
let type_of_element ty = match ty with
| Ltype ({lt_name = "set"},[t]) -> t
| _ -> failwith "not a set type"
(** [plain_or_set f t] applies [f] to [t] or to the type of elements of [t]
if it is a set type *)
let plain_or_set f = function
| Ltype ({lt_name = "set"},[t]) -> f t
| t -> f t
let transform_element f t = set_conversion (plain_or_set f t) t
let is_plain_type = function
| Ltype ({lt_name = "set"},[_]) -> false
| _ -> true
let is_boolean_type = function
| Ltype ({ lt_name = s }, []) when s = Utf8_logic.boolean -> true
| _ -> false
let boolean_type = Ltype ({ lt_name = Utf8_logic.boolean ; lt_params = [] ; lt_def = None } , [])
* { 2 Offsets }
let rec lastTermOffset (off: term_offset) : term_offset =
match off with
| TNoOffset | TField(_,TNoOffset) | TIndex(_,TNoOffset)
| TModel(_,TNoOffset)-> off
| TField(_,off) | TIndex(_,off) | TModel(_,off) -> lastTermOffset off
let rec addTermOffset (toadd: term_offset) (off: term_offset) : term_offset =
match off with
| TNoOffset -> toadd
| TField(fid', offset) -> TField(fid', addTermOffset toadd offset)
| TIndex(t, offset) -> TIndex(t, addTermOffset toadd offset)
| TModel(m,offset) -> TModel(m,addTermOffset toadd offset)
let addTermOffsetLval toadd (b, off) : term_lval =
b, addTermOffset toadd off
* { 2 Terms }
(* empty line for ocamldoc *)
(** @plugin development guide *)
let term ?(loc=Cil_datatype.Location.unknown) term typ =
{ term_node = term;
term_type = typ;
term_name = [];
term_loc = loc }
let taddrof ?(loc=Cil_datatype.Location.unknown) lv typ =
match lv with
| TMem h, TNoOffset -> h
| _ -> term ~loc (TAddrOf lv) typ
(** range of integers *)
let trange ?(loc=Cil_datatype.Location.unknown) (low,high) =
term ~loc (Trange(low,high))
(Ltype(Logic_env.find_logic_type "set",[Linteger]))
(** An integer constant (of type integer). *)
let tinteger ?(loc=Cil_datatype.Location.unknown) i =
term ~loc (TConst (Integer (Integer.of_int i,None))) Linteger
* An integer constant ( of type integer ) from an int64 .
let tinteger_s64
?(loc=Cil_datatype.Location.unknown) i64 =
term ~loc (TConst (Integer (Integer.of_int64 i64,None))) Linteger
let tint ?(loc=Cil_datatype.Location.unknown) i =
term ~loc (TConst (Integer (i,None))) Linteger
* A real constant ( of type real ) from a float .
let treal ?(loc=Cil_datatype.Location.unknown) f =
let s = Pretty_utils.to_string Floating_point.pretty f in
let r = {
r_literal = s ;
r_upper = f ; r_lower = f ; r_nearest = f ;
} in
term ~loc (TConst (LReal r)) Lreal
let treal_zero ?(loc=Cil_datatype.Location.unknown) ?(ltyp=Lreal) () =
let zero = { r_nearest = 0.0 ; r_upper = 0.0 ; r_lower = 0.0 ; r_literal = "0." } in
term ~loc (TConst (LReal zero)) ltyp
let tstring ?(loc=Cil_datatype.Location.unknown) s =
Can not refer to Cil.charConstPtrType in this module ...
let typ = TPtr(TInt(IChar, [Attr("const", [])]),[]) in
term ~loc (TConst (LStr s)) (Ctype typ)
let tat ?(loc=Cil_datatype.Location.unknown) (t,label) =
term ~loc (Tat(t,label)) t.term_type
let told ?(loc=Cil_datatype.Location.unknown) t = tat ~loc (t,old_label)
let tlogic_coerce ?(loc=Cil_datatype.Location.unknown) t lt =
term ~loc (TLogic_coerce (lt, t)) lt
let tvar ?(loc=Cil_datatype.Location.unknown) lv =
term ~loc (TLval(TVar lv,TNoOffset)) lv.lv_type
let tresult ?(loc=Cil_datatype.Location.unknown) typ =
term ~loc (TLval(TResult typ,TNoOffset)) (Ctype typ)
needed by , upon which Logic_utils depends .
TODO : some refactoring of these two files
TODO: some refactoring of these two files *)
(** true if the given term is a lvalue denoting result or part of it *)
let rec is_result t = match t.term_node with
| TLval (TResult _,_) -> true
| Tat(t,_) -> is_result t
| _ -> false
let rec is_exit_status t = match t.term_node with
| TLval (TVar n,_) when n.lv_name = "\\exit_status" -> true
| Tat(t,_) -> is_exit_status t
| _ -> false
* { 2 Predicate constructors }
(* empty line for ocamldoc *)
let unamed ?(loc=Cil_datatype.Location.unknown) p =
{content = p ; loc = loc; name = [] }
let ptrue = unamed Ptrue
let pfalse = unamed Pfalse
let pold ?(loc=Cil_datatype.Location.unknown) p = match p.content with
| Ptrue | Pfalse -> p
| _ -> {p with content = Pat(p, old_label); loc = loc}
let papp ?(loc=Cil_datatype.Location.unknown) (p,lab,a) =
unamed ~loc (Papp(p,lab,a))
let pand ?(loc=Cil_datatype.Location.unknown) (p1, p2) =
match p1.content, p2.content with
| Ptrue, _ -> p2
| _, Ptrue -> p1
| Pfalse, _ -> p1
| _, Pfalse -> p2
| _, _ -> unamed ~loc (Pand (p1, p2))
let por ?(loc=Cil_datatype.Location.unknown) (p1, p2) =
match p1.content, p2.content with
| Ptrue, _ -> p1
| _, Ptrue -> p2
| Pfalse, _ -> p2
| _, Pfalse -> p1
| _, _ -> unamed ~loc (Por (p1, p2))
let pxor ?(loc=Cil_datatype.Location.unknown) (p1, p2) =
match p1.content, p2.content with
| Ptrue, Ptrue -> unamed ~loc Pfalse
| Ptrue, _ -> p1
| _, Ptrue -> p2
| Pfalse, _ -> p2
| _, Pfalse -> p1
| _,_ -> unamed ~loc (Pxor (p1,p2))
let pnot ?(loc=Cil_datatype.Location.unknown) p2 = match p2.content with
| Ptrue -> {p2 with content = Pfalse; loc = loc }
| Pfalse -> {p2 with content = Ptrue; loc = loc }
| Pnot p -> p
| _ -> unamed ~loc (Pnot p2)
let pands l = List.fold_right (fun p1 p2 -> pand (p1, p2)) l ptrue
let pors l = List.fold_right (fun p1 p2 -> por (p1, p2)) l pfalse
let plet ?(loc=Cil_datatype.Location.unknown) p = match p.content with
| (_, ({content = Ptrue} as p)) -> p
| (v, p) -> unamed ~loc (Plet (v, p))
let pimplies ?(loc=Cil_datatype.Location.unknown) (p1,p2) =
match p1.content, p2.content with
| Ptrue, _ | _, Ptrue -> p2
| Pfalse, _ -> { name = p1.name; loc = loc; content = Ptrue }
| _, _ -> unamed ~loc (Pimplies (p1, p2))
let pif ?(loc=Cil_datatype.Location.unknown) (t,p2,p3) =
match (p2.content, p3.content) with
| Ptrue, Ptrue -> ptrue
| Pfalse, Pfalse -> pfalse
| _,_ -> unamed ~loc (Pif (t,p2,p3))
let piff ?(loc=Cil_datatype.Location.unknown) (p2,p3) =
match p2.content, p3.content with
| Pfalse, Pfalse -> ptrue
| Ptrue, _ -> p3
| _, Ptrue -> p2
| _,_ -> unamed ~loc (Piff (p2,p3))
(** @plugin development guide *)
let prel ?(loc=Cil_datatype.Location.unknown) (a,b,c) =
unamed ~loc (Prel(a,b,c))
let pforall ?(loc=Cil_datatype.Location.unknown) (l,p) = match l with
| [] -> p
| _ :: _ ->
match p.content with
| Ptrue -> p
| _ -> unamed ~loc (Pforall (l,p))
let pexists ?(loc=Cil_datatype.Location.unknown) (l,p) = match l with
| [] -> p
| _ :: _ -> match p.content with
| Pfalse -> p
| _ -> unamed ~loc (Pexists (l,p))
let pfresh ?(loc=Cil_datatype.Location.unknown) (l1,l2,p,n) = unamed ~loc (Pfresh (l1,l2,p,n))
let pallocable ?(loc=Cil_datatype.Location.unknown) (l,p) = unamed ~loc (Pallocable (l,p))
let pfreeable ?(loc=Cil_datatype.Location.unknown) (l,p) = unamed ~loc (Pfreeable (l,p))
let pvalid ?(loc=Cil_datatype.Location.unknown) (l,p) = unamed ~loc (Pvalid (l,p))
let pvalid_read ?(loc=Cil_datatype.Location.unknown) (l,p) = unamed ~loc (Pvalid_read (l,p))
let pvalid_function ?(loc=Cil_datatype.Location.unknown) p = unamed ~loc (Pvalid_function p)
(* the index should be an integer or a range of integers *)
let pvalid_index ?(loc=Cil_datatype.Location.unknown) (l,t1,t2) =
let ty1 = t1.term_type in
let ty2 = t2.term_type in
let t, ty =(match t1.term_node with
| TStartOf lv ->
TAddrOf (addTermOffsetLval (TIndex(t2,TNoOffset)) lv)
| _ -> TBinOp (PlusPI, t1, t2)),
set_conversion ty1 ty2 in
let t = term ~loc t ty in
pvalid ~loc (l,t)
(* the range should be a range of integers *)
let pvalid_range ?(loc=Cil_datatype.Location.unknown) (l,t1,b1,b2) =
let t2 = trange ((Some b1), (Some b2)) in
pvalid_index ~loc (l,t1,t2)
let pat ?(loc=Cil_datatype.Location.unknown) (p,q) = unamed ~loc (Pat (p,q))
let pinitialized ?(loc=Cil_datatype.Location.unknown) (l,p) =
unamed ~loc (Pinitialized (l,p))
let pdangling ?(loc=Cil_datatype.Location.unknown) (l,p) =
unamed ~loc (Pdangling (l,p))
let psubtype ?(loc=Cil_datatype.Location.unknown) (p,q) =
unamed ~loc (Psubtype (p,q))
let pseparated ?(loc=Cil_datatype.Location.unknown) seps =
unamed ~loc (Pseparated seps)
(*
Local Variables:
compile-command: "make -C ../../.."
End:
*)
| null | https://raw.githubusercontent.com/TrustInSoft/tis-interpreter/33132ce4a825494ea48bf2dd6fd03a56b62cc5c3/src/kernel_services/ast_queries/logic_const.ml | ocaml | ************************************************************************
alternatives)
Automatique)
you can redistribute it and/or modify it under the terms of the GNU
It 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.
************************************************************************
* Smart constructors for the logic.
@plugin development guide
empty line for ocamldoc
* {2 Types}
* returns the type of elements of a list type.
@raise Failure if the input type is not a list type.
* build the type list of [ty].
* converts a type into the corresponding set type if needed.
* returns the type of elements of a set type.
@raise Failure if the input type is not a set type.
* [plain_or_set f t] applies [f] to [t] or to the type of elements of [t]
if it is a set type
empty line for ocamldoc
* @plugin development guide
* range of integers
* An integer constant (of type integer).
* true if the given term is a lvalue denoting result or part of it
empty line for ocamldoc
* @plugin development guide
the index should be an integer or a range of integers
the range should be a range of integers
Local Variables:
compile-command: "make -C ../../.."
End:
| Modified by TrustInSoft
This file is part of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat à l'énergie atomique et aux énergies
( Institut National de Recherche en Informatique et en
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Cil_types
* { 1 Identification Numbers }
module AnnotId =
State_builder.SharedCounter(struct let name = "annot_counter" end)
module PredicateId =
State_builder.SharedCounter(struct let name = "predicate_counter" end)
module TermId =
State_builder.SharedCounter(struct let name = "term_counter" end)
let new_code_annotation annot =
{ annot_content = annot ; annot_id = AnnotId.next () }
let fresh_code_annotation = AnnotId.next
let new_predicate p =
{ ip_id = PredicateId.next ();
ip_content = p.content; ip_loc = p.loc; ip_name = p.name }
let fresh_predicate_id = PredicateId.next
let pred_of_id_pred p =
{ name = p.ip_name; loc = p.ip_loc; content = p.ip_content }
let refresh_predicate p = { p with ip_id = PredicateId.next () }
let new_identified_term t =
{ it_id = TermId.next (); it_content = t }
let fresh_term_id = TermId.next
let refresh_identified_term d = new_identified_term d.it_content
let refresh_identified_term_list = List.map refresh_identified_term
let refresh_deps = function
| FromAny -> FromAny
| From l ->
From(refresh_identified_term_list l)
let refresh_from (a,d) = (new_identified_term a.it_content, refresh_deps d)
let refresh_allocation = function
| FreeAllocAny -> FreeAllocAny
| FreeAlloc(f,a) ->
FreeAlloc((refresh_identified_term_list f),refresh_identified_term_list a)
let refresh_assigns = function
| WritesAny -> WritesAny
| Writes l ->
Writes(List.map refresh_from l)
let refresh_behavior b =
{ b with
b_requires = List.map refresh_predicate b.b_requires;
b_assumes = List.map refresh_predicate b.b_assumes;
b_post_cond =
List.map (fun (k,p) -> (k, refresh_predicate p)) b.b_post_cond;
b_assigns = refresh_assigns b.b_assigns;
b_allocation = refresh_allocation b.b_allocation;
b_extended =
List.map (fun (s,n,p) -> (s,n,List.map refresh_predicate p)) b.b_extended
}
let refresh_spec s =
{ spec_behavior = List.map refresh_behavior s.spec_behavior;
spec_variant = s.spec_variant;
spec_terminates = Extlib.opt_map refresh_predicate s.spec_terminates;
spec_complete_behaviors = s.spec_complete_behaviors;
spec_disjoint_behaviors = s.spec_disjoint_behaviors;
}
let refresh_code_annotation annot =
let content =
match annot.annot_content with
| AAssert _ | AInvariant _ | AAllocation _ | AVariant _ | APragma _ as c -> c
| AStmtSpec(l,spec) -> AStmtSpec(l, refresh_spec spec)
| AAssigns(l,a) -> AAssigns(l, refresh_assigns a)
in
new_code_annotation content
* { 1 Smart constructors }
* { 2 pre - defined logic labels }
let init_label = LogicLabel (None, "Init")
let pre_label = LogicLabel (None, "Pre")
let post_label = LogicLabel (None, "Post")
let here_label = LogicLabel (None, "Here")
let old_label = LogicLabel (None, "Old")
let loop_current_label = LogicLabel (None, "LoopCurrent")
let loop_entry_label = LogicLabel (None, "LoopEntry")
let is_list_type = function
| Ltype ({lt_name = "\\list"},[_]) -> true
| _ -> false
let type_of_list_elem ty = match ty with
| Ltype ({lt_name = "\\list"},[t]) -> t
| _ -> failwith "not a list type"
let make_type_list_of ty =
Ltype(Logic_env.find_logic_type "\\list",[ty])
let is_set_type = function
| Ltype ({lt_name = "set"},[_]) -> true
| _ -> false
* [ set_conversion ty1 ty2 ] returns a set type as soon as [ ] and/or [ ty2 ]
is a set . Elements have type [ ] , or the type of the elements of [ ] if
it is itself a set - type ( { i.e. } we do not build set of sets that way ) .
is a set. Elements have type [ty1], or the type of the elements of [ty1] if
it is itself a set-type ({i.e.} we do not build set of sets that way).*)
let set_conversion ty1 ty2 =
match ty1,ty2 with
| Ltype ({lt_name = "set"},[_]),_ -> ty1
| ty1, Ltype({lt_name = "set"} as lt,[_]) -> Ltype(lt,[ty1])
| _ -> ty1
let make_set_type ty =
if is_set_type ty then ty
else Ltype(Logic_env.find_logic_type "set",[ty])
let type_of_element ty = match ty with
| Ltype ({lt_name = "set"},[t]) -> t
| _ -> failwith "not a set type"
let plain_or_set f = function
| Ltype ({lt_name = "set"},[t]) -> f t
| t -> f t
let transform_element f t = set_conversion (plain_or_set f t) t
let is_plain_type = function
| Ltype ({lt_name = "set"},[_]) -> false
| _ -> true
let is_boolean_type = function
| Ltype ({ lt_name = s }, []) when s = Utf8_logic.boolean -> true
| _ -> false
let boolean_type = Ltype ({ lt_name = Utf8_logic.boolean ; lt_params = [] ; lt_def = None } , [])
* { 2 Offsets }
let rec lastTermOffset (off: term_offset) : term_offset =
match off with
| TNoOffset | TField(_,TNoOffset) | TIndex(_,TNoOffset)
| TModel(_,TNoOffset)-> off
| TField(_,off) | TIndex(_,off) | TModel(_,off) -> lastTermOffset off
let rec addTermOffset (toadd: term_offset) (off: term_offset) : term_offset =
match off with
| TNoOffset -> toadd
| TField(fid', offset) -> TField(fid', addTermOffset toadd offset)
| TIndex(t, offset) -> TIndex(t, addTermOffset toadd offset)
| TModel(m,offset) -> TModel(m,addTermOffset toadd offset)
let addTermOffsetLval toadd (b, off) : term_lval =
b, addTermOffset toadd off
* { 2 Terms }
let term ?(loc=Cil_datatype.Location.unknown) term typ =
{ term_node = term;
term_type = typ;
term_name = [];
term_loc = loc }
let taddrof ?(loc=Cil_datatype.Location.unknown) lv typ =
match lv with
| TMem h, TNoOffset -> h
| _ -> term ~loc (TAddrOf lv) typ
let trange ?(loc=Cil_datatype.Location.unknown) (low,high) =
term ~loc (Trange(low,high))
(Ltype(Logic_env.find_logic_type "set",[Linteger]))
let tinteger ?(loc=Cil_datatype.Location.unknown) i =
term ~loc (TConst (Integer (Integer.of_int i,None))) Linteger
* An integer constant ( of type integer ) from an int64 .
let tinteger_s64
?(loc=Cil_datatype.Location.unknown) i64 =
term ~loc (TConst (Integer (Integer.of_int64 i64,None))) Linteger
let tint ?(loc=Cil_datatype.Location.unknown) i =
term ~loc (TConst (Integer (i,None))) Linteger
* A real constant ( of type real ) from a float .
let treal ?(loc=Cil_datatype.Location.unknown) f =
let s = Pretty_utils.to_string Floating_point.pretty f in
let r = {
r_literal = s ;
r_upper = f ; r_lower = f ; r_nearest = f ;
} in
term ~loc (TConst (LReal r)) Lreal
let treal_zero ?(loc=Cil_datatype.Location.unknown) ?(ltyp=Lreal) () =
let zero = { r_nearest = 0.0 ; r_upper = 0.0 ; r_lower = 0.0 ; r_literal = "0." } in
term ~loc (TConst (LReal zero)) ltyp
let tstring ?(loc=Cil_datatype.Location.unknown) s =
Can not refer to Cil.charConstPtrType in this module ...
let typ = TPtr(TInt(IChar, [Attr("const", [])]),[]) in
term ~loc (TConst (LStr s)) (Ctype typ)
let tat ?(loc=Cil_datatype.Location.unknown) (t,label) =
term ~loc (Tat(t,label)) t.term_type
let told ?(loc=Cil_datatype.Location.unknown) t = tat ~loc (t,old_label)
let tlogic_coerce ?(loc=Cil_datatype.Location.unknown) t lt =
term ~loc (TLogic_coerce (lt, t)) lt
let tvar ?(loc=Cil_datatype.Location.unknown) lv =
term ~loc (TLval(TVar lv,TNoOffset)) lv.lv_type
let tresult ?(loc=Cil_datatype.Location.unknown) typ =
term ~loc (TLval(TResult typ,TNoOffset)) (Ctype typ)
needed by , upon which Logic_utils depends .
TODO : some refactoring of these two files
TODO: some refactoring of these two files *)
let rec is_result t = match t.term_node with
| TLval (TResult _,_) -> true
| Tat(t,_) -> is_result t
| _ -> false
let rec is_exit_status t = match t.term_node with
| TLval (TVar n,_) when n.lv_name = "\\exit_status" -> true
| Tat(t,_) -> is_exit_status t
| _ -> false
* { 2 Predicate constructors }
let unamed ?(loc=Cil_datatype.Location.unknown) p =
{content = p ; loc = loc; name = [] }
let ptrue = unamed Ptrue
let pfalse = unamed Pfalse
let pold ?(loc=Cil_datatype.Location.unknown) p = match p.content with
| Ptrue | Pfalse -> p
| _ -> {p with content = Pat(p, old_label); loc = loc}
let papp ?(loc=Cil_datatype.Location.unknown) (p,lab,a) =
unamed ~loc (Papp(p,lab,a))
let pand ?(loc=Cil_datatype.Location.unknown) (p1, p2) =
match p1.content, p2.content with
| Ptrue, _ -> p2
| _, Ptrue -> p1
| Pfalse, _ -> p1
| _, Pfalse -> p2
| _, _ -> unamed ~loc (Pand (p1, p2))
let por ?(loc=Cil_datatype.Location.unknown) (p1, p2) =
match p1.content, p2.content with
| Ptrue, _ -> p1
| _, Ptrue -> p2
| Pfalse, _ -> p2
| _, Pfalse -> p1
| _, _ -> unamed ~loc (Por (p1, p2))
let pxor ?(loc=Cil_datatype.Location.unknown) (p1, p2) =
match p1.content, p2.content with
| Ptrue, Ptrue -> unamed ~loc Pfalse
| Ptrue, _ -> p1
| _, Ptrue -> p2
| Pfalse, _ -> p2
| _, Pfalse -> p1
| _,_ -> unamed ~loc (Pxor (p1,p2))
let pnot ?(loc=Cil_datatype.Location.unknown) p2 = match p2.content with
| Ptrue -> {p2 with content = Pfalse; loc = loc }
| Pfalse -> {p2 with content = Ptrue; loc = loc }
| Pnot p -> p
| _ -> unamed ~loc (Pnot p2)
let pands l = List.fold_right (fun p1 p2 -> pand (p1, p2)) l ptrue
let pors l = List.fold_right (fun p1 p2 -> por (p1, p2)) l pfalse
let plet ?(loc=Cil_datatype.Location.unknown) p = match p.content with
| (_, ({content = Ptrue} as p)) -> p
| (v, p) -> unamed ~loc (Plet (v, p))
let pimplies ?(loc=Cil_datatype.Location.unknown) (p1,p2) =
match p1.content, p2.content with
| Ptrue, _ | _, Ptrue -> p2
| Pfalse, _ -> { name = p1.name; loc = loc; content = Ptrue }
| _, _ -> unamed ~loc (Pimplies (p1, p2))
let pif ?(loc=Cil_datatype.Location.unknown) (t,p2,p3) =
match (p2.content, p3.content) with
| Ptrue, Ptrue -> ptrue
| Pfalse, Pfalse -> pfalse
| _,_ -> unamed ~loc (Pif (t,p2,p3))
let piff ?(loc=Cil_datatype.Location.unknown) (p2,p3) =
match p2.content, p3.content with
| Pfalse, Pfalse -> ptrue
| Ptrue, _ -> p3
| _, Ptrue -> p2
| _,_ -> unamed ~loc (Piff (p2,p3))
let prel ?(loc=Cil_datatype.Location.unknown) (a,b,c) =
unamed ~loc (Prel(a,b,c))
let pforall ?(loc=Cil_datatype.Location.unknown) (l,p) = match l with
| [] -> p
| _ :: _ ->
match p.content with
| Ptrue -> p
| _ -> unamed ~loc (Pforall (l,p))
let pexists ?(loc=Cil_datatype.Location.unknown) (l,p) = match l with
| [] -> p
| _ :: _ -> match p.content with
| Pfalse -> p
| _ -> unamed ~loc (Pexists (l,p))
let pfresh ?(loc=Cil_datatype.Location.unknown) (l1,l2,p,n) = unamed ~loc (Pfresh (l1,l2,p,n))
let pallocable ?(loc=Cil_datatype.Location.unknown) (l,p) = unamed ~loc (Pallocable (l,p))
let pfreeable ?(loc=Cil_datatype.Location.unknown) (l,p) = unamed ~loc (Pfreeable (l,p))
let pvalid ?(loc=Cil_datatype.Location.unknown) (l,p) = unamed ~loc (Pvalid (l,p))
let pvalid_read ?(loc=Cil_datatype.Location.unknown) (l,p) = unamed ~loc (Pvalid_read (l,p))
let pvalid_function ?(loc=Cil_datatype.Location.unknown) p = unamed ~loc (Pvalid_function p)
let pvalid_index ?(loc=Cil_datatype.Location.unknown) (l,t1,t2) =
let ty1 = t1.term_type in
let ty2 = t2.term_type in
let t, ty =(match t1.term_node with
| TStartOf lv ->
TAddrOf (addTermOffsetLval (TIndex(t2,TNoOffset)) lv)
| _ -> TBinOp (PlusPI, t1, t2)),
set_conversion ty1 ty2 in
let t = term ~loc t ty in
pvalid ~loc (l,t)
let pvalid_range ?(loc=Cil_datatype.Location.unknown) (l,t1,b1,b2) =
let t2 = trange ((Some b1), (Some b2)) in
pvalid_index ~loc (l,t1,t2)
let pat ?(loc=Cil_datatype.Location.unknown) (p,q) = unamed ~loc (Pat (p,q))
let pinitialized ?(loc=Cil_datatype.Location.unknown) (l,p) =
unamed ~loc (Pinitialized (l,p))
let pdangling ?(loc=Cil_datatype.Location.unknown) (l,p) =
unamed ~loc (Pdangling (l,p))
let psubtype ?(loc=Cil_datatype.Location.unknown) (p,q) =
unamed ~loc (Psubtype (p,q))
let pseparated ?(loc=Cil_datatype.Location.unknown) seps =
unamed ~loc (Pseparated seps)
|
882befdee4a100bc24a2bf0eb48a3fae6619b105815815255942f9fabf0e0754 | openmusic-project/openmusic | splineseditor.lisp | ;=========================================================================
OpenMusic : Visual Programming Language for Music Composition
;
Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France .
;
This file is part of the OpenMusic environment sources
;
OpenMusic 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.
;
OpenMusic 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 OpenMusic . If not , see < / > .
;
Authors : , ,
;=========================================================================
;;;===================================
;;; INTERFACE SPLINES dans BPF EDITOR
jb . 2005
;;;===================================
(in-package :om)
(defmethod spline-p ((self bpfeditor)) t)
(defmethod spline-p ((self t)) nil)
(defclass editor-spline-manager ()
((editor :accessor editor :initform nil :initarg :editor)
(active :accessor active :initform nil :initarg :active)
(degre :accessor degre :initform 3 :initarg :degre)
(s-resolution :accessor s-resolution :initform 100 :initarg :s-resolution)
(opt-items :accessor opt-items :initform nil :initarg :opt-items)
(outspline :accessor outspline :initform nil :initarg :outspline)))
(defmethod init-spline-manager ((self bpfeditor))
(let ((splm (make-instance 'editor-spline-manager :editor self)))
(setf (spline self) splm)
(om-add-subviews (control self)
;(om-make-dialog-item 'om-static-text (om-make-point 220 6) (om-make-point 80 12) "Spline"
; :font *controls-font*
; :bg-color *controls-color*
; )
(om-make-dialog-item 'om-check-box (om-make-point 400 7) (om-make-point 110 8)
(format nil "Spline preview")
:di-action (om-dialog-item-act item
(set-spline-preview (spline (om-view-container (om-view-container item)))
(om-checked-p item))
(om-invalidate-view (panel (om-view-container (om-view-container item))) t))
:checked-p (active splm)
:font *om-default-font1*
:bg-color *controls-color*
))
(when (active splm)
(add-opt-items splm 550))
))
(defmethod add-opt-items ((self editor-spline-manager) pos)
(let ((x0 pos))
(setf (opt-items self)
(list (om-make-dialog-item 'om-static-text
(om-make-point x0 2)
(om-make-point 70 20) "Degree"
:font *om-default-font1*
:bg-color *controls-color*
)
(om-make-dialog-item 'numBox (om-make-point (+ x0 70) 3) (om-make-point 20 18)
(format nil " ~D" (degre self))
:min-val 2
:max-val 5
:value (degre self)
:bg-color *om-white-color*
:afterfun #'(lambda (item)
(setf (degre self) (value item))
(compute-spline self)
(om-invalidate-view (panel (om-view-container (om-view-container item))) t))
:font *om-default-font1*
)
(om-make-dialog-item 'om-static-text
(om-make-point x0 22)
(om-make-point 70 20) "Resolution"
:font *om-default-font1*
:bg-color *controls-color*
)
(om-make-dialog-item 'numBox (om-make-point (+ x0 70) 23) (om-make-point 36 18)
(format nil " ~D" (s-resolution self))
:min-val 10
:max-val 999
:bg-color *om-white-color*
:value (s-resolution self)
:afterfun #'(lambda (item)
(setf (s-resolution self) (value item))
(compute-spline self)
(om-invalidate-view (panel (om-view-container (om-view-container item))) t))
:font *om-default-font1*
)
))
(loop for item in (opt-items self) do
(om-add-subviews (control (editor self)) item))
))
(defmethod remove-opt-items ((self editor-spline-manager))
(loop while (opt-items self) do
(om-remove-subviews (control (editor self)) (pop (opt-items self))))
)
(defmethod set-spline-preview ((self editor-spline-manager) t-or-nil)
(setf (active self) t-or-nil)
(if t-or-nil
(progn
(add-opt-items self 550)
(compute-spline self))
(remove-opt-items self))
(om-invalidate-view (panel (editor self)))
)
(defparameter *max-spline-points* 300)
(defmethod compute-spline ((self editor-spline-manager))
(let* ((bpf (currentbpf (panel (editor self))))
(points (point-list bpf))
(N (- (length points) 1))
knots inpts)
(when (> N 0)
(if (< N *max-spline-points*)
(progn
(setf knots (SplineKnots N (degre self)))
(setf inpts (mat-trans (list (x-points bpf) (y-points bpf))))
(setf (outspline self) (SplineCurve2D inpts N knots (degre self) (s-resolution self)))
)
(om-print "spline can not be calculated because of too many points")
))))
(defmethod draw-bpf :after ((Self Bpfpanel) (Bpf Bpf) Minx Maxx Miny Maxy &optional (Deltax 0) (Deltay 0) (dr-points nil))
(when (spline-p (editor self))
(let* ((spline (spline (editor self)))
(points (outspline spline))
(system-etat (get-system-etat self))
(bpf-selected? (and (equal (selection? self) t) (equal bpf (currentbpf self))))
(fact (expt 10.0 (decimals bpf))))
(when (and (active spline) points); bpf-selected?)
(om-with-fg-color self *om-red2-color*
(if (show-lines-p self)
(loop for thepoint in points do
(let* ((pix-point (point2pixel self (om-make-big-point (round (* fact (car thepoint)))
(round (* fact (cadr thepoint))))
system-etat)))
(om-fill-rect (om-point-h pix-point) (om-point-v pix-point) 2 2)
))
(let ((p1 (point2pixel self (om-make-big-point (round (* fact (car (car points))))
(round (* fact (cadr (car points)))))
system-etat)))
(loop for thepoint in (cdr points) do
(let* ((p2 (point2pixel self (om-make-big-point (round (* fact (car thepoint)))
(round (* fact (cadr thepoint))))
system-etat)))
(om-draw-line (om-point-h p1) (om-point-v p1) (om-point-h p2) (om-point-v p2))
(setf p1 p2)))))
))
)))
(defmethod spline ((self t)) nil)
(defmethod release-scroll-point :after ((Self Bpfpanel) initpos pos)
(when (and (spline (editor self)) (active (spline (editor self))))
(compute-spline (spline (editor self)))))
(defmethod release-scroll-bpf :after ((Self Bpfpanel) initpos pos)
(when (and (spline (editor self)) (active (spline (editor self))))
(compute-spline (spline (editor self)))))
(defmethod handle-key-event :after ((Self Bpfpanel) char)
(when (and (spline (editor self)) (active (spline (editor self))))
(compute-spline (spline (editor self)))))
| null | https://raw.githubusercontent.com/openmusic-project/openmusic/9560c064512a1598cd57bcc9f0151c0815178e6f/OPENMUSIC/code/projects/basicproject/editors/splineseditor.lisp | lisp | =========================================================================
(at your option) any later version.
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
=========================================================================
===================================
INTERFACE SPLINES dans BPF EDITOR
===================================
(om-make-dialog-item 'om-static-text (om-make-point 220 6) (om-make-point 80 12) "Spline"
:font *controls-font*
:bg-color *controls-color*
)
bpf-selected?)
| OpenMusic : Visual Programming Language for Music Composition
Copyright ( c ) 1997- ... IRCAM - Centre , Paris , France .
This file is part of the OpenMusic environment sources
OpenMusic 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
OpenMusic is distributed in the hope that it will be useful ,
You should have received a copy of the GNU General Public License
along with OpenMusic . If not , see < / > .
Authors : , ,
jb . 2005
(in-package :om)
(defmethod spline-p ((self bpfeditor)) t)
(defmethod spline-p ((self t)) nil)
(defclass editor-spline-manager ()
((editor :accessor editor :initform nil :initarg :editor)
(active :accessor active :initform nil :initarg :active)
(degre :accessor degre :initform 3 :initarg :degre)
(s-resolution :accessor s-resolution :initform 100 :initarg :s-resolution)
(opt-items :accessor opt-items :initform nil :initarg :opt-items)
(outspline :accessor outspline :initform nil :initarg :outspline)))
(defmethod init-spline-manager ((self bpfeditor))
(let ((splm (make-instance 'editor-spline-manager :editor self)))
(setf (spline self) splm)
(om-add-subviews (control self)
(om-make-dialog-item 'om-check-box (om-make-point 400 7) (om-make-point 110 8)
(format nil "Spline preview")
:di-action (om-dialog-item-act item
(set-spline-preview (spline (om-view-container (om-view-container item)))
(om-checked-p item))
(om-invalidate-view (panel (om-view-container (om-view-container item))) t))
:checked-p (active splm)
:font *om-default-font1*
:bg-color *controls-color*
))
(when (active splm)
(add-opt-items splm 550))
))
(defmethod add-opt-items ((self editor-spline-manager) pos)
(let ((x0 pos))
(setf (opt-items self)
(list (om-make-dialog-item 'om-static-text
(om-make-point x0 2)
(om-make-point 70 20) "Degree"
:font *om-default-font1*
:bg-color *controls-color*
)
(om-make-dialog-item 'numBox (om-make-point (+ x0 70) 3) (om-make-point 20 18)
(format nil " ~D" (degre self))
:min-val 2
:max-val 5
:value (degre self)
:bg-color *om-white-color*
:afterfun #'(lambda (item)
(setf (degre self) (value item))
(compute-spline self)
(om-invalidate-view (panel (om-view-container (om-view-container item))) t))
:font *om-default-font1*
)
(om-make-dialog-item 'om-static-text
(om-make-point x0 22)
(om-make-point 70 20) "Resolution"
:font *om-default-font1*
:bg-color *controls-color*
)
(om-make-dialog-item 'numBox (om-make-point (+ x0 70) 23) (om-make-point 36 18)
(format nil " ~D" (s-resolution self))
:min-val 10
:max-val 999
:bg-color *om-white-color*
:value (s-resolution self)
:afterfun #'(lambda (item)
(setf (s-resolution self) (value item))
(compute-spline self)
(om-invalidate-view (panel (om-view-container (om-view-container item))) t))
:font *om-default-font1*
)
))
(loop for item in (opt-items self) do
(om-add-subviews (control (editor self)) item))
))
(defmethod remove-opt-items ((self editor-spline-manager))
(loop while (opt-items self) do
(om-remove-subviews (control (editor self)) (pop (opt-items self))))
)
(defmethod set-spline-preview ((self editor-spline-manager) t-or-nil)
(setf (active self) t-or-nil)
(if t-or-nil
(progn
(add-opt-items self 550)
(compute-spline self))
(remove-opt-items self))
(om-invalidate-view (panel (editor self)))
)
(defparameter *max-spline-points* 300)
(defmethod compute-spline ((self editor-spline-manager))
(let* ((bpf (currentbpf (panel (editor self))))
(points (point-list bpf))
(N (- (length points) 1))
knots inpts)
(when (> N 0)
(if (< N *max-spline-points*)
(progn
(setf knots (SplineKnots N (degre self)))
(setf inpts (mat-trans (list (x-points bpf) (y-points bpf))))
(setf (outspline self) (SplineCurve2D inpts N knots (degre self) (s-resolution self)))
)
(om-print "spline can not be calculated because of too many points")
))))
(defmethod draw-bpf :after ((Self Bpfpanel) (Bpf Bpf) Minx Maxx Miny Maxy &optional (Deltax 0) (Deltay 0) (dr-points nil))
(when (spline-p (editor self))
(let* ((spline (spline (editor self)))
(points (outspline spline))
(system-etat (get-system-etat self))
(bpf-selected? (and (equal (selection? self) t) (equal bpf (currentbpf self))))
(fact (expt 10.0 (decimals bpf))))
(om-with-fg-color self *om-red2-color*
(if (show-lines-p self)
(loop for thepoint in points do
(let* ((pix-point (point2pixel self (om-make-big-point (round (* fact (car thepoint)))
(round (* fact (cadr thepoint))))
system-etat)))
(om-fill-rect (om-point-h pix-point) (om-point-v pix-point) 2 2)
))
(let ((p1 (point2pixel self (om-make-big-point (round (* fact (car (car points))))
(round (* fact (cadr (car points)))))
system-etat)))
(loop for thepoint in (cdr points) do
(let* ((p2 (point2pixel self (om-make-big-point (round (* fact (car thepoint)))
(round (* fact (cadr thepoint))))
system-etat)))
(om-draw-line (om-point-h p1) (om-point-v p1) (om-point-h p2) (om-point-v p2))
(setf p1 p2)))))
))
)))
(defmethod spline ((self t)) nil)
(defmethod release-scroll-point :after ((Self Bpfpanel) initpos pos)
(when (and (spline (editor self)) (active (spline (editor self))))
(compute-spline (spline (editor self)))))
(defmethod release-scroll-bpf :after ((Self Bpfpanel) initpos pos)
(when (and (spline (editor self)) (active (spline (editor self))))
(compute-spline (spline (editor self)))))
(defmethod handle-key-event :after ((Self Bpfpanel) char)
(when (and (spline (editor self)) (active (spline (editor self))))
(compute-spline (spline (editor self)))))
|
2939c94f67e9107cb0927a4d886b0a0035d69e811471351a883fb12e1df32413 | amalloy/aoc-2021 | Main.hs | module Main where
import Control.Arrow ((&&&))
import Data.Coerce (coerce)
import Data.List.NonEmpty (NonEmpty(..), nonEmpty)
import Data.Maybe (fromMaybe)
import Data.Semigroup (Min(..), Max(..))
import Text.Regex.Applicative
import Text.Regex.Applicative.Common (decimal)
data Input = Input {_min, _max :: Int, _crabs :: NonEmpty Int}
solve :: (Int -> Int) -> Input -> Int
solve cost (Input min max crabs) = minimum $ do
pos <- [min..max]
pure . sum . fmap (cost . abs . (pos -)) $ crabs
part1 :: Input -> Int
part1 = solve abs
part2 :: Input -> Int
part2 = solve cost
where cost n = n * (n + 1) `div` 2
prepare :: String -> Maybe Input
prepare = mkCrabs . fromMaybe [] . (=~ input)
where mkCrabs input = let (min, max) = coerce $ foldMap (Just . Min &&& Just . Max) input
in liftA3 Input min max (nonEmpty input)
input = many (decimal <* anySym)
main :: IO ()
main = readFile "input.txt" >>= print . maybe (0, 0) (part1 &&& part2) . prepare
| null | https://raw.githubusercontent.com/amalloy/aoc-2021/e169e8326dac5e1ccfa9ba35f1c3575e5be28690/day07/src/Main.hs | haskell | module Main where
import Control.Arrow ((&&&))
import Data.Coerce (coerce)
import Data.List.NonEmpty (NonEmpty(..), nonEmpty)
import Data.Maybe (fromMaybe)
import Data.Semigroup (Min(..), Max(..))
import Text.Regex.Applicative
import Text.Regex.Applicative.Common (decimal)
data Input = Input {_min, _max :: Int, _crabs :: NonEmpty Int}
solve :: (Int -> Int) -> Input -> Int
solve cost (Input min max crabs) = minimum $ do
pos <- [min..max]
pure . sum . fmap (cost . abs . (pos -)) $ crabs
part1 :: Input -> Int
part1 = solve abs
part2 :: Input -> Int
part2 = solve cost
where cost n = n * (n + 1) `div` 2
prepare :: String -> Maybe Input
prepare = mkCrabs . fromMaybe [] . (=~ input)
where mkCrabs input = let (min, max) = coerce $ foldMap (Just . Min &&& Just . Max) input
in liftA3 Input min max (nonEmpty input)
input = many (decimal <* anySym)
main :: IO ()
main = readFile "input.txt" >>= print . maybe (0, 0) (part1 &&& part2) . prepare
| |
fdff57bce8a9814003748418dfa49c345a6cd3f0317a8c26abaa52761881a311 | helium/miner | miner_blockchain_SUITE.erl | -module(miner_blockchain_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("blockchain/include/blockchain_vars.hrl").
-include_lib("blockchain/include/blockchain.hrl").
-export([
init_per_suite/1,
end_per_suite/1,
init_per_testcase/2,
end_per_testcase/2,
all/0
]).
-export([
autoskip_chain_vars_test/1,
autoskip_on_timeout_test/1,
restart_test/1,
dkg_restart_test/1,
validator_transition_test/1,
election_test/1,
election_multi_test/1,
group_change_test/1,
election_v3_test/1,
snapshot_test/1,
high_snapshot_test/1
]).
%% TODO Relocate all helper functions below tests.
all() -> [
RELOC NOTE def KEEP testing of DKG
RELOC NOTE def KEEP testing of election
RELOC NOTE def MOVE testing of variable changes
RELOC NOTE may MOVE if raw transactions are being submitted
autoskip_chain_vars_test,
RELOC KEEP - tests miner - unique feature
autoskip_on_timeout_test,
RELOC KEEP - tests miner - unique feature
restart_test,
RELOC KEEP - tests whole miner
dkg_restart_test,
RELOC KEEP - tests DKG
validator_transition_test,
RELOC TBD :
%% FOR:
%% - submits txns
%% - submits vars
%% AGAINST:
%% - seems to intend to test miner-specific functionality - validators
election_test,
RELOC KEEP - tests election
election_multi_test,
RELOC KEEP - tests election
group_change_test,
RELOC TBD :
%% FOR:
%% - seems to be mostly calling a single miner
%% - submits txns
%% AGAINST:
%% - seems to expect different outcomes in multiple miners
election_v3_test,
RELOC KEEP - tests election
%% snapshot_test is an OK smoke test but doesn't hit every time, the
%% high_snapshot_test test is more reliable:
%%snapshot_test,
high_snapshot_test
RELOC KEEP - why ?
].
init_per_suite(Config) ->
Config.
end_per_suite(Config) ->
Config.
init_per_testcase(TestCase, Config0) ->
%% TODO Describe what global state we intend to setup, besides vals added to config.
%% TODO Redefine as a parameterized helper, because some cased need different params.
Config = miner_ct_utils:init_per_testcase(?MODULE, TestCase, Config0),
try
Miners = ?config(miners, Config),
Addresses = ?config(addresses, Config),
NumConsensusMembers = ?config(num_consensus_members, Config),
BlockTime = case TestCase of
restart_test ->
3000;
_ ->
?config(block_time, Config)
end,
Interval = ?config(election_interval, Config),
BatchSize = ?config(batch_size, Config),
Curve = ?config(dkg_curve, Config),
#{secret := Priv, public := Pub} = Keys =
libp2p_crypto:generate_keys(ecc_compact),
Extras =
TODO Parametarize init_per_testcase instead leaking per - case internals .
case TestCase of
dkg_restart_test ->
#{?election_interval => 10,
?election_restart_interval => 99};
validator_test ->
#{?election_interval => 5,
?monthly_reward => ?bones(1000),
?election_restart_interval => 5};
validator_unstake_test ->
#{?election_interval => 5,
?election_restart_interval => 5};
validator_transition_test ->
#{?election_version => 4,
?election_interval => 5,
?election_restart_interval => 5};
autoskip_chain_vars_test ->
#{?election_interval => 100};
T when T == snapshot_test;
T == high_snapshot_test;
T == group_change_test ->
#{?snapshot_version => 1,
?snapshot_interval => 5,
?election_bba_penalty => 0.01,
?election_seen_penalty => 0.05,
?election_version => 5};
election_v3_test ->
#{
?election_version => 2
};
_ ->
#{}
end,
Vars = #{garbage_value => totes_garb,
?block_time => max(3000, BlockTime),
?election_interval => Interval,
?num_consensus_members => NumConsensusMembers,
?batch_size => BatchSize,
?dkg_curve => Curve},
FinalVars = maps:merge(Vars, Extras),
ct:pal("final vars ~p", [FinalVars]),
InitialVars = miner_ct_utils:make_vars(Keys, FinalVars),
InitialPayment = [ blockchain_txn_coinbase_v1:new(Addr, 5000) || Addr <- Addresses],
%% create a new account to own validators for staking
#{public := AuxPub} = AuxKeys = libp2p_crypto:generate_keys(ecc_compact),
AuxAddr = libp2p_crypto:pubkey_to_bin(AuxPub),
Locations = lists:foldl(
fun(I, Acc) ->
[h3:from_geo({37.780586, -122.469470 + I/50}, 13)|Acc]
end,
[],
lists:seq(1, length(Addresses))
),
InitGen =
case blockchain_txn_vars_v1:decoded_vars(hd(InitialVars)) of
#{?election_version := V} when V >= 5 ->
[blockchain_txn_gen_validator_v1:new(Addr, Addr, ?bones(10000))
|| Addr <- Addresses] ++ [blockchain_txn_coinbase_v1:new(AuxAddr, ?bones(15000))];
_ ->
[blockchain_txn_gen_gateway_v1:new(Addr, Addr, Loc, 0)
|| {Addr, Loc} <- lists:zip(Addresses, Locations)] ++
%% bigger stake for transfer test
[blockchain_txn_coinbase_v1:new(AuxAddr, ?bones(150000))]
end,
Txns = InitialVars ++ InitialPayment ++ InitGen,
{ok, DKGCompletedNodes} = miner_ct_utils:initial_dkg(Miners, Txns, Addresses, NumConsensusMembers, Curve),
%% integrate genesis block
_GenesisLoadResults = miner_ct_utils:integrate_genesis_block(hd(DKGCompletedNodes), Miners -- DKGCompletedNodes),
{ConsensusMiners, NonConsensusMiners} = miner_ct_utils:miners_by_consensus_state(Miners),
ct:pal("ConsensusMiners: ~p, NonConsensusMiners: ~p", [ConsensusMiners, NonConsensusMiners]),
ok = miner_ct_utils:wait_for_gte(height, Miners, 3, all, 15),
[ {master_key, {Priv, Pub}},
{consensus_miners, ConsensusMiners},
{non_consensus_miners, NonConsensusMiners},
{aux_acct, {AuxAddr, AuxKeys}}
| Config]
catch
What:Why:Stack ->
end_per_testcase(TestCase, Config),
ct:pal("Stack ~p", [Stack]),
erlang:What(Why)
end.
end_per_testcase(_TestCase, Config) ->
miner_ct_utils:end_per_testcase(_TestCase, Config).
autoskip_chain_vars_test(Config) ->
%% The idea here is to reproduce the following chain stall scenario:
1 . 1/2 of consensus members recognize a new chain var ;
2 . 1/2 of consensus members do not ;
3 .
%% If autoskip doesn't work:
%% chain halts - no more blocks are created on any of the nodes
%% otherwise
%% chain advances, so autoskip must've worked
MinersAll = ?config(miners, Config),
MinersInConsensus = miner_ct_utils:in_consensus_miners(MinersAll),
N = length(MinersInConsensus),
?assert(N > 1, "We have at least 2 miner nodes."),
M = N div 2,
?assertEqual(N, 2 * M, "Even split of consensus nodes."),
MinersWithBogusVar = lists:sublist(MinersInConsensus, M),
BogusKey = bogus_key,
BogusVal = bogus_val,
ct:pal("N: ~p", [N]),
ct:pal("M: ~p", [M]),
ct:pal("MinersAll: ~p", [MinersAll]),
ct:pal("MinersInConsensus: ~p", [MinersInConsensus]),
ct:pal("MinersWithBogusVar: ~p", [MinersWithBogusVar]),
The mocked 1/2 of consensus group will allow bogus vars :
[
ok =
ct_rpc:call(
Node,
meck,
expect,
[blockchain_txn_vars_v1, is_valid, fun(_, _) -> ok end],
300
)
||
Node <- MinersWithBogusVar
],
%% Submit bogus var transaction:
(fun() ->
{SecretKey, _} = ?config(master_key, Config),
Txn0 = blockchain_txn_vars_v1:new(#{BogusKey => BogusVal}, 2),
Proof = blockchain_txn_vars_v1:create_proof(SecretKey, Txn0),
Txn = blockchain_txn_vars_v1:proof(Txn0, Proof),
miner_ct_utils:submit_txn(Txn, MinersInConsensus)
end)(),
AllHeights =
fun() ->
lists:usort([H || {_, H} <- miner_ct_utils:heights(MinersAll)])
end,
?assert(
miner_ct_utils:wait_until(
fun() ->
case AllHeights() of
[_] -> true;
[_|_] -> false
end
end,
50,
1000
),
"Heights equalized."
),
[Height1] = AllHeights(),
?assertMatch(
ok,
miner_ct_utils:wait_for_gte(height, MinersAll, Height1 + 10),
"Chain has advanced, so autoskip must've worked."
),
%% Extra sanity check - no one should've accepted the bogus var:
?assertMatch(
[{error, not_found}],
lists:usort(miner_ct_utils:chain_var_lookup_all(BogusKey, MinersAll)),
"No node accepted the bogus chain var."
),
{comment, miner_ct_utils:heights(MinersAll)}.
autoskip_on_timeout_test(Config) ->
%% The idea is to reproduce the following chain stall scenario:
1 . 1/2 of consensus members produce timed blocks ;
2 . 1/2 of consensus members do not ;
3 .
%% If time-based autoskip doesn't work:
%% chain halts - no more blocks are created on any of the nodes
%% otherwise
%% chain advances, so time-based autoskip must've worked
MinersAll = ?config(miners, Config),
MinersCG = miner_ct_utils:in_consensus_miners(MinersAll),
N = length(MinersCG),
?assert(N > 1, "We have at least 2 miner nodes."),
M = N div 2,
?assertEqual(N, 2 * M, "Even split of consensus nodes."),
MinersCGBroken = lists:sublist(MinersCG, M),
ct:pal("N: ~p", [N]),
ct:pal("MinersAll: ~p", [MinersAll]),
ct:pal("MinersCG: ~p", [MinersCG]),
ct:pal("MinersCGBroken: ~p", [MinersCGBroken]),
Default is 120 sesonds , but for testing we want to trigger skip faster :
_ = [
ok = ct_rpc:call(Node, application, set_env, [miner, late_block_timeout_seconds, 10], 300)
||
Node <- MinersAll
],
_ = [
ok = ct_rpc:call(Node, miner, hbbft_skip, [], 300)
||
Node <- MinersCGBroken
],
_ = [
ok = ct_rpc:call(Node, miner, hbbft_skip, [], 300)
||
Node <- MinersCGBroken
],
%% TODO The following needs better explanation and/or better methods.
send some more skips at broken miner 1 so we 're not all on the same round
Node1 = hd(MinersCGBroken),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = miner_ct_utils:assert_chain_halted(MinersAll),
ok = miner_ct_utils:assert_chain_advanced(MinersAll, 2500, 5),
{comment, miner_ct_utils:heights(MinersAll)}.
restart_test(Config) ->
%% NOTES:
%% restart_test is hitting coinsensus restore pathway
consesus group is lost but is retained
%%
finish the dkg ,
%% crash,
%% restart
%%
%% trying to check restore after crash
%%
%% the main is to test that group information is not lost after a crash
%%
BaseDir = ?config(base_dir, Config),
Miners = ?config(miners, Config),
wait till the chain reaches height 2 for all miners
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 2, all, 60),
Env = miner_ct_utils:stop_miners(lists:sublist(Miners, 1, 2)),
[begin
ct_rpc:call(Miner, miner_consensus_mgr, cancel_dkg, [], 300)
end
|| Miner <- lists:sublist(Miners, 3, 4)],
%% just kill the consensus groups, we should be able to restore them
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_*{1,2}*", "/blockchain_swarm/groups/consensus_*"),
ok = miner_ct_utils:start_miners(Env),
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 2, all, 90),
{comment, miner_ct_utils:heights(Miners)}.
dkg_restart_test(Config) ->
%% TODO Describe main idea and method.
Miners = ?config(miners, Config),
Interval = ?config(election_interval, Config),
AddrList = ?config(tagged_miner_addresses, Config),
stop the out of consensus miners and the last two consensus
members . this should keep the dkg from completing
wait up to 90s for epoch to or exceed 2
Members = miner_ct_utils:consensus_members(2, Miners),
%% there are issues with this. if it's more of a problem than the
%% last time, we can either have the old list and reject it if we
%% get it again, or we get all of them and select the majority one?
{CMiners, NCMiners} = miner_ct_utils:partition_miners(Members, AddrList),
FirstCMiner = hd(CMiners),
Height = miner_ct_utils:height(FirstCMiner),
Stoppers = lists:sublist(CMiners, 5, 2),
%% make sure that everyone has accepted the epoch block
ok = miner_ct_utils:wait_for_gte(height, Miners, Height + 2),
Stop1 = miner_ct_utils:stop_miners(NCMiners ++ Stoppers, 60),
ct:pal("stopping nc ~p stoppers ~p", [NCMiners, Stoppers]),
%% wait until we're sure that the election is running
ok = miner_ct_utils:wait_for_gte(height, lists:sublist(CMiners, 1, 4), Height + (Interval * 2), all, 180),
stop half of the remaining miners
Restarters = lists:sublist(CMiners, 1, 2),
ct:pal("stopping restarters ~p", [Restarters]),
Stop2 = miner_ct_utils:stop_miners(Restarters, 60),
restore that half
ct:pal("starting restarters ~p", [Restarters]),
miner_ct_utils:start_miners(Stop2, 60),
restore the last two
ct:pal("starting blockers"),
miner_ct_utils:start_miners(Stop1, 60),
%% make sure that we elect again
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 3, any, 90),
%% make sure that we did the restore
EndHeight = miner_ct_utils:height(FirstCMiner),
?assert(EndHeight < (Height + Interval + 99)).
validator_transition_test(Config) ->
%% TODO Describe main idea and method.
%% get all the miners
Miners = ?config(miners, Config),
Options = ?config(node_options, Config),
{Owner, #{secret := AuxPriv}} = ?config(aux_acct, Config),
AuxSigFun = libp2p_crypto:mk_sig_fun(AuxPriv),
setup makes sure that the cluster is running , so the first thing is to create and connect two
%% new nodes.
Blockchain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, GenesisBlock} = ct_rpc:call(hd(Miners), blockchain, genesis_block, [Blockchain]),
ListenAddrs = miner_ct_utils:get_addrs(Miners),
ValidatorAddrList =
[begin
Num = integer_to_list(N),
{NewVal, Keys} = miner_ct_utils:start_miner(list_to_atom(Num ++ miner_ct_utils:randname(5)), Options),
{_, _, _, _Pub, Addr, _SigFun} = Keys,
ct_rpc:call(NewVal, blockchain_worker, integrate_genesis_block, [GenesisBlock]),
Swarm = ct_rpc:call(NewVal, blockchain_swarm, swarm, [], 2000),
lists:foreach(
fun(A) ->
ct_rpc:call(NewVal, libp2p_swarm, connect, [Swarm, A], 2000)
end, ListenAddrs),
UTxn1 = blockchain_txn_stake_validator_v1:new(Addr, Owner, ?bones(10000), 100000),
Txn1 = blockchain_txn_stake_validator_v1:sign(UTxn1, AuxSigFun),
_ = [ok = ct_rpc:call(M, blockchain_worker, submit_txn, [Txn1]) || M <- Miners],
{NewVal, Addr}
end || N <- lists:seq(9, 12)],
{Validators, _Addrs} = lists:unzip(ValidatorAddrList),
{Priv, _Pub} = ?config(master_key, Config),
Vars = #{?election_version => 5},
UEVTxn = blockchain_txn_vars_v1:new(Vars, 2),
Proof = blockchain_txn_vars_v1:create_proof(Priv, UEVTxn),
EVTxn = blockchain_txn_vars_v1:proof(UEVTxn, Proof),
_ = [ok = ct_rpc:call(M, blockchain_worker, submit_txn, [EVTxn]) || M <- Miners],
Me = self(),
spawn(miner_ct_utils, election_check,
[Validators, Validators,
ValidatorAddrList ++ ?config(tagged_miner_addresses, Config),
Me]),
check_loop(180, Validators).
check_loop(0, _Miners) ->
error(seen_timeout);
check_loop(N, Miners) ->
TODO Describe main idea and method . What will send the mesgs ? What is its API ?
TODO Need more transparent API , since the above is n't clear .
%% TODO See if this function can be re-used in election_test
receive
seen_all ->
ok;
{not_seen, []} ->
ok;
{not_seen, Not} ->
Miner = lists:nth(rand:uniform(length(Miners)), Miners),
try
Height = miner_ct_utils:height(Miner),
{_, _, Epoch} = ct_rpc:call(Miner, miner_cli_info, get_info, [], 500),
ct:pal("not seen: ~p height ~p epoch ~p", [Not, Height, Epoch])
catch _:_ ->
ct:pal("not seen: ~p ", [Not]),
ok
end,
timer:sleep(100),
check_loop(N - 1, Miners)
after timer:seconds(30) ->
error(message_timeout)
end.
election_test(Config) ->
%% TODO Describe main idea and method.
%% TODO Break into subcomponents, it's very long and hard to reason about.
BaseDir = ?config(base_dir, Config),
%% get all the miners
Miners = ?config(miners, Config),
AddrList = ?config(tagged_miner_addresses, Config),
Me = self(),
spawn(miner_ct_utils, election_check, [Miners, Miners, AddrList, Me]),
TODO Looks like copy - pasta - see if check_loop/2 can be used instead .
fun Loop(0) ->
error(seen_timeout);
Loop(N) ->
receive
seen_all ->
ok;
{not_seen, []} ->
ok;
{not_seen, Not} ->
Miner = lists:nth(rand:uniform(length(Miners)), Miners),
try
Height = miner_ct_utils:height(Miner),
{_, _, Epoch} = ct_rpc:call(Miner, miner_cli_info, get_info, [], 500),
ct:pal("not seen: ~p height ~p epoch ~p", [Not, Height, Epoch])
catch _:_ ->
ct:pal("not seen: ~p ", [Not]),
ok
end,
timer:sleep(100),
Loop(N - 1)
after timer:seconds(30) ->
error(message_timeout)
end
end(60),
%% we've seen all of the nodes, yay. now make sure that more than
one election can happen .
we wait until we have seen all miners hit an epoch of 3
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 3, all, 90),
stop the first 4 miners
TargetMiners = lists:sublist(Miners, 1, 4),
Stop = miner_ct_utils:stop_miners(TargetMiners),
ct:pal("stopped, waiting"),
%% confirm miner is stopped
ok = miner_ct_utils:wait_for_app_stop(TargetMiners, miner),
%% delete the groups
timer:sleep(1000),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_{1,2,3,4}*/blockchain_swarm/groups/*", ""),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_{1,2,3,4}*/blockchain_swarm/groups/*", ""),
ct:pal("stopped and deleted"),
%% start the stopped miners back up again
miner_ct_utils:start_miners(Stop),
second : make sure we 're not making blocks anymore
HChain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, Height} = ct_rpc:call(hd(Miners), blockchain, height, [HChain]),
height might go up by one , but it should not go up by 5
{_, false} = miner_ct_utils:wait_for_gte(height, Miners, Height + 5, any, 10),
%% third: mint and submit the rescue txn, shrinking the group at
%% the same time.
Addresses = ?config(addresses, Config),
NewGroup = lists:sublist(Addresses, 3, 4),
HChain2 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, HeadBlock} = ct_rpc:call(hd(Miners), blockchain, head_block, [HChain2]),
NewHeight = blockchain_block:height(HeadBlock) + 1,
ct:pal("new height is ~p", [NewHeight]),
Hash = blockchain_block:hash_block(HeadBlock),
Vars = #{?num_consensus_members => 4},
{Priv, _Pub} = ?config(master_key, Config),
Txn = blockchain_txn_vars_v1:new(Vars, 3),
Proof = blockchain_txn_vars_v1:create_proof(Priv, Txn),
VarsTxn = blockchain_txn_vars_v1:proof(Txn, Proof),
{ElectionEpoch, _EpochStart} = blockchain_block_v1:election_info(HeadBlock),
ct:pal("current election epoch: ~p new height: ~p", [ElectionEpoch, NewHeight]),
GrpTxn = blockchain_txn_consensus_group_v1:new(NewGroup, <<>>, Height, 0),
RescueBlock = blockchain_block_v1:rescue(
#{prev_hash => Hash,
height => NewHeight,
transactions => [VarsTxn, GrpTxn],
hbbft_round => NewHeight,
time => erlang:system_time(seconds),
election_epoch => ElectionEpoch + 1,
epoch_start => NewHeight}),
EncodedBlock = blockchain_block:serialize(
blockchain_block_v1:set_signatures(RescueBlock, [])),
RescueSigFun = libp2p_crypto:mk_sig_fun(Priv),
RescueSig = RescueSigFun(EncodedBlock),
SignedBlock = blockchain_block_v1:set_signatures(RescueBlock, [], RescueSig),
now that we have a signed block , cause one of the nodes to
%% absorb it (and gossip it around)
FirstNode = hd(Miners),
Chain = ct_rpc:call(FirstNode, blockchain_worker, blockchain, []),
ct:pal("FirstNode Chain: ~p", [Chain]),
Swarm = ct_rpc:call(FirstNode, blockchain_swarm, swarm, []),
ct:pal("FirstNode Swarm: ~p", [Swarm]),
N = length(Miners),
ct:pal("N: ~p", [N]),
ok = ct_rpc:call(FirstNode, blockchain_gossip_handler, add_block, [SignedBlock, Chain, self(), blockchain_swarm:tid()]),
wait until height has increased by 3
ok = miner_ct_utils:wait_for_gte(height, Miners, NewHeight + 2),
%% check consensus and non consensus miners
{NewConsensusMiners, NewNonConsensusMiners} = miner_ct_utils:miners_by_consensus_state(Miners),
%% stop some nodes and restart them to check group restore works
StopList = lists:sublist(NewConsensusMiners, 2) ++ lists:sublist(NewNonConsensusMiners, 2),
ct:pal("stop list ~p", [StopList]),
Stop2 = miner_ct_utils:stop_miners(StopList),
%% sleep a lil then start the nodes back up again
timer:sleep(1000),
miner_ct_utils:start_miners(Stop2),
fourth : confirm that blocks and elections are proceeding
ok = miner_ct_utils:wait_for_gte(epoch, Miners, ElectionEpoch + 1).
election_multi_test(Config) ->
%% TODO Describe main idea and method.
%% TODO Break into subcomponents, it's very long and hard to reason about.
BaseDir = ?config(base_dir, Config),
%% get all the miners
Miners = ?config(miners, Config),
AddrList = ? config(tagged_miner_addresses , Config ) ,
Addresses = ?config(addresses, Config),
{Priv, _Pub} = ?config(master_key, Config),
we wait until we have seen all miners hit an epoch of 2
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 2, all, 90),
ct:pal("starting multisig attempt"),
TODO Looks automatable - 5 unique things that are n't used uniquely :
{ , BinPubs } = ( fun(N ) - >
[ libp2p_crypto : generate_keys(ecc_compact ) || { } < - lists : , { } ) ] ,
[ Priv || # { secret : = Priv } < - Keys ] ,
% Pubs = [Pub || #{public := Pub} <- Keys],
= lists : map(fun libp2p_crypto : pubkey_to_bin/1 , Pubs ) ,
, BinPubs }
) ( 5 )
#{secret := Priv1, public := Pub1} = libp2p_crypto:generate_keys(ecc_compact),
#{secret := Priv2, public := Pub2} = libp2p_crypto:generate_keys(ecc_compact),
#{secret := Priv3, public := Pub3} = libp2p_crypto:generate_keys(ecc_compact),
#{secret := Priv4, public := Pub4} = libp2p_crypto:generate_keys(ecc_compact),
#{secret := Priv5, public := Pub5} = libp2p_crypto:generate_keys(ecc_compact),
BinPub1 = libp2p_crypto:pubkey_to_bin(Pub1),
BinPub2 = libp2p_crypto:pubkey_to_bin(Pub2),
BinPub3 = libp2p_crypto:pubkey_to_bin(Pub3),
BinPub4 = libp2p_crypto:pubkey_to_bin(Pub4),
BinPub5 = libp2p_crypto:pubkey_to_bin(Pub5),
Txn7_0 = blockchain_txn_vars_v1:new(
#{?use_multi_keys => true}, 2,
#{multi_keys => [BinPub1, BinPub2, BinPub3, BinPub4, BinPub5]}),
Proofs7 = [blockchain_txn_vars_v1:create_proof(P, Txn7_0)
|| P <- [Priv1, Priv2, Priv3, Priv4, Priv5]],
Txn7_1 = blockchain_txn_vars_v1:multi_key_proofs(Txn7_0, Proofs7),
Proof7 = blockchain_txn_vars_v1:create_proof(Priv, Txn7_1),
Txn7 = blockchain_txn_vars_v1:proof(Txn7_1, Proof7),
_ = [ok = ct_rpc:call(M, blockchain_worker, submit_txn, [Txn7]) || M <- Miners],
ok = miner_ct_utils:wait_for_chain_var_update(Miners, ?use_multi_keys, true),
ct:pal("transitioned to multikey"),
stop the first 4 miners
TargetMiners = lists:sublist(Miners, 1, 4),
Stop = miner_ct_utils:stop_miners(TargetMiners),
%% confirm miner is stopped
ok = miner_ct_utils:wait_for_app_stop(TargetMiners, miner),
%% delete the groups
timer:sleep(1000),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_{1,2,3,4}*/blockchain_swarm/groups/*", ""),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_{1,2,3,4}*/blockchain_swarm/groups/*", ""),
%% start the stopped miners back up again
miner_ct_utils:start_miners(Stop),
NewAddrs =
[begin
Swarm = ct_rpc:call(Target, blockchain_swarm, swarm, [], 2000),
[H|_] = LAs= ct_rpc:call(Target, libp2p_swarm, listen_addrs, [Swarm], 2000),
ct:pal("addrs ~p ~p", [Target, LAs]),
H
end || Target <- TargetMiners],
miner_ct_utils:pmap(
fun(M) ->
[begin
Sw = ct_rpc:call(M, blockchain_swarm, swarm, [], 2000),
ct_rpc:call(M, libp2p_swarm, connect, [Sw, Addr], 2000)
end || Addr <- NewAddrs]
end, Miners),
second : make sure we 're not making blocks anymore
HChain1 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, Height1} = ct_rpc:call(hd(Miners), blockchain, height, [HChain1]),
height might go up by one , but it should not go up by 5
{_, false} = miner_ct_utils:wait_for_gte(height, Miners, Height1 + 5, any, 10),
HeadAddress = ct_rpc:call(hd(Miners), blockchain_swarm, pubkey_bin, []),
GroupTail = Addresses -- [HeadAddress],
ct:pal("l ~p tail ~p", [length(GroupTail), GroupTail]),
{NewHeight, HighBlock} =
lists:max(
[begin
C = ct_rpc:call(M, blockchain_worker, blockchain, []),
{ok, HB} = ct_rpc:call(M, blockchain, head_block, [C]),
{blockchain_block:height(HB) + 1, HB}
end || M <- Miners]),
ct:pal("new height is ~p", [NewHeight]),
Hash2 = blockchain_block:hash_block(HighBlock),
{ElectionEpoch1, _EpochStart1} = blockchain_block_v1:election_info(HighBlock),
GrpTxn2 = blockchain_txn_consensus_group_v1:new(GroupTail, <<>>, NewHeight, 0),
RescueBlock2 =
blockchain_block_v1:rescue(
#{prev_hash => Hash2,
height => NewHeight,
transactions => [GrpTxn2],
hbbft_round => NewHeight,
time => erlang:system_time(seconds),
election_epoch => ElectionEpoch1 + 1,
epoch_start => NewHeight}),
EncodedBlock2 = blockchain_block:serialize(
blockchain_block_v1:set_signatures(RescueBlock2, [])),
RescueSigs =
[begin
RescueSigFun2 = libp2p_crypto:mk_sig_fun(P),
RescueSigFun2(EncodedBlock2)
end
|| P <- [Priv1, Priv2, Priv3, Priv4, Priv5]],
SignedBlock = blockchain_block_v1:set_signatures(RescueBlock2, [], RescueSigs),
now that we have a signed block , cause one of the nodes to
%% absorb it (and gossip it around)
FirstNode = hd(Miners),
SecondNode = lists:last(Miners),
Chain1 = ct_rpc:call(FirstNode, blockchain_worker, blockchain, []),
Chain2 = ct_rpc:call(SecondNode, blockchain_worker, blockchain, []),
N = length(Miners),
ct:pal("first node ~p second ~pN: ~p", [FirstNode, SecondNode, N]),
ok = ct_rpc:call(FirstNode, blockchain_gossip_handler, add_block, [SignedBlock, Chain1, self(), blockchain_swarm:tid()]),
ok = ct_rpc:call(SecondNode, blockchain_gossip_handler, add_block, [SignedBlock, Chain2, self(), blockchain_swarm:tid()]),
%% wait until height has increased
case miner_ct_utils:wait_for_gte(height, Miners, NewHeight + 3, any, 30) of
ok -> ok;
_ ->
[begin
Status = ct_rpc:call(M, miner, hbbft_status, []),
ct:pal("miner ~p, status: ~p", [M, Status])
end
|| M <- Miners],
error(rescue_group_made_no_progress)
end.
group_change_test(Config) ->
%% TODO Describe main idea and method.
%% TODO Break into subcomponents, it's very long and hard to reason about.
%% get all the miners
Miners = ?config(miners, Config),
BaseDir = ?config(base_dir, Config),
ConsensusMiners = ?config(consensus_miners, Config),
?assertNotEqual([], ConsensusMiners),
?assertEqual(4, length(ConsensusMiners)),
%% make sure that elections are rolling
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 1),
%% submit the transaction
Blockchain1 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
Ledger1 = ct_rpc:call(hd(Miners), blockchain, ledger, [Blockchain1]),
?assertEqual({ok, totes_garb}, ct_rpc:call(hd(Miners), blockchain, config, [garbage_value, Ledger1])),
Vars = #{num_consensus_members => 7},
{Priv, _Pub} = ?config(master_key, Config),
Txn = blockchain_txn_vars_v1:new(Vars, 2, #{version_predicate => 2,
unsets => [garbage_value]}),
Proof = blockchain_txn_vars_v1:create_proof(Priv, Txn),
Txn1 = blockchain_txn_vars_v1:proof(Txn, Proof),
%% wait for it to take effect
_ = [ok = ct_rpc:call(Miner, blockchain_worker, submit_txn, [Txn1])
|| Miner <- Miners],
HChain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, Height} = ct_rpc:call(hd(Miners), blockchain, height, [HChain]),
wait until height has increased by 10
ok = miner_ct_utils:wait_for_gte(height, Miners, Height + 10, all, 80),
[{Target, TargetEnv}] = miner_ct_utils:stop_miners([lists:last(Miners)]),
Miners1 = Miners -- [Target],
ct:pal("stopped target: ~p", [Target]),
%% make sure we still haven't executed it
C = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
L = ct_rpc:call(hd(Miners), blockchain, ledger, [C]),
{ok, Members} = ct_rpc:call(hd(Miners), blockchain_ledger_v1, consensus_members, [L]),
?assertEqual(4, length(Members)),
%% take a snapshot to load *before* the threshold is processed
Chain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{SnapshotBlockHeight, _SnapshotBlockHash, SnapshotHash} =
ct_rpc:call(hd(Miners), blockchain, find_last_snapshot, [Chain]),
%% alter the "version" for all of them that are up.
lists:foreach(
fun(Miner) ->
ct_rpc:call(Miner, miner, inc_tv, [rand:uniform(4)]) %% make sure we're exercising the summing
end, Miners1),
true = miner_ct_utils:wait_until(
fun() ->
lists:all(
fun(Miner) ->
NewVersion = ct_rpc:call(Miner, miner, test_version, [], 1000),
ct:pal("test version ~p ~p", [Miner, NewVersion]),
NewVersion > 1
end, Miners1)
end),
%% wait for the change to take effect
Timeout = 200,
true = miner_ct_utils:wait_until(
fun() ->
lists:all(
fun(Miner) ->
C1 = ct_rpc:call(Miner, blockchain_worker, blockchain, [], Timeout),
L1 = ct_rpc:call(Miner, blockchain, ledger, [C1], Timeout),
case ct_rpc:call(Miner, blockchain, config, [num_consensus_members, L1], Timeout) of
{ok, Sz} ->
Versions =
ct_rpc:call(Miner, blockchain_ledger_v1, cg_versions,
[L1], Timeout),
ct:pal("size = ~p versions = ~p", [Sz, Versions]),
Sz == 7;
_ ->
%% badrpc
false
end
end, Miners1)
end, 120, 1000),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_*{8}*/*", ""),
[EightDir] = filelib:wildcard(BaseDir ++ "_*{8}*"),
BlockchainR = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, GenesisBlock} = ct_rpc:call(hd(Miners), blockchain, genesis_block, [BlockchainR]),
GenSer = blockchain_block:serialize(GenesisBlock),
ok = file:make_dir(EightDir ++ "/update"),
ok = file:write_file(EightDir ++ "/update/genesis", GenSer),
%% clean out everything from the stopped node
BlockchainEnv = proplists:get_value(blockchain, TargetEnv),
NewBlockchainEnv = [{blessed_snapshot_block_hash, SnapshotHash}, {blessed_snapshot_block_height, SnapshotBlockHeight},
{quick_sync_mode, blessed_snapshot}, {honor_quick_sync, true}|BlockchainEnv],
MinerEnv = proplists:get_value(miner, TargetEnv),
NewMinerEnv = [{update_dir, EightDir ++ "/update"} | MinerEnv],
NewTargetEnv0 = lists:keyreplace(blockchain, 1, TargetEnv, {blockchain, NewBlockchainEnv}),
NewTargetEnv = lists:keyreplace(miner, 1, NewTargetEnv0, {miner, NewMinerEnv}),
%% restart it
miner_ct_utils:start_miners([{Target, NewTargetEnv}]),
Swarm = ct_rpc:call(Target, blockchain_swarm, swarm, [], 2000),
[H|_] = ct_rpc:call(Target, libp2p_swarm, listen_addrs, [Swarm], 2000),
miner_ct_utils:pmap(
fun(M) ->
Sw = ct_rpc:call(M, blockchain_swarm, swarm, [], 2000),
ct_rpc:call(M, libp2p_swarm, connect, [Sw, H], 2000)
end, Miners1),
Blockchain2 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
Ledger2 = ct_rpc:call(hd(Miners), blockchain, ledger, [Blockchain2]),
?assertEqual({error, not_found}, ct_rpc:call(hd(Miners), blockchain, config, [garbage_value, Ledger2])),
HChain2 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, Height2} = ct_rpc:call(hd(Miners), blockchain, height, [HChain2]),
ct:pal("post change miner ~p height ~p", [hd(Miners), Height2]),
%% TODO: probably need to parameterize this via the delay
?assert(Height2 > Height + 10 + 5),
%% do some additional checks to make sure that we restored across.
ok = miner_ct_utils:wait_for_gte(height, [Target], Height2, all, 120),
TC = ct_rpc:call(Target, blockchain_worker, blockchain, [], Timeout),
TL = ct_rpc:call(Target, blockchain, ledger, [TC], Timeout),
{ok, TSz} = ct_rpc:call(Target, blockchain, config, [num_consensus_members, TL], Timeout),
?assertEqual(TSz, 7),
ok.
election_v3_test(Config) ->
%% TODO Describe main idea and method.
%% get all the miners
Miners = ?config(miners, Config),
ConsensusMiners = ?config(consensus_miners, Config),
?assertNotEqual([], ConsensusMiners),
?assertEqual(7, length(ConsensusMiners)),
%% make sure that elections are rolling
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 2),
Blockchain1 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{Priv, _Pub} = ?config(master_key, Config),
Vars = #{?election_version => 3,
?election_bba_penalty => 0.01,
?election_seen_penalty => 0.05},
Txn = blockchain_txn_vars_v1:new(Vars, 2),
Proof = blockchain_txn_vars_v1:create_proof(Priv, Txn),
Txn1 = blockchain_txn_vars_v1:proof(Txn, Proof),
_ = [ok = ct_rpc:call(Miner, blockchain_worker, submit_txn, [Txn1])
|| Miner <- Miners],
ok = miner_ct_utils:wait_for_chain_var_update(Miners, ?election_version, 3),
{ok, Start} = ct_rpc:call(hd(Miners), blockchain, height, [Blockchain1]),
wait until height has increased by 10
ok = miner_ct_utils:wait_for_gte(height, Miners, Start + 10),
%% get all blocks and check that they have the appropriate
%% metadata
[begin
PrevBlock = miner_ct_utils:get_block(N - 1, hd(Miners)),
Block = miner_ct_utils:get_block(N, hd(Miners)),
ct:pal("n ~p s ~p b ~p", [N, Start, Block]),
case N of
_ when N < Start ->
?assertEqual([], blockchain_block_v1:seen_votes(Block)),
?assertEqual(<<>>, blockchain_block_v1:bba_completion(Block));
skip these because we 're not 100 % certain when the var
%% will become effective.
_ when N < Start + 5 ->
ok;
_ ->
Ts = blockchain_block:transactions(PrevBlock),
case lists:filter(fun(T) ->
blockchain_txn:type(T) == blockchain_txn_consensus_group_v1
end, Ts) of
[] ->
?assertNotEqual([], blockchain_block_v1:seen_votes(Block)),
?assertNotEqual(<<>>, blockchain_block_v1:bba_completion(Block));
first post - election block has no info
_ ->
?assertEqual([<<>>], lists:usort([X || {_, X} <- blockchain_block_v1:seen_votes(Block)])),
?assertEqual(<<>>, blockchain_block_v1:bba_completion(Block))
end
end
end
|| N <- lists:seq(2, Start + 10)],
two should guarantee at least one consensus member is down but
%% that block production is still happening
StopList = lists:sublist(Miners, 7, 2),
ct:pal("stop list ~p", [StopList]),
_Stop = miner_ct_utils:stop_miners(StopList),
{ok, Start2} = ct_rpc:call(hd(Miners), blockchain, height, [Blockchain1]),
%% try a skip to move past the occasional stuck group
[ct_rpc:call(M, miner, hbbft_skip, []) || M <- lists:sublist(Miners, 1, 6)],
ok = miner_ct_utils:wait_for_gte(height, lists:sublist(Miners, 1, 6), Start2 + 10, all, 120),
[begin
PrevBlock = miner_ct_utils:get_block(N - 1, hd(Miners)),
Block = miner_ct_utils:get_block(N, hd(Miners)),
ct:pal("n ~p s ~p b ~p", [N, Start, Block]),
Ts = blockchain_block:transactions(PrevBlock),
case lists:filter(fun(T) ->
blockchain_txn:type(T) == blockchain_txn_consensus_group_v1
end, Ts) of
[] ->
Seen = blockchain_block_v1:seen_votes(Block),
given the current code , BBA will always be 2f+1 ,
%% so there's no point in checking it other than
%% seeing that it is not <<>> or <<0>>
%% when we have something to check, this might be
helpful : lists : sum([case $ ; band ( 1 bsl N ) of 0 - > 0 ; _ - > 1 end || N < - lists : seq(1 , 7 ) ] ) .
BBA = blockchain_block_v1:bba_completion(Block),
?assertNotEqual([], Seen),
?assertNotEqual(<<>>, BBA),
?assertNotEqual(<<0>>, BBA),
Len = length(Seen),
?assert(Len == 6 orelse Len == 5),
Votes = lists:usort([Vote || {_ID, Vote} <- Seen]),
[?assertNotEqual(<<127>>, V) || V <- Votes];
first post - election block has no info
_ ->
Seen = blockchain_block_v1:seen_votes(Block),
Votes = lists:usort([Vote || {_ID, Vote} <- Seen]),
?assertEqual([<<>>], Votes),
?assertEqual(<<>>, blockchain_block_v1:bba_completion(Block))
end
end
%% start at +2 so we don't get a stale block that saw the
%% stopping nodes.
|| N <- lists:seq(Start2 + 2, Start2 + 10)],
ok.
snapshot_test(Config) ->
%% TODO Describe main idea and method.
%% get all the miners
Miners0 = ?config(miners, Config),
ConsensusMiners = ?config(consensus_miners, Config),
[Target | Miners] = Miners0,
ct:pal("target ~p", [Target]),
?assertNotEqual([], ConsensusMiners),
?assertEqual(7, length(ConsensusMiners)),
%% make sure that elections are rolling
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 1),
ok = miner_ct_utils:wait_for_gte(height, Miners, 7),
[{Target, TargetEnv}] = miner_ct_utils:stop_miners([Target]),
ok = miner_ct_utils:wait_for_gte(height, Miners, 15),
Chain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{SnapshotBlockHeight, SnapshotBlockHash, SnapshotHash} =
ct_rpc:call(hd(Miners), blockchain, find_last_snapshot, [Chain]),
?assert(is_binary(SnapshotHash)),
?assert(is_binary(SnapshotBlockHash)),
?assert(is_integer(SnapshotBlockHeight)),
ct:pal("Snapshot hash is ~p at height ~p~n in block ~p",
[SnapshotHash, SnapshotBlockHeight, SnapshotBlockHash]),
BlockchainEnv = proplists:get_value(blockchain, TargetEnv),
NewBlockchainEnv = [{blessed_snapshot_block_hash, SnapshotHash}, {blessed_snapshot_block_height, SnapshotBlockHeight},
{quick_sync_mode, blessed_snapshot}, {honor_quick_sync, true}|BlockchainEnv],
NewTargetEnv = lists:keyreplace(blockchain, 1, TargetEnv, {blockchain, NewBlockchainEnv}),
ct:pal("new blockchain env ~p", [NewTargetEnv]),
miner_ct_utils:start_miners([{Target, NewTargetEnv}]),
miner_ct_utils:wait_until(
fun() ->
try
undefined =/= ct_rpc:call(Target, blockchain_worker, blockchain, [])
catch _:_ ->
false
end
end, 50, 200),
ok = ct_rpc:call(Target, blockchain, reset_ledger_to_snap, []),
ok = miner_ct_utils:wait_for_gte(height, Miners0, 25, all, 20),
ok.
high_snapshot_test(Config) ->
%% TODO Describe main idea and method.
%% get all the miners
Miners0 = ?config(miners, Config),
ConsensusMiners = ?config(consensus_miners, Config),
[Target | Miners] = Miners0,
ct:pal("target ~p", [Target]),
?assertNotEqual([], ConsensusMiners),
?assertEqual(7, length(ConsensusMiners)),
%% make sure that elections are rolling
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 1),
ok = miner_ct_utils:wait_for_gte(height, Miners, 7),
[{Target, TargetEnv}] = miner_ct_utils:stop_miners([Target]),
ok = miner_ct_utils:wait_for_gte(height, Miners, 70, all, 600),
Chain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{SnapshotBlockHeight, SnapshotBlockHash, SnapshotHash} =
ct_rpc:call(hd(Miners), blockchain, find_last_snapshot, [Chain]),
?assert(is_binary(SnapshotHash)),
?assert(is_binary(SnapshotBlockHash)),
?assert(is_integer(SnapshotBlockHeight)),
ct:pal("Snapshot hash is ~p at height ~p~n in block ~p",
[SnapshotHash, SnapshotBlockHeight, SnapshotBlockHash]),
%% TODO: probably at this step we should delete all the blocks
%% that the downed node has
BlockchainEnv = proplists:get_value(blockchain, TargetEnv),
NewBlockchainEnv = [{blessed_snapshot_block_hash, SnapshotHash}, {blessed_snapshot_block_height, SnapshotBlockHeight},
{quick_sync_mode, blessed_snapshot}, {honor_quick_sync, true}|BlockchainEnv],
NewTargetEnv = lists:keyreplace(blockchain, 1, TargetEnv, {blockchain, NewBlockchainEnv}),
ct:pal("new blockchain env ~p", [NewTargetEnv]),
miner_ct_utils:start_miners([{Target, NewTargetEnv}]),
timer:sleep(5000),
ok = ct_rpc:call(Target, blockchain, reset_ledger_to_snap, []),
ok = miner_ct_utils:wait_for_gte(height, Miners0, 80, all, 30),
ok.
%% ------------------------------------------------------------------
%% Local Helper functions
%% ------------------------------------------------------------------
| null | https://raw.githubusercontent.com/helium/miner/f5f71d7dcd9c6633cf5d80c8fee60def9a608f65/test/miner_blockchain_SUITE.erl | erlang | TODO Relocate all helper functions below tests.
FOR:
- submits txns
- submits vars
AGAINST:
- seems to intend to test miner-specific functionality - validators
FOR:
- seems to be mostly calling a single miner
- submits txns
AGAINST:
- seems to expect different outcomes in multiple miners
snapshot_test is an OK smoke test but doesn't hit every time, the
high_snapshot_test test is more reliable:
snapshot_test,
TODO Describe what global state we intend to setup, besides vals added to config.
TODO Redefine as a parameterized helper, because some cased need different params.
create a new account to own validators for staking
bigger stake for transfer test
integrate genesis block
The idea here is to reproduce the following chain stall scenario:
If autoskip doesn't work:
chain halts - no more blocks are created on any of the nodes
otherwise
chain advances, so autoskip must've worked
Submit bogus var transaction:
Extra sanity check - no one should've accepted the bogus var:
The idea is to reproduce the following chain stall scenario:
If time-based autoskip doesn't work:
chain halts - no more blocks are created on any of the nodes
otherwise
chain advances, so time-based autoskip must've worked
TODO The following needs better explanation and/or better methods.
NOTES:
restart_test is hitting coinsensus restore pathway
crash,
restart
trying to check restore after crash
the main is to test that group information is not lost after a crash
just kill the consensus groups, we should be able to restore them
TODO Describe main idea and method.
there are issues with this. if it's more of a problem than the
last time, we can either have the old list and reject it if we
get it again, or we get all of them and select the majority one?
make sure that everyone has accepted the epoch block
wait until we're sure that the election is running
make sure that we elect again
make sure that we did the restore
TODO Describe main idea and method.
get all the miners
new nodes.
TODO See if this function can be re-used in election_test
TODO Describe main idea and method.
TODO Break into subcomponents, it's very long and hard to reason about.
get all the miners
we've seen all of the nodes, yay. now make sure that more than
confirm miner is stopped
delete the groups
start the stopped miners back up again
third: mint and submit the rescue txn, shrinking the group at
the same time.
absorb it (and gossip it around)
check consensus and non consensus miners
stop some nodes and restart them to check group restore works
sleep a lil then start the nodes back up again
TODO Describe main idea and method.
TODO Break into subcomponents, it's very long and hard to reason about.
get all the miners
Pubs = [Pub || #{public := Pub} <- Keys],
confirm miner is stopped
delete the groups
start the stopped miners back up again
absorb it (and gossip it around)
wait until height has increased
TODO Describe main idea and method.
TODO Break into subcomponents, it's very long and hard to reason about.
get all the miners
make sure that elections are rolling
submit the transaction
wait for it to take effect
make sure we still haven't executed it
take a snapshot to load *before* the threshold is processed
alter the "version" for all of them that are up.
make sure we're exercising the summing
wait for the change to take effect
badrpc
clean out everything from the stopped node
restart it
TODO: probably need to parameterize this via the delay
do some additional checks to make sure that we restored across.
TODO Describe main idea and method.
get all the miners
make sure that elections are rolling
get all blocks and check that they have the appropriate
metadata
certain when the var
will become effective.
that block production is still happening
try a skip to move past the occasional stuck group
so there's no point in checking it other than
seeing that it is not <<>> or <<0>>
when we have something to check, this might be
start at +2 so we don't get a stale block that saw the
stopping nodes.
TODO Describe main idea and method.
get all the miners
make sure that elections are rolling
TODO Describe main idea and method.
get all the miners
make sure that elections are rolling
TODO: probably at this step we should delete all the blocks
that the downed node has
------------------------------------------------------------------
Local Helper functions
------------------------------------------------------------------ | -module(miner_blockchain_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("blockchain/include/blockchain_vars.hrl").
-include_lib("blockchain/include/blockchain.hrl").
-export([
init_per_suite/1,
end_per_suite/1,
init_per_testcase/2,
end_per_testcase/2,
all/0
]).
-export([
autoskip_chain_vars_test/1,
autoskip_on_timeout_test/1,
restart_test/1,
dkg_restart_test/1,
validator_transition_test/1,
election_test/1,
election_multi_test/1,
group_change_test/1,
election_v3_test/1,
snapshot_test/1,
high_snapshot_test/1
]).
all() -> [
RELOC NOTE def KEEP testing of DKG
RELOC NOTE def KEEP testing of election
RELOC NOTE def MOVE testing of variable changes
RELOC NOTE may MOVE if raw transactions are being submitted
autoskip_chain_vars_test,
RELOC KEEP - tests miner - unique feature
autoskip_on_timeout_test,
RELOC KEEP - tests miner - unique feature
restart_test,
RELOC KEEP - tests whole miner
dkg_restart_test,
RELOC KEEP - tests DKG
validator_transition_test,
RELOC TBD :
election_test,
RELOC KEEP - tests election
election_multi_test,
RELOC KEEP - tests election
group_change_test,
RELOC TBD :
election_v3_test,
RELOC KEEP - tests election
high_snapshot_test
RELOC KEEP - why ?
].
init_per_suite(Config) ->
Config.
end_per_suite(Config) ->
Config.
init_per_testcase(TestCase, Config0) ->
Config = miner_ct_utils:init_per_testcase(?MODULE, TestCase, Config0),
try
Miners = ?config(miners, Config),
Addresses = ?config(addresses, Config),
NumConsensusMembers = ?config(num_consensus_members, Config),
BlockTime = case TestCase of
restart_test ->
3000;
_ ->
?config(block_time, Config)
end,
Interval = ?config(election_interval, Config),
BatchSize = ?config(batch_size, Config),
Curve = ?config(dkg_curve, Config),
#{secret := Priv, public := Pub} = Keys =
libp2p_crypto:generate_keys(ecc_compact),
Extras =
TODO Parametarize init_per_testcase instead leaking per - case internals .
case TestCase of
dkg_restart_test ->
#{?election_interval => 10,
?election_restart_interval => 99};
validator_test ->
#{?election_interval => 5,
?monthly_reward => ?bones(1000),
?election_restart_interval => 5};
validator_unstake_test ->
#{?election_interval => 5,
?election_restart_interval => 5};
validator_transition_test ->
#{?election_version => 4,
?election_interval => 5,
?election_restart_interval => 5};
autoskip_chain_vars_test ->
#{?election_interval => 100};
T when T == snapshot_test;
T == high_snapshot_test;
T == group_change_test ->
#{?snapshot_version => 1,
?snapshot_interval => 5,
?election_bba_penalty => 0.01,
?election_seen_penalty => 0.05,
?election_version => 5};
election_v3_test ->
#{
?election_version => 2
};
_ ->
#{}
end,
Vars = #{garbage_value => totes_garb,
?block_time => max(3000, BlockTime),
?election_interval => Interval,
?num_consensus_members => NumConsensusMembers,
?batch_size => BatchSize,
?dkg_curve => Curve},
FinalVars = maps:merge(Vars, Extras),
ct:pal("final vars ~p", [FinalVars]),
InitialVars = miner_ct_utils:make_vars(Keys, FinalVars),
InitialPayment = [ blockchain_txn_coinbase_v1:new(Addr, 5000) || Addr <- Addresses],
#{public := AuxPub} = AuxKeys = libp2p_crypto:generate_keys(ecc_compact),
AuxAddr = libp2p_crypto:pubkey_to_bin(AuxPub),
Locations = lists:foldl(
fun(I, Acc) ->
[h3:from_geo({37.780586, -122.469470 + I/50}, 13)|Acc]
end,
[],
lists:seq(1, length(Addresses))
),
InitGen =
case blockchain_txn_vars_v1:decoded_vars(hd(InitialVars)) of
#{?election_version := V} when V >= 5 ->
[blockchain_txn_gen_validator_v1:new(Addr, Addr, ?bones(10000))
|| Addr <- Addresses] ++ [blockchain_txn_coinbase_v1:new(AuxAddr, ?bones(15000))];
_ ->
[blockchain_txn_gen_gateway_v1:new(Addr, Addr, Loc, 0)
|| {Addr, Loc} <- lists:zip(Addresses, Locations)] ++
[blockchain_txn_coinbase_v1:new(AuxAddr, ?bones(150000))]
end,
Txns = InitialVars ++ InitialPayment ++ InitGen,
{ok, DKGCompletedNodes} = miner_ct_utils:initial_dkg(Miners, Txns, Addresses, NumConsensusMembers, Curve),
_GenesisLoadResults = miner_ct_utils:integrate_genesis_block(hd(DKGCompletedNodes), Miners -- DKGCompletedNodes),
{ConsensusMiners, NonConsensusMiners} = miner_ct_utils:miners_by_consensus_state(Miners),
ct:pal("ConsensusMiners: ~p, NonConsensusMiners: ~p", [ConsensusMiners, NonConsensusMiners]),
ok = miner_ct_utils:wait_for_gte(height, Miners, 3, all, 15),
[ {master_key, {Priv, Pub}},
{consensus_miners, ConsensusMiners},
{non_consensus_miners, NonConsensusMiners},
{aux_acct, {AuxAddr, AuxKeys}}
| Config]
catch
What:Why:Stack ->
end_per_testcase(TestCase, Config),
ct:pal("Stack ~p", [Stack]),
erlang:What(Why)
end.
end_per_testcase(_TestCase, Config) ->
miner_ct_utils:end_per_testcase(_TestCase, Config).
autoskip_chain_vars_test(Config) ->
1 . 1/2 of consensus members recognize a new chain var ;
2 . 1/2 of consensus members do not ;
3 .
MinersAll = ?config(miners, Config),
MinersInConsensus = miner_ct_utils:in_consensus_miners(MinersAll),
N = length(MinersInConsensus),
?assert(N > 1, "We have at least 2 miner nodes."),
M = N div 2,
?assertEqual(N, 2 * M, "Even split of consensus nodes."),
MinersWithBogusVar = lists:sublist(MinersInConsensus, M),
BogusKey = bogus_key,
BogusVal = bogus_val,
ct:pal("N: ~p", [N]),
ct:pal("M: ~p", [M]),
ct:pal("MinersAll: ~p", [MinersAll]),
ct:pal("MinersInConsensus: ~p", [MinersInConsensus]),
ct:pal("MinersWithBogusVar: ~p", [MinersWithBogusVar]),
The mocked 1/2 of consensus group will allow bogus vars :
[
ok =
ct_rpc:call(
Node,
meck,
expect,
[blockchain_txn_vars_v1, is_valid, fun(_, _) -> ok end],
300
)
||
Node <- MinersWithBogusVar
],
(fun() ->
{SecretKey, _} = ?config(master_key, Config),
Txn0 = blockchain_txn_vars_v1:new(#{BogusKey => BogusVal}, 2),
Proof = blockchain_txn_vars_v1:create_proof(SecretKey, Txn0),
Txn = blockchain_txn_vars_v1:proof(Txn0, Proof),
miner_ct_utils:submit_txn(Txn, MinersInConsensus)
end)(),
AllHeights =
fun() ->
lists:usort([H || {_, H} <- miner_ct_utils:heights(MinersAll)])
end,
?assert(
miner_ct_utils:wait_until(
fun() ->
case AllHeights() of
[_] -> true;
[_|_] -> false
end
end,
50,
1000
),
"Heights equalized."
),
[Height1] = AllHeights(),
?assertMatch(
ok,
miner_ct_utils:wait_for_gte(height, MinersAll, Height1 + 10),
"Chain has advanced, so autoskip must've worked."
),
?assertMatch(
[{error, not_found}],
lists:usort(miner_ct_utils:chain_var_lookup_all(BogusKey, MinersAll)),
"No node accepted the bogus chain var."
),
{comment, miner_ct_utils:heights(MinersAll)}.
autoskip_on_timeout_test(Config) ->
1 . 1/2 of consensus members produce timed blocks ;
2 . 1/2 of consensus members do not ;
3 .
MinersAll = ?config(miners, Config),
MinersCG = miner_ct_utils:in_consensus_miners(MinersAll),
N = length(MinersCG),
?assert(N > 1, "We have at least 2 miner nodes."),
M = N div 2,
?assertEqual(N, 2 * M, "Even split of consensus nodes."),
MinersCGBroken = lists:sublist(MinersCG, M),
ct:pal("N: ~p", [N]),
ct:pal("MinersAll: ~p", [MinersAll]),
ct:pal("MinersCG: ~p", [MinersCG]),
ct:pal("MinersCGBroken: ~p", [MinersCGBroken]),
Default is 120 sesonds , but for testing we want to trigger skip faster :
_ = [
ok = ct_rpc:call(Node, application, set_env, [miner, late_block_timeout_seconds, 10], 300)
||
Node <- MinersAll
],
_ = [
ok = ct_rpc:call(Node, miner, hbbft_skip, [], 300)
||
Node <- MinersCGBroken
],
_ = [
ok = ct_rpc:call(Node, miner, hbbft_skip, [], 300)
||
Node <- MinersCGBroken
],
send some more skips at broken miner 1 so we 're not all on the same round
Node1 = hd(MinersCGBroken),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = ct_rpc:call(Node1, miner, hbbft_skip, [], 300),
ok = miner_ct_utils:assert_chain_halted(MinersAll),
ok = miner_ct_utils:assert_chain_advanced(MinersAll, 2500, 5),
{comment, miner_ct_utils:heights(MinersAll)}.
restart_test(Config) ->
consesus group is lost but is retained
finish the dkg ,
BaseDir = ?config(base_dir, Config),
Miners = ?config(miners, Config),
wait till the chain reaches height 2 for all miners
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 2, all, 60),
Env = miner_ct_utils:stop_miners(lists:sublist(Miners, 1, 2)),
[begin
ct_rpc:call(Miner, miner_consensus_mgr, cancel_dkg, [], 300)
end
|| Miner <- lists:sublist(Miners, 3, 4)],
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_*{1,2}*", "/blockchain_swarm/groups/consensus_*"),
ok = miner_ct_utils:start_miners(Env),
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 2, all, 90),
{comment, miner_ct_utils:heights(Miners)}.
dkg_restart_test(Config) ->
Miners = ?config(miners, Config),
Interval = ?config(election_interval, Config),
AddrList = ?config(tagged_miner_addresses, Config),
stop the out of consensus miners and the last two consensus
members . this should keep the dkg from completing
wait up to 90s for epoch to or exceed 2
Members = miner_ct_utils:consensus_members(2, Miners),
{CMiners, NCMiners} = miner_ct_utils:partition_miners(Members, AddrList),
FirstCMiner = hd(CMiners),
Height = miner_ct_utils:height(FirstCMiner),
Stoppers = lists:sublist(CMiners, 5, 2),
ok = miner_ct_utils:wait_for_gte(height, Miners, Height + 2),
Stop1 = miner_ct_utils:stop_miners(NCMiners ++ Stoppers, 60),
ct:pal("stopping nc ~p stoppers ~p", [NCMiners, Stoppers]),
ok = miner_ct_utils:wait_for_gte(height, lists:sublist(CMiners, 1, 4), Height + (Interval * 2), all, 180),
stop half of the remaining miners
Restarters = lists:sublist(CMiners, 1, 2),
ct:pal("stopping restarters ~p", [Restarters]),
Stop2 = miner_ct_utils:stop_miners(Restarters, 60),
restore that half
ct:pal("starting restarters ~p", [Restarters]),
miner_ct_utils:start_miners(Stop2, 60),
restore the last two
ct:pal("starting blockers"),
miner_ct_utils:start_miners(Stop1, 60),
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 3, any, 90),
EndHeight = miner_ct_utils:height(FirstCMiner),
?assert(EndHeight < (Height + Interval + 99)).
validator_transition_test(Config) ->
Miners = ?config(miners, Config),
Options = ?config(node_options, Config),
{Owner, #{secret := AuxPriv}} = ?config(aux_acct, Config),
AuxSigFun = libp2p_crypto:mk_sig_fun(AuxPriv),
setup makes sure that the cluster is running , so the first thing is to create and connect two
Blockchain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, GenesisBlock} = ct_rpc:call(hd(Miners), blockchain, genesis_block, [Blockchain]),
ListenAddrs = miner_ct_utils:get_addrs(Miners),
ValidatorAddrList =
[begin
Num = integer_to_list(N),
{NewVal, Keys} = miner_ct_utils:start_miner(list_to_atom(Num ++ miner_ct_utils:randname(5)), Options),
{_, _, _, _Pub, Addr, _SigFun} = Keys,
ct_rpc:call(NewVal, blockchain_worker, integrate_genesis_block, [GenesisBlock]),
Swarm = ct_rpc:call(NewVal, blockchain_swarm, swarm, [], 2000),
lists:foreach(
fun(A) ->
ct_rpc:call(NewVal, libp2p_swarm, connect, [Swarm, A], 2000)
end, ListenAddrs),
UTxn1 = blockchain_txn_stake_validator_v1:new(Addr, Owner, ?bones(10000), 100000),
Txn1 = blockchain_txn_stake_validator_v1:sign(UTxn1, AuxSigFun),
_ = [ok = ct_rpc:call(M, blockchain_worker, submit_txn, [Txn1]) || M <- Miners],
{NewVal, Addr}
end || N <- lists:seq(9, 12)],
{Validators, _Addrs} = lists:unzip(ValidatorAddrList),
{Priv, _Pub} = ?config(master_key, Config),
Vars = #{?election_version => 5},
UEVTxn = blockchain_txn_vars_v1:new(Vars, 2),
Proof = blockchain_txn_vars_v1:create_proof(Priv, UEVTxn),
EVTxn = blockchain_txn_vars_v1:proof(UEVTxn, Proof),
_ = [ok = ct_rpc:call(M, blockchain_worker, submit_txn, [EVTxn]) || M <- Miners],
Me = self(),
spawn(miner_ct_utils, election_check,
[Validators, Validators,
ValidatorAddrList ++ ?config(tagged_miner_addresses, Config),
Me]),
check_loop(180, Validators).
check_loop(0, _Miners) ->
error(seen_timeout);
check_loop(N, Miners) ->
TODO Describe main idea and method . What will send the mesgs ? What is its API ?
TODO Need more transparent API , since the above is n't clear .
receive
seen_all ->
ok;
{not_seen, []} ->
ok;
{not_seen, Not} ->
Miner = lists:nth(rand:uniform(length(Miners)), Miners),
try
Height = miner_ct_utils:height(Miner),
{_, _, Epoch} = ct_rpc:call(Miner, miner_cli_info, get_info, [], 500),
ct:pal("not seen: ~p height ~p epoch ~p", [Not, Height, Epoch])
catch _:_ ->
ct:pal("not seen: ~p ", [Not]),
ok
end,
timer:sleep(100),
check_loop(N - 1, Miners)
after timer:seconds(30) ->
error(message_timeout)
end.
election_test(Config) ->
BaseDir = ?config(base_dir, Config),
Miners = ?config(miners, Config),
AddrList = ?config(tagged_miner_addresses, Config),
Me = self(),
spawn(miner_ct_utils, election_check, [Miners, Miners, AddrList, Me]),
TODO Looks like copy - pasta - see if check_loop/2 can be used instead .
fun Loop(0) ->
error(seen_timeout);
Loop(N) ->
receive
seen_all ->
ok;
{not_seen, []} ->
ok;
{not_seen, Not} ->
Miner = lists:nth(rand:uniform(length(Miners)), Miners),
try
Height = miner_ct_utils:height(Miner),
{_, _, Epoch} = ct_rpc:call(Miner, miner_cli_info, get_info, [], 500),
ct:pal("not seen: ~p height ~p epoch ~p", [Not, Height, Epoch])
catch _:_ ->
ct:pal("not seen: ~p ", [Not]),
ok
end,
timer:sleep(100),
Loop(N - 1)
after timer:seconds(30) ->
error(message_timeout)
end
end(60),
one election can happen .
we wait until we have seen all miners hit an epoch of 3
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 3, all, 90),
stop the first 4 miners
TargetMiners = lists:sublist(Miners, 1, 4),
Stop = miner_ct_utils:stop_miners(TargetMiners),
ct:pal("stopped, waiting"),
ok = miner_ct_utils:wait_for_app_stop(TargetMiners, miner),
timer:sleep(1000),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_{1,2,3,4}*/blockchain_swarm/groups/*", ""),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_{1,2,3,4}*/blockchain_swarm/groups/*", ""),
ct:pal("stopped and deleted"),
miner_ct_utils:start_miners(Stop),
second : make sure we 're not making blocks anymore
HChain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, Height} = ct_rpc:call(hd(Miners), blockchain, height, [HChain]),
height might go up by one , but it should not go up by 5
{_, false} = miner_ct_utils:wait_for_gte(height, Miners, Height + 5, any, 10),
Addresses = ?config(addresses, Config),
NewGroup = lists:sublist(Addresses, 3, 4),
HChain2 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, HeadBlock} = ct_rpc:call(hd(Miners), blockchain, head_block, [HChain2]),
NewHeight = blockchain_block:height(HeadBlock) + 1,
ct:pal("new height is ~p", [NewHeight]),
Hash = blockchain_block:hash_block(HeadBlock),
Vars = #{?num_consensus_members => 4},
{Priv, _Pub} = ?config(master_key, Config),
Txn = blockchain_txn_vars_v1:new(Vars, 3),
Proof = blockchain_txn_vars_v1:create_proof(Priv, Txn),
VarsTxn = blockchain_txn_vars_v1:proof(Txn, Proof),
{ElectionEpoch, _EpochStart} = blockchain_block_v1:election_info(HeadBlock),
ct:pal("current election epoch: ~p new height: ~p", [ElectionEpoch, NewHeight]),
GrpTxn = blockchain_txn_consensus_group_v1:new(NewGroup, <<>>, Height, 0),
RescueBlock = blockchain_block_v1:rescue(
#{prev_hash => Hash,
height => NewHeight,
transactions => [VarsTxn, GrpTxn],
hbbft_round => NewHeight,
time => erlang:system_time(seconds),
election_epoch => ElectionEpoch + 1,
epoch_start => NewHeight}),
EncodedBlock = blockchain_block:serialize(
blockchain_block_v1:set_signatures(RescueBlock, [])),
RescueSigFun = libp2p_crypto:mk_sig_fun(Priv),
RescueSig = RescueSigFun(EncodedBlock),
SignedBlock = blockchain_block_v1:set_signatures(RescueBlock, [], RescueSig),
now that we have a signed block , cause one of the nodes to
FirstNode = hd(Miners),
Chain = ct_rpc:call(FirstNode, blockchain_worker, blockchain, []),
ct:pal("FirstNode Chain: ~p", [Chain]),
Swarm = ct_rpc:call(FirstNode, blockchain_swarm, swarm, []),
ct:pal("FirstNode Swarm: ~p", [Swarm]),
N = length(Miners),
ct:pal("N: ~p", [N]),
ok = ct_rpc:call(FirstNode, blockchain_gossip_handler, add_block, [SignedBlock, Chain, self(), blockchain_swarm:tid()]),
wait until height has increased by 3
ok = miner_ct_utils:wait_for_gte(height, Miners, NewHeight + 2),
{NewConsensusMiners, NewNonConsensusMiners} = miner_ct_utils:miners_by_consensus_state(Miners),
StopList = lists:sublist(NewConsensusMiners, 2) ++ lists:sublist(NewNonConsensusMiners, 2),
ct:pal("stop list ~p", [StopList]),
Stop2 = miner_ct_utils:stop_miners(StopList),
timer:sleep(1000),
miner_ct_utils:start_miners(Stop2),
fourth : confirm that blocks and elections are proceeding
ok = miner_ct_utils:wait_for_gte(epoch, Miners, ElectionEpoch + 1).
election_multi_test(Config) ->
BaseDir = ?config(base_dir, Config),
Miners = ?config(miners, Config),
AddrList = ? config(tagged_miner_addresses , Config ) ,
Addresses = ?config(addresses, Config),
{Priv, _Pub} = ?config(master_key, Config),
we wait until we have seen all miners hit an epoch of 2
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 2, all, 90),
ct:pal("starting multisig attempt"),
TODO Looks automatable - 5 unique things that are n't used uniquely :
{ , BinPubs } = ( fun(N ) - >
[ libp2p_crypto : generate_keys(ecc_compact ) || { } < - lists : , { } ) ] ,
[ Priv || # { secret : = Priv } < - Keys ] ,
= lists : map(fun libp2p_crypto : pubkey_to_bin/1 , Pubs ) ,
, BinPubs }
) ( 5 )
#{secret := Priv1, public := Pub1} = libp2p_crypto:generate_keys(ecc_compact),
#{secret := Priv2, public := Pub2} = libp2p_crypto:generate_keys(ecc_compact),
#{secret := Priv3, public := Pub3} = libp2p_crypto:generate_keys(ecc_compact),
#{secret := Priv4, public := Pub4} = libp2p_crypto:generate_keys(ecc_compact),
#{secret := Priv5, public := Pub5} = libp2p_crypto:generate_keys(ecc_compact),
BinPub1 = libp2p_crypto:pubkey_to_bin(Pub1),
BinPub2 = libp2p_crypto:pubkey_to_bin(Pub2),
BinPub3 = libp2p_crypto:pubkey_to_bin(Pub3),
BinPub4 = libp2p_crypto:pubkey_to_bin(Pub4),
BinPub5 = libp2p_crypto:pubkey_to_bin(Pub5),
Txn7_0 = blockchain_txn_vars_v1:new(
#{?use_multi_keys => true}, 2,
#{multi_keys => [BinPub1, BinPub2, BinPub3, BinPub4, BinPub5]}),
Proofs7 = [blockchain_txn_vars_v1:create_proof(P, Txn7_0)
|| P <- [Priv1, Priv2, Priv3, Priv4, Priv5]],
Txn7_1 = blockchain_txn_vars_v1:multi_key_proofs(Txn7_0, Proofs7),
Proof7 = blockchain_txn_vars_v1:create_proof(Priv, Txn7_1),
Txn7 = blockchain_txn_vars_v1:proof(Txn7_1, Proof7),
_ = [ok = ct_rpc:call(M, blockchain_worker, submit_txn, [Txn7]) || M <- Miners],
ok = miner_ct_utils:wait_for_chain_var_update(Miners, ?use_multi_keys, true),
ct:pal("transitioned to multikey"),
stop the first 4 miners
TargetMiners = lists:sublist(Miners, 1, 4),
Stop = miner_ct_utils:stop_miners(TargetMiners),
ok = miner_ct_utils:wait_for_app_stop(TargetMiners, miner),
timer:sleep(1000),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_{1,2,3,4}*/blockchain_swarm/groups/*", ""),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_{1,2,3,4}*/blockchain_swarm/groups/*", ""),
miner_ct_utils:start_miners(Stop),
NewAddrs =
[begin
Swarm = ct_rpc:call(Target, blockchain_swarm, swarm, [], 2000),
[H|_] = LAs= ct_rpc:call(Target, libp2p_swarm, listen_addrs, [Swarm], 2000),
ct:pal("addrs ~p ~p", [Target, LAs]),
H
end || Target <- TargetMiners],
miner_ct_utils:pmap(
fun(M) ->
[begin
Sw = ct_rpc:call(M, blockchain_swarm, swarm, [], 2000),
ct_rpc:call(M, libp2p_swarm, connect, [Sw, Addr], 2000)
end || Addr <- NewAddrs]
end, Miners),
second : make sure we 're not making blocks anymore
HChain1 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, Height1} = ct_rpc:call(hd(Miners), blockchain, height, [HChain1]),
height might go up by one , but it should not go up by 5
{_, false} = miner_ct_utils:wait_for_gte(height, Miners, Height1 + 5, any, 10),
HeadAddress = ct_rpc:call(hd(Miners), blockchain_swarm, pubkey_bin, []),
GroupTail = Addresses -- [HeadAddress],
ct:pal("l ~p tail ~p", [length(GroupTail), GroupTail]),
{NewHeight, HighBlock} =
lists:max(
[begin
C = ct_rpc:call(M, blockchain_worker, blockchain, []),
{ok, HB} = ct_rpc:call(M, blockchain, head_block, [C]),
{blockchain_block:height(HB) + 1, HB}
end || M <- Miners]),
ct:pal("new height is ~p", [NewHeight]),
Hash2 = blockchain_block:hash_block(HighBlock),
{ElectionEpoch1, _EpochStart1} = blockchain_block_v1:election_info(HighBlock),
GrpTxn2 = blockchain_txn_consensus_group_v1:new(GroupTail, <<>>, NewHeight, 0),
RescueBlock2 =
blockchain_block_v1:rescue(
#{prev_hash => Hash2,
height => NewHeight,
transactions => [GrpTxn2],
hbbft_round => NewHeight,
time => erlang:system_time(seconds),
election_epoch => ElectionEpoch1 + 1,
epoch_start => NewHeight}),
EncodedBlock2 = blockchain_block:serialize(
blockchain_block_v1:set_signatures(RescueBlock2, [])),
RescueSigs =
[begin
RescueSigFun2 = libp2p_crypto:mk_sig_fun(P),
RescueSigFun2(EncodedBlock2)
end
|| P <- [Priv1, Priv2, Priv3, Priv4, Priv5]],
SignedBlock = blockchain_block_v1:set_signatures(RescueBlock2, [], RescueSigs),
now that we have a signed block , cause one of the nodes to
FirstNode = hd(Miners),
SecondNode = lists:last(Miners),
Chain1 = ct_rpc:call(FirstNode, blockchain_worker, blockchain, []),
Chain2 = ct_rpc:call(SecondNode, blockchain_worker, blockchain, []),
N = length(Miners),
ct:pal("first node ~p second ~pN: ~p", [FirstNode, SecondNode, N]),
ok = ct_rpc:call(FirstNode, blockchain_gossip_handler, add_block, [SignedBlock, Chain1, self(), blockchain_swarm:tid()]),
ok = ct_rpc:call(SecondNode, blockchain_gossip_handler, add_block, [SignedBlock, Chain2, self(), blockchain_swarm:tid()]),
case miner_ct_utils:wait_for_gte(height, Miners, NewHeight + 3, any, 30) of
ok -> ok;
_ ->
[begin
Status = ct_rpc:call(M, miner, hbbft_status, []),
ct:pal("miner ~p, status: ~p", [M, Status])
end
|| M <- Miners],
error(rescue_group_made_no_progress)
end.
group_change_test(Config) ->
Miners = ?config(miners, Config),
BaseDir = ?config(base_dir, Config),
ConsensusMiners = ?config(consensus_miners, Config),
?assertNotEqual([], ConsensusMiners),
?assertEqual(4, length(ConsensusMiners)),
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 1),
Blockchain1 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
Ledger1 = ct_rpc:call(hd(Miners), blockchain, ledger, [Blockchain1]),
?assertEqual({ok, totes_garb}, ct_rpc:call(hd(Miners), blockchain, config, [garbage_value, Ledger1])),
Vars = #{num_consensus_members => 7},
{Priv, _Pub} = ?config(master_key, Config),
Txn = blockchain_txn_vars_v1:new(Vars, 2, #{version_predicate => 2,
unsets => [garbage_value]}),
Proof = blockchain_txn_vars_v1:create_proof(Priv, Txn),
Txn1 = blockchain_txn_vars_v1:proof(Txn, Proof),
_ = [ok = ct_rpc:call(Miner, blockchain_worker, submit_txn, [Txn1])
|| Miner <- Miners],
HChain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, Height} = ct_rpc:call(hd(Miners), blockchain, height, [HChain]),
wait until height has increased by 10
ok = miner_ct_utils:wait_for_gte(height, Miners, Height + 10, all, 80),
[{Target, TargetEnv}] = miner_ct_utils:stop_miners([lists:last(Miners)]),
Miners1 = Miners -- [Target],
ct:pal("stopped target: ~p", [Target]),
C = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
L = ct_rpc:call(hd(Miners), blockchain, ledger, [C]),
{ok, Members} = ct_rpc:call(hd(Miners), blockchain_ledger_v1, consensus_members, [L]),
?assertEqual(4, length(Members)),
Chain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{SnapshotBlockHeight, _SnapshotBlockHash, SnapshotHash} =
ct_rpc:call(hd(Miners), blockchain, find_last_snapshot, [Chain]),
lists:foreach(
fun(Miner) ->
end, Miners1),
true = miner_ct_utils:wait_until(
fun() ->
lists:all(
fun(Miner) ->
NewVersion = ct_rpc:call(Miner, miner, test_version, [], 1000),
ct:pal("test version ~p ~p", [Miner, NewVersion]),
NewVersion > 1
end, Miners1)
end),
Timeout = 200,
true = miner_ct_utils:wait_until(
fun() ->
lists:all(
fun(Miner) ->
C1 = ct_rpc:call(Miner, blockchain_worker, blockchain, [], Timeout),
L1 = ct_rpc:call(Miner, blockchain, ledger, [C1], Timeout),
case ct_rpc:call(Miner, blockchain, config, [num_consensus_members, L1], Timeout) of
{ok, Sz} ->
Versions =
ct_rpc:call(Miner, blockchain_ledger_v1, cg_versions,
[L1], Timeout),
ct:pal("size = ~p versions = ~p", [Sz, Versions]),
Sz == 7;
_ ->
false
end
end, Miners1)
end, 120, 1000),
ok = miner_ct_utils:delete_dirs(BaseDir ++ "_*{8}*/*", ""),
[EightDir] = filelib:wildcard(BaseDir ++ "_*{8}*"),
BlockchainR = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, GenesisBlock} = ct_rpc:call(hd(Miners), blockchain, genesis_block, [BlockchainR]),
GenSer = blockchain_block:serialize(GenesisBlock),
ok = file:make_dir(EightDir ++ "/update"),
ok = file:write_file(EightDir ++ "/update/genesis", GenSer),
BlockchainEnv = proplists:get_value(blockchain, TargetEnv),
NewBlockchainEnv = [{blessed_snapshot_block_hash, SnapshotHash}, {blessed_snapshot_block_height, SnapshotBlockHeight},
{quick_sync_mode, blessed_snapshot}, {honor_quick_sync, true}|BlockchainEnv],
MinerEnv = proplists:get_value(miner, TargetEnv),
NewMinerEnv = [{update_dir, EightDir ++ "/update"} | MinerEnv],
NewTargetEnv0 = lists:keyreplace(blockchain, 1, TargetEnv, {blockchain, NewBlockchainEnv}),
NewTargetEnv = lists:keyreplace(miner, 1, NewTargetEnv0, {miner, NewMinerEnv}),
miner_ct_utils:start_miners([{Target, NewTargetEnv}]),
Swarm = ct_rpc:call(Target, blockchain_swarm, swarm, [], 2000),
[H|_] = ct_rpc:call(Target, libp2p_swarm, listen_addrs, [Swarm], 2000),
miner_ct_utils:pmap(
fun(M) ->
Sw = ct_rpc:call(M, blockchain_swarm, swarm, [], 2000),
ct_rpc:call(M, libp2p_swarm, connect, [Sw, H], 2000)
end, Miners1),
Blockchain2 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
Ledger2 = ct_rpc:call(hd(Miners), blockchain, ledger, [Blockchain2]),
?assertEqual({error, not_found}, ct_rpc:call(hd(Miners), blockchain, config, [garbage_value, Ledger2])),
HChain2 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{ok, Height2} = ct_rpc:call(hd(Miners), blockchain, height, [HChain2]),
ct:pal("post change miner ~p height ~p", [hd(Miners), Height2]),
?assert(Height2 > Height + 10 + 5),
ok = miner_ct_utils:wait_for_gte(height, [Target], Height2, all, 120),
TC = ct_rpc:call(Target, blockchain_worker, blockchain, [], Timeout),
TL = ct_rpc:call(Target, blockchain, ledger, [TC], Timeout),
{ok, TSz} = ct_rpc:call(Target, blockchain, config, [num_consensus_members, TL], Timeout),
?assertEqual(TSz, 7),
ok.
election_v3_test(Config) ->
Miners = ?config(miners, Config),
ConsensusMiners = ?config(consensus_miners, Config),
?assertNotEqual([], ConsensusMiners),
?assertEqual(7, length(ConsensusMiners)),
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 2),
Blockchain1 = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{Priv, _Pub} = ?config(master_key, Config),
Vars = #{?election_version => 3,
?election_bba_penalty => 0.01,
?election_seen_penalty => 0.05},
Txn = blockchain_txn_vars_v1:new(Vars, 2),
Proof = blockchain_txn_vars_v1:create_proof(Priv, Txn),
Txn1 = blockchain_txn_vars_v1:proof(Txn, Proof),
_ = [ok = ct_rpc:call(Miner, blockchain_worker, submit_txn, [Txn1])
|| Miner <- Miners],
ok = miner_ct_utils:wait_for_chain_var_update(Miners, ?election_version, 3),
{ok, Start} = ct_rpc:call(hd(Miners), blockchain, height, [Blockchain1]),
wait until height has increased by 10
ok = miner_ct_utils:wait_for_gte(height, Miners, Start + 10),
[begin
PrevBlock = miner_ct_utils:get_block(N - 1, hd(Miners)),
Block = miner_ct_utils:get_block(N, hd(Miners)),
ct:pal("n ~p s ~p b ~p", [N, Start, Block]),
case N of
_ when N < Start ->
?assertEqual([], blockchain_block_v1:seen_votes(Block)),
?assertEqual(<<>>, blockchain_block_v1:bba_completion(Block));
_ when N < Start + 5 ->
ok;
_ ->
Ts = blockchain_block:transactions(PrevBlock),
case lists:filter(fun(T) ->
blockchain_txn:type(T) == blockchain_txn_consensus_group_v1
end, Ts) of
[] ->
?assertNotEqual([], blockchain_block_v1:seen_votes(Block)),
?assertNotEqual(<<>>, blockchain_block_v1:bba_completion(Block));
first post - election block has no info
_ ->
?assertEqual([<<>>], lists:usort([X || {_, X} <- blockchain_block_v1:seen_votes(Block)])),
?assertEqual(<<>>, blockchain_block_v1:bba_completion(Block))
end
end
end
|| N <- lists:seq(2, Start + 10)],
two should guarantee at least one consensus member is down but
StopList = lists:sublist(Miners, 7, 2),
ct:pal("stop list ~p", [StopList]),
_Stop = miner_ct_utils:stop_miners(StopList),
{ok, Start2} = ct_rpc:call(hd(Miners), blockchain, height, [Blockchain1]),
[ct_rpc:call(M, miner, hbbft_skip, []) || M <- lists:sublist(Miners, 1, 6)],
ok = miner_ct_utils:wait_for_gte(height, lists:sublist(Miners, 1, 6), Start2 + 10, all, 120),
[begin
PrevBlock = miner_ct_utils:get_block(N - 1, hd(Miners)),
Block = miner_ct_utils:get_block(N, hd(Miners)),
ct:pal("n ~p s ~p b ~p", [N, Start, Block]),
Ts = blockchain_block:transactions(PrevBlock),
case lists:filter(fun(T) ->
blockchain_txn:type(T) == blockchain_txn_consensus_group_v1
end, Ts) of
[] ->
Seen = blockchain_block_v1:seen_votes(Block),
given the current code , BBA will always be 2f+1 ,
helpful : lists : sum([case $ ; band ( 1 bsl N ) of 0 - > 0 ; _ - > 1 end || N < - lists : seq(1 , 7 ) ] ) .
BBA = blockchain_block_v1:bba_completion(Block),
?assertNotEqual([], Seen),
?assertNotEqual(<<>>, BBA),
?assertNotEqual(<<0>>, BBA),
Len = length(Seen),
?assert(Len == 6 orelse Len == 5),
Votes = lists:usort([Vote || {_ID, Vote} <- Seen]),
[?assertNotEqual(<<127>>, V) || V <- Votes];
first post - election block has no info
_ ->
Seen = blockchain_block_v1:seen_votes(Block),
Votes = lists:usort([Vote || {_ID, Vote} <- Seen]),
?assertEqual([<<>>], Votes),
?assertEqual(<<>>, blockchain_block_v1:bba_completion(Block))
end
end
|| N <- lists:seq(Start2 + 2, Start2 + 10)],
ok.
snapshot_test(Config) ->
Miners0 = ?config(miners, Config),
ConsensusMiners = ?config(consensus_miners, Config),
[Target | Miners] = Miners0,
ct:pal("target ~p", [Target]),
?assertNotEqual([], ConsensusMiners),
?assertEqual(7, length(ConsensusMiners)),
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 1),
ok = miner_ct_utils:wait_for_gte(height, Miners, 7),
[{Target, TargetEnv}] = miner_ct_utils:stop_miners([Target]),
ok = miner_ct_utils:wait_for_gte(height, Miners, 15),
Chain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{SnapshotBlockHeight, SnapshotBlockHash, SnapshotHash} =
ct_rpc:call(hd(Miners), blockchain, find_last_snapshot, [Chain]),
?assert(is_binary(SnapshotHash)),
?assert(is_binary(SnapshotBlockHash)),
?assert(is_integer(SnapshotBlockHeight)),
ct:pal("Snapshot hash is ~p at height ~p~n in block ~p",
[SnapshotHash, SnapshotBlockHeight, SnapshotBlockHash]),
BlockchainEnv = proplists:get_value(blockchain, TargetEnv),
NewBlockchainEnv = [{blessed_snapshot_block_hash, SnapshotHash}, {blessed_snapshot_block_height, SnapshotBlockHeight},
{quick_sync_mode, blessed_snapshot}, {honor_quick_sync, true}|BlockchainEnv],
NewTargetEnv = lists:keyreplace(blockchain, 1, TargetEnv, {blockchain, NewBlockchainEnv}),
ct:pal("new blockchain env ~p", [NewTargetEnv]),
miner_ct_utils:start_miners([{Target, NewTargetEnv}]),
miner_ct_utils:wait_until(
fun() ->
try
undefined =/= ct_rpc:call(Target, blockchain_worker, blockchain, [])
catch _:_ ->
false
end
end, 50, 200),
ok = ct_rpc:call(Target, blockchain, reset_ledger_to_snap, []),
ok = miner_ct_utils:wait_for_gte(height, Miners0, 25, all, 20),
ok.
high_snapshot_test(Config) ->
Miners0 = ?config(miners, Config),
ConsensusMiners = ?config(consensus_miners, Config),
[Target | Miners] = Miners0,
ct:pal("target ~p", [Target]),
?assertNotEqual([], ConsensusMiners),
?assertEqual(7, length(ConsensusMiners)),
ok = miner_ct_utils:wait_for_gte(epoch, Miners, 1),
ok = miner_ct_utils:wait_for_gte(height, Miners, 7),
[{Target, TargetEnv}] = miner_ct_utils:stop_miners([Target]),
ok = miner_ct_utils:wait_for_gte(height, Miners, 70, all, 600),
Chain = ct_rpc:call(hd(Miners), blockchain_worker, blockchain, []),
{SnapshotBlockHeight, SnapshotBlockHash, SnapshotHash} =
ct_rpc:call(hd(Miners), blockchain, find_last_snapshot, [Chain]),
?assert(is_binary(SnapshotHash)),
?assert(is_binary(SnapshotBlockHash)),
?assert(is_integer(SnapshotBlockHeight)),
ct:pal("Snapshot hash is ~p at height ~p~n in block ~p",
[SnapshotHash, SnapshotBlockHeight, SnapshotBlockHash]),
BlockchainEnv = proplists:get_value(blockchain, TargetEnv),
NewBlockchainEnv = [{blessed_snapshot_block_hash, SnapshotHash}, {blessed_snapshot_block_height, SnapshotBlockHeight},
{quick_sync_mode, blessed_snapshot}, {honor_quick_sync, true}|BlockchainEnv],
NewTargetEnv = lists:keyreplace(blockchain, 1, TargetEnv, {blockchain, NewBlockchainEnv}),
ct:pal("new blockchain env ~p", [NewTargetEnv]),
miner_ct_utils:start_miners([{Target, NewTargetEnv}]),
timer:sleep(5000),
ok = ct_rpc:call(Target, blockchain, reset_ledger_to_snap, []),
ok = miner_ct_utils:wait_for_gte(height, Miners0, 80, all, 30),
ok.
|
1830308fb85c70e735aaffbae89f7ea6733ef3e82e59304f79bdd61d2a6550ed | ngrunwald/ring-middleware-format | impl.clj | (ns ring.middleware.format.impl)
(defn extract-options [args]
(if (map? (first args))
(do
(assert (empty? (rest args)) "When using options map arity, middlewares take only one parameter.")
(first args))
(do
(assert (even? (count args)) "When using keyword args arity, there should be even number of parameters.")
(apply hash-map args))))
| null | https://raw.githubusercontent.com/ngrunwald/ring-middleware-format/32b1c07e4369dd8b797ff6f727426ec561ed25a8/src/ring/middleware/format/impl.clj | clojure | (ns ring.middleware.format.impl)
(defn extract-options [args]
(if (map? (first args))
(do
(assert (empty? (rest args)) "When using options map arity, middlewares take only one parameter.")
(first args))
(do
(assert (even? (count args)) "When using keyword args arity, there should be even number of parameters.")
(apply hash-map args))))
| |
fd2860c210740376965f3d770665d0fb514b036d8d8819770e0605b38ce17dbf | NetworkVerification/nv | MapUnrolling.ml | open Batteries
open Nv_lang
open Syntax
* Unroll all map types contained in decls . Can not handle polymorphism ,
* so requires that inlining has been run first .
* Maps over nodes and edges are unrolled according to the order their keys
* are returned by ` AdjGraph.fold_vertex ` and ` AdjGraph.fold_edges_e ` , respectively .
* so requires that inlining has been run first.
* Maps over nodes and edges are unrolled according to the order their keys
* are returned by `AdjGraph.fold_vertex` and `AdjGraph.fold_edges_e`, respectively.
*)
let unroll _ decls =
let maplist = MapUnrollingUtils.collect_map_types_and_keys decls in
let unrolled_decls, map_back1 =
BatList.fold_left
(fun (decls, f) (mty, keys) ->
let const_keys = Collections.ExpSet.elements (fst keys) in
let symb_keys = Collections.VarSet.elements (snd keys) in
let new_decls, f' =
MapUnrollingSingle.unroll_declarations mty (const_keys, symb_keys) decls
in
new_decls, fun x -> f (f' x))
(decls, fun x -> x)
maplist
in
let final_decls, map_back2 = CleanupTuples.cleanup_declarations unrolled_decls in
final_decls, map_back1 % map_back2
;;
| null | https://raw.githubusercontent.com/NetworkVerification/nv/e76824c537dcd535f2224b31f35cd37601a60957/src/lib/transformations/mapUnrolling/MapUnrolling.ml | ocaml | open Batteries
open Nv_lang
open Syntax
* Unroll all map types contained in decls . Can not handle polymorphism ,
* so requires that inlining has been run first .
* Maps over nodes and edges are unrolled according to the order their keys
* are returned by ` AdjGraph.fold_vertex ` and ` AdjGraph.fold_edges_e ` , respectively .
* so requires that inlining has been run first.
* Maps over nodes and edges are unrolled according to the order their keys
* are returned by `AdjGraph.fold_vertex` and `AdjGraph.fold_edges_e`, respectively.
*)
let unroll _ decls =
let maplist = MapUnrollingUtils.collect_map_types_and_keys decls in
let unrolled_decls, map_back1 =
BatList.fold_left
(fun (decls, f) (mty, keys) ->
let const_keys = Collections.ExpSet.elements (fst keys) in
let symb_keys = Collections.VarSet.elements (snd keys) in
let new_decls, f' =
MapUnrollingSingle.unroll_declarations mty (const_keys, symb_keys) decls
in
new_decls, fun x -> f (f' x))
(decls, fun x -> x)
maplist
in
let final_decls, map_back2 = CleanupTuples.cleanup_declarations unrolled_decls in
final_decls, map_back1 % map_back2
;;
| |
3d4493924cd4a2b036986a97ed800dd8f07e1dcdcab5dea8034d82fda3b32bf8 | carl-eastlund/dracula | syntax.rkt | #lang racket
(require "proof.rkt")
(define key 'dracula)
;; annotate : ? Syntax -> Syntax
Stores a annotation with the given syntax .
(define (annotate v stx)
(syntax-property stx key v))
;; extract : Syntax -> ?
Extracts a annotation from the given syntax
(define (extract stx)
(syntax-property stx key))
;; get : Any -> List
Get all annotations stored with a value .
(define (get v)
(cond
[(and (syntax? v) (extract v)) => list]
[(syntax? v) (get (syntax-e v))]
[(pair? v) (append (get (car v)) (get (cdr v)))]
[else null]))
;; get-proof : Syntax -> Proof
Gets the proof stored in a value .
(define (get-proof stx)
(match (filter proof? (get stx))
[(list pf) pf]
[v
(error 'get-proof
"expected (list Proof); got:\n~s\nfrom:\n~s"
v (syntax->datum stx))]))
(provide/contract
[rename annotate annotate-term (-> term? syntax? syntax?)]
[rename annotate annotate-part (-> part? syntax? syntax?)]
[rename annotate annotate-proof (-> proof? syntax? syntax?)]
[rename get get-terms (-> syntax? (listof term?))]
[rename get get-parts (-> syntax? (listof part?))]
[get-proof (-> syntax? proof?)])
| null | https://raw.githubusercontent.com/carl-eastlund/dracula/a937f4b40463779246e3544e4021c53744a33847/proof/syntax.rkt | racket | annotate : ? Syntax -> Syntax
extract : Syntax -> ?
get : Any -> List
get-proof : Syntax -> Proof | #lang racket
(require "proof.rkt")
(define key 'dracula)
Stores a annotation with the given syntax .
(define (annotate v stx)
(syntax-property stx key v))
Extracts a annotation from the given syntax
(define (extract stx)
(syntax-property stx key))
Get all annotations stored with a value .
(define (get v)
(cond
[(and (syntax? v) (extract v)) => list]
[(syntax? v) (get (syntax-e v))]
[(pair? v) (append (get (car v)) (get (cdr v)))]
[else null]))
Gets the proof stored in a value .
(define (get-proof stx)
(match (filter proof? (get stx))
[(list pf) pf]
[v
(error 'get-proof
"expected (list Proof); got:\n~s\nfrom:\n~s"
v (syntax->datum stx))]))
(provide/contract
[rename annotate annotate-term (-> term? syntax? syntax?)]
[rename annotate annotate-part (-> part? syntax? syntax?)]
[rename annotate annotate-proof (-> proof? syntax? syntax?)]
[rename get get-terms (-> syntax? (listof term?))]
[rename get get-parts (-> syntax? (listof part?))]
[get-proof (-> syntax? proof?)])
|
5c8446b130674bca80dcbf276a2cf41de53cab0335069643b906f4a1b3fdfe8d | earl-ducaine/cl-garnet | post-processing.lisp | (in-package :garnet-user)
(eval-when (:load-toplevel)
(let ((demo-apps
'("(demo-3d::do-go)"
"(demo-angle::do-go)"
"(demo-animator::do-go)"
"(demo-arith::do-go)"
"(demo-array::do-go)"
"(demo-clock::do-go)"
"(demo-editor::do-go)"
"(demo-file-browser::do-go)"
"(demo-gadgets::do-go)"
"(demo-3d::do-go)"
"(demo-gesture::do-go)"
"(demo-graph::do-go)"
"(demo-grow::do-go)"
"(demo-logo::do-go)"
"(demo-manyobjs::do-go)"
"(demo-menu::do-go)"
"(demo-mode::do-go)"
"(demo-motif::do-go)"
"(demo-moveline::do-go)"
"(demo-multifont::do-go)"
"(demo-multiwin::do-go)"
"(demo-othello::do-go)"
"(demo-pixmap::do-go)"
"(demo-schema-browser::do-go)"
"(demos-compiler::do-go)"
"(demos-controller::do-go)"
"(demo-scrollbar::do-go)"
"(demo-sequence::do-go)"
"(demo-text::do-go)"
"(demo-truck::do-go)"
"(demo-twop::do-go)"
"(demo-unistrokes::do-go)"
"(demo-virtual-agg::do-go)"
"(demo-xasperate::do-go)"
"(garnet-calculator::do-go)"
"(garnetdraw::do-go)"
;; "(mge::do-go)"
;; "(quicklisp::do-go)"
;; "(tourcommands::do-go)"
;; "(tour::do-go)"
"(demos-controller:do-go)")))
(format t "~%To run various app eval one of the following:~%")
(dolist (demo-app demo-apps)
(format t "~a~%" demo-app))))
| null | https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/post-processing.lisp | lisp | "(mge::do-go)"
"(quicklisp::do-go)"
"(tourcommands::do-go)"
"(tour::do-go)" | (in-package :garnet-user)
(eval-when (:load-toplevel)
(let ((demo-apps
'("(demo-3d::do-go)"
"(demo-angle::do-go)"
"(demo-animator::do-go)"
"(demo-arith::do-go)"
"(demo-array::do-go)"
"(demo-clock::do-go)"
"(demo-editor::do-go)"
"(demo-file-browser::do-go)"
"(demo-gadgets::do-go)"
"(demo-3d::do-go)"
"(demo-gesture::do-go)"
"(demo-graph::do-go)"
"(demo-grow::do-go)"
"(demo-logo::do-go)"
"(demo-manyobjs::do-go)"
"(demo-menu::do-go)"
"(demo-mode::do-go)"
"(demo-motif::do-go)"
"(demo-moveline::do-go)"
"(demo-multifont::do-go)"
"(demo-multiwin::do-go)"
"(demo-othello::do-go)"
"(demo-pixmap::do-go)"
"(demo-schema-browser::do-go)"
"(demos-compiler::do-go)"
"(demos-controller::do-go)"
"(demo-scrollbar::do-go)"
"(demo-sequence::do-go)"
"(demo-text::do-go)"
"(demo-truck::do-go)"
"(demo-twop::do-go)"
"(demo-unistrokes::do-go)"
"(demo-virtual-agg::do-go)"
"(demo-xasperate::do-go)"
"(garnet-calculator::do-go)"
"(garnetdraw::do-go)"
"(demos-controller:do-go)")))
(format t "~%To run various app eval one of the following:~%")
(dolist (demo-app demo-apps)
(format t "~a~%" demo-app))))
|
157791440823af9cbefea6dc2e933ebc6dfa11c379a57ea87c496fb28ba1966b | bazqux/bazqux-urweb | Auth.hs | # LANGUAGE OverloadedStrings , ViewPatterns , RecordWildCards , TupleSections ,
StandaloneDeriving #
StandaloneDeriving #-}
module Auth
( loginGetForwardUrl, loginCallback
, parseQueryStringUtf8Only
, signTwitter, signTwitterWithAccessToken
, readerDownloaderSettings, withReaderDL
, postUrlEncoded, postUrlEncodedRaw
) where
import Lib.Log
import Control.Monad
import Control.Applicative
import qualified Control.Exception as E
import Data.List
import qualified Data.Aeson as JSON
import Lib.Json
import qualified Data.HashMap.Lazy as HM
import qualified Data.ByteString.Char8 as B
import Generated.DataTypes
import Web.Authenticate.OAuth
import Web.Authenticate.OpenId (getForwardUrl, authenticateClaimed, OpenIdResponse(..), identifier)
import Data.String
import qualified Network.HTTP.Client as C
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Maybe
import URL
import System.IO.Unsafe
import qualified Network.HTTP.Types as N
import qualified Data.CaseInsensitive as CI
import Network.HTTP.Conduit.Downloader
import qualified Data.Default as C
import Lib.StringConversion
import Config
import Parser.Facebook (parseFacebookError)
withReaderDL f = f readerDL
readerDL = unsafePerformIO $
withDownloaderSettings readerDownloaderSettings return
# NOINLINE readerDL #
-- appAccessToken = withReaderDL $ \ d -> do
-- DROK
-- concat [ fbApiPath, "/oauth/access_token?client_id="
-- , fbAppId, "&client_secret=", fbSecret
-- , "&grant_type=client_credentials" ]
-- rsp <- C.httpLbs req m
return $ BL.unpack $ BL.drop ( BL.length " access_token= " ) $ C.responseBody rsp
twitterOAuth cb =
def
{ oauthServerName = error "oauthServerName"
, oauthRequestUri = ""
, oauthAccessTokenUri = ""
, oauthAuthorizeUri = ""
, oauthSignatureMethod = HMACSHA1
, oauthConsumerKey = twitterOAuthConsumerKey
, oauthConsumerSecret = twitterOAuthConsumerSecret
, oauthCallback = Just cb
, oauthRealm = Nothing
}
prefixUrl host u = T.concat ["https://", host, u]
fbTokenCallback host cb q = do
case lookup "code" q of
Just code -> withReaderDL $ \ d -> do
at <- download d
(T.unpack $ T.concat
[ fbApiPath, "/oauth/access_token?"
, "client_id=", fbAppId
, "&redirect_uri="
, encodeURIComponentT (prefixUrl host cb)
, "&client_secret=", fbSecret
, "&code=", code ]) Nothing []
let fbAt r = do
JSON.Object root <- decodeJson r
JSON.String i <- HM.lookup "access_token" root
return i
q <- case at of
DROK r _ -> return r
DRError e ->
fail $ "Can’t get access_token: " ++ e
_ -> fail "Can’t get access_token"
shortLivedToken <-
maybe (fail "Can’t find access_token") return $ fbAt q
lat <- download d
(T.unpack $ T.concat
[ fbApiPath, "/oauth/access_token?"
, "grant_type=fb_exchange_token"
, "&client_id=", fbAppId
, "&client_secret=", fbSecret
, "&fb_exchange_token=", shortLivedToken]) Nothing []
lq <- case lat of
DROK r _ -> return r
DRError e ->
fail $ "Can’t get long-lived access_token: " ++ e
_ -> fail "Can’t get long-lived access_token"
longLivedToken <-
maybe (fail "Can’t find long-lived access_token") return $ fbAt lq
-- logS $ "Short-lived token: " ++ T.unpack shortLivedToken
-- logS $ "Long-lived token: " ++ T.unpack longLivedToken
(me, meRdr) <- rawDownload return d (T.unpack fbApiPath ++ "/me?fields=email,id&access_token="
++ T.unpack longLivedToken) Nothing []
протестить fb - посты / группы / комменты / techcrunch
logT $ rspT rsp
let fbProfile r = do
JSON.Object root <- decodeJson r
JSON.String i <- HM.lookup "id" root
-- JSON.String n <- HM.lookup "name" root
-- JSON.String u <- HM.lookup "username" root
-- JSON.String l <- HM.lookup "link" root
JSON.String e <- HM.lookup "email" root
<|>
fmap JSON.String (lookup i facebookIdsToEmail)
<|>
return (JSON.String "")
return (LTFacebook e, LATFacebook longLivedToken,
Just $ "=" <> i)
-- , Just (T.concat [u, " (", n, ") ", e]))
case me of
DROK r _
| Just (LTFacebook "", _, _) <- fbProfile r -> do
logT $ bst r
fail "Can’t get email. Have you removed the email permission? It’s required for identification inside the reader."
| Just p <- fbProfile r ->
return p
| otherwise -> do
logT $ bst r
fail "Error getting facebook profile id"
DRError e -> do
maybe (return ()) (logT . bst . showRdr) meRdr
fail $ "Can’t get profile id: " ++
case fmap (parseFacebookError . rdrBody) meRdr of
Just (Right fbe) -> T.unpack fbe
_ -> e
_ ->
fail "Can’t get profile id"
_ | Just "access_denied" <- lookup "error" q
-> fail "Can’t login: access denied"
| otherwise
-> fail "Can’t login"
showRdr (RawDownloadResult {..}) =
B.unlines $
["===== Response headers ====="] ++
[B.concat [CI.original h, ": ", v] | (h,v) <- rdrHeaders] ++
["===== Response body ========", rdrBody]
loginGetForwardUrl :: ExternalLoginType -> T.Text -> ExternalLoginAction -> TURL -> IO TURL
loginGetForwardUrl elt host ela u = case elt of
Google -> return $ T.concat
[ ""
, "?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email"
, "&client_id=", googleOAuthClientId
, "&response_type=code"
, "&redirect_uri=", encodeURIComponentT (prefixUrl host u)
, "&state=", s
]
OpenId ou -> openIdForwardUrlG (T.unpack ou) host [] uWithState
Facebook -> return $ T.concat
[ "/", fbApiVersion, "/dialog/oauth"
, "?scope=email&auth_type=rerequest&display=page"
, "&client_id=", fbAppId
, "&response_type=code"
, "&redirect_uri=", encodeURIComponentT (prefixUrl host u)
, "&state=", s
]
Twitter -> E.handle handleTwitter $ withManager $ \ m -> do
let o = twitterOAuth $ T.encodeUtf8 $ prefixUrl host uWithState
rt <- getTemporaryCredential o m
-- logS $ show rt
return $ T.pack $ authorizeUrl o rt
where uWithState = u <> "?state=" <> s
s = encodeURIComponentT $ showT ela
handleTwitter :: E.SomeException -> IO a
handleTwitter = fail . show
loginCallback :: ExternalLoginType -> T.Text -> TURL -> T.Text -> IO (LoginType, LoginAccessToken, ExternalLoginAction, Maybe T.Text)
loginCallback elt host cb qss = addLA <$> case elt of
Google -> googleCallback host (T.unpack cb) qs
OpenId _ -> do
oir <- withManager $ authenticateClaimed qs
-- print (i, ps)
return (LTOpenId $ identifier $ oirOpLocal oir, LATNone, Nothing)
Facebook -> fbTokenCallback host cb qs
Twitter -> withManager $ \ m -> do
let o = twitterOAuth $ T.encodeUtf8 $ prefixUrl host cb
c = Credential [(tbs p, tbs v) | (p,v) <- qs]
at <- getAccessToken o c m
-- logS $ show at
^ содержит oauth_token , oauth_token_secret , user_id , screen_name
maybe (fail "Can’t get profile id") return
(do uid <- lookup "user_id" $ unCredential at
sn <- lookup "screen_name" $ unCredential at
return ( LTTwitter (bst uid)
, LATTwitter [(bst n, bst v) | (n, v) <- unCredential at]
, Just $ T.decodeUtf8 sn ))
where qs0 = parseQueryStringUtf8Only qss
qs = filter ((/= "state") . fst) qs0
addLA (lt, lat, who) = (lt, lat, externalLoginAction qs0, who)
-- "="
loginManager = unsafePerformIO $ C.newManager ((dsManagerSettings C.def))-- { C.managerResponseTimeout = Just 19000000 })
чтобы уложиться в наш таймаут
вместо timeout вылезает C.FailedConnectionException , что менее понятно ,
чем timeout
# NOINLINE loginManager #
withManager :: (C.Manager -> IO a) -> IO a
withManager act = withReaderDL $ const $ act loginManager
-- ^ для инициализации OpenSSL
openIdForwardUrlG :: String -> T.Text -> [(T.Text, T.Text)] -> TURL -> IO TURL
openIdForwardUrlG endpoint host a u =
withManager $ getForwardUrl (fromString endpoint)
(prefixUrl host u)
^ для OAuth должно соответствовать Consumer
необязательно , можно и Nothing
$ [ ( "openid.ns.ui"
, "" ) ] ++ a
externalLoginAction :: [(T.Text, T.Text)] -> ExternalLoginAction
externalLoginAction qs = case lookup "state" qs of
Nothing -> error "Can’t get “state” parameter to extract login action"
Just a
| [(r, "")] <- reads $ T.unpack a -> r
| otherwise -> error "Can’t parse login action"
deriving instance Read ExternalLoginAction
googleCallback :: T.Text -> URL -> [(T.Text, T.Text)] -> IO (LoginType, LoginAccessToken, Maybe T.Text)
googleCallback host cb =
googleCallback' True "user info" host cb
"?" $ \ _ ui ->
case decodeJson $ BL.toStrict ui of
Just (JSON.Object o)
| Just (JSON.String e) <- HM.lookup "email" o ->
(LTGoogle e, LATNone, Nothing)
_ -> error $ "Can’t get email:\n" ++ BL.unpack ui
googleCallback' :: Bool -> String -> T.Text -> URL -> URL -> (T.Text -> BL.ByteString -> a) -> [(T.Text, T.Text)] -> IO a
googleCallback' firstTime what host cb url f q = withReaderDL $ \ d -> do
case lookup "error" q of
Just "access_denied" ->
fail "Access denied"
Just e ->
fail $ T.unpack e
_ -> return ()
logS $ show q
let c = T.encodeUtf8 $ fromMaybe "no code?" $ lookup "code" q
body = B.concat ["code=", c
, "&client_id=", googleOAuthClientId
, "&client_secret=", googleOAuthClientSecret
, "&redirect_uri=https%3A%2F%2F"
, tbs host
, B.pack $ encodeURIComponent cb
, "&grant_type=authorization_code" ]
dr <- postUrlEncoded d "" Nothing
body
case dr of
DROK r _ -> do
at <- case decodeJson r of
Just (JSON.Object o)
| Just (JSON.String at) <- HM.lookup "access_token" o ->
return at
_ -> error $ "Can’t get access_token:\n" ++ T.unpack (bst r)
when ("import" `isInfixOf` cb) $
logS $ "Import access token: " ++ T.unpack at
dr <- download d (url ++ "access_token=" ++ T.unpack at) Nothing []
case dr of
DROK r _ ->
return $ f at $ BL.fromStrict r
DRError e
| firstTime -> googleCallback' False what host cb url f q
| otherwise -> fail $ "Can’t get " ++ what ++ ":\n" ++ e
_ -> fail $ "Can’t get " ++ what
DRError e
| firstTime -> googleCallback' False what host cb url f q
| otherwise -> fail $ "Can’t get access_token:\n" ++ e
_ -> fail $ "Can’t get access_token"
signTwitterWithAccessToken c r = do
r' <- signOAuth (twitterOAuth "")
(Credential
[(tbs n, tbs v) | (n, v) <- c
,n == "oauth_token" || n == "oauth_token_secret"])
учитываем , что у нас могут быть ipUrl
return $ r' { C.host = C.host r
, C.requestHeaders =
("Accept-Encoding", "") : C.requestHeaders r'
--
}
signTwitter r =
r { C.requestHeaders =
("Accept-Encoding", "")
--
: ("Authorization", "Bearer " <> tbs twitterBearer)
: C.requestHeaders r
}
testTwitterUrl u = withManager $ \ m -> do
req <- C.parseRequest u
let sreq0 = signTwitter req
sreq = sreq0 { C.requestHeaders =
[("Accept", "*/*")
,("User-Agent", "curl/7.25.0 (x86_64-apple-darwin11.3.0) libcurl/7.25.0 OpenSSL/1.0.1e zlib/1.2.7 libidn/1.22")]
++
map (\(h,v) -> (h, T.encodeUtf8 $ T.replace "," ", " $ T.pack $ B.unpack v))
(C.requestHeaders sreq0)
}
-- не помогает
forM_ (C.requestHeaders sreq) $ \ (h,v) ->
putStrLn $ B.unpack (CI.original h) ++ ": " ++ B.unpack v
rsp <- C.httpLbs sreq m
mapM_ print $ C.responseHeaders rsp
BL.putStrLn $ C.responseBody rsp
-- testTwitterUrl ""
postUrlEncoded d u ha body = fmap fst $ postUrlEncodedRaw return d u ha body
postUrlEncodedRaw f d u ha body =
rawDownload
(\ req -> f $
req { C.requestHeaders =
[( "Content-Type"
, "application/x-www-form-urlencoded" )]
, C.method = N.methodPost
, C.requestBody = C.RequestBodyBS body
})
d u ha []
| null | https://raw.githubusercontent.com/bazqux/bazqux-urweb/bf2d5a65b5b286348c131e91b6e57df9e8045c3f/crawler/Auth.hs | haskell | appAccessToken = withReaderDL $ \ d -> do
DROK
concat [ fbApiPath, "/oauth/access_token?client_id="
, fbAppId, "&client_secret=", fbSecret
, "&grant_type=client_credentials" ]
rsp <- C.httpLbs req m
logS $ "Short-lived token: " ++ T.unpack shortLivedToken
logS $ "Long-lived token: " ++ T.unpack longLivedToken
JSON.String n <- HM.lookup "name" root
JSON.String u <- HM.lookup "username" root
JSON.String l <- HM.lookup "link" root
, Just (T.concat [u, " (", n, ") ", e]))
logS $ show rt
print (i, ps)
logS $ show at
"="
{ C.managerResponseTimeout = Just 19000000 })
^ для инициализации OpenSSL
не помогает
testTwitterUrl "" | # LANGUAGE OverloadedStrings , ViewPatterns , RecordWildCards , TupleSections ,
StandaloneDeriving #
StandaloneDeriving #-}
module Auth
( loginGetForwardUrl, loginCallback
, parseQueryStringUtf8Only
, signTwitter, signTwitterWithAccessToken
, readerDownloaderSettings, withReaderDL
, postUrlEncoded, postUrlEncodedRaw
) where
import Lib.Log
import Control.Monad
import Control.Applicative
import qualified Control.Exception as E
import Data.List
import qualified Data.Aeson as JSON
import Lib.Json
import qualified Data.HashMap.Lazy as HM
import qualified Data.ByteString.Char8 as B
import Generated.DataTypes
import Web.Authenticate.OAuth
import Web.Authenticate.OpenId (getForwardUrl, authenticateClaimed, OpenIdResponse(..), identifier)
import Data.String
import qualified Network.HTTP.Client as C
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.Maybe
import URL
import System.IO.Unsafe
import qualified Network.HTTP.Types as N
import qualified Data.CaseInsensitive as CI
import Network.HTTP.Conduit.Downloader
import qualified Data.Default as C
import Lib.StringConversion
import Config
import Parser.Facebook (parseFacebookError)
withReaderDL f = f readerDL
readerDL = unsafePerformIO $
withDownloaderSettings readerDownloaderSettings return
# NOINLINE readerDL #
return $ BL.unpack $ BL.drop ( BL.length " access_token= " ) $ C.responseBody rsp
twitterOAuth cb =
def
{ oauthServerName = error "oauthServerName"
, oauthRequestUri = ""
, oauthAccessTokenUri = ""
, oauthAuthorizeUri = ""
, oauthSignatureMethod = HMACSHA1
, oauthConsumerKey = twitterOAuthConsumerKey
, oauthConsumerSecret = twitterOAuthConsumerSecret
, oauthCallback = Just cb
, oauthRealm = Nothing
}
prefixUrl host u = T.concat ["https://", host, u]
fbTokenCallback host cb q = do
case lookup "code" q of
Just code -> withReaderDL $ \ d -> do
at <- download d
(T.unpack $ T.concat
[ fbApiPath, "/oauth/access_token?"
, "client_id=", fbAppId
, "&redirect_uri="
, encodeURIComponentT (prefixUrl host cb)
, "&client_secret=", fbSecret
, "&code=", code ]) Nothing []
let fbAt r = do
JSON.Object root <- decodeJson r
JSON.String i <- HM.lookup "access_token" root
return i
q <- case at of
DROK r _ -> return r
DRError e ->
fail $ "Can’t get access_token: " ++ e
_ -> fail "Can’t get access_token"
shortLivedToken <-
maybe (fail "Can’t find access_token") return $ fbAt q
lat <- download d
(T.unpack $ T.concat
[ fbApiPath, "/oauth/access_token?"
, "grant_type=fb_exchange_token"
, "&client_id=", fbAppId
, "&client_secret=", fbSecret
, "&fb_exchange_token=", shortLivedToken]) Nothing []
lq <- case lat of
DROK r _ -> return r
DRError e ->
fail $ "Can’t get long-lived access_token: " ++ e
_ -> fail "Can’t get long-lived access_token"
longLivedToken <-
maybe (fail "Can’t find long-lived access_token") return $ fbAt lq
(me, meRdr) <- rawDownload return d (T.unpack fbApiPath ++ "/me?fields=email,id&access_token="
++ T.unpack longLivedToken) Nothing []
протестить fb - посты / группы / комменты / techcrunch
logT $ rspT rsp
let fbProfile r = do
JSON.Object root <- decodeJson r
JSON.String i <- HM.lookup "id" root
JSON.String e <- HM.lookup "email" root
<|>
fmap JSON.String (lookup i facebookIdsToEmail)
<|>
return (JSON.String "")
return (LTFacebook e, LATFacebook longLivedToken,
Just $ "=" <> i)
case me of
DROK r _
| Just (LTFacebook "", _, _) <- fbProfile r -> do
logT $ bst r
fail "Can’t get email. Have you removed the email permission? It’s required for identification inside the reader."
| Just p <- fbProfile r ->
return p
| otherwise -> do
logT $ bst r
fail "Error getting facebook profile id"
DRError e -> do
maybe (return ()) (logT . bst . showRdr) meRdr
fail $ "Can’t get profile id: " ++
case fmap (parseFacebookError . rdrBody) meRdr of
Just (Right fbe) -> T.unpack fbe
_ -> e
_ ->
fail "Can’t get profile id"
_ | Just "access_denied" <- lookup "error" q
-> fail "Can’t login: access denied"
| otherwise
-> fail "Can’t login"
showRdr (RawDownloadResult {..}) =
B.unlines $
["===== Response headers ====="] ++
[B.concat [CI.original h, ": ", v] | (h,v) <- rdrHeaders] ++
["===== Response body ========", rdrBody]
loginGetForwardUrl :: ExternalLoginType -> T.Text -> ExternalLoginAction -> TURL -> IO TURL
loginGetForwardUrl elt host ela u = case elt of
Google -> return $ T.concat
[ ""
, "?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email"
, "&client_id=", googleOAuthClientId
, "&response_type=code"
, "&redirect_uri=", encodeURIComponentT (prefixUrl host u)
, "&state=", s
]
OpenId ou -> openIdForwardUrlG (T.unpack ou) host [] uWithState
Facebook -> return $ T.concat
[ "/", fbApiVersion, "/dialog/oauth"
, "?scope=email&auth_type=rerequest&display=page"
, "&client_id=", fbAppId
, "&response_type=code"
, "&redirect_uri=", encodeURIComponentT (prefixUrl host u)
, "&state=", s
]
Twitter -> E.handle handleTwitter $ withManager $ \ m -> do
let o = twitterOAuth $ T.encodeUtf8 $ prefixUrl host uWithState
rt <- getTemporaryCredential o m
return $ T.pack $ authorizeUrl o rt
where uWithState = u <> "?state=" <> s
s = encodeURIComponentT $ showT ela
handleTwitter :: E.SomeException -> IO a
handleTwitter = fail . show
loginCallback :: ExternalLoginType -> T.Text -> TURL -> T.Text -> IO (LoginType, LoginAccessToken, ExternalLoginAction, Maybe T.Text)
loginCallback elt host cb qss = addLA <$> case elt of
Google -> googleCallback host (T.unpack cb) qs
OpenId _ -> do
oir <- withManager $ authenticateClaimed qs
return (LTOpenId $ identifier $ oirOpLocal oir, LATNone, Nothing)
Facebook -> fbTokenCallback host cb qs
Twitter -> withManager $ \ m -> do
let o = twitterOAuth $ T.encodeUtf8 $ prefixUrl host cb
c = Credential [(tbs p, tbs v) | (p,v) <- qs]
at <- getAccessToken o c m
^ содержит oauth_token , oauth_token_secret , user_id , screen_name
maybe (fail "Can’t get profile id") return
(do uid <- lookup "user_id" $ unCredential at
sn <- lookup "screen_name" $ unCredential at
return ( LTTwitter (bst uid)
, LATTwitter [(bst n, bst v) | (n, v) <- unCredential at]
, Just $ T.decodeUtf8 sn ))
where qs0 = parseQueryStringUtf8Only qss
qs = filter ((/= "state") . fst) qs0
addLA (lt, lat, who) = (lt, lat, externalLoginAction qs0, who)
чтобы уложиться в наш таймаут
вместо timeout вылезает C.FailedConnectionException , что менее понятно ,
чем timeout
# NOINLINE loginManager #
withManager :: (C.Manager -> IO a) -> IO a
withManager act = withReaderDL $ const $ act loginManager
openIdForwardUrlG :: String -> T.Text -> [(T.Text, T.Text)] -> TURL -> IO TURL
openIdForwardUrlG endpoint host a u =
withManager $ getForwardUrl (fromString endpoint)
(prefixUrl host u)
^ для OAuth должно соответствовать Consumer
необязательно , можно и Nothing
$ [ ( "openid.ns.ui"
, "" ) ] ++ a
externalLoginAction :: [(T.Text, T.Text)] -> ExternalLoginAction
externalLoginAction qs = case lookup "state" qs of
Nothing -> error "Can’t get “state” parameter to extract login action"
Just a
| [(r, "")] <- reads $ T.unpack a -> r
| otherwise -> error "Can’t parse login action"
deriving instance Read ExternalLoginAction
googleCallback :: T.Text -> URL -> [(T.Text, T.Text)] -> IO (LoginType, LoginAccessToken, Maybe T.Text)
googleCallback host cb =
googleCallback' True "user info" host cb
"?" $ \ _ ui ->
case decodeJson $ BL.toStrict ui of
Just (JSON.Object o)
| Just (JSON.String e) <- HM.lookup "email" o ->
(LTGoogle e, LATNone, Nothing)
_ -> error $ "Can’t get email:\n" ++ BL.unpack ui
googleCallback' :: Bool -> String -> T.Text -> URL -> URL -> (T.Text -> BL.ByteString -> a) -> [(T.Text, T.Text)] -> IO a
googleCallback' firstTime what host cb url f q = withReaderDL $ \ d -> do
case lookup "error" q of
Just "access_denied" ->
fail "Access denied"
Just e ->
fail $ T.unpack e
_ -> return ()
logS $ show q
let c = T.encodeUtf8 $ fromMaybe "no code?" $ lookup "code" q
body = B.concat ["code=", c
, "&client_id=", googleOAuthClientId
, "&client_secret=", googleOAuthClientSecret
, "&redirect_uri=https%3A%2F%2F"
, tbs host
, B.pack $ encodeURIComponent cb
, "&grant_type=authorization_code" ]
dr <- postUrlEncoded d "" Nothing
body
case dr of
DROK r _ -> do
at <- case decodeJson r of
Just (JSON.Object o)
| Just (JSON.String at) <- HM.lookup "access_token" o ->
return at
_ -> error $ "Can’t get access_token:\n" ++ T.unpack (bst r)
when ("import" `isInfixOf` cb) $
logS $ "Import access token: " ++ T.unpack at
dr <- download d (url ++ "access_token=" ++ T.unpack at) Nothing []
case dr of
DROK r _ ->
return $ f at $ BL.fromStrict r
DRError e
| firstTime -> googleCallback' False what host cb url f q
| otherwise -> fail $ "Can’t get " ++ what ++ ":\n" ++ e
_ -> fail $ "Can’t get " ++ what
DRError e
| firstTime -> googleCallback' False what host cb url f q
| otherwise -> fail $ "Can’t get access_token:\n" ++ e
_ -> fail $ "Can’t get access_token"
signTwitterWithAccessToken c r = do
r' <- signOAuth (twitterOAuth "")
(Credential
[(tbs n, tbs v) | (n, v) <- c
,n == "oauth_token" || n == "oauth_token_secret"])
учитываем , что у нас могут быть ipUrl
return $ r' { C.host = C.host r
, C.requestHeaders =
("Accept-Encoding", "") : C.requestHeaders r'
}
signTwitter r =
r { C.requestHeaders =
("Accept-Encoding", "")
: ("Authorization", "Bearer " <> tbs twitterBearer)
: C.requestHeaders r
}
testTwitterUrl u = withManager $ \ m -> do
req <- C.parseRequest u
let sreq0 = signTwitter req
sreq = sreq0 { C.requestHeaders =
[("Accept", "*/*")
,("User-Agent", "curl/7.25.0 (x86_64-apple-darwin11.3.0) libcurl/7.25.0 OpenSSL/1.0.1e zlib/1.2.7 libidn/1.22")]
++
map (\(h,v) -> (h, T.encodeUtf8 $ T.replace "," ", " $ T.pack $ B.unpack v))
(C.requestHeaders sreq0)
}
forM_ (C.requestHeaders sreq) $ \ (h,v) ->
putStrLn $ B.unpack (CI.original h) ++ ": " ++ B.unpack v
rsp <- C.httpLbs sreq m
mapM_ print $ C.responseHeaders rsp
BL.putStrLn $ C.responseBody rsp
postUrlEncoded d u ha body = fmap fst $ postUrlEncodedRaw return d u ha body
postUrlEncodedRaw f d u ha body =
rawDownload
(\ req -> f $
req { C.requestHeaders =
[( "Content-Type"
, "application/x-www-form-urlencoded" )]
, C.method = N.methodPost
, C.requestBody = C.RequestBodyBS body
})
d u ha []
|
9048dc5421e2d9cb3559b455227bda963e112323bd480462947d543a13bd1a5a | ml4tp/tcoq | stm.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Vernacexpr
open Names
open Feedback
open Loc
(** state-transaction-machine interface *)
[ add ontop check vebose eid s ] adds a new command [ s ] on the state [ ontop ]
having edit i d [ eid ] . [ check ] is called on the AST .
The [ ontop ] parameter is just for asserting the GUI is on sync , but
will eventually call edit_at on the fly if needed .
The sentence [ s ] is parsed in the state [ ontop ] .
If [ newtip ] is provided , then the returned state i d is guaranteed to be
[ newtip ]
having edit id [eid]. [check] is called on the AST.
The [ontop] parameter is just for asserting the GUI is on sync, but
will eventually call edit_at on the fly if needed.
The sentence [s] is parsed in the state [ontop].
If [newtip] is provided, then the returned state id is guaranteed to be
[newtip] *)
val add :
ontop:Stateid.t -> ?newtip:Stateid.t ->
?check:(vernac_expr located -> unit) ->
bool -> edit_id -> string ->
Stateid.t * [ `NewTip | `Unfocus of Stateid.t ]
(* parses and executes a command at a given state, throws away its side effects
but for the printings. Feedback is sent with report_with (defaults to dummy
state id) *)
val query :
at:Stateid.t -> ?report_with:(Stateid.t * Feedback.route_id) -> string -> unit
[ edit_at i d ] is issued to change the editing zone . [ ` NewTip ] is returned if
the requested i d is the new document tip hence the document portion following
[ i d ] is dropped by Coq . [ ` Focus fo ] is returned to say that [ fo.tip ] is the
new document tip , the document between [ i d ] and [ fo.stop ] has been dropped .
The portion between [ fo.stop ] and [ fo.tip ] has been kept . [ fo.start ] is
just to tell the gui where the editing zone starts , in case it wants to
graphically denote it . All subsequent [ add ] happen on top of [ i d ] .
If Flags.async_proofs_full is set , then [ i d ] is not [ observe]d , else it is .
the requested id is the new document tip hence the document portion following
[id] is dropped by Coq. [`Focus fo] is returned to say that [fo.tip] is the
new document tip, the document between [id] and [fo.stop] has been dropped.
The portion between [fo.stop] and [fo.tip] has been kept. [fo.start] is
just to tell the gui where the editing zone starts, in case it wants to
graphically denote it. All subsequent [add] happen on top of [id].
If Flags.async_proofs_full is set, then [id] is not [observe]d, else it is.
*)
type focus = { start : Stateid.t; stop : Stateid.t; tip : Stateid.t }
val edit_at : Stateid.t -> [ `NewTip | `Focus of focus ]
(* Evaluates the tip of the current branch *)
val finish : unit -> unit
val observe : Stateid.t -> unit
val stop_worker : string -> unit
(* Joins the entire document. Implies finish, but also checks proofs *)
val join : unit -> unit
Saves on the disk a .vio corresponding to the current status :
- if the worker pool is empty , all tasks are saved
- if the worker proof is not empty , then it waits until all workers
are done with their current jobs and then dumps ( or fails if one
of the completed tasks is a failure )
- if the worker pool is empty, all tasks are saved
- if the worker proof is not empty, then it waits until all workers
are done with their current jobs and then dumps (or fails if one
of the completed tasks is a failure) *)
val snapshot_vio : DirPath.t -> string -> unit
(* Empties the task queue, can be used only if the worker pool is empty (E.g.
* after having built a .vio in batch mode *)
val reset_task_queue : unit -> unit
(* A .vio contains tasks to be completed *)
type tasks
val check_task : string -> tasks -> int -> bool
val info_tasks : tasks -> (string * float * int) list
val finish_tasks : string ->
Library.seg_univ -> Library.seg_discharge -> Library.seg_proofs ->
tasks -> Library.seg_univ * Library.seg_proofs
(* Id of the tip of the current branch *)
val get_current_state : unit -> Stateid.t
(* Misc *)
val init : unit -> unit
(* This returns the node at that position *)
val get_ast : Stateid.t -> (Vernacexpr.vernac_expr * Loc.t) option
(* Filename *)
val set_compilation_hints : string -> unit
(* Reorders the task queue putting forward what is in the perspective *)
val set_perspective : Stateid.t list -> unit
type document
val backup : unit -> document
val restore : document -> unit
(** workers **************************************************************** **)
module ProofTask : AsyncTaskQueue.Task
module TacTask : AsyncTaskQueue.Task
module QueryTask : AsyncTaskQueue.Task
(** document structure customization *************************************** **)
A proof block delimiter defines a syntactic delimiter for sub proofs
that , when contain an error , do not impact the rest of the proof .
While checking a proof , if an error occurs in a ( valid ) block then
processing can skip the entire block and go on to give feedback
on the rest of the proof .
static_block_detection and dynamic_block_validation are run when
the closing block marker is parsed / executed respectively .
static_block_detection is for example called when " } " is parsed and
declares a block containing all proof steps between it and the matching
" { " .
dynamic_block_validation is called when an error " crosses " the " } " statement .
Depending on the nature of the goal focused by " { " the block may absorb the
error or not . For example if the focused goal occurs in the type of
another goal , then the block is leaky .
Note that one can design proof commands that need no dynamic validation .
Example of document :
.. { tac1 . tac2 . } ..
Corresponding DAG :
.. ( 3 ) < -- { -- ( 4 ) < -- tac1 -- ( 5 ) < -- tac2 -- ( 6 ) < -- } -- ( 7 ) ..
Declaration of block [ ------------------------------------------- ]
start = 5 the first state_id that could fail in the block
stop = 7 the node that may absorb the error
dynamic_switch = 4 dynamic check on this node
carry_on_data = ( ) no need to carry extra data from static to dynamic
checks
that, when contain an error, do not impact the rest of the proof.
While checking a proof, if an error occurs in a (valid) block then
processing can skip the entire block and go on to give feedback
on the rest of the proof.
static_block_detection and dynamic_block_validation are run when
the closing block marker is parsed/executed respectively.
static_block_detection is for example called when "}" is parsed and
declares a block containing all proof steps between it and the matching
"{".
dynamic_block_validation is called when an error "crosses" the "}" statement.
Depending on the nature of the goal focused by "{" the block may absorb the
error or not. For example if the focused goal occurs in the type of
another goal, then the block is leaky.
Note that one can design proof commands that need no dynamic validation.
Example of document:
.. { tac1. tac2. } ..
Corresponding DAG:
.. (3) <-- { -- (4) <-- tac1 -- (5) <-- tac2 -- (6) <-- } -- (7) ..
Declaration of block [-------------------------------------------]
start = 5 the first state_id that could fail in the block
stop = 7 the node that may absorb the error
dynamic_switch = 4 dynamic check on this node
carry_on_data = () no need to carry extra data from static to dynamic
checks
*)
module DynBlockData : Dyn.S
type static_block_declaration = {
block_start : Stateid.t;
block_stop : Stateid.t;
dynamic_switch : Stateid.t;
carry_on_data : DynBlockData.t;
}
type document_node = {
indentation : int;
ast : Vernacexpr.vernac_expr;
id : Stateid.t;
}
type document_view = {
entry_point : document_node;
prev_node : document_node -> document_node option;
}
type static_block_detection =
document_view -> static_block_declaration option
type recovery_action = {
base_state : Stateid.t;
goals_to_admit : Goal.goal list;
recovery_command : Vernacexpr.vernac_expr option;
}
type dynamic_block_error_recovery =
static_block_declaration -> [ `ValidBlock of recovery_action | `Leaks ]
val register_proof_block_delimiter :
Vernacexpr.proof_block_name ->
static_block_detection ->
dynamic_block_error_recovery ->
unit
(** customization ********************************************************** **)
(* From the master (or worker, but beware that to install the hook
* into a worker one has to build the worker toploop to do so and
* the alternative toploop for the worker can be selected by changing
* the name of the Task(s) above) *)
val state_computed_hook : (Stateid.t -> in_cache:bool -> unit) Hook.t
val parse_error_hook :
(Feedback.edit_or_state_id -> Loc.t -> Pp.std_ppcmds -> unit) Hook.t
val execution_error_hook : (Stateid.t -> Loc.t -> Pp.std_ppcmds -> unit) Hook.t
val unreachable_state_hook : (Stateid.t -> Exninfo.iexn -> unit) Hook.t
(* ready means that master has it at hand *)
val state_ready_hook : (Stateid.t -> unit) Hook.t
(* called with true before and with false after a tactic explicitly
* in the document is run *)
val tactic_being_run_hook : (bool -> unit) Hook.t
(* Messages from the workers to the master *)
val forward_feedback_hook : (Feedback.feedback -> unit) Hook.t
type state = {
system : States.state;
proof : Proof_global.state;
shallow : bool
}
val state_of_id :
Stateid.t -> [ `Valid of state option | `Expired | `Error of exn ]
(** read-eval-print loop compatible interface ****************************** **)
Adds a new line to the document . It replaces the core of Vernac.interp .
[ finish ] is called as the last bit of this function if the system
is running interactively ( -emacs or coqtop ) .
[finish] is called as the last bit of this function if the system
is running interactively (-emacs or coqtop). *)
val interp : bool -> vernac_expr located -> unit
(* Queries for backward compatibility *)
val current_proof_depth : unit -> int
val get_all_proof_names : unit -> Id.t list
val get_current_proof_name : unit -> Id.t option
val show_script : ?proof:Proof_global.closed_proof -> unit -> unit
Hooks to be set by other Coq components in order to break file cycles
val process_error_hook : Future.fix_exn Hook.t
val interp_hook : (?verbosely:bool -> ?proof:Proof_global.closed_proof ->
Loc.t * Vernacexpr.vernac_expr -> unit) Hook.t
val with_fail_hook : (bool -> (unit -> unit) -> unit) Hook.t
val get_fix_exn : unit -> (Exninfo.iexn -> Exninfo.iexn)
| null | https://raw.githubusercontent.com/ml4tp/tcoq/7a78c31df480fba721648f277ab0783229c8bece/stm/stm.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
* state-transaction-machine interface
parses and executes a command at a given state, throws away its side effects
but for the printings. Feedback is sent with report_with (defaults to dummy
state id)
Evaluates the tip of the current branch
Joins the entire document. Implies finish, but also checks proofs
Empties the task queue, can be used only if the worker pool is empty (E.g.
* after having built a .vio in batch mode
A .vio contains tasks to be completed
Id of the tip of the current branch
Misc
This returns the node at that position
Filename
Reorders the task queue putting forward what is in the perspective
* workers **************************************************************** *
* document structure customization *************************************** *
* customization ********************************************************** *
From the master (or worker, but beware that to install the hook
* into a worker one has to build the worker toploop to do so and
* the alternative toploop for the worker can be selected by changing
* the name of the Task(s) above)
ready means that master has it at hand
called with true before and with false after a tactic explicitly
* in the document is run
Messages from the workers to the master
* read-eval-print loop compatible interface ****************************** *
Queries for backward compatibility | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Vernacexpr
open Names
open Feedback
open Loc
[ add ontop check vebose eid s ] adds a new command [ s ] on the state [ ontop ]
having edit i d [ eid ] . [ check ] is called on the AST .
The [ ontop ] parameter is just for asserting the GUI is on sync , but
will eventually call edit_at on the fly if needed .
The sentence [ s ] is parsed in the state [ ontop ] .
If [ newtip ] is provided , then the returned state i d is guaranteed to be
[ newtip ]
having edit id [eid]. [check] is called on the AST.
The [ontop] parameter is just for asserting the GUI is on sync, but
will eventually call edit_at on the fly if needed.
The sentence [s] is parsed in the state [ontop].
If [newtip] is provided, then the returned state id is guaranteed to be
[newtip] *)
val add :
ontop:Stateid.t -> ?newtip:Stateid.t ->
?check:(vernac_expr located -> unit) ->
bool -> edit_id -> string ->
Stateid.t * [ `NewTip | `Unfocus of Stateid.t ]
val query :
at:Stateid.t -> ?report_with:(Stateid.t * Feedback.route_id) -> string -> unit
[ edit_at i d ] is issued to change the editing zone . [ ` NewTip ] is returned if
the requested i d is the new document tip hence the document portion following
[ i d ] is dropped by Coq . [ ` Focus fo ] is returned to say that [ fo.tip ] is the
new document tip , the document between [ i d ] and [ fo.stop ] has been dropped .
The portion between [ fo.stop ] and [ fo.tip ] has been kept . [ fo.start ] is
just to tell the gui where the editing zone starts , in case it wants to
graphically denote it . All subsequent [ add ] happen on top of [ i d ] .
If Flags.async_proofs_full is set , then [ i d ] is not [ observe]d , else it is .
the requested id is the new document tip hence the document portion following
[id] is dropped by Coq. [`Focus fo] is returned to say that [fo.tip] is the
new document tip, the document between [id] and [fo.stop] has been dropped.
The portion between [fo.stop] and [fo.tip] has been kept. [fo.start] is
just to tell the gui where the editing zone starts, in case it wants to
graphically denote it. All subsequent [add] happen on top of [id].
If Flags.async_proofs_full is set, then [id] is not [observe]d, else it is.
*)
type focus = { start : Stateid.t; stop : Stateid.t; tip : Stateid.t }
val edit_at : Stateid.t -> [ `NewTip | `Focus of focus ]
val finish : unit -> unit
val observe : Stateid.t -> unit
val stop_worker : string -> unit
val join : unit -> unit
Saves on the disk a .vio corresponding to the current status :
- if the worker pool is empty , all tasks are saved
- if the worker proof is not empty , then it waits until all workers
are done with their current jobs and then dumps ( or fails if one
of the completed tasks is a failure )
- if the worker pool is empty, all tasks are saved
- if the worker proof is not empty, then it waits until all workers
are done with their current jobs and then dumps (or fails if one
of the completed tasks is a failure) *)
val snapshot_vio : DirPath.t -> string -> unit
val reset_task_queue : unit -> unit
type tasks
val check_task : string -> tasks -> int -> bool
val info_tasks : tasks -> (string * float * int) list
val finish_tasks : string ->
Library.seg_univ -> Library.seg_discharge -> Library.seg_proofs ->
tasks -> Library.seg_univ * Library.seg_proofs
val get_current_state : unit -> Stateid.t
val init : unit -> unit
val get_ast : Stateid.t -> (Vernacexpr.vernac_expr * Loc.t) option
val set_compilation_hints : string -> unit
val set_perspective : Stateid.t list -> unit
type document
val backup : unit -> document
val restore : document -> unit
module ProofTask : AsyncTaskQueue.Task
module TacTask : AsyncTaskQueue.Task
module QueryTask : AsyncTaskQueue.Task
A proof block delimiter defines a syntactic delimiter for sub proofs
that , when contain an error , do not impact the rest of the proof .
While checking a proof , if an error occurs in a ( valid ) block then
processing can skip the entire block and go on to give feedback
on the rest of the proof .
static_block_detection and dynamic_block_validation are run when
the closing block marker is parsed / executed respectively .
static_block_detection is for example called when " } " is parsed and
declares a block containing all proof steps between it and the matching
" { " .
dynamic_block_validation is called when an error " crosses " the " } " statement .
Depending on the nature of the goal focused by " { " the block may absorb the
error or not . For example if the focused goal occurs in the type of
another goal , then the block is leaky .
Note that one can design proof commands that need no dynamic validation .
Example of document :
.. { tac1 . tac2 . } ..
Corresponding DAG :
.. ( 3 ) < -- { -- ( 4 ) < -- tac1 -- ( 5 ) < -- tac2 -- ( 6 ) < -- } -- ( 7 ) ..
Declaration of block [ ------------------------------------------- ]
start = 5 the first state_id that could fail in the block
stop = 7 the node that may absorb the error
dynamic_switch = 4 dynamic check on this node
carry_on_data = ( ) no need to carry extra data from static to dynamic
checks
that, when contain an error, do not impact the rest of the proof.
While checking a proof, if an error occurs in a (valid) block then
processing can skip the entire block and go on to give feedback
on the rest of the proof.
static_block_detection and dynamic_block_validation are run when
the closing block marker is parsed/executed respectively.
static_block_detection is for example called when "}" is parsed and
declares a block containing all proof steps between it and the matching
"{".
dynamic_block_validation is called when an error "crosses" the "}" statement.
Depending on the nature of the goal focused by "{" the block may absorb the
error or not. For example if the focused goal occurs in the type of
another goal, then the block is leaky.
Note that one can design proof commands that need no dynamic validation.
Example of document:
.. { tac1. tac2. } ..
Corresponding DAG:
.. (3) <-- { -- (4) <-- tac1 -- (5) <-- tac2 -- (6) <-- } -- (7) ..
Declaration of block [-------------------------------------------]
start = 5 the first state_id that could fail in the block
stop = 7 the node that may absorb the error
dynamic_switch = 4 dynamic check on this node
carry_on_data = () no need to carry extra data from static to dynamic
checks
*)
module DynBlockData : Dyn.S
type static_block_declaration = {
block_start : Stateid.t;
block_stop : Stateid.t;
dynamic_switch : Stateid.t;
carry_on_data : DynBlockData.t;
}
type document_node = {
indentation : int;
ast : Vernacexpr.vernac_expr;
id : Stateid.t;
}
type document_view = {
entry_point : document_node;
prev_node : document_node -> document_node option;
}
type static_block_detection =
document_view -> static_block_declaration option
type recovery_action = {
base_state : Stateid.t;
goals_to_admit : Goal.goal list;
recovery_command : Vernacexpr.vernac_expr option;
}
type dynamic_block_error_recovery =
static_block_declaration -> [ `ValidBlock of recovery_action | `Leaks ]
val register_proof_block_delimiter :
Vernacexpr.proof_block_name ->
static_block_detection ->
dynamic_block_error_recovery ->
unit
val state_computed_hook : (Stateid.t -> in_cache:bool -> unit) Hook.t
val parse_error_hook :
(Feedback.edit_or_state_id -> Loc.t -> Pp.std_ppcmds -> unit) Hook.t
val execution_error_hook : (Stateid.t -> Loc.t -> Pp.std_ppcmds -> unit) Hook.t
val unreachable_state_hook : (Stateid.t -> Exninfo.iexn -> unit) Hook.t
val state_ready_hook : (Stateid.t -> unit) Hook.t
val tactic_being_run_hook : (bool -> unit) Hook.t
val forward_feedback_hook : (Feedback.feedback -> unit) Hook.t
type state = {
system : States.state;
proof : Proof_global.state;
shallow : bool
}
val state_of_id :
Stateid.t -> [ `Valid of state option | `Expired | `Error of exn ]
Adds a new line to the document . It replaces the core of Vernac.interp .
[ finish ] is called as the last bit of this function if the system
is running interactively ( -emacs or coqtop ) .
[finish] is called as the last bit of this function if the system
is running interactively (-emacs or coqtop). *)
val interp : bool -> vernac_expr located -> unit
val current_proof_depth : unit -> int
val get_all_proof_names : unit -> Id.t list
val get_current_proof_name : unit -> Id.t option
val show_script : ?proof:Proof_global.closed_proof -> unit -> unit
Hooks to be set by other Coq components in order to break file cycles
val process_error_hook : Future.fix_exn Hook.t
val interp_hook : (?verbosely:bool -> ?proof:Proof_global.closed_proof ->
Loc.t * Vernacexpr.vernac_expr -> unit) Hook.t
val with_fail_hook : (bool -> (unit -> unit) -> unit) Hook.t
val get_fix_exn : unit -> (Exninfo.iexn -> Exninfo.iexn)
|
a7a79906ba71961c4fd6a899488405855de7d36bab21fb3ba9205febf825507c | wdanilo/haskell-logger | Base.hs | # LANGUAGE TypeFamilies #
-----------------------------------------------------------------------------
-- |
-- Module : System.Log.Logger.Base
Copyright : ( C ) 2015 Flowbox
-- License : Apache-2.0
Maintainer : < >
-- Stability : stable
-- Portability : portable
-----------------------------------------------------------------------------
module System.Log.Logger.Base where
import Control.Monad.Trans
import System.Log.Data (Data, MonadRecord(appendRecord))
import Control.Applicative
import System.Log.Tuples
import System.Log.Log (LogFormat, MonadLogger, appendLog)
import Control.Monad.Identity (runIdentity)
----------------------------------------------------------------------
-- BaseLoggerT
----------------------------------------------------------------------
newtype BaseLoggerT l m a = BaseLoggerT { runRawBaseLoggerT :: m a } deriving (Monad, MonadIO, Applicative, Functor)
runBaseLoggerT :: l -> BaseLoggerT (MapRTuple Data (Tuple2RTuple l)) m a -> m a
runBaseLoggerT _ = runRawBaseLoggerT
runBaseLogger d = runIdentity . runBaseLoggerT d
-- === instances ===
type instance LogFormat (BaseLoggerT l m) = l
instance (Applicative m, Monad m) => MonadLogger (BaseLoggerT l m) where
appendLog _ = return ()
instance MonadTrans (BaseLoggerT l) where
lift = BaseLoggerT
instance Monad m => MonadRecord d (BaseLoggerT l m) where
appendRecord _ = return ()
| null | https://raw.githubusercontent.com/wdanilo/haskell-logger/bdf3b64f50c0a8e26bd44fdb882e72ffbe19fd3f/src/System/Log/Logger/Base.hs | haskell | ---------------------------------------------------------------------------
|
Module : System.Log.Logger.Base
License : Apache-2.0
Stability : stable
Portability : portable
---------------------------------------------------------------------------
--------------------------------------------------------------------
BaseLoggerT
--------------------------------------------------------------------
=== instances === | # LANGUAGE TypeFamilies #
Copyright : ( C ) 2015 Flowbox
Maintainer : < >
module System.Log.Logger.Base where
import Control.Monad.Trans
import System.Log.Data (Data, MonadRecord(appendRecord))
import Control.Applicative
import System.Log.Tuples
import System.Log.Log (LogFormat, MonadLogger, appendLog)
import Control.Monad.Identity (runIdentity)
newtype BaseLoggerT l m a = BaseLoggerT { runRawBaseLoggerT :: m a } deriving (Monad, MonadIO, Applicative, Functor)
runBaseLoggerT :: l -> BaseLoggerT (MapRTuple Data (Tuple2RTuple l)) m a -> m a
runBaseLoggerT _ = runRawBaseLoggerT
runBaseLogger d = runIdentity . runBaseLoggerT d
type instance LogFormat (BaseLoggerT l m) = l
instance (Applicative m, Monad m) => MonadLogger (BaseLoggerT l m) where
appendLog _ = return ()
instance MonadTrans (BaseLoggerT l) where
lift = BaseLoggerT
instance Monad m => MonadRecord d (BaseLoggerT l m) where
appendRecord _ = return ()
|
c634275cb4d06d0cb57262c5bb25be4692f916f6a69efd18b389c050a300c59e | onedata/op-worker | tree_traverse_job.erl | %%%-------------------------------------------------------------------
@author
( C ) 2019 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
%%% @end
%%%-------------------------------------------------------------------
%%% @doc Model for holding traverse jobs (see tree_traverse.erl). Main jobs for each task
%%% are synchronized between providers, other are local for provider executing task.
%%% @end
%%%-------------------------------------------------------------------
-module(tree_traverse_job).
-author("Michal Wrzeszcz").
-include("tree_traverse.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/datastore/datastore_models.hrl").
-include("modules/datastore/datastore_runner.hrl").
%% API
-export([save_master_job/5, delete_master_job/4, get_master_job/1]).
%% datastore_model callbacks
-export([get_ctx/0, get_record_struct/1, upgrade_record/2, get_record_version/0]).
-type key() :: datastore:key().
-type record() :: #tree_traverse_job{}.
-type doc() :: datastore_doc:doc(record()).
-export_type([doc/0]).
-define(CTX, #{
model => ?MODULE
}).
-define(SYNC_CTX, #{
model => ?MODULE,
sync_enabled => true,
mutator => oneprovider:get_id_or_undefined()
}).
-define(MAIN_JOB_PREFIX, "main_job").
Time in seconds for main job document to expire after delete ( one year ) .
% After expiration of main job document, information about traverse cancellation
% cannot be propagated to other providers.
-define(MAIN_JOB_EXPIRY, 31536000).
%%%===================================================================
%%% API
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Saves information about job. See save/3 for more information.
%% @end
%%--------------------------------------------------------------------
-spec save_master_job(datastore:key() | main_job, tree_traverse:master_job(), traverse:pool(), traverse:id(),
traverse:callback_module()) -> {ok, key()} | {error, term()}.
save_master_job(Key, Job = #tree_traverse{
file_ctx = FileCtx,
user_id = UserId,
tune_for_large_continuous_listing = TuneForLargeContinuousListing,
pagination_token = ListingPaginationToken,
child_dirs_job_generation_policy = ChildDirsJobGenerationPolicy,
children_master_jobs_mode = ChildrenMasterJobsMode,
track_subtree_status = TrackSubtreeStatus,
batch_size = BatchSize,
traverse_info = TraverseInfo,
resolved_root_uuids = ResolvedRootUuids,
symlink_resolution_policy = SymlinkResolutionPolicy,
relative_path = RelativePath,
encountered_files = EncounteredFilesMap
}, Pool, TaskId, CallbackModule) ->
Uuid = file_ctx:get_logical_uuid_const(FileCtx),
Scope = file_ctx:get_space_id_const(FileCtx),
Record = #tree_traverse_job{
pool = Pool,
callback_module = CallbackModule,
task_id = TaskId,
doc_id = Uuid,
user_id = UserId,
tune_for_large_continuous_listing = TuneForLargeContinuousListing,
pagination_token = ListingPaginationToken,
child_dirs_job_generation_policy = ChildDirsJobGenerationPolicy,
children_master_jobs_mode = ChildrenMasterJobsMode,
track_subtree_status = TrackSubtreeStatus,
batch_size = BatchSize,
traverse_info = term_to_binary(TraverseInfo),
symlink_resolution_policy = SymlinkResolutionPolicy,
resolved_root_uuids = ResolvedRootUuids,
relative_path = RelativePath,
encountered_files = EncounteredFilesMap
},
Ctx = get_extended_ctx(Job, CallbackModule),
save(Key, Scope, Record, Ctx).
-spec delete_master_job(datastore:key(), tree_traverse:master_job(), datastore_doc:scope(), traverse:callback_module()) ->
ok | {error, term()}.
delete_master_job(<<?MAIN_JOB_PREFIX, _/binary>> = Key, Job, Scope, CallbackModule) ->
Ctx = get_extended_ctx(Job, CallbackModule),
Ctx2 = case maps:get(sync_enabled, Ctx, false) of
true -> Ctx#{scope => Scope};
false -> Ctx
end,
Ctx3 = datastore_model:set_expiry(Ctx2, ?MAIN_JOB_EXPIRY),
datastore_model:delete(Ctx3, Key);
delete_master_job(Key, _Job, _, _CallbackModule) ->
datastore_model:delete(?CTX, Key).
-spec get_master_job(key() | doc()) ->
{ok, tree_traverse:master_job(), traverse:pool(), traverse:id()} | {error, term()}.
get_master_job(#document{value = #tree_traverse_job{
pool = Pool,
task_id = TaskId,
doc_id = DocId,
user_id = UserId,
tune_for_large_continuous_listing = TuneForLargeContinuousListing,
pagination_token = PaginationToken,
child_dirs_job_generation_policy = ChildDirsJobGenerationPolicy,
children_master_jobs_mode = ChildrenMasterJobsMode,
track_subtree_status = TrackSubtreeStatus,
batch_size = BatchSize,
traverse_info = TraverseInfo,
symlink_resolution_policy = SymlinkResolutionPolicy,
resolved_root_uuids = ResolvedRootUuids,
relative_path = RelativePath,
encountered_files = EncounteredFilesMap
}}) ->
case file_meta:get_including_deleted(DocId) of
{ok, Doc = #document{scope = SpaceId}} ->
FileCtx = file_ctx:new_by_doc(Doc, SpaceId),
Job = #tree_traverse{
file_ctx = FileCtx,
user_id = UserId,
tune_for_large_continuous_listing = TuneForLargeContinuousListing,
pagination_token = PaginationToken,
child_dirs_job_generation_policy = ChildDirsJobGenerationPolicy,
children_master_jobs_mode = ChildrenMasterJobsMode,
track_subtree_status = TrackSubtreeStatus,
batch_size = BatchSize,
traverse_info = binary_to_term(TraverseInfo),
symlink_resolution_policy = SymlinkResolutionPolicy,
resolved_root_uuids = ResolvedRootUuids,
relative_path = RelativePath,
encountered_files = EncounteredFilesMap
},
{ok, Job, Pool, TaskId};
{error, _} = Error ->
Error
end;
get_master_job(Key) ->
case datastore_model:get(?CTX#{include_deleted => true}, Key) of
{ok, Doc} ->
get_master_job(Doc);
Other ->
Other
end.
%%%===================================================================
%%% datastore_model callbacks
%%%===================================================================
%%--------------------------------------------------------------------
%% @doc
%% Returns model's context used by datastore and dbsync.
%% @end
%%--------------------------------------------------------------------
-spec get_ctx() -> datastore:ctx().
get_ctx() ->
?SYNC_CTX.
%%--------------------------------------------------------------------
%% @doc
%% Returns model's record version.
%% @end
%%--------------------------------------------------------------------
-spec get_record_version() -> datastore_model:record_version().
get_record_version() ->
6.
-spec get_record_struct(datastore_model:record_version()) ->
datastore_model:record_struct().
get_record_struct(1) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{last_name, string},
{last_tree, string},
{execute_slave_on_dir, boolean},
{batch_size, integer},
{traverse_info, binary}
]};
get_record_struct(2) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
% user_id has been added in this version
{user_id, string},
% use_listing_token field has been added in this version
{use_listing_token, boolean},
{last_name, string},
{last_tree, string},
{execute_slave_on_dir, boolean},
% children_master_jobs_mode has been added in this version
{children_master_jobs_mode, atom},
% track_subtree_status has been added in this version
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary}
]};
get_record_struct(3) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{user_id, string},
{use_listing_token, boolean},
{last_name, string},
{last_tree, string},
% execute_slave_on_dir has been changed to child_dirs_job_generation_policy in this version
{child_dirs_job_generation_policy, atom},
{children_master_jobs_mode, atom},
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary}
]};
get_record_struct(4) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{user_id, string},
{use_listing_token, boolean},
{last_name, string},
{last_tree, string},
{child_dirs_job_generation_policy, atom},
{children_master_jobs_mode, atom},
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary},
% new fields - follow_symlinks, relative_path and encountered_files
{follow_symlinks, boolean},
{relative_path, binary},
{encountered_files, #{string => boolean}}
]};
get_record_struct(5) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{user_id, string},
{use_listing_token, boolean},
{last_name, string},
{last_tree, string},
{child_dirs_job_generation_policy, atom},
{children_master_jobs_mode, atom},
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary},
{symlink_resolution_policy, atom}, % modified field
{resolved_root_uuids, [string]}, % new field
{relative_path, binary},
{encountered_files, #{string => boolean}}
]};
get_record_struct(6) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{user_id, string},
modified field ( renamed from use_listing_token )
{pagination_token, {custom, string, {file_listing, encode_pagination_token, decode_pagination_token}}}, % new field
% removed fields last_name and last_tree
{child_dirs_job_generation_policy, atom},
{children_master_jobs_mode, atom},
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary},
{symlink_resolution_policy, atom},
{resolved_root_uuids, [string]},
{relative_path, binary},
{encountered_files, #{string => boolean}}
]}.
%%--------------------------------------------------------------------
%% @doc
%% Upgrades model's record from provided version to the next one.
%% @end
%%--------------------------------------------------------------------
-spec upgrade_record(datastore_model:record_version(), datastore_model:record()) ->
{datastore_model:record_version(), datastore_model:record()}.
upgrade_record(1, {?MODULE, Pool, CallbackModule, TaskId, DocId, LastName, LastTree, ExecuteSlaveOnDir,
BatchSize, TraverseInfo}
) ->
{2, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
% user_id has been added in this version
?ROOT_USER_ID,
% use_listing_token field has been added in this version
true,
LastName,
LastTree,
ExecuteSlaveOnDir,
% children_master_jobs_mode has been added in this version
sync,
% track_subtree_status has been added in this version
false,
BatchSize,
TraverseInfo
}};
upgrade_record(2, Record) ->
{
?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ExecuteSlaveOnDir,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo
} = Record,
ChildDirsJobGenerationPolicy = case ExecuteSlaveOnDir of
false -> generate_master_jobs;
true -> generate_slave_and_master_jobs
end,
{3, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo
}};
upgrade_record(3, Record) ->
{
?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo
} = Record,
{4, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
% new fields follow_symlinks, relative path and encountered files
false,
<<>>,
#{}
}};
upgrade_record(4, Record) ->
{
?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
FollowSymlinks,
RelativePath,
EncounteredFiles
} = Record,
SymlinkResolutionPolicy = case FollowSymlinks of
true -> follow_external;
false -> preserve
end,
{5, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
SymlinkResolutionPolicy, % modified field
[], % new field resolved_root_uuids
RelativePath,
EncounteredFiles
}};
upgrade_record(5, Record) ->
{
?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
SymlinkResolutionPolicy,
RootUuids,
RelativePath,
EncounteredFiles
} = Record,
TuneForLargeContinuousListing = UseListingToken,
Index = file_listing:build_index(LastName, LastTree),
% listing with limit 0 does not list anything, but returns a pagination_token that can be used
% to continue listing from this point
{ok, [], ListingPaginationToken} = file_listing:list(<<"dummy_uuid">>, #{
index => Index,
tune_for_large_continuous_listing => TuneForLargeContinuousListing,
limit => 0
}),
{6, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
TuneForLargeContinuousListing,
ListingPaginationToken,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
SymlinkResolutionPolicy,
RootUuids,
RelativePath,
EncounteredFiles
}}.
%%%===================================================================
Internal functions
%%%===================================================================
%%--------------------------------------------------------------------
@private
%% @doc
%% Saves information about job. Generates special key for main jobs (see tree_traverse.erl) to treat the differently
%% (main jobs are synchronized between providers - other not).
%% @end
%%--------------------------------------------------------------------
-spec save(datastore:key() | main_job, datastore_doc:scope(), record(), datastore:ctx()) -> {ok, key()} | {error, term()}.
save(main_job, Scope, Value, ExtendedCtx) ->
RandomPart = datastore_key:new(),
GenKey = <<?MAIN_JOB_PREFIX, RandomPart/binary>>,
Doc = #document{key = GenKey, value = Value},
Doc2 = set_scope_if_sync_enabled(Doc, Scope, ExtendedCtx),
?extract_key(datastore_model:save(ExtendedCtx#{generated_key => true}, Doc2));
save(<<?MAIN_JOB_PREFIX, _/binary>> = Key, Scope, Value, ExtendedCtx) ->
Doc = #document{key = Key, value = Value},
Doc2 = set_scope_if_sync_enabled(Doc, Scope, ExtendedCtx),
?extract_key(datastore_model:save(ExtendedCtx, Doc2));
save(Key, _, Value, _ExtendedCtx) ->
?extract_key(datastore_model:save(?CTX, #document{key = Key, value = Value})).
-spec set_scope_if_sync_enabled(doc(), datastore_doc:scope(), datastore:ctx()) -> doc().
set_scope_if_sync_enabled(Doc, Scope, #{sync_enabled := true}) ->
Doc#document{scope = Scope};
set_scope_if_sync_enabled(Doc, _Scope, _Ctx) ->
Doc.
-spec get_extended_ctx(tree_traverse:master_job(), traverse:callback_module()) -> datastore:ctx().
get_extended_ctx(Job, CallbackModule) ->
{ok, ExtendedCtx} = case erlang:function_exported(CallbackModule, get_sync_info, 1) of
true ->
CallbackModule:get_sync_info(Job);
_ ->
{ok, #{}}
end,
maps:merge(?CTX, ExtendedCtx). | null | https://raw.githubusercontent.com/onedata/op-worker/99b86a7229f6db6a694997bd5df4aa69e140e7ee/src/modules/datastore/models/tree_traverse/tree_traverse_job.erl | erlang | -------------------------------------------------------------------
@end
-------------------------------------------------------------------
@doc Model for holding traverse jobs (see tree_traverse.erl). Main jobs for each task
are synchronized between providers, other are local for provider executing task.
@end
-------------------------------------------------------------------
API
datastore_model callbacks
After expiration of main job document, information about traverse cancellation
cannot be propagated to other providers.
===================================================================
API
===================================================================
--------------------------------------------------------------------
@doc
Saves information about job. See save/3 for more information.
@end
--------------------------------------------------------------------
===================================================================
datastore_model callbacks
===================================================================
--------------------------------------------------------------------
@doc
Returns model's context used by datastore and dbsync.
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
Returns model's record version.
@end
--------------------------------------------------------------------
user_id has been added in this version
use_listing_token field has been added in this version
children_master_jobs_mode has been added in this version
track_subtree_status has been added in this version
execute_slave_on_dir has been changed to child_dirs_job_generation_policy in this version
new fields - follow_symlinks, relative_path and encountered_files
modified field
new field
new field
removed fields last_name and last_tree
--------------------------------------------------------------------
@doc
Upgrades model's record from provided version to the next one.
@end
--------------------------------------------------------------------
user_id has been added in this version
use_listing_token field has been added in this version
children_master_jobs_mode has been added in this version
track_subtree_status has been added in this version
new fields follow_symlinks, relative path and encountered files
modified field
new field resolved_root_uuids
listing with limit 0 does not list anything, but returns a pagination_token that can be used
to continue listing from this point
===================================================================
===================================================================
--------------------------------------------------------------------
@doc
Saves information about job. Generates special key for main jobs (see tree_traverse.erl) to treat the differently
(main jobs are synchronized between providers - other not).
@end
-------------------------------------------------------------------- | @author
( C ) 2019 ACK CYFRONET AGH
This software is released under the MIT license
cited in ' LICENSE.txt ' .
-module(tree_traverse_job).
-author("Michal Wrzeszcz").
-include("tree_traverse.hrl").
-include("modules/fslogic/fslogic_common.hrl").
-include("modules/datastore/datastore_models.hrl").
-include("modules/datastore/datastore_runner.hrl").
-export([save_master_job/5, delete_master_job/4, get_master_job/1]).
-export([get_ctx/0, get_record_struct/1, upgrade_record/2, get_record_version/0]).
-type key() :: datastore:key().
-type record() :: #tree_traverse_job{}.
-type doc() :: datastore_doc:doc(record()).
-export_type([doc/0]).
-define(CTX, #{
model => ?MODULE
}).
-define(SYNC_CTX, #{
model => ?MODULE,
sync_enabled => true,
mutator => oneprovider:get_id_or_undefined()
}).
-define(MAIN_JOB_PREFIX, "main_job").
Time in seconds for main job document to expire after delete ( one year ) .
-define(MAIN_JOB_EXPIRY, 31536000).
-spec save_master_job(datastore:key() | main_job, tree_traverse:master_job(), traverse:pool(), traverse:id(),
traverse:callback_module()) -> {ok, key()} | {error, term()}.
save_master_job(Key, Job = #tree_traverse{
file_ctx = FileCtx,
user_id = UserId,
tune_for_large_continuous_listing = TuneForLargeContinuousListing,
pagination_token = ListingPaginationToken,
child_dirs_job_generation_policy = ChildDirsJobGenerationPolicy,
children_master_jobs_mode = ChildrenMasterJobsMode,
track_subtree_status = TrackSubtreeStatus,
batch_size = BatchSize,
traverse_info = TraverseInfo,
resolved_root_uuids = ResolvedRootUuids,
symlink_resolution_policy = SymlinkResolutionPolicy,
relative_path = RelativePath,
encountered_files = EncounteredFilesMap
}, Pool, TaskId, CallbackModule) ->
Uuid = file_ctx:get_logical_uuid_const(FileCtx),
Scope = file_ctx:get_space_id_const(FileCtx),
Record = #tree_traverse_job{
pool = Pool,
callback_module = CallbackModule,
task_id = TaskId,
doc_id = Uuid,
user_id = UserId,
tune_for_large_continuous_listing = TuneForLargeContinuousListing,
pagination_token = ListingPaginationToken,
child_dirs_job_generation_policy = ChildDirsJobGenerationPolicy,
children_master_jobs_mode = ChildrenMasterJobsMode,
track_subtree_status = TrackSubtreeStatus,
batch_size = BatchSize,
traverse_info = term_to_binary(TraverseInfo),
symlink_resolution_policy = SymlinkResolutionPolicy,
resolved_root_uuids = ResolvedRootUuids,
relative_path = RelativePath,
encountered_files = EncounteredFilesMap
},
Ctx = get_extended_ctx(Job, CallbackModule),
save(Key, Scope, Record, Ctx).
-spec delete_master_job(datastore:key(), tree_traverse:master_job(), datastore_doc:scope(), traverse:callback_module()) ->
ok | {error, term()}.
delete_master_job(<<?MAIN_JOB_PREFIX, _/binary>> = Key, Job, Scope, CallbackModule) ->
Ctx = get_extended_ctx(Job, CallbackModule),
Ctx2 = case maps:get(sync_enabled, Ctx, false) of
true -> Ctx#{scope => Scope};
false -> Ctx
end,
Ctx3 = datastore_model:set_expiry(Ctx2, ?MAIN_JOB_EXPIRY),
datastore_model:delete(Ctx3, Key);
delete_master_job(Key, _Job, _, _CallbackModule) ->
datastore_model:delete(?CTX, Key).
-spec get_master_job(key() | doc()) ->
{ok, tree_traverse:master_job(), traverse:pool(), traverse:id()} | {error, term()}.
get_master_job(#document{value = #tree_traverse_job{
pool = Pool,
task_id = TaskId,
doc_id = DocId,
user_id = UserId,
tune_for_large_continuous_listing = TuneForLargeContinuousListing,
pagination_token = PaginationToken,
child_dirs_job_generation_policy = ChildDirsJobGenerationPolicy,
children_master_jobs_mode = ChildrenMasterJobsMode,
track_subtree_status = TrackSubtreeStatus,
batch_size = BatchSize,
traverse_info = TraverseInfo,
symlink_resolution_policy = SymlinkResolutionPolicy,
resolved_root_uuids = ResolvedRootUuids,
relative_path = RelativePath,
encountered_files = EncounteredFilesMap
}}) ->
case file_meta:get_including_deleted(DocId) of
{ok, Doc = #document{scope = SpaceId}} ->
FileCtx = file_ctx:new_by_doc(Doc, SpaceId),
Job = #tree_traverse{
file_ctx = FileCtx,
user_id = UserId,
tune_for_large_continuous_listing = TuneForLargeContinuousListing,
pagination_token = PaginationToken,
child_dirs_job_generation_policy = ChildDirsJobGenerationPolicy,
children_master_jobs_mode = ChildrenMasterJobsMode,
track_subtree_status = TrackSubtreeStatus,
batch_size = BatchSize,
traverse_info = binary_to_term(TraverseInfo),
symlink_resolution_policy = SymlinkResolutionPolicy,
resolved_root_uuids = ResolvedRootUuids,
relative_path = RelativePath,
encountered_files = EncounteredFilesMap
},
{ok, Job, Pool, TaskId};
{error, _} = Error ->
Error
end;
get_master_job(Key) ->
case datastore_model:get(?CTX#{include_deleted => true}, Key) of
{ok, Doc} ->
get_master_job(Doc);
Other ->
Other
end.
-spec get_ctx() -> datastore:ctx().
get_ctx() ->
?SYNC_CTX.
-spec get_record_version() -> datastore_model:record_version().
get_record_version() ->
6.
-spec get_record_struct(datastore_model:record_version()) ->
datastore_model:record_struct().
get_record_struct(1) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{last_name, string},
{last_tree, string},
{execute_slave_on_dir, boolean},
{batch_size, integer},
{traverse_info, binary}
]};
get_record_struct(2) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{user_id, string},
{use_listing_token, boolean},
{last_name, string},
{last_tree, string},
{execute_slave_on_dir, boolean},
{children_master_jobs_mode, atom},
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary}
]};
get_record_struct(3) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{user_id, string},
{use_listing_token, boolean},
{last_name, string},
{last_tree, string},
{child_dirs_job_generation_policy, atom},
{children_master_jobs_mode, atom},
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary}
]};
get_record_struct(4) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{user_id, string},
{use_listing_token, boolean},
{last_name, string},
{last_tree, string},
{child_dirs_job_generation_policy, atom},
{children_master_jobs_mode, atom},
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary},
{follow_symlinks, boolean},
{relative_path, binary},
{encountered_files, #{string => boolean}}
]};
get_record_struct(5) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{user_id, string},
{use_listing_token, boolean},
{last_name, string},
{last_tree, string},
{child_dirs_job_generation_policy, atom},
{children_master_jobs_mode, atom},
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary},
{relative_path, binary},
{encountered_files, #{string => boolean}}
]};
get_record_struct(6) ->
{record, [
{pool, string},
{callback_module, atom},
{task_id, string},
{doc_id, string},
{user_id, string},
modified field ( renamed from use_listing_token )
{child_dirs_job_generation_policy, atom},
{children_master_jobs_mode, atom},
{track_subtree_status, boolean},
{batch_size, integer},
{traverse_info, binary},
{symlink_resolution_policy, atom},
{resolved_root_uuids, [string]},
{relative_path, binary},
{encountered_files, #{string => boolean}}
]}.
-spec upgrade_record(datastore_model:record_version(), datastore_model:record()) ->
{datastore_model:record_version(), datastore_model:record()}.
upgrade_record(1, {?MODULE, Pool, CallbackModule, TaskId, DocId, LastName, LastTree, ExecuteSlaveOnDir,
BatchSize, TraverseInfo}
) ->
{2, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
?ROOT_USER_ID,
true,
LastName,
LastTree,
ExecuteSlaveOnDir,
sync,
false,
BatchSize,
TraverseInfo
}};
upgrade_record(2, Record) ->
{
?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ExecuteSlaveOnDir,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo
} = Record,
ChildDirsJobGenerationPolicy = case ExecuteSlaveOnDir of
false -> generate_master_jobs;
true -> generate_slave_and_master_jobs
end,
{3, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo
}};
upgrade_record(3, Record) ->
{
?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo
} = Record,
{4, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
false,
<<>>,
#{}
}};
upgrade_record(4, Record) ->
{
?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
FollowSymlinks,
RelativePath,
EncounteredFiles
} = Record,
SymlinkResolutionPolicy = case FollowSymlinks of
true -> follow_external;
false -> preserve
end,
{5, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
RelativePath,
EncounteredFiles
}};
upgrade_record(5, Record) ->
{
?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
UseListingToken,
LastName,
LastTree,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
SymlinkResolutionPolicy,
RootUuids,
RelativePath,
EncounteredFiles
} = Record,
TuneForLargeContinuousListing = UseListingToken,
Index = file_listing:build_index(LastName, LastTree),
{ok, [], ListingPaginationToken} = file_listing:list(<<"dummy_uuid">>, #{
index => Index,
tune_for_large_continuous_listing => TuneForLargeContinuousListing,
limit => 0
}),
{6, {?MODULE,
Pool,
CallbackModule,
TaskId,
DocId,
UserId,
TuneForLargeContinuousListing,
ListingPaginationToken,
ChildDirsJobGenerationPolicy,
ChildrenMasterJobsMode,
TrackSubtreeStatus,
BatchSize,
TraverseInfo,
SymlinkResolutionPolicy,
RootUuids,
RelativePath,
EncounteredFiles
}}.
Internal functions
@private
-spec save(datastore:key() | main_job, datastore_doc:scope(), record(), datastore:ctx()) -> {ok, key()} | {error, term()}.
save(main_job, Scope, Value, ExtendedCtx) ->
RandomPart = datastore_key:new(),
GenKey = <<?MAIN_JOB_PREFIX, RandomPart/binary>>,
Doc = #document{key = GenKey, value = Value},
Doc2 = set_scope_if_sync_enabled(Doc, Scope, ExtendedCtx),
?extract_key(datastore_model:save(ExtendedCtx#{generated_key => true}, Doc2));
save(<<?MAIN_JOB_PREFIX, _/binary>> = Key, Scope, Value, ExtendedCtx) ->
Doc = #document{key = Key, value = Value},
Doc2 = set_scope_if_sync_enabled(Doc, Scope, ExtendedCtx),
?extract_key(datastore_model:save(ExtendedCtx, Doc2));
save(Key, _, Value, _ExtendedCtx) ->
?extract_key(datastore_model:save(?CTX, #document{key = Key, value = Value})).
-spec set_scope_if_sync_enabled(doc(), datastore_doc:scope(), datastore:ctx()) -> doc().
set_scope_if_sync_enabled(Doc, Scope, #{sync_enabled := true}) ->
Doc#document{scope = Scope};
set_scope_if_sync_enabled(Doc, _Scope, _Ctx) ->
Doc.
-spec get_extended_ctx(tree_traverse:master_job(), traverse:callback_module()) -> datastore:ctx().
get_extended_ctx(Job, CallbackModule) ->
{ok, ExtendedCtx} = case erlang:function_exported(CallbackModule, get_sync_info, 1) of
true ->
CallbackModule:get_sync_info(Job);
_ ->
{ok, #{}}
end,
maps:merge(?CTX, ExtendedCtx). |
738e2bff06557b71ae241aee0c23f913d5129a33a5490982b4a25af441472df0 | ghc/testsuite | tc243.hs |
# OPTIONS_GHC -Wall #
module Bug where
-- When we warn about this, we give a warning saying
Inferred type : ( .+ . ) : : forall a. a
-- but we used to not print the parentheses.
(.+.) = undefined
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_compile/tc243.hs | haskell | When we warn about this, we give a warning saying
but we used to not print the parentheses. |
# OPTIONS_GHC -Wall #
module Bug where
Inferred type : ( .+ . ) : : forall a. a
(.+.) = undefined
|
de85e43c090dd15858be2bd27731b14e93679dc3659ea8e90e831bfd0b7cddcf | softlab-ntua/bencherl | soda_integral_loading_test.erl | Copyright ( C ) 2008 - 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca 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 .
Sim - Diasca 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 .
% If not, see </>.
Author : ( )
% Benchmarking case obtained from the soda deterministic example case.
%
% See also:
%
% - class_SodaVendingMachine.erl
%
% - class_DeterministicThirstyCustomer.erl
%
% - soda_benchmarking_test for a counterpart test case, exactly the same except
% that it creates its initial instances programmatically
%
-module(soda_integral_loading_test).
% For all facilities common to all tests:
-include("test_constructs.hrl").
% Runs the test.
%
-spec run() -> no_return().
run() ->
?test_start,
Use default simulation settings ( 50Hz , batch reproducible ):
SimulationSettings = #simulation_settings{
simulation_name = "Sim-Diasca Soda Integral Loading Test",
initialisation_files = [ "soda-integral-loading-test.init" ]
},
DeploymentSettings = #deployment_settings{
computing_hosts = { use_host_file_otherwise_local,
"sim-diasca-host-candidates.txt" },
%node_availability_tolerance = fail_on_unavailable_node,
% We want to embed additionally this test and its specific
% prerequisites, defined in the Mock Simulators, hence we want all the
% code from the current directory, soda-test/src:
%
additional_elements_to_deploy = [ { "..", code } ],
% Note that the configuration file below has not to be declared above as
% well:
%
enable_data_exchanger = { true, [ "soda_parameters.cfg" ] }
},
% Default load balancing settings (round-robin placement heuristic):
LoadBalancingSettings = #load_balancing_settings{},
% A deployment manager is created directly on the user node:
DeploymentManagerPid = sim_diasca:init( SimulationSettings,
DeploymentSettings, LoadBalancingSettings ),
StopTick = 50000,
DeploymentManagerPid ! { getRootTimeManager, [], self() },
RootTimeManagerPid = test_receive(),
?test_info_fmt( "Starting simulation, "
"for a stop at tick offset ~B.", [ StopTick ] ),
RootTimeManagerPid ! { start, [ StopTick, self() ] },
?test_info( "Waiting for the simulation to end, "
"since having been declared as a simulation listener." ),
receive
simulation_stopped ->
?test_info( "Simulation stopped spontaneously, "
"specified stop tick must have been reached." )
end,
?test_info( "Browsing the report results, if in batch mode." ),
class_ResultManager:browse_reports(),
sim_diasca:shutdown(),
?test_stop.
| null | https://raw.githubusercontent.com/softlab-ntua/bencherl/317bdbf348def0b2f9ed32cb6621e21083b7e0ca/app/sim-diasca/mock-simulators/soda-test/src/soda_integral_loading_test.erl | erlang | it under the terms of the GNU Lesser General Public License as
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
If not, see </>.
Benchmarking case obtained from the soda deterministic example case.
See also:
- class_SodaVendingMachine.erl
- class_DeterministicThirstyCustomer.erl
- soda_benchmarking_test for a counterpart test case, exactly the same except
that it creates its initial instances programmatically
For all facilities common to all tests:
Runs the test.
node_availability_tolerance = fail_on_unavailable_node,
We want to embed additionally this test and its specific
prerequisites, defined in the Mock Simulators, hence we want all the
code from the current directory, soda-test/src:
Note that the configuration file below has not to be declared above as
well:
Default load balancing settings (round-robin placement heuristic):
A deployment manager is created directly on the user node: | Copyright ( C ) 2008 - 2014 EDF R&D
This file is part of Sim - Diasca .
Sim - Diasca is free software : you can redistribute it and/or modify
published by the Free Software Foundation , either version 3 of
the License , or ( at your option ) any later version .
Sim - Diasca is distributed in the hope that it will be useful ,
GNU Lesser General Public License for more details .
You should have received a copy of the GNU Lesser General Public
License along with .
Author : ( )
-module(soda_integral_loading_test).
-include("test_constructs.hrl").
-spec run() -> no_return().
run() ->
?test_start,
Use default simulation settings ( 50Hz , batch reproducible ):
SimulationSettings = #simulation_settings{
simulation_name = "Sim-Diasca Soda Integral Loading Test",
initialisation_files = [ "soda-integral-loading-test.init" ]
},
DeploymentSettings = #deployment_settings{
computing_hosts = { use_host_file_otherwise_local,
"sim-diasca-host-candidates.txt" },
additional_elements_to_deploy = [ { "..", code } ],
enable_data_exchanger = { true, [ "soda_parameters.cfg" ] }
},
LoadBalancingSettings = #load_balancing_settings{},
DeploymentManagerPid = sim_diasca:init( SimulationSettings,
DeploymentSettings, LoadBalancingSettings ),
StopTick = 50000,
DeploymentManagerPid ! { getRootTimeManager, [], self() },
RootTimeManagerPid = test_receive(),
?test_info_fmt( "Starting simulation, "
"for a stop at tick offset ~B.", [ StopTick ] ),
RootTimeManagerPid ! { start, [ StopTick, self() ] },
?test_info( "Waiting for the simulation to end, "
"since having been declared as a simulation listener." ),
receive
simulation_stopped ->
?test_info( "Simulation stopped spontaneously, "
"specified stop tick must have been reached." )
end,
?test_info( "Browsing the report results, if in batch mode." ),
class_ResultManager:browse_reports(),
sim_diasca:shutdown(),
?test_stop.
|
5372bb0b79124c74ce86aa1b514e55913000e2ecc9f2e9e06f9f3bccc1b404cb | nd/bird | 6.4.1.hs | nothing other than
height xt <= size xt | null | https://raw.githubusercontent.com/nd/bird/06dba97af7cfb11f558eaeb31a75bd04cacf7201/ch06/6.4.1.hs | haskell | nothing other than
height xt <= size xt | |
b56b4705a96ac570a5ae876cb7e795b688d4fcd2af1eaa311801314a66bae26a | dgtized/shimmers | ring.cljs | (ns shimmers.sketches.ring
(:require
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[shimmers.common.framerate :as framerate]
[shimmers.math.vector :as v]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
(defn setup []
{:theta 0.0})
(defn update-state [state]
(update state :theta + 0.08))
(defn draw [{:keys [theta]}]
(q/background 255 4)
(q/stroke 10 64)
(q/translate (/ (q/width) 2) (/ (q/height) 2))
(let [radial-noise (q/noise (q/cos (/ theta 2)) (q/sin (/ theta 2)))
radius (+ 120 (* (- radial-noise 0.5) 10))
x (* radius (q/cos theta))
y (* radius (q/sin theta))]
(q/stroke-weight (+ 0.8 radial-noise))
(q/line [x y]
(tm/+ (gv/vec2 x y)
(v/polar (* radial-noise 32) (+ theta radial-noise))))))
(sketch/defquil ring
:created-at "2020-12-27"
:size [600 400]
:setup setup
:update update-state
:draw draw
:middleware [m/fun-mode framerate/mode])
| null | https://raw.githubusercontent.com/dgtized/shimmers/f096c20d7ebcb9796c7830efcd7e3f24767a46db/src/shimmers/sketches/ring.cljs | clojure | (ns shimmers.sketches.ring
(:require
[quil.core :as q :include-macros true]
[quil.middleware :as m]
[shimmers.common.framerate :as framerate]
[shimmers.math.vector :as v]
[shimmers.sketch :as sketch :include-macros true]
[thi.ng.geom.vector :as gv]
[thi.ng.math.core :as tm]))
(defn setup []
{:theta 0.0})
(defn update-state [state]
(update state :theta + 0.08))
(defn draw [{:keys [theta]}]
(q/background 255 4)
(q/stroke 10 64)
(q/translate (/ (q/width) 2) (/ (q/height) 2))
(let [radial-noise (q/noise (q/cos (/ theta 2)) (q/sin (/ theta 2)))
radius (+ 120 (* (- radial-noise 0.5) 10))
x (* radius (q/cos theta))
y (* radius (q/sin theta))]
(q/stroke-weight (+ 0.8 radial-noise))
(q/line [x y]
(tm/+ (gv/vec2 x y)
(v/polar (* radial-noise 32) (+ theta radial-noise))))))
(sketch/defquil ring
:created-at "2020-12-27"
:size [600 400]
:setup setup
:update update-state
:draw draw
:middleware [m/fun-mode framerate/mode])
| |
309f6ca6e14ef6e8103402702f7ef4b6bf6b31c26539374cff343ea95e36e1ef | dgiot/dgiot | dgiot_topic.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2017 - 2021 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(dgiot_topic).
%% APIs
-export([ match/2
, validate/1
, validate/2
, levels/1
, tokens/1
, words/1
, wildcard/1
, join/1
, prepend/2
, feed_var/3
, systop/1
, parse/1
, parse/2
]).
-export_type([ group/0
, topic/0
, word/0
]).
-type(group() :: binary()).
-type(topic() :: binary()).
-type(word() :: '' | '+' | '#' | binary()).
-type(words() :: list(word())).
-define(MAX_TOPIC_LEN, 65535).
%%--------------------------------------------------------------------
%% APIs
%%--------------------------------------------------------------------
%% @doc Is wildcard topic?
-spec(wildcard(topic() | words()) -> true | false).
wildcard(Topic) when is_binary(Topic) ->
wildcard(words(Topic));
wildcard([]) ->
false;
wildcard(['#'|_]) ->
true;
wildcard(['+'|_]) ->
true;
wildcard([_H|T]) ->
wildcard(T).
%% @doc Match Topic name with filter.
-spec(match(Name, Filter) -> boolean() when
Name :: topic() | words(),
Filter :: topic() | words()).
match(<<$$, _/binary>>, <<$+, _/binary>>) ->
false;
match(<<$$, _/binary>>, <<$#, _/binary>>) ->
false;
match(Name, Filter) when is_binary(Name), is_binary(Filter) ->
match(words(Name), words(Filter));
match([], []) ->
true;
match([H|T1], [H|T2]) ->
match(T1, T2);
match([_H|T1], ['+'|T2]) ->
match(T1, T2);
match(_, ['#']) ->
true;
match([_H1|_], [_H2|_]) ->
false;
match([_H1|_], []) ->
false;
match([], [_H|_T2]) ->
false.
@doc Validate topic name or filter
-spec(validate(topic() | {name | filter, topic()}) -> true).
validate(Topic) when is_binary(Topic) ->
validate(filter, Topic);
validate({Type, Topic}) when Type =:= name; Type =:= filter ->
validate(Type, Topic).
-spec(validate(name | filter, topic()) -> true).
validate(_, <<>>) ->
error(empty_topic);
validate(_, Topic) when is_binary(Topic) andalso (size(Topic) > ?MAX_TOPIC_LEN) ->
error(topic_too_long);
validate(filter, Topic) when is_binary(Topic) ->
validate2(words(Topic));
validate(name, Topic) when is_binary(Topic) ->
Words = words(Topic),
validate2(Words)
andalso (not wildcard(Words))
orelse error(topic_name_error).
validate2([]) ->
true;
validate2(['#']) -> % end with '#'
true;
validate2(['#'|Words]) when length(Words) > 0 ->
error('topic_invalid_#');
validate2([''|Words]) ->
validate2(Words);
validate2(['+'|Words]) ->
validate2(Words);
validate2([W|Words]) ->
validate3(W) andalso validate2(Words).
validate3(<<>>) ->
true;
validate3(<<C/utf8, _Rest/binary>>) when C == $#; C == $+; C == 0 ->
error('topic_invalid_char');
validate3(<<_/utf8, Rest/binary>>) ->
validate3(Rest).
%% @doc Prepend a topic prefix.
Ensured to have only one / between prefix and suffix .
prepend(undefined, W) -> bin(W);
prepend(<<>>, W) -> bin(W);
prepend(Parent0, W) ->
Parent = bin(Parent0),
case binary:last(Parent) of
$/ -> <<Parent/binary, (bin(W))/binary>>;
_ -> <<Parent/binary, $/, (bin(W))/binary>>
end.
bin('') -> <<>>;
bin('+') -> <<"+">>;
bin('#') -> <<"#">>;
bin(B) when is_binary(B) -> B;
bin(L) when is_list(L) -> list_to_binary(L).
-spec(levels(topic()) -> pos_integer()).
levels(Topic) when is_binary(Topic) ->
length(tokens(Topic)).
-compile({inline, [tokens/1]}).
%% @doc Split topic to tokens.
-spec(tokens(topic()) -> list(binary())).
tokens(Topic) ->
binary:split(Topic, <<"/">>, [global]).
@doc Split Topic Path to Words
-spec(words(topic()) -> words()).
words(Topic) when is_binary(Topic) ->
[word(W) || W <- tokens(Topic)].
word(<<>>) -> '';
word(<<"+">>) -> '+';
word(<<"#">>) -> '#';
word(Bin) -> Bin.
%% @doc '$SYS' Topic.
-spec(systop(atom()|string()|binary()) -> topic()).
systop(Name) when is_atom(Name); is_list(Name) ->
iolist_to_binary(lists:concat(["$SYS/brokers/", node(), "/", Name]));
systop(Name) when is_binary(Name) ->
iolist_to_binary(["$SYS/brokers/", atom_to_list(node()), "/", Name]).
-spec(feed_var(binary(), binary(), binary()) -> binary()).
feed_var(Var, Val, Topic) ->
feed_var(Var, Val, words(Topic), []).
feed_var(_Var, _Val, [], Acc) ->
join(lists:reverse(Acc));
feed_var(Var, Val, [Var|Words], Acc) ->
feed_var(Var, Val, Words, [Val|Acc]);
feed_var(Var, Val, [W|Words], Acc) ->
feed_var(Var, Val, Words, [W|Acc]).
-spec(join(list(binary())) -> binary()).
join([]) ->
<<>>;
join([W]) ->
bin(W);
join(Words) ->
{_, Bin} = lists:foldr(
fun(W, {true, Tail}) ->
{false, <<W/binary, Tail/binary>>};
(W, {false, Tail}) ->
{false, <<W/binary, "/", Tail/binary>>}
end, {true, <<>>}, [bin(W) || W <- Words]),
Bin.
-spec(parse(topic() | {topic(), map()}) -> {topic(), #{share => binary()}}).
parse(TopicFilter) when is_binary(TopicFilter) ->
parse(TopicFilter, #{});
parse({TopicFilter, Options}) when is_binary(TopicFilter) ->
parse(TopicFilter, Options).
-spec(parse(topic(), map()) -> {topic(), map()}).
parse(TopicFilter = <<"$queue/", _/binary>>, #{share := _Group}) ->
error({invalid_topic_filter, TopicFilter});
parse(TopicFilter = <<"$share/", _/binary>>, #{share := _Group}) ->
error({invalid_topic_filter, TopicFilter});
parse(<<"$queue/", TopicFilter/binary>>, Options) ->
parse(TopicFilter, Options#{share => <<"$queue">>});
parse(TopicFilter = <<"$share/", Rest/binary>>, Options) ->
case binary:split(Rest, <<"/">>) of
[_Any] -> error({invalid_topic_filter, TopicFilter});
[ShareName, Filter] ->
case binary:match(ShareName, [<<"+">>, <<"#">>]) of
nomatch -> parse(Filter, Options#{share => ShareName});
_ -> error({invalid_topic_filter, TopicFilter})
end
end;
parse(TopicFilter, Options) ->
{TopicFilter, Options}.
| null | https://raw.githubusercontent.com/dgiot/dgiot/777c878acd0c89e445c3b8992febbc925b8ee060/apps/dgiot/src/utils/dgiot_topic.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--------------------------------------------------------------------
APIs
--------------------------------------------------------------------
APIs
--------------------------------------------------------------------
@doc Is wildcard topic?
@doc Match Topic name with filter.
end with '#'
@doc Prepend a topic prefix.
@doc Split topic to tokens.
@doc '$SYS' Topic. | Copyright ( c ) 2017 - 2021 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(dgiot_topic).
-export([ match/2
, validate/1
, validate/2
, levels/1
, tokens/1
, words/1
, wildcard/1
, join/1
, prepend/2
, feed_var/3
, systop/1
, parse/1
, parse/2
]).
-export_type([ group/0
, topic/0
, word/0
]).
-type(group() :: binary()).
-type(topic() :: binary()).
-type(word() :: '' | '+' | '#' | binary()).
-type(words() :: list(word())).
-define(MAX_TOPIC_LEN, 65535).
-spec(wildcard(topic() | words()) -> true | false).
wildcard(Topic) when is_binary(Topic) ->
wildcard(words(Topic));
wildcard([]) ->
false;
wildcard(['#'|_]) ->
true;
wildcard(['+'|_]) ->
true;
wildcard([_H|T]) ->
wildcard(T).
-spec(match(Name, Filter) -> boolean() when
Name :: topic() | words(),
Filter :: topic() | words()).
match(<<$$, _/binary>>, <<$+, _/binary>>) ->
false;
match(<<$$, _/binary>>, <<$#, _/binary>>) ->
false;
match(Name, Filter) when is_binary(Name), is_binary(Filter) ->
match(words(Name), words(Filter));
match([], []) ->
true;
match([H|T1], [H|T2]) ->
match(T1, T2);
match([_H|T1], ['+'|T2]) ->
match(T1, T2);
match(_, ['#']) ->
true;
match([_H1|_], [_H2|_]) ->
false;
match([_H1|_], []) ->
false;
match([], [_H|_T2]) ->
false.
@doc Validate topic name or filter
-spec(validate(topic() | {name | filter, topic()}) -> true).
validate(Topic) when is_binary(Topic) ->
validate(filter, Topic);
validate({Type, Topic}) when Type =:= name; Type =:= filter ->
validate(Type, Topic).
-spec(validate(name | filter, topic()) -> true).
validate(_, <<>>) ->
error(empty_topic);
validate(_, Topic) when is_binary(Topic) andalso (size(Topic) > ?MAX_TOPIC_LEN) ->
error(topic_too_long);
validate(filter, Topic) when is_binary(Topic) ->
validate2(words(Topic));
validate(name, Topic) when is_binary(Topic) ->
Words = words(Topic),
validate2(Words)
andalso (not wildcard(Words))
orelse error(topic_name_error).
validate2([]) ->
true;
true;
validate2(['#'|Words]) when length(Words) > 0 ->
error('topic_invalid_#');
validate2([''|Words]) ->
validate2(Words);
validate2(['+'|Words]) ->
validate2(Words);
validate2([W|Words]) ->
validate3(W) andalso validate2(Words).
validate3(<<>>) ->
true;
validate3(<<C/utf8, _Rest/binary>>) when C == $#; C == $+; C == 0 ->
error('topic_invalid_char');
validate3(<<_/utf8, Rest/binary>>) ->
validate3(Rest).
Ensured to have only one / between prefix and suffix .
prepend(undefined, W) -> bin(W);
prepend(<<>>, W) -> bin(W);
prepend(Parent0, W) ->
Parent = bin(Parent0),
case binary:last(Parent) of
$/ -> <<Parent/binary, (bin(W))/binary>>;
_ -> <<Parent/binary, $/, (bin(W))/binary>>
end.
bin('') -> <<>>;
bin('+') -> <<"+">>;
bin('#') -> <<"#">>;
bin(B) when is_binary(B) -> B;
bin(L) when is_list(L) -> list_to_binary(L).
-spec(levels(topic()) -> pos_integer()).
levels(Topic) when is_binary(Topic) ->
length(tokens(Topic)).
-compile({inline, [tokens/1]}).
-spec(tokens(topic()) -> list(binary())).
tokens(Topic) ->
binary:split(Topic, <<"/">>, [global]).
@doc Split Topic Path to Words
-spec(words(topic()) -> words()).
words(Topic) when is_binary(Topic) ->
[word(W) || W <- tokens(Topic)].
word(<<>>) -> '';
word(<<"+">>) -> '+';
word(<<"#">>) -> '#';
word(Bin) -> Bin.
-spec(systop(atom()|string()|binary()) -> topic()).
systop(Name) when is_atom(Name); is_list(Name) ->
iolist_to_binary(lists:concat(["$SYS/brokers/", node(), "/", Name]));
systop(Name) when is_binary(Name) ->
iolist_to_binary(["$SYS/brokers/", atom_to_list(node()), "/", Name]).
-spec(feed_var(binary(), binary(), binary()) -> binary()).
feed_var(Var, Val, Topic) ->
feed_var(Var, Val, words(Topic), []).
feed_var(_Var, _Val, [], Acc) ->
join(lists:reverse(Acc));
feed_var(Var, Val, [Var|Words], Acc) ->
feed_var(Var, Val, Words, [Val|Acc]);
feed_var(Var, Val, [W|Words], Acc) ->
feed_var(Var, Val, Words, [W|Acc]).
-spec(join(list(binary())) -> binary()).
join([]) ->
<<>>;
join([W]) ->
bin(W);
join(Words) ->
{_, Bin} = lists:foldr(
fun(W, {true, Tail}) ->
{false, <<W/binary, Tail/binary>>};
(W, {false, Tail}) ->
{false, <<W/binary, "/", Tail/binary>>}
end, {true, <<>>}, [bin(W) || W <- Words]),
Bin.
-spec(parse(topic() | {topic(), map()}) -> {topic(), #{share => binary()}}).
parse(TopicFilter) when is_binary(TopicFilter) ->
parse(TopicFilter, #{});
parse({TopicFilter, Options}) when is_binary(TopicFilter) ->
parse(TopicFilter, Options).
-spec(parse(topic(), map()) -> {topic(), map()}).
parse(TopicFilter = <<"$queue/", _/binary>>, #{share := _Group}) ->
error({invalid_topic_filter, TopicFilter});
parse(TopicFilter = <<"$share/", _/binary>>, #{share := _Group}) ->
error({invalid_topic_filter, TopicFilter});
parse(<<"$queue/", TopicFilter/binary>>, Options) ->
parse(TopicFilter, Options#{share => <<"$queue">>});
parse(TopicFilter = <<"$share/", Rest/binary>>, Options) ->
case binary:split(Rest, <<"/">>) of
[_Any] -> error({invalid_topic_filter, TopicFilter});
[ShareName, Filter] ->
case binary:match(ShareName, [<<"+">>, <<"#">>]) of
nomatch -> parse(Filter, Options#{share => ShareName});
_ -> error({invalid_topic_filter, TopicFilter})
end
end;
parse(TopicFilter, Options) ->
{TopicFilter, Options}.
|
af6e70a34d64101a6f55bf524f5d042063095f1aa2db27d6f62a67bc011c68c0 | B-Lang-org/bsc | GlobPattern.hs | module GlobPattern (parseGlobPattern, matchGlobPattern, getGlobErr,
GlobPattern) where
import Control.Monad(msum)
import Data.List(isPrefixOf, tails)
-- import Debug.Trace
data CharClass = CharRange Char Char
| CharList [Char]
| BadCharClass String
deriving (Eq)
instance Show CharClass where
show (CharRange lo hi) = [lo,'-',hi]
show (CharList cs) = cs
show (BadCharClass s) = "<BADCHARCLASS: " ++ s ++ ">"
data GlobPattern = GlobEnd
| GlobMatch String GlobPattern
| GlobOneChar GlobPattern
| GlobAnyChars GlobPattern
| GlobOneOf [CharClass] GlobPattern
| GlobNotOneOf [CharClass] GlobPattern
| GlobBadPattern String
deriving (Eq)
instance Show GlobPattern where
show GlobEnd = ""
show (GlobMatch s p) = s ++ (show p)
show (GlobOneChar p) = "?" ++ (show p)
show (GlobAnyChars p) = "*" ++ (show p)
show (GlobOneOf cs p) = "[" ++ (concatMap show cs) ++ "]" ++ (show p)
show (GlobNotOneOf cs p) = "[!" ++ (concatMap show cs) ++ "]" ++ (show p)
show (GlobBadPattern s) = "<BADPATTERN: " ++ s ++ ">"
globSeparator :: Char
globSeparator = '.'
Parse a string into a GlobPattern
parseGlobPattern :: String -> GlobPattern
parseGlobPattern "" = GlobEnd
parseGlobPattern ('*':rest) = GlobAnyChars (parseGlobPattern rest)
parseGlobPattern ('?':rest) = GlobOneChar (parseGlobPattern rest)
parseGlobPattern ('[':'!':rest) =
let (cs,xs) = parseCharClasses rest
in case (msum (map getClassErr cs)) of
(Just err) -> GlobBadPattern err
Nothing -> GlobNotOneOf cs (parseGlobPattern xs)
parseGlobPattern ('[':rest) =
let (cs,xs) = parseCharClasses rest
in case (msum (map getClassErr cs)) of
(Just err) -> GlobBadPattern err
Nothing -> GlobOneOf cs (parseGlobPattern xs)
parseGlobPattern ['\\'] = GlobBadPattern $ "escape character ends pattern"
parseGlobPattern ('\\':c:rest) =
if (c == globSeparator)
then GlobBadPattern $ "illegal escaped separator character at '" ++ (c:rest) ++ "'"
else GlobMatch [c] (parseGlobPattern rest)
parseGlobPattern s =
let (exact,rest) = break (`elem` (globSeparator:"*?[\\")) s
in if ([globSeparator] `isPrefixOf` exact)
then GlobBadPattern $ "illegal separator character at '" ++ exact ++ "'"
else GlobMatch exact (parseGlobPattern rest)
Parse character class specifications
parseCharClasses :: String -> ([CharClass],String)
parseCharClasses "" = ([BadCharClass "no terminating ']'"],"")
parseCharClasses (x:s) =
let (xs,rest) = break (== ']') s
in if (null rest)
then ([BadCharClass "no terminating ']'"],"")
else (parseCC (x:xs), tail rest)
where parseCC "" = []
parseCC (c1:'-':c2:rest) = (CharRange c1 c2):(parseCC rest)
parseCC ('-':rest) = (CharList ['-']) `combineCC` (parseCC rest)
parseCC [c] = [CharList [c]]
parseCC s = let (first,rest) = break (== '-') s
in (CharList (init first)) `combineCC` (parseCC ((last first):rest))
combineCC (CharList []) xs = xs
combineCC (CharList xs) ((CharList ys):cs) = (CharList (xs ++ ys)):cs
combineCC x xs = x:xs
-- Test if a pattern contains GlobBadPattern
getGlobErr :: GlobPattern -> Maybe String
getGlobErr GlobEnd = Nothing
getGlobErr (GlobMatch _ p) = getGlobErr p
getGlobErr (GlobOneChar p) = getGlobErr p
getGlobErr (GlobAnyChars p) = getGlobErr p
getGlobErr (GlobOneOf _ p) = getGlobErr p
getGlobErr (GlobNotOneOf _ p) = getGlobErr p
getGlobErr (GlobBadPattern s) = Just s
Test if a character class is a BadCharClass
getClassErr :: CharClass -> Maybe String
getClassErr (BadCharClass s) = Just s
getClassErr _ = Nothing
-- Test is a character is in a class
classContains :: CharClass -> Char -> Bool
classContains (CharRange lo hi) c = (c >= lo) && (c <= hi)
classContains (CharList cs) c = c `elem` cs
classContains (BadCharClass _) _ = False
-- Match a string against a glob pattern
matchGlobPattern :: GlobPattern -> String -> Bool
matchGlobPattern GlobEnd s = null s
matchGlobPattern (GlobMatch m p) s =
if (m `isPrefixOf` s)
then matchGlobPattern p (drop (length m) s)
else False
matchGlobPattern (GlobOneChar p) [] = False
matchGlobPattern (GlobOneChar p) (_:s) = matchGlobPattern p s
matchGlobPattern (GlobAnyChars p) s =
let (s',rest) = break ( == globSeparator) s
in any (matchGlobPattern p) (map (++ rest) (tails s'))
matchGlobPattern (GlobOneOf xs p) [] = False
matchGlobPattern (GlobOneOf xs p) (c:s) = if (any (`classContains` c) xs)
then matchGlobPattern p s
else False
matchGlobPattern (GlobNotOneOf xs p) [] = False
matchGlobPattern (GlobNotOneOf xs p) (c:s) = if (any (`classContains` c) xs)
then False
else matchGlobPattern p s
matchGlobPattern (GlobBadPattern _) _ = False
| null | https://raw.githubusercontent.com/B-Lang-org/bsc/bd141b505394edc5a4bdd3db442a9b0a8c101f0f/src/comp/GlobPattern.hs | haskell | import Debug.Trace
Test if a pattern contains GlobBadPattern
Test is a character is in a class
Match a string against a glob pattern | module GlobPattern (parseGlobPattern, matchGlobPattern, getGlobErr,
GlobPattern) where
import Control.Monad(msum)
import Data.List(isPrefixOf, tails)
data CharClass = CharRange Char Char
| CharList [Char]
| BadCharClass String
deriving (Eq)
instance Show CharClass where
show (CharRange lo hi) = [lo,'-',hi]
show (CharList cs) = cs
show (BadCharClass s) = "<BADCHARCLASS: " ++ s ++ ">"
data GlobPattern = GlobEnd
| GlobMatch String GlobPattern
| GlobOneChar GlobPattern
| GlobAnyChars GlobPattern
| GlobOneOf [CharClass] GlobPattern
| GlobNotOneOf [CharClass] GlobPattern
| GlobBadPattern String
deriving (Eq)
instance Show GlobPattern where
show GlobEnd = ""
show (GlobMatch s p) = s ++ (show p)
show (GlobOneChar p) = "?" ++ (show p)
show (GlobAnyChars p) = "*" ++ (show p)
show (GlobOneOf cs p) = "[" ++ (concatMap show cs) ++ "]" ++ (show p)
show (GlobNotOneOf cs p) = "[!" ++ (concatMap show cs) ++ "]" ++ (show p)
show (GlobBadPattern s) = "<BADPATTERN: " ++ s ++ ">"
globSeparator :: Char
globSeparator = '.'
Parse a string into a GlobPattern
parseGlobPattern :: String -> GlobPattern
parseGlobPattern "" = GlobEnd
parseGlobPattern ('*':rest) = GlobAnyChars (parseGlobPattern rest)
parseGlobPattern ('?':rest) = GlobOneChar (parseGlobPattern rest)
parseGlobPattern ('[':'!':rest) =
let (cs,xs) = parseCharClasses rest
in case (msum (map getClassErr cs)) of
(Just err) -> GlobBadPattern err
Nothing -> GlobNotOneOf cs (parseGlobPattern xs)
parseGlobPattern ('[':rest) =
let (cs,xs) = parseCharClasses rest
in case (msum (map getClassErr cs)) of
(Just err) -> GlobBadPattern err
Nothing -> GlobOneOf cs (parseGlobPattern xs)
parseGlobPattern ['\\'] = GlobBadPattern $ "escape character ends pattern"
parseGlobPattern ('\\':c:rest) =
if (c == globSeparator)
then GlobBadPattern $ "illegal escaped separator character at '" ++ (c:rest) ++ "'"
else GlobMatch [c] (parseGlobPattern rest)
parseGlobPattern s =
let (exact,rest) = break (`elem` (globSeparator:"*?[\\")) s
in if ([globSeparator] `isPrefixOf` exact)
then GlobBadPattern $ "illegal separator character at '" ++ exact ++ "'"
else GlobMatch exact (parseGlobPattern rest)
Parse character class specifications
parseCharClasses :: String -> ([CharClass],String)
parseCharClasses "" = ([BadCharClass "no terminating ']'"],"")
parseCharClasses (x:s) =
let (xs,rest) = break (== ']') s
in if (null rest)
then ([BadCharClass "no terminating ']'"],"")
else (parseCC (x:xs), tail rest)
where parseCC "" = []
parseCC (c1:'-':c2:rest) = (CharRange c1 c2):(parseCC rest)
parseCC ('-':rest) = (CharList ['-']) `combineCC` (parseCC rest)
parseCC [c] = [CharList [c]]
parseCC s = let (first,rest) = break (== '-') s
in (CharList (init first)) `combineCC` (parseCC ((last first):rest))
combineCC (CharList []) xs = xs
combineCC (CharList xs) ((CharList ys):cs) = (CharList (xs ++ ys)):cs
combineCC x xs = x:xs
getGlobErr :: GlobPattern -> Maybe String
getGlobErr GlobEnd = Nothing
getGlobErr (GlobMatch _ p) = getGlobErr p
getGlobErr (GlobOneChar p) = getGlobErr p
getGlobErr (GlobAnyChars p) = getGlobErr p
getGlobErr (GlobOneOf _ p) = getGlobErr p
getGlobErr (GlobNotOneOf _ p) = getGlobErr p
getGlobErr (GlobBadPattern s) = Just s
Test if a character class is a BadCharClass
getClassErr :: CharClass -> Maybe String
getClassErr (BadCharClass s) = Just s
getClassErr _ = Nothing
classContains :: CharClass -> Char -> Bool
classContains (CharRange lo hi) c = (c >= lo) && (c <= hi)
classContains (CharList cs) c = c `elem` cs
classContains (BadCharClass _) _ = False
matchGlobPattern :: GlobPattern -> String -> Bool
matchGlobPattern GlobEnd s = null s
matchGlobPattern (GlobMatch m p) s =
if (m `isPrefixOf` s)
then matchGlobPattern p (drop (length m) s)
else False
matchGlobPattern (GlobOneChar p) [] = False
matchGlobPattern (GlobOneChar p) (_:s) = matchGlobPattern p s
matchGlobPattern (GlobAnyChars p) s =
let (s',rest) = break ( == globSeparator) s
in any (matchGlobPattern p) (map (++ rest) (tails s'))
matchGlobPattern (GlobOneOf xs p) [] = False
matchGlobPattern (GlobOneOf xs p) (c:s) = if (any (`classContains` c) xs)
then matchGlobPattern p s
else False
matchGlobPattern (GlobNotOneOf xs p) [] = False
matchGlobPattern (GlobNotOneOf xs p) (c:s) = if (any (`classContains` c) xs)
then False
else matchGlobPattern p s
matchGlobPattern (GlobBadPattern _) _ = False
|
7b7dbefa9bf1a14c8d0bb4124087c9333f27282e9958aedf069a96fb9555fb0e | pa-ba/compdata | Multi_Test.hs | module Data.Comp.Multi_Test where
import Test.Framework
import qualified Data.Comp.Multi.Variables_Test
--------------------------------------------------------------------------------
-- Test Suits
--------------------------------------------------------------------------------
main = defaultMain [tests]
tests = testGroup "Multi" [
Data.Comp.Multi.Variables_Test.tests
]
--------------------------------------------------------------------------------
-- Properties
-------------------------------------------------------------------------------- | null | https://raw.githubusercontent.com/pa-ba/compdata/5783d0e11129097e045cabba61643114b154e3f2/testsuite/tests/Data/Comp/Multi_Test.hs | haskell | ------------------------------------------------------------------------------
Test Suits
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Properties
------------------------------------------------------------------------------ | module Data.Comp.Multi_Test where
import Test.Framework
import qualified Data.Comp.Multi.Variables_Test
main = defaultMain [tests]
tests = testGroup "Multi" [
Data.Comp.Multi.Variables_Test.tests
]
|
3fa2da9d75c56512601809059263ae94330916ea2aed7e6013d905ad125e22f2 | Shirakumo/kandria | package.lisp | (defpackage #:org.shirakumo.fraf.kandria.fish)
(defpackage #:org.shirakumo.fraf.kandria.item)
(defpackage #:kandria
(:nicknames #:org.shirakumo.fraf.kandria)
(:use #:cl+trial)
(:shadow #:main #:launch #:tile #:block
#:located-entity #:sized-entity #:sprite-entity
#:camera #:light #:shadow-map-pass #:tile-data
#:shadow-render-pass #:action #:editor-camera
#:animatable #:sprite-data #:sprite-animation
#:commit #:prompt #:in-view-p #:layer #:*modules*)
(:local-nicknames
(#:fish #:org.shirakumo.fraf.kandria.fish)
(#:item #:org.shirakumo.fraf.kandria.item)
(#:dialogue #:org.shirakumo.fraf.speechless)
(#:quest #:org.shirakumo.fraf.kandria.quest)
(#:alloy #:org.shirakumo.alloy)
(#:trial-alloy #:org.shirakumo.fraf.trial.alloy)
(#:simple #:org.shirakumo.alloy.renderers.simple)
(#:presentations #:org.shirakumo.alloy.renderers.simple.presentations)
(#:opengl #:org.shirakumo.alloy.renderers.opengl)
(#:colored #:org.shirakumo.alloy.colored)
(#:colors #:org.shirakumo.alloy.colored.colors)
(#:animation #:org.shirakumo.alloy.animation)
(#:file-select #:org.shirakumo.file-select)
(#:gamepad #:org.shirakumo.fraf.gamepad)
(#:harmony #:org.shirakumo.fraf.harmony.user)
(#:trial-harmony #:org.shirakumo.fraf.trial.harmony)
(#:mixed #:org.shirakumo.fraf.mixed)
(#:steam #:org.shirakumo.fraf.steamworks)
(#:steam* #:org.shirakumo.fraf.steamworks.cffi)
(#:notify #:org.shirakumo.fraf.trial.notify)
(#:bvh #:org.shirakumo.fraf.trial.bvh2)
(#:markless #:org.shirakumo.markless)
(#:components #:org.shirakumo.markless.components)
(#:depot #:org.shirakumo.depot)
(#:action-list #:org.shirakumo.fraf.action-list)
(#:sequences #:org.shirakumo.trivial-extensible-sequences)
(#:filesystem-utils #:org.shirakumo.filesystem-utils)
(#:promise #:org.shirakumo.promise)
(#:modio #:org.shirakumo.fraf.modio))
(:export
#:launch)
;; ui/general.lisp
(:export
#:show
#:show-panel)
;; ui/popup.lisp
(:export
#:info-panel)
;; module.lisp
(:export
#:module
#:name
#:title
#:version
#:author
#:description
#:upstream
#:preview
#:module-root
#:module-package
#:list-worlds
#:list-modules
#:load-module
#:find-module
#:define-module
#:register-worlds)
;; world.lisp
(:export
#:+world+
#:world-loaded))
| null | https://raw.githubusercontent.com/Shirakumo/kandria/26b88c6963b2d2e3457628abbee44604cf11c7db/package.lisp | lisp | ui/general.lisp
ui/popup.lisp
module.lisp
world.lisp | (defpackage #:org.shirakumo.fraf.kandria.fish)
(defpackage #:org.shirakumo.fraf.kandria.item)
(defpackage #:kandria
(:nicknames #:org.shirakumo.fraf.kandria)
(:use #:cl+trial)
(:shadow #:main #:launch #:tile #:block
#:located-entity #:sized-entity #:sprite-entity
#:camera #:light #:shadow-map-pass #:tile-data
#:shadow-render-pass #:action #:editor-camera
#:animatable #:sprite-data #:sprite-animation
#:commit #:prompt #:in-view-p #:layer #:*modules*)
(:local-nicknames
(#:fish #:org.shirakumo.fraf.kandria.fish)
(#:item #:org.shirakumo.fraf.kandria.item)
(#:dialogue #:org.shirakumo.fraf.speechless)
(#:quest #:org.shirakumo.fraf.kandria.quest)
(#:alloy #:org.shirakumo.alloy)
(#:trial-alloy #:org.shirakumo.fraf.trial.alloy)
(#:simple #:org.shirakumo.alloy.renderers.simple)
(#:presentations #:org.shirakumo.alloy.renderers.simple.presentations)
(#:opengl #:org.shirakumo.alloy.renderers.opengl)
(#:colored #:org.shirakumo.alloy.colored)
(#:colors #:org.shirakumo.alloy.colored.colors)
(#:animation #:org.shirakumo.alloy.animation)
(#:file-select #:org.shirakumo.file-select)
(#:gamepad #:org.shirakumo.fraf.gamepad)
(#:harmony #:org.shirakumo.fraf.harmony.user)
(#:trial-harmony #:org.shirakumo.fraf.trial.harmony)
(#:mixed #:org.shirakumo.fraf.mixed)
(#:steam #:org.shirakumo.fraf.steamworks)
(#:steam* #:org.shirakumo.fraf.steamworks.cffi)
(#:notify #:org.shirakumo.fraf.trial.notify)
(#:bvh #:org.shirakumo.fraf.trial.bvh2)
(#:markless #:org.shirakumo.markless)
(#:components #:org.shirakumo.markless.components)
(#:depot #:org.shirakumo.depot)
(#:action-list #:org.shirakumo.fraf.action-list)
(#:sequences #:org.shirakumo.trivial-extensible-sequences)
(#:filesystem-utils #:org.shirakumo.filesystem-utils)
(#:promise #:org.shirakumo.promise)
(#:modio #:org.shirakumo.fraf.modio))
(:export
#:launch)
(:export
#:show
#:show-panel)
(:export
#:info-panel)
(:export
#:module
#:name
#:title
#:version
#:author
#:description
#:upstream
#:preview
#:module-root
#:module-package
#:list-worlds
#:list-modules
#:load-module
#:find-module
#:define-module
#:register-worlds)
(:export
#:+world+
#:world-loaded))
|
234f8bee8af69bcd728f1fcd1855837b26635f74509c94aba5db68b9eb0fd0a1 | egonSchiele/dominion | Original.hs | module Dominion.Cards.Original (
-- | Playing a card is easy:
--
-- > playerId `plays` adventurer
module Dominion.Cards.Original
) where
import Dominion.Types
adventurer = Card "Adventurer" 6 [Action] [AdventurerEffect]
bureaucrat = Card "Bureaucrat" 4 [Action, Attack] [BureaucratEffect]
-- |
-- > playerId `plays` cellar `with` (Cellar [list of cards to discard])
cellar = Card "Cellar" 2 [Action] [PlusAction 1, CellarEffect]
-- > To move your deck into the discard pile:
--
-- > playerId `plays` chancellor `with` (Chancellor True)
--
-- If you don't want to, you don't have to use the followup action at all:
--
-- > playerId `plays` chancellor
chancellor = Card "Chancellor" 3 [Action] [PlusCoin 2, ChancellorEffect]
-- |
-- > playerId `plays` chapel `with` (Chapel [list of cards to trash])
chapel = Card "Chapel" 2 [Action] [TrashCards 4]
councilRoom = Card "Council Room" 5 [Action] [PlusCard 4, PlusBuy 1, OthersPlusCard 1]
-- | To gain a market, for example:
--
-- > playerId `plays` feast `with` (Feast market)
feast = Card "Feast" 4 [Action] [TrashThisCard, GainCardUpto 5]
festival = Card "Festival" 5 [Action] [PlusAction 2, PlusCoin 2, PlusBuy 1]
laboratory = Card "Laboratory" 5 [Action] [PlusCard 2, PlusAction 1]
library = Card "Library" 5 [Action] [LibraryEffect]
market = Card "Market" 5 [Action] [PlusAction 1, PlusCoin 1, PlusCard 1, PlusBuy 1]
militia = Card "Militia" 4 [Action, Attack] [PlusCoin 2, OthersDiscardTo 3]
-- |
-- > playerId `plays` mine `with` (Mine copper)
mine = Card "Mine" 5 [Action] [MineEffect]
moat = Card "Moat" 2 [Action, Reaction] [PlusCard 2]
moneylender = Card "Moneylender" 4 [Action] [MoneylenderEffect]
-- | To turn a gold into a province:
--
-- > playerId `plays` remodel `with` (Remodel (gold, province))
remodel = Card "Remodel" 4 [Action] [RemodelEffect]
smithy = Card "Smithy" 4 [Action] [PlusCard 3]
| The ` Spy ` ` FollowupAction ` takes two lists : a list of cards you would
-- discard for yourself, and a list of cards you would discard for others:
--
-- > playerId `plays` spy `with` ([estate, duchy, province], [silver, gold])
spy = Card "Spy" 4 [Action, Attack] [PlusCard 1, PlusAction 1, SpyEffect]
-- gets a list of the treasure cards that the player
had . You return either TrashOnly to have the player
-- trash a card, or GainTrashedCard to gain the trashed
-- card.
-- | You need to provide a function that takes a list of treasure cards and
picks one to trash . You can either return a ` TrashOnly ` to trash the
-- card, or a `GainTrashedCard` to put it into your discard pile.
--
> playerId ` plays ` thief ` with ` ( Thief ( GainTrashedCard . ( comparing coinValue ) ) )
thief = Card "Thief" 4 [Action, Attack] [ThiefEffect]
-- |
> playerId ` plays ` throneRoom ` with ` ( ThroneRoom market )
throneRoom = Card "Throne Room" 4 [Action] [PlayActionCard 2]
village = Card "Village" 3 [Action] [PlusCard 1, PlusAction 2]
witch = Card "Witch" 5 [Action, Attack] [PlusCard 2, OthersGainCurse 1]
woodcutter = Card "Woodcutter" 3 [Action] [PlusCoin 2, PlusBuy 1]
-- |
-- > playerId `plays` workshop `with` (Workshop gardens)
workshop = Card "Workshop" 3 [Action] [GainCardUpto 4]
gardens = Card "Gardens" 4 [Victory] [GardensEffect]
-- All the action cards from the original game.
originalCards = [adventurer ,
bureaucrat ,
cellar ,
chancellor ,
chapel ,
councilRoom,
feast ,
festival ,
laboratory ,
library ,
market ,
militia ,
mine ,
moat ,
moneylender,
remodel ,
smithy ,
spy ,
thief ,
throneRoom ,
village ,
witch ,
woodcutter ,
workshop ,
gardens ]
| null | https://raw.githubusercontent.com/egonSchiele/dominion/a4b7300f2e445da5e7cfcc1cf9029243a3561ed6/src/Dominion/Cards/Original.hs | haskell | | Playing a card is easy:
> playerId `plays` adventurer
|
> playerId `plays` cellar `with` (Cellar [list of cards to discard])
> To move your deck into the discard pile:
> playerId `plays` chancellor `with` (Chancellor True)
If you don't want to, you don't have to use the followup action at all:
> playerId `plays` chancellor
|
> playerId `plays` chapel `with` (Chapel [list of cards to trash])
| To gain a market, for example:
> playerId `plays` feast `with` (Feast market)
|
> playerId `plays` mine `with` (Mine copper)
| To turn a gold into a province:
> playerId `plays` remodel `with` (Remodel (gold, province))
discard for yourself, and a list of cards you would discard for others:
> playerId `plays` spy `with` ([estate, duchy, province], [silver, gold])
gets a list of the treasure cards that the player
trash a card, or GainTrashedCard to gain the trashed
card.
| You need to provide a function that takes a list of treasure cards and
card, or a `GainTrashedCard` to put it into your discard pile.
|
|
> playerId `plays` workshop `with` (Workshop gardens)
All the action cards from the original game. | module Dominion.Cards.Original (
module Dominion.Cards.Original
) where
import Dominion.Types
adventurer = Card "Adventurer" 6 [Action] [AdventurerEffect]
bureaucrat = Card "Bureaucrat" 4 [Action, Attack] [BureaucratEffect]
cellar = Card "Cellar" 2 [Action] [PlusAction 1, CellarEffect]
chancellor = Card "Chancellor" 3 [Action] [PlusCoin 2, ChancellorEffect]
chapel = Card "Chapel" 2 [Action] [TrashCards 4]
councilRoom = Card "Council Room" 5 [Action] [PlusCard 4, PlusBuy 1, OthersPlusCard 1]
feast = Card "Feast" 4 [Action] [TrashThisCard, GainCardUpto 5]
festival = Card "Festival" 5 [Action] [PlusAction 2, PlusCoin 2, PlusBuy 1]
laboratory = Card "Laboratory" 5 [Action] [PlusCard 2, PlusAction 1]
library = Card "Library" 5 [Action] [LibraryEffect]
market = Card "Market" 5 [Action] [PlusAction 1, PlusCoin 1, PlusCard 1, PlusBuy 1]
militia = Card "Militia" 4 [Action, Attack] [PlusCoin 2, OthersDiscardTo 3]
mine = Card "Mine" 5 [Action] [MineEffect]
moat = Card "Moat" 2 [Action, Reaction] [PlusCard 2]
moneylender = Card "Moneylender" 4 [Action] [MoneylenderEffect]
remodel = Card "Remodel" 4 [Action] [RemodelEffect]
smithy = Card "Smithy" 4 [Action] [PlusCard 3]
| The ` Spy ` ` FollowupAction ` takes two lists : a list of cards you would
spy = Card "Spy" 4 [Action, Attack] [PlusCard 1, PlusAction 1, SpyEffect]
had . You return either TrashOnly to have the player
picks one to trash . You can either return a ` TrashOnly ` to trash the
> playerId ` plays ` thief ` with ` ( Thief ( GainTrashedCard . ( comparing coinValue ) ) )
thief = Card "Thief" 4 [Action, Attack] [ThiefEffect]
> playerId ` plays ` throneRoom ` with ` ( ThroneRoom market )
throneRoom = Card "Throne Room" 4 [Action] [PlayActionCard 2]
village = Card "Village" 3 [Action] [PlusCard 1, PlusAction 2]
witch = Card "Witch" 5 [Action, Attack] [PlusCard 2, OthersGainCurse 1]
woodcutter = Card "Woodcutter" 3 [Action] [PlusCoin 2, PlusBuy 1]
workshop = Card "Workshop" 3 [Action] [GainCardUpto 4]
gardens = Card "Gardens" 4 [Victory] [GardensEffect]
originalCards = [adventurer ,
bureaucrat ,
cellar ,
chancellor ,
chapel ,
councilRoom,
feast ,
festival ,
laboratory ,
library ,
market ,
militia ,
mine ,
moat ,
moneylender,
remodel ,
smithy ,
spy ,
thief ,
throneRoom ,
village ,
witch ,
woodcutter ,
workshop ,
gardens ]
|
b5447fb31a2dc4afad4a1f002d52f23e1eb0f4edd6880c37d42b10c47048344d | TrustInSoft/tis-kernel | engine.mli | (**************************************************************************)
(* *)
This file is part of .
(* *)
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
(* *)
is released under GPLv2
(* *)
(**************************************************************************)
(**************************************************************************)
(* *)
This file is part of WP plug - in of Frama - C.
(* *)
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
(* alternatives) *)
(* *)
(* 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 , version 2.1 .
(* *)
(* It 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. *)
(* *)
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
(* *)
(**************************************************************************)
(* -------------------------------------------------------------------------- *)
(* --- Engine Signature --- *)
(* -------------------------------------------------------------------------- *)
(** Generic Engine Signature *)
open Format
open Logic
open Plib
type op =
| Op of string (** Infix or prefix operator *)
| Assoc of string (** Left-associative binary operator (like + and -) *)
| Call of string (** Logic function or predicate *)
type link =
| F_call of string (** n-ary function *)
| F_subst of string (** n-ary function with substitution "foo(%1,%2)" *)
* 2 - ary function left - to - right +
* 2 - ary function right - to - left +
| F_list of string * string (** n-ary function with (cons,nil) constructors *)
| F_assoc of string (** associative infix operator *)
| F_bool_prop of string * string (** Has a bool and prop version *)
type callstyle =
| CallVar (** Call is [f(x,...)] ; [f()] can be written [f] *)
| CallVoid (** Call is [f(x,...)] ; in [f()], [()] is mandatory *)
| CallApply (** Call is [f x ...] *)
type mode =
| Mpositive (** Current scope is [Prop] in positive position. *)
| Mnegative (** Current scope is [Prop] in negative position. *)
| Mterm (** Current scope is [Term]. *)
| Mterm_int (** [Int] is required but actual scope is [Term]. *)
| Mterm_real (** [Real] is required but actual scope is [Term]. *)
| Mint (** Current scope is [Int]. *)
| Mreal (** Current scope is [Real]. *)
type flow = Flow | Atom
type cmode = Cprop | Cterm
type amode = Aint | Areal
type pmode = Positive | Negative | Boolean
type ('x,'f) ftrigger =
| TgAny
| TgVar of 'x
| TgGet of ('x,'f) ftrigger * ('x,'f) ftrigger
| TgSet of ('x,'f) ftrigger * ('x,'f) ftrigger * ('x,'f) ftrigger
| TgFun of 'f * ('x,'f) ftrigger list
| TgProp of 'f * ('x,'f) ftrigger list
type ('t,'f,'c) ftypedef =
| Tabs
| Tdef of 't
| Trec of ('f * 't) list
| Tsum of ('c * 't list) list
type scope = [ `Auto | `Unfolded | `Defined of string ]
module type Env =
sig
type t
type term
val create : unit -> t
val copy : t -> t
val clear : t -> unit
val used : t -> string -> bool
val fresh : t -> ?suggest:bool -> string -> string
val define : t -> string -> term -> unit
val unfold : t -> term -> unit
val shared : t -> term -> bool
val shareable : t -> term -> bool (** not unfolded *)
val lookup : t -> term -> scope
end
(** Generic Engine Signature *)
class type virtual ['z,'adt,'field,'logic,'tau,'var,'term,'env] engine =
object
* { 3 Linking }
method virtual datatype : 'adt -> string
method virtual field : 'field -> string
method basename : string -> string
(** Allows to sanitize the basename used for every name except function. *)
method virtual link : 'logic -> link
* { 3 Global and Local Environment }
method env : 'env (** Returns a fresh copy of the current environment. *)
method lookup : 'term -> scope (** Term scope in the current environment. *)
method scope : 'env -> (unit -> unit) -> unit
(** Calls the continuation in the provided environment.
Previous environment is restored after return. *)
method local : (unit -> unit) -> unit
(** Calls the continuation in a local copy of the environment.
Previous environment is restored after return, but allocators
are left unchanged to enforce on-the-fly alpha-conversion. *)
method global : (unit -> unit) -> unit
(** Calls the continuation in a fresh local environment.
Previous environment is restored after return. *)
method bind : 'var -> string
method find : 'var -> string
(** {3 Types} *)
method t_int : string
method t_real : string
method t_bool : string
method t_prop : string
method t_atomic : 'tau -> bool
method pp_array : 'tau printer (** For [Z->a] arrays *)
method pp_farray : 'tau printer2 (** For [k->a] arrays *)
method pp_tvar : int printer (** Type variables. *)
method pp_datatype : 'adt -> 'tau list printer
method pp_tau : 'tau printer (** Without parentheses. *)
method pp_subtau : 'tau printer (** With parentheses if non-atomic. *)
(** {3 Current Mode}
The mode represents the expected type for a
term to printed. A requirement for all term printers in the
engine is that current mode must be correctly set before call.
Each term printer is then responsible for setting appropriate
modes for its sub-terms.
*)
method mode : mode
method with_mode : mode -> (mode -> unit) -> unit
(** Calls the continuation with given mode for sub-terms.
The englobing mode is passed to continuation and then restored. *)
method op_scope : amode -> string option
(** Optional scoping post-fix operator when entering arithmetic mode. *)
* { 3 Primitives }
method e_true : cmode -> string (** ["true"] *)
method e_false : cmode -> string (** ["false"] *)
method pp_int : amode -> 'z printer
method pp_real : R.t printer
method pp_cst : Numbers.cst printer (** Non-zero reals *)
(** {3 Variables} *)
method pp_var : string printer
(** {3 Calls}
These printers only applies to connective, operators and
functions that are morphisms {i w.r.t} current mode.
*)
method callstyle : callstyle
method pp_fun : cmode -> 'logic -> 'term list printer
method pp_apply : cmode -> 'term -> 'term list printer
(** {3 Arithmetics Operators} *)
method op_real_of_int : op
method op_add : amode -> op
method op_sub : amode -> op
method op_mul : amode -> op
method op_div : amode -> op
method op_mod : amode -> op
method op_minus : amode -> op
method pp_times : formatter -> 'z -> 'term -> unit
* Defaults to [ self#op_minus ] or [ self#op_mul ]
* { 3 Comparison Operators }
method op_equal : cmode -> op
method op_noteq : cmode -> op
method op_eq : cmode -> amode -> op
method op_neq : cmode -> amode -> op
method op_lt : cmode -> amode -> op
method op_leq : cmode -> amode -> op
method pp_equal : 'term printer2
method pp_noteq : 'term printer2
(** {3 Arrays} *)
method pp_array_get : formatter -> 'term -> 'term -> unit
(** Access ["a[k]"]. *)
method pp_array_set : formatter -> 'term -> 'term -> 'term -> unit
(** Update ["a[k <- v]"]. *)
* { 3 Records }
method pp_get_field : formatter -> 'term -> 'field -> unit
(** Field access. *)
method pp_def_fields : ('field * 'term) list printer
(** Record construction. *)
* { 3 Logical Connectives }
method op_not : cmode -> op
method op_and : cmode -> op
method op_or : cmode -> op
method op_imply : cmode -> op
method op_equiv : cmode -> op
* { 3 Conditionals }
method pp_not : 'term printer
method pp_imply : formatter -> 'term list -> 'term -> unit
method pp_conditional : formatter -> 'term -> 'term -> 'term -> unit
* { 3 Binders }
method pp_forall : 'tau -> string list printer
method pp_exists : 'tau -> string list printer
method pp_lambda : (string * 'tau) list printer
* { 3 Bindings }
method is_shareable : 'term -> bool
method pp_let : formatter -> pmode -> string -> 'term -> unit
* { 3 Terms }
method is_atomic : 'term -> bool
(** Sub-terms that require parentheses.
Shared sub-terms are detected on behalf of this method. *)
method pp_flow : 'term printer
(** Printer with shared sub-terms and without parentheses. *)
method pp_atom : 'term printer
(** Printer with shared sun-terms and parentheses for non-atomic expressions. *)
* { 3 Top Level }
method pp_term : 'term printer
* Prints in { i term } mode .
uses [ self#pp_shared ] with mode [ Mterm ] inside an [ < hov > ] box .
Default uses [self#pp_shared] with mode [Mterm] inside an [<hov>] box. *)
method pp_prop : 'term printer
* Prints in { i prop } mode .
uses [ self#pp_shared ] with mode [ Mprop ] inside an [ < hv > ] box .
Default uses [self#pp_shared] with mode [Mprop] inside an [<hv>] box. *)
method pp_expr : 'tau -> 'term printer
(** Prints in {i term}, {i arithemtic} or {i prop} mode with
respect to provided type. *)
method pp_sort : 'term printer
(** Prints in {i term}, {i arithemtic} or {i prop} mode with
respect to the sort of term. Boolean expression that also have a
property form are printed in [Mprop] mode. *)
end
| null | https://raw.githubusercontent.com/TrustInSoft/tis-kernel/748d28baba90c03c0f5f4654d2e7bb47dfbe4e7d/src/plugins/wp/qed/src/engine.mli | ocaml | ************************************************************************
************************************************************************
************************************************************************
alternatives)
you can redistribute it and/or modify it under the terms of the GNU
It 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.
************************************************************************
--------------------------------------------------------------------------
--- Engine Signature ---
--------------------------------------------------------------------------
* Generic Engine Signature
* Infix or prefix operator
* Left-associative binary operator (like + and -)
* Logic function or predicate
* n-ary function
* n-ary function with substitution "foo(%1,%2)"
* n-ary function with (cons,nil) constructors
* associative infix operator
* Has a bool and prop version
* Call is [f(x,...)] ; [f()] can be written [f]
* Call is [f(x,...)] ; in [f()], [()] is mandatory
* Call is [f x ...]
* Current scope is [Prop] in positive position.
* Current scope is [Prop] in negative position.
* Current scope is [Term].
* [Int] is required but actual scope is [Term].
* [Real] is required but actual scope is [Term].
* Current scope is [Int].
* Current scope is [Real].
* not unfolded
* Generic Engine Signature
* Allows to sanitize the basename used for every name except function.
* Returns a fresh copy of the current environment.
* Term scope in the current environment.
* Calls the continuation in the provided environment.
Previous environment is restored after return.
* Calls the continuation in a local copy of the environment.
Previous environment is restored after return, but allocators
are left unchanged to enforce on-the-fly alpha-conversion.
* Calls the continuation in a fresh local environment.
Previous environment is restored after return.
* {3 Types}
* For [Z->a] arrays
* For [k->a] arrays
* Type variables.
* Without parentheses.
* With parentheses if non-atomic.
* {3 Current Mode}
The mode represents the expected type for a
term to printed. A requirement for all term printers in the
engine is that current mode must be correctly set before call.
Each term printer is then responsible for setting appropriate
modes for its sub-terms.
* Calls the continuation with given mode for sub-terms.
The englobing mode is passed to continuation and then restored.
* Optional scoping post-fix operator when entering arithmetic mode.
* ["true"]
* ["false"]
* Non-zero reals
* {3 Variables}
* {3 Calls}
These printers only applies to connective, operators and
functions that are morphisms {i w.r.t} current mode.
* {3 Arithmetics Operators}
* {3 Arrays}
* Access ["a[k]"].
* Update ["a[k <- v]"].
* Field access.
* Record construction.
* Sub-terms that require parentheses.
Shared sub-terms are detected on behalf of this method.
* Printer with shared sub-terms and without parentheses.
* Printer with shared sun-terms and parentheses for non-atomic expressions.
* Prints in {i term}, {i arithemtic} or {i prop} mode with
respect to provided type.
* Prints in {i term}, {i arithemtic} or {i prop} mode with
respect to the sort of term. Boolean expression that also have a
property form are printed in [Mprop] mode. | This file is part of .
is a fork of Frama - C. All the differences are :
Copyright ( C ) 2016 - 2017
is released under GPLv2
This file is part of WP plug - in of Frama - C.
Copyright ( C ) 2007 - 2015
CEA ( Commissariat a l'energie atomique et aux energies
Lesser General Public License as published by the Free Software
Foundation , version 2.1 .
See the GNU Lesser General Public License version 2.1
for more details ( enclosed in the file licenses / LGPLv2.1 ) .
open Format
open Logic
open Plib
type op =
type link =
* 2 - ary function left - to - right +
* 2 - ary function right - to - left +
type callstyle =
type mode =
type flow = Flow | Atom
type cmode = Cprop | Cterm
type amode = Aint | Areal
type pmode = Positive | Negative | Boolean
type ('x,'f) ftrigger =
| TgAny
| TgVar of 'x
| TgGet of ('x,'f) ftrigger * ('x,'f) ftrigger
| TgSet of ('x,'f) ftrigger * ('x,'f) ftrigger * ('x,'f) ftrigger
| TgFun of 'f * ('x,'f) ftrigger list
| TgProp of 'f * ('x,'f) ftrigger list
type ('t,'f,'c) ftypedef =
| Tabs
| Tdef of 't
| Trec of ('f * 't) list
| Tsum of ('c * 't list) list
type scope = [ `Auto | `Unfolded | `Defined of string ]
module type Env =
sig
type t
type term
val create : unit -> t
val copy : t -> t
val clear : t -> unit
val used : t -> string -> bool
val fresh : t -> ?suggest:bool -> string -> string
val define : t -> string -> term -> unit
val unfold : t -> term -> unit
val shared : t -> term -> bool
val lookup : t -> term -> scope
end
class type virtual ['z,'adt,'field,'logic,'tau,'var,'term,'env] engine =
object
* { 3 Linking }
method virtual datatype : 'adt -> string
method virtual field : 'field -> string
method basename : string -> string
method virtual link : 'logic -> link
* { 3 Global and Local Environment }
method scope : 'env -> (unit -> unit) -> unit
method local : (unit -> unit) -> unit
method global : (unit -> unit) -> unit
method bind : 'var -> string
method find : 'var -> string
method t_int : string
method t_real : string
method t_bool : string
method t_prop : string
method t_atomic : 'tau -> bool
method pp_datatype : 'adt -> 'tau list printer
method mode : mode
method with_mode : mode -> (mode -> unit) -> unit
method op_scope : amode -> string option
* { 3 Primitives }
method pp_int : amode -> 'z printer
method pp_real : R.t printer
method pp_var : string printer
method callstyle : callstyle
method pp_fun : cmode -> 'logic -> 'term list printer
method pp_apply : cmode -> 'term -> 'term list printer
method op_real_of_int : op
method op_add : amode -> op
method op_sub : amode -> op
method op_mul : amode -> op
method op_div : amode -> op
method op_mod : amode -> op
method op_minus : amode -> op
method pp_times : formatter -> 'z -> 'term -> unit
* Defaults to [ self#op_minus ] or [ self#op_mul ]
* { 3 Comparison Operators }
method op_equal : cmode -> op
method op_noteq : cmode -> op
method op_eq : cmode -> amode -> op
method op_neq : cmode -> amode -> op
method op_lt : cmode -> amode -> op
method op_leq : cmode -> amode -> op
method pp_equal : 'term printer2
method pp_noteq : 'term printer2
method pp_array_get : formatter -> 'term -> 'term -> unit
method pp_array_set : formatter -> 'term -> 'term -> 'term -> unit
* { 3 Records }
method pp_get_field : formatter -> 'term -> 'field -> unit
method pp_def_fields : ('field * 'term) list printer
* { 3 Logical Connectives }
method op_not : cmode -> op
method op_and : cmode -> op
method op_or : cmode -> op
method op_imply : cmode -> op
method op_equiv : cmode -> op
* { 3 Conditionals }
method pp_not : 'term printer
method pp_imply : formatter -> 'term list -> 'term -> unit
method pp_conditional : formatter -> 'term -> 'term -> 'term -> unit
* { 3 Binders }
method pp_forall : 'tau -> string list printer
method pp_exists : 'tau -> string list printer
method pp_lambda : (string * 'tau) list printer
* { 3 Bindings }
method is_shareable : 'term -> bool
method pp_let : formatter -> pmode -> string -> 'term -> unit
* { 3 Terms }
method is_atomic : 'term -> bool
method pp_flow : 'term printer
method pp_atom : 'term printer
* { 3 Top Level }
method pp_term : 'term printer
* Prints in { i term } mode .
uses [ self#pp_shared ] with mode [ Mterm ] inside an [ < hov > ] box .
Default uses [self#pp_shared] with mode [Mterm] inside an [<hov>] box. *)
method pp_prop : 'term printer
* Prints in { i prop } mode .
uses [ self#pp_shared ] with mode [ Mprop ] inside an [ < hv > ] box .
Default uses [self#pp_shared] with mode [Mprop] inside an [<hv>] box. *)
method pp_expr : 'tau -> 'term printer
method pp_sort : 'term printer
end
|
6024ac2a9ec72c7bcff65cda1b50938c1d1ec776eca01b236b5e0658feba4268 | spechub/Hets | Merge.hs | |
Module : ./HasCASL / Merge.hs
Description : union of signature parts
Copyright : ( c ) and Uni Bremen 2003 - 2005
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : experimental
Portability : portable
merging parts of local environment
Module : ./HasCASL/Merge.hs
Description : union of signature parts
Copyright : (c) Christian Maeder and Uni Bremen 2003-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : experimental
Portability : portable
merging parts of local environment
-}
module HasCASL.Merge
( merge
, mergeTypeInfo
, mergeTypeDefn
, mergeOpInfo
, addUnit
) where
import Common.Id
import Common.DocUtils
import Common.Result
import HasCASL.As
import HasCASL.Le
import HasCASL.AsUtils
import HasCASL.PrintLe
import HasCASL.ClassAna
import HasCASL.TypeAna
import HasCASL.Builtin
import HasCASL.MapTerm
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Maybe
import Control.Monad (foldM)
import qualified Control.Monad.Fail as Fail
mergeTypeInfo :: ClassMap -> TypeInfo -> TypeInfo -> Result TypeInfo
mergeTypeInfo cm t1 t2 = do
let o = keepMinKinds cm [otherTypeKinds t1, otherTypeKinds t2]
s = Set.union (superTypes t1) $ superTypes t2
k <- minRawKind "type raw kind" (typeKind t1) $ typeKind t2
d <- mergeTypeDefn (typeDefn t1) $ typeDefn t2
return $ TypeInfo k o s d
mergeTypeDefn :: TypeDefn -> TypeDefn -> Result TypeDefn
mergeTypeDefn d1 d2 = case (d1, d2) of
(_, DatatypeDefn _) -> return d2
(PreDatatype, _) -> Fail.fail "expected data type definition"
(_, PreDatatype) -> return d1
(NoTypeDefn, _) -> return d2
(_, NoTypeDefn) -> return d1
(AliasTypeDefn s1, AliasTypeDefn s2) -> do
s <- mergeAlias s1 s2
return $ AliasTypeDefn s
(_, _) -> mergeA "TypeDefn" d1 d2
mergeAlias :: Type -> Type -> Result Type
mergeAlias s1 s2 = if eqStrippedType s1 s2 then return s1 else
Fail.fail $ "wrong type" ++ expected s1 s2
mergeOpBrand :: OpBrand -> OpBrand -> OpBrand
mergeOpBrand b1 b2 = case (b1, b2) of
(Pred, _) -> Pred
(_, Pred) -> Pred
(Op, _) -> Op
(_, Op) -> Op
_ -> Fun
mergeOpDefn :: OpDefn -> OpDefn -> Result OpDefn
mergeOpDefn d1 d2 = case (d1, d2) of
(NoOpDefn b1, NoOpDefn b2) -> do
let b = mergeOpBrand b1 b2
return $ NoOpDefn b
(SelectData c1 s, SelectData c2 _) -> do
let c = Set.union c1 c2
return $ SelectData c s
(Definition b1 e1, Definition b2 e2) -> do
d <- mergeTerm Hint e1 e2
let b = mergeOpBrand b1 b2
return $ Definition b d
(NoOpDefn b1, Definition b2 e2) -> do
let b = mergeOpBrand b1 b2
return $ Definition b e2
(Definition b1 e1, NoOpDefn b2) -> do
let b = mergeOpBrand b1 b2
return $ Definition b e1
(ConstructData _, SelectData _ _) ->
Fail.fail "illegal selector as constructor redefinition"
(SelectData _ _, ConstructData _) ->
Fail.fail "illegal constructor as selector redefinition"
(ConstructData _, _) -> return d1
(_, ConstructData _) -> return d2
(SelectData _ _, _) -> return d1
(_, SelectData _ _) -> return d2
addUnit :: ClassMap -> TypeMap -> TypeMap
addUnit cm = fromMaybe (error "addUnit") . maybeResult . mergeTypeMap cm bTypes
mergeOpInfos :: Set.Set OpInfo -> Set.Set OpInfo -> Result (Set.Set OpInfo)
mergeOpInfos s1 s2 = if Set.null s1 then return s2 else do
let (o, os) = Set.deleteFindMin s1
(es, us) = Set.partition ((opType o ==) . opType) s2
s <- mergeOpInfos os us
r <- foldM mergeOpInfo o $ Set.toList es
return $ Set.insert r s
mergeOpInfo :: OpInfo -> OpInfo -> Result OpInfo
mergeOpInfo o1 o2 = do
let as = Set.union (opAttrs o1) $ opAttrs o2
d <- mergeOpDefn (opDefn o1) $ opDefn o2
return $ OpInfo (opType o1) as d
mergeTypeMap :: ClassMap -> TypeMap -> TypeMap -> Result TypeMap
mergeTypeMap = mergeMap . mergeTypeInfo
merge :: Env -> Env -> Result Env
merge e1 e2 = do
clMap <- mergeClassMap (classMap e1) $ classMap e2
tMap <- mergeTypeMap clMap (typeMap e1) $ typeMap e2
let tAs = filterAliases tMap
as <- mergeMap mergeOpInfos (assumps e1) $ assumps e2
bs <- mergeMap (\ i1 i2 -> if i1 == i2 then return i1 else
Fail.fail "conflicting operation for binder syntax")
(binders e1) $ binders e2
return initialEnv
{ classMap = clMap
, typeMap = tMap
, assumps = Map.map (Set.map $ mapOpInfo (id, expandAliases tAs)) as
, binders = bs }
mergeA :: (Pretty a, Eq a) => String -> a -> a -> Result a
mergeA str t1 t2 = if t1 == t2 then return t1 else
Fail.fail ("different " ++ str ++ expected t1 t2)
mergeTerm :: DiagKind -> Term -> Term -> Result Term
mergeTerm k t1 t2 = if t1 == t2 then return t1 else
Result [Diag k ("different terms" ++ expected t1 t2) $ getRange t2] $ Just t2
| null | https://raw.githubusercontent.com/spechub/Hets/f582640a174df08d4c965d7c0a1ab24d1a31000d/HasCASL/Merge.hs | haskell | |
Module : ./HasCASL / Merge.hs
Description : union of signature parts
Copyright : ( c ) and Uni Bremen 2003 - 2005
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : experimental
Portability : portable
merging parts of local environment
Module : ./HasCASL/Merge.hs
Description : union of signature parts
Copyright : (c) Christian Maeder and Uni Bremen 2003-2005
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : experimental
Portability : portable
merging parts of local environment
-}
module HasCASL.Merge
( merge
, mergeTypeInfo
, mergeTypeDefn
, mergeOpInfo
, addUnit
) where
import Common.Id
import Common.DocUtils
import Common.Result
import HasCASL.As
import HasCASL.Le
import HasCASL.AsUtils
import HasCASL.PrintLe
import HasCASL.ClassAna
import HasCASL.TypeAna
import HasCASL.Builtin
import HasCASL.MapTerm
import qualified Data.Map as Map
import qualified Data.Set as Set
import Data.Maybe
import Control.Monad (foldM)
import qualified Control.Monad.Fail as Fail
mergeTypeInfo :: ClassMap -> TypeInfo -> TypeInfo -> Result TypeInfo
mergeTypeInfo cm t1 t2 = do
let o = keepMinKinds cm [otherTypeKinds t1, otherTypeKinds t2]
s = Set.union (superTypes t1) $ superTypes t2
k <- minRawKind "type raw kind" (typeKind t1) $ typeKind t2
d <- mergeTypeDefn (typeDefn t1) $ typeDefn t2
return $ TypeInfo k o s d
mergeTypeDefn :: TypeDefn -> TypeDefn -> Result TypeDefn
mergeTypeDefn d1 d2 = case (d1, d2) of
(_, DatatypeDefn _) -> return d2
(PreDatatype, _) -> Fail.fail "expected data type definition"
(_, PreDatatype) -> return d1
(NoTypeDefn, _) -> return d2
(_, NoTypeDefn) -> return d1
(AliasTypeDefn s1, AliasTypeDefn s2) -> do
s <- mergeAlias s1 s2
return $ AliasTypeDefn s
(_, _) -> mergeA "TypeDefn" d1 d2
mergeAlias :: Type -> Type -> Result Type
mergeAlias s1 s2 = if eqStrippedType s1 s2 then return s1 else
Fail.fail $ "wrong type" ++ expected s1 s2
mergeOpBrand :: OpBrand -> OpBrand -> OpBrand
mergeOpBrand b1 b2 = case (b1, b2) of
(Pred, _) -> Pred
(_, Pred) -> Pred
(Op, _) -> Op
(_, Op) -> Op
_ -> Fun
mergeOpDefn :: OpDefn -> OpDefn -> Result OpDefn
mergeOpDefn d1 d2 = case (d1, d2) of
(NoOpDefn b1, NoOpDefn b2) -> do
let b = mergeOpBrand b1 b2
return $ NoOpDefn b
(SelectData c1 s, SelectData c2 _) -> do
let c = Set.union c1 c2
return $ SelectData c s
(Definition b1 e1, Definition b2 e2) -> do
d <- mergeTerm Hint e1 e2
let b = mergeOpBrand b1 b2
return $ Definition b d
(NoOpDefn b1, Definition b2 e2) -> do
let b = mergeOpBrand b1 b2
return $ Definition b e2
(Definition b1 e1, NoOpDefn b2) -> do
let b = mergeOpBrand b1 b2
return $ Definition b e1
(ConstructData _, SelectData _ _) ->
Fail.fail "illegal selector as constructor redefinition"
(SelectData _ _, ConstructData _) ->
Fail.fail "illegal constructor as selector redefinition"
(ConstructData _, _) -> return d1
(_, ConstructData _) -> return d2
(SelectData _ _, _) -> return d1
(_, SelectData _ _) -> return d2
addUnit :: ClassMap -> TypeMap -> TypeMap
addUnit cm = fromMaybe (error "addUnit") . maybeResult . mergeTypeMap cm bTypes
mergeOpInfos :: Set.Set OpInfo -> Set.Set OpInfo -> Result (Set.Set OpInfo)
mergeOpInfos s1 s2 = if Set.null s1 then return s2 else do
let (o, os) = Set.deleteFindMin s1
(es, us) = Set.partition ((opType o ==) . opType) s2
s <- mergeOpInfos os us
r <- foldM mergeOpInfo o $ Set.toList es
return $ Set.insert r s
mergeOpInfo :: OpInfo -> OpInfo -> Result OpInfo
mergeOpInfo o1 o2 = do
let as = Set.union (opAttrs o1) $ opAttrs o2
d <- mergeOpDefn (opDefn o1) $ opDefn o2
return $ OpInfo (opType o1) as d
mergeTypeMap :: ClassMap -> TypeMap -> TypeMap -> Result TypeMap
mergeTypeMap = mergeMap . mergeTypeInfo
merge :: Env -> Env -> Result Env
merge e1 e2 = do
clMap <- mergeClassMap (classMap e1) $ classMap e2
tMap <- mergeTypeMap clMap (typeMap e1) $ typeMap e2
let tAs = filterAliases tMap
as <- mergeMap mergeOpInfos (assumps e1) $ assumps e2
bs <- mergeMap (\ i1 i2 -> if i1 == i2 then return i1 else
Fail.fail "conflicting operation for binder syntax")
(binders e1) $ binders e2
return initialEnv
{ classMap = clMap
, typeMap = tMap
, assumps = Map.map (Set.map $ mapOpInfo (id, expandAliases tAs)) as
, binders = bs }
mergeA :: (Pretty a, Eq a) => String -> a -> a -> Result a
mergeA str t1 t2 = if t1 == t2 then return t1 else
Fail.fail ("different " ++ str ++ expected t1 t2)
mergeTerm :: DiagKind -> Term -> Term -> Result Term
mergeTerm k t1 t2 = if t1 == t2 then return t1 else
Result [Diag k ("different terms" ++ expected t1 t2) $ getRange t2] $ Just t2
| |
ab39b8ef4f5769b97d0dcc27c66a7fde175948fd890312cc692fa66a90f1533c | michaxm/task-distribution | Configuration.hs | module Control.Distributed.Task.Util.Configuration (
Configuration(..), getConfiguration, DistributionStrategy(..)
)where
import Data.List.Split (splitOn)
import Control.Distributed.Task.Types.HdfsConfigTypes
data Configuration = Configuration {
_maxTasksPerNode :: Int,
_hdfsConfig :: HdfsConfig,
_pseudoDBPath :: FilePath,
_distributionStrategy :: DistributionStrategy,
_taskLogFile :: FilePath,
_sourceCodeDistributionHome :: FilePath,
_sourceCodeModules :: [(String, Maybe String)],
_objectCodePathOnMaster :: FilePath,
_packageDbPath :: FilePath,
_objectCodeResourcesPathSrc :: FilePath,
_objectCodeResourcesPathExtra :: FilePath
}
data DistributionStrategy
= FirstTaskWithData
| AnywhereIsFine
getConfiguration :: IO Configuration
getConfiguration = do
confFile <- readFile "etc/config"
sourceCodeModulesFile <- readFile "etc/sourcecodemodules"
return $ parseConfig confFile sourceCodeModulesFile
where
parseConfig conf sourceCodeModulesFile =
Configuration
(read $ f "max-tasks-per-node")
(readEndpoint $ f "hdfs")
(f "pseudo-db-path")
(readStrat $ f "distribution-strategy")
(f "task-log-file")
(f "source-code-distribution-home")
(map mkSourceCodeModule $ lines sourceCodeModulesFile)
(f "object-code-path-on-master")
(f "package-db-path")
(f "object-code-resources-path-src")
(f "object-code-resources-path-extra")
where
f = getConfig conf
readStrat s = case s of
"local" -> FirstTaskWithData
"anywhere" -> AnywhereIsFine
_ -> error $ "unknown strategy: "++s
readEndpoint str = let es = splitOn ":" str
in if length es == 2
then (es !! 0, read $ es !! 1)
else error $ "endpoint not properly configured in etc/config (example: hdfs=localhost:55555): "++str
mkSourceCodeModule line = let es = splitOn ":" line in if (length es) == 1 then (es !! 0, Nothing) else (es !! 0, Just $ es !! 1)
getConfig :: String -> String -> String
getConfig file key =
let conf = (filter (not . null . fst) . map parseConfig . map (splitOn "=") . lines) file
in maybe (error $ "not configured: "++key) id $ lookup key conf
where
parseConfig :: [String] -> (String, String)
parseConfig es = if length es < 2 then ("", "") else (head es, concat $ tail es)
| null | https://raw.githubusercontent.com/michaxm/task-distribution/d0dee6a661390b7d1279389fa8c7b711309dab6a/src/Control/Distributed/Task/Util/Configuration.hs | haskell | module Control.Distributed.Task.Util.Configuration (
Configuration(..), getConfiguration, DistributionStrategy(..)
)where
import Data.List.Split (splitOn)
import Control.Distributed.Task.Types.HdfsConfigTypes
data Configuration = Configuration {
_maxTasksPerNode :: Int,
_hdfsConfig :: HdfsConfig,
_pseudoDBPath :: FilePath,
_distributionStrategy :: DistributionStrategy,
_taskLogFile :: FilePath,
_sourceCodeDistributionHome :: FilePath,
_sourceCodeModules :: [(String, Maybe String)],
_objectCodePathOnMaster :: FilePath,
_packageDbPath :: FilePath,
_objectCodeResourcesPathSrc :: FilePath,
_objectCodeResourcesPathExtra :: FilePath
}
data DistributionStrategy
= FirstTaskWithData
| AnywhereIsFine
getConfiguration :: IO Configuration
getConfiguration = do
confFile <- readFile "etc/config"
sourceCodeModulesFile <- readFile "etc/sourcecodemodules"
return $ parseConfig confFile sourceCodeModulesFile
where
parseConfig conf sourceCodeModulesFile =
Configuration
(read $ f "max-tasks-per-node")
(readEndpoint $ f "hdfs")
(f "pseudo-db-path")
(readStrat $ f "distribution-strategy")
(f "task-log-file")
(f "source-code-distribution-home")
(map mkSourceCodeModule $ lines sourceCodeModulesFile)
(f "object-code-path-on-master")
(f "package-db-path")
(f "object-code-resources-path-src")
(f "object-code-resources-path-extra")
where
f = getConfig conf
readStrat s = case s of
"local" -> FirstTaskWithData
"anywhere" -> AnywhereIsFine
_ -> error $ "unknown strategy: "++s
readEndpoint str = let es = splitOn ":" str
in if length es == 2
then (es !! 0, read $ es !! 1)
else error $ "endpoint not properly configured in etc/config (example: hdfs=localhost:55555): "++str
mkSourceCodeModule line = let es = splitOn ":" line in if (length es) == 1 then (es !! 0, Nothing) else (es !! 0, Just $ es !! 1)
getConfig :: String -> String -> String
getConfig file key =
let conf = (filter (not . null . fst) . map parseConfig . map (splitOn "=") . lines) file
in maybe (error $ "not configured: "++key) id $ lookup key conf
where
parseConfig :: [String] -> (String, String)
parseConfig es = if length es < 2 then ("", "") else (head es, concat $ tail es)
| |
74e8e5636ba875fc7b972aa8f8a086224c430896b5efa22f56172c067b692028 | dimitri/pgloader | command-cast-rules.lisp | ;;;
Now parsing CAST rules for migrating from MySQL
;;;
(in-package :pgloader.parser)
(defrule cast-typemod-guard (and kw-when sexp)
(:destructure (w expr) (declare (ignore w)) (cons :typemod expr)))
(defrule cast-default-guard (and kw-when kw-default quoted-string)
(:destructure (w d value) (declare (ignore w d)) (cons :default value)))
(defrule cast-unsigned-guard (and kw-when kw-unsigned)
(:constant (cons :unsigned t)))
(defrule cast-signed-guard (and kw-when kw-signed)
(:constant (cons :signed t)))
;; at the moment we only know about extra auto_increment
(defrule cast-source-extra (and kw-with kw-extra
(or kw-auto-increment
kw-on-update-current-timestamp))
(:lambda (extra)
(cons (third extra) t)))
;; type names may be "double quoted"
(defrule cast-type-name (or double-quoted-namestring
(and (alpha-char-p character)
(* (or (alpha-char-p character)
(digit-char-p character)
#\_))))
(:text t))
(defrule cast-source-type (and kw-type cast-type-name)
(:destructure (kw name) (declare (ignore kw)) (list :type name)))
(defrule table-column-name (and maybe-quoted-namestring
"."
maybe-quoted-namestring)
(:destructure (table-name dot column-name)
(declare (ignore dot))
(list :column (cons (text table-name) (text column-name)))))
(defrule cast-source-column (and kw-column table-column-name)
;; well, we want namestring . namestring
(:destructure (kw name) (declare (ignore kw)) name))
(defrule cast-source-extra-or-guard (* (or cast-unsigned-guard
cast-signed-guard
cast-default-guard
cast-typemod-guard
cast-source-extra))
(:function alexandria:alist-plist))
(defrule cast-source (and (or cast-source-type cast-source-column)
cast-source-extra-or-guard)
(:lambda (source)
(bind (((name-and-type extra-and-guards) source)
((&key (default nil d-s-p)
(typemod nil t-s-p)
(signed nil s-s-p)
(unsigned nil u-s-p)
(auto-increment nil ai-s-p)
(on-update-current-timestamp nil ouct-s-p)
&allow-other-keys)
extra-and-guards))
`(,@name-and-type
,@(when t-s-p (list :typemod typemod))
,@(when d-s-p (list :default default))
,@(when s-s-p (list :signed signed))
,@(when u-s-p (list :unsigned unsigned))
,@(when ai-s-p (list :auto-increment auto-increment))
,@(when ouct-s-p (list :on-update-current-timestamp
on-update-current-timestamp))))))
(defrule cast-to-type (and kw-to cast-type-name ignore-whitespace)
(:lambda (source)
(bind (((_ type-name _) source))
(list :type type-name))))
(defrule cast-keep-default (and kw-keep kw-default)
(:constant (list :drop-default nil)))
(defrule cast-keep-typemod (and kw-keep kw-typemod)
(:constant (list :drop-typemod nil)))
(defrule cast-keep-not-null (and kw-keep kw-not kw-null)
(:constant (list :drop-not-null nil)))
(defrule cast-drop-default (and kw-drop kw-default)
(:constant (list :drop-default t)))
(defrule cast-drop-typemod (and kw-drop kw-typemod)
(:constant (list :drop-typemod t)))
(defrule cast-drop-not-null (and kw-drop kw-not kw-null)
(:constant (list :drop-not-null t)))
(defrule cast-set-not-null (and kw-set kw-not kw-null)
(:constant (list :set-not-null t)))
(defrule cast-keep-extra (and kw-keep kw-extra)
(:constant (list :keep-extra t)))
(defrule cast-drop-extra (and kw-drop kw-extra)
(:constant (list :drop-extra t)))
(defrule cast-def (+ (or cast-to-type
cast-keep-default
cast-drop-default
cast-keep-extra
cast-drop-extra
cast-keep-typemod
cast-drop-typemod
cast-keep-not-null
cast-drop-not-null
cast-set-not-null))
(:lambda (source)
(destructuring-bind
(&key type drop-default drop-extra drop-typemod
drop-not-null set-not-null &allow-other-keys)
(apply #'append source)
(list :type type
:drop-extra drop-extra
:drop-default drop-default
:drop-typemod drop-typemod
:drop-not-null drop-not-null
:set-not-null set-not-null))))
(defun function-name-character-p (char)
(or (member char #.(quote (coerce "/.-%" 'list)))
(alphanumericp char)))
(defrule function-name (+ (function-name-character-p character))
(:lambda (fname)
(text fname)))
(defrule package-and-function-names (and function-name
(or ":" "::")
function-name)
(:lambda (pfn)
(bind (((pname _ fname) pfn))
(intern (string-upcase fname) (find-package (string-upcase pname))))))
(defrule maybe-qualified-function-name (or package-and-function-names
function-name)
(:lambda (fname)
(typecase fname
(string (intern (string-upcase fname) :pgloader.transforms))
(symbol fname))))
(defrule transform-expression sexp
(:lambda (sexp)
(eval sexp)))
(defrule cast-function (and kw-using (or maybe-qualified-function-name
transform-expression))
(:destructure (using symbol) (declare (ignore using)) symbol))
(defun fix-target-type (source target)
"When target has :type nil, steal the source :type definition."
(if (getf target :type)
target
(loop
for (key value) on target by #'cddr
append (list key (if (eq :type key) (getf source :type) value)))))
(defrule cast-rule (and cast-source (? cast-def) (? cast-function))
(:lambda (cast)
(destructuring-bind (source target function) cast
(list :source source
:target (fix-target-type source target)
:using function))))
(defrule another-cast-rule (and comma cast-rule)
(:lambda (source)
(bind (((_ rule) source)) rule)))
(defrule cast-rule-list (and cast-rule (* another-cast-rule))
(:lambda (source)
(destructuring-bind (rule1 rules) source
(list* rule1 rules))))
(defrule casts (and kw-cast cast-rule-list)
(:lambda (source)
(bind (((_ casts) source))
(cons :casts casts))))
| null | https://raw.githubusercontent.com/dimitri/pgloader/7e1f7c51c80630263673f6dc1297a275c087cb03/src/parsers/command-cast-rules.lisp | lisp |
at the moment we only know about extra auto_increment
type names may be "double quoted"
well, we want namestring . namestring | Now parsing CAST rules for migrating from MySQL
(in-package :pgloader.parser)
(defrule cast-typemod-guard (and kw-when sexp)
(:destructure (w expr) (declare (ignore w)) (cons :typemod expr)))
(defrule cast-default-guard (and kw-when kw-default quoted-string)
(:destructure (w d value) (declare (ignore w d)) (cons :default value)))
(defrule cast-unsigned-guard (and kw-when kw-unsigned)
(:constant (cons :unsigned t)))
(defrule cast-signed-guard (and kw-when kw-signed)
(:constant (cons :signed t)))
(defrule cast-source-extra (and kw-with kw-extra
(or kw-auto-increment
kw-on-update-current-timestamp))
(:lambda (extra)
(cons (third extra) t)))
(defrule cast-type-name (or double-quoted-namestring
(and (alpha-char-p character)
(* (or (alpha-char-p character)
(digit-char-p character)
#\_))))
(:text t))
(defrule cast-source-type (and kw-type cast-type-name)
(:destructure (kw name) (declare (ignore kw)) (list :type name)))
(defrule table-column-name (and maybe-quoted-namestring
"."
maybe-quoted-namestring)
(:destructure (table-name dot column-name)
(declare (ignore dot))
(list :column (cons (text table-name) (text column-name)))))
(defrule cast-source-column (and kw-column table-column-name)
(:destructure (kw name) (declare (ignore kw)) name))
(defrule cast-source-extra-or-guard (* (or cast-unsigned-guard
cast-signed-guard
cast-default-guard
cast-typemod-guard
cast-source-extra))
(:function alexandria:alist-plist))
(defrule cast-source (and (or cast-source-type cast-source-column)
cast-source-extra-or-guard)
(:lambda (source)
(bind (((name-and-type extra-and-guards) source)
((&key (default nil d-s-p)
(typemod nil t-s-p)
(signed nil s-s-p)
(unsigned nil u-s-p)
(auto-increment nil ai-s-p)
(on-update-current-timestamp nil ouct-s-p)
&allow-other-keys)
extra-and-guards))
`(,@name-and-type
,@(when t-s-p (list :typemod typemod))
,@(when d-s-p (list :default default))
,@(when s-s-p (list :signed signed))
,@(when u-s-p (list :unsigned unsigned))
,@(when ai-s-p (list :auto-increment auto-increment))
,@(when ouct-s-p (list :on-update-current-timestamp
on-update-current-timestamp))))))
(defrule cast-to-type (and kw-to cast-type-name ignore-whitespace)
(:lambda (source)
(bind (((_ type-name _) source))
(list :type type-name))))
(defrule cast-keep-default (and kw-keep kw-default)
(:constant (list :drop-default nil)))
(defrule cast-keep-typemod (and kw-keep kw-typemod)
(:constant (list :drop-typemod nil)))
(defrule cast-keep-not-null (and kw-keep kw-not kw-null)
(:constant (list :drop-not-null nil)))
(defrule cast-drop-default (and kw-drop kw-default)
(:constant (list :drop-default t)))
(defrule cast-drop-typemod (and kw-drop kw-typemod)
(:constant (list :drop-typemod t)))
(defrule cast-drop-not-null (and kw-drop kw-not kw-null)
(:constant (list :drop-not-null t)))
(defrule cast-set-not-null (and kw-set kw-not kw-null)
(:constant (list :set-not-null t)))
(defrule cast-keep-extra (and kw-keep kw-extra)
(:constant (list :keep-extra t)))
(defrule cast-drop-extra (and kw-drop kw-extra)
(:constant (list :drop-extra t)))
(defrule cast-def (+ (or cast-to-type
cast-keep-default
cast-drop-default
cast-keep-extra
cast-drop-extra
cast-keep-typemod
cast-drop-typemod
cast-keep-not-null
cast-drop-not-null
cast-set-not-null))
(:lambda (source)
(destructuring-bind
(&key type drop-default drop-extra drop-typemod
drop-not-null set-not-null &allow-other-keys)
(apply #'append source)
(list :type type
:drop-extra drop-extra
:drop-default drop-default
:drop-typemod drop-typemod
:drop-not-null drop-not-null
:set-not-null set-not-null))))
(defun function-name-character-p (char)
(or (member char #.(quote (coerce "/.-%" 'list)))
(alphanumericp char)))
(defrule function-name (+ (function-name-character-p character))
(:lambda (fname)
(text fname)))
(defrule package-and-function-names (and function-name
(or ":" "::")
function-name)
(:lambda (pfn)
(bind (((pname _ fname) pfn))
(intern (string-upcase fname) (find-package (string-upcase pname))))))
(defrule maybe-qualified-function-name (or package-and-function-names
function-name)
(:lambda (fname)
(typecase fname
(string (intern (string-upcase fname) :pgloader.transforms))
(symbol fname))))
(defrule transform-expression sexp
(:lambda (sexp)
(eval sexp)))
(defrule cast-function (and kw-using (or maybe-qualified-function-name
transform-expression))
(:destructure (using symbol) (declare (ignore using)) symbol))
(defun fix-target-type (source target)
"When target has :type nil, steal the source :type definition."
(if (getf target :type)
target
(loop
for (key value) on target by #'cddr
append (list key (if (eq :type key) (getf source :type) value)))))
(defrule cast-rule (and cast-source (? cast-def) (? cast-function))
(:lambda (cast)
(destructuring-bind (source target function) cast
(list :source source
:target (fix-target-type source target)
:using function))))
(defrule another-cast-rule (and comma cast-rule)
(:lambda (source)
(bind (((_ rule) source)) rule)))
(defrule cast-rule-list (and cast-rule (* another-cast-rule))
(:lambda (source)
(destructuring-bind (rule1 rules) source
(list* rule1 rules))))
(defrule casts (and kw-cast cast-rule-list)
(:lambda (source)
(bind (((_ casts) source))
(cons :casts casts))))
|
729b307f95325bb4cda5b56995b5fc50f8406dd8c727bf03d51937b96709e302 | camlp5/camlp5 | oprint.ml | (* camlp5r *)
oprint.ml , v
Copyright ( c ) INRIA 2007 - 2017
open Format;
open Outcometree;
exception Ellipsis;
value cautious f ppf arg =
try f ppf arg with [ Ellipsis -> fprintf ppf "..." ]
;
value rec print_ident ppf =
fun
[ Oide_ident s -> fprintf ppf "%s" s
| Oide_dot id s -> fprintf ppf "%a.%s" print_ident id s
| Oide_apply id1 id2 ->
fprintf ppf "%a(%a)" print_ident id1 print_ident id2 ]
;
value value_ident ppf name =
if List.mem name ["or"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"]
then
fprintf ppf "( %s )" name
else
match name.[0] with
[ 'a'..'z' | '\223'..'\246' | '\248'..'\255' | '_' ->
fprintf ppf "%s" name
| _ -> fprintf ppf "( %s )" name ]
;
(* Values *)
value print_out_value ppf tree =
let rec print_tree ppf =
fun
[ Oval_tuple tree_list ->
fprintf ppf "@[%a@]" (print_tree_list print_tree_1 ",") tree_list
| tree -> print_tree_1 ppf tree ]
and print_tree_1 ppf =
fun
[ Oval_constr name [param] ->
fprintf ppf "@[<1>%a@ %a@]" print_ident name print_simple_tree param
| Oval_constr name ([_ :: _] as params) ->
fprintf ppf "@[<1>%a@ (%a)@]" print_ident name
(print_tree_list print_tree_1 ",") params
| Oval_variant name (Some param) ->
fprintf ppf "@[<2>`%s@ %a@]" name print_simple_tree param
| tree -> print_simple_tree ppf tree ]
and print_simple_tree ppf =
fun
[ Oval_int i -> fprintf ppf "%i" i
| Oval_int32 i -> fprintf ppf "%li" i
| Oval_int64 i -> fprintf ppf "%Li" i
| Oval_nativeint i -> fprintf ppf "%ni" i
| Oval_float f -> fprintf ppf "%s" (string_of_float f)
| Oval_char c -> fprintf ppf "'%s'" (Char.escaped c)
| Oval_string s ->
try fprintf ppf "\"%s\"" (String.escaped s) with
[ Invalid_argument "String.create" -> fprintf ppf "<huge string>" ]
| Oval_list tl ->
fprintf ppf "@[<1>[%a]@]" (print_tree_list print_tree_1 ";") tl
| Oval_array tl ->
fprintf ppf "@[<2>[|%a|]@]" (print_tree_list print_tree_1 ";") tl
| Oval_constr name [] -> print_ident ppf name
| Oval_variant name None -> fprintf ppf "`%s" name
| Oval_stuff s -> fprintf ppf "%s" s
| Oval_record fel ->
fprintf ppf "@[<1>{%a}@]" (cautious (print_fields True)) fel
| Oval_ellipsis -> raise Ellipsis
| Oval_printer f -> f ppf
| tree -> fprintf ppf "@[<1>(%a)@]" (cautious print_tree) tree ]
and print_fields first ppf =
fun
[ [] -> ()
| [(name, tree) :: fields] -> do {
if not first then fprintf ppf ";@ " else ();
fprintf ppf "@[<1>%a@ =@ %a@]" print_ident name (cautious print_tree)
tree;
print_fields False ppf fields
} ]
and print_tree_list print_item sep ppf tree_list =
let rec print_list first ppf =
fun
[ [] -> ()
| [tree :: tree_list] -> do {
if not first then fprintf ppf "%s@ " sep else ();
print_item ppf tree;
print_list False ppf tree_list
} ]
in
cautious (print_list True) ppf tree_list
in
cautious print_tree ppf tree
;
(* Types *)
value rec print_list_init pr sep ppf =
fun
[ [] -> ()
| [a :: l] -> do { sep ppf; pr ppf a; print_list_init pr sep ppf l } ]
;
value rec print_list pr sep ppf =
fun
[ [] -> ()
| [a] -> pr ppf a
| [a :: l] -> do { pr ppf a; sep ppf; print_list pr sep ppf l } ]
;
value pr_present =
print_list (fun ppf s -> fprintf ppf "`%s" s) (fun ppf -> fprintf ppf "@ ")
;
value rec print_out_type ppf =
fun
[ Otyp_alias ty s -> fprintf ppf "@[%a as '%s@]" print_out_type ty s
| ty -> print_out_type_1 ppf ty ]
and print_out_type_1 ppf =
fun
[ Otyp_arrow lab ty1 ty2 ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
print_out_type_2 ty1 print_out_type_1 ty2
| ty -> print_out_type_2 ppf ty ]
and print_out_type_2 ppf =
fun
[ Otyp_tuple tyl ->
fprintf ppf "@[<0>%a@]" (print_typlist print_simple_out_type " *") tyl
| ty -> print_simple_out_type ppf ty ]
and print_simple_out_type ppf =
fun
[ Otyp_class ng id tyl ->
fprintf ppf "@[%a%s#%a@]" print_typargs tyl (if ng then "_" else "")
print_ident id
| Otyp_constr id tyl ->
fprintf ppf "@[%a%a@]" print_typargs tyl print_ident id
| Otyp_object fields rest ->
fprintf ppf "@[<2>< %a >@]" (print_fields rest) fields
| Otyp_stuff s -> fprintf ppf "%s" s
| Otyp_var ng s -> fprintf ppf "'%s%s" (if ng then "_" else "") s
| Otyp_variant non_gen poly_variants closed tags ->
let print_present ppf =
fun
[ None | Some [] -> ()
| Some l -> fprintf ppf "@;<1 -2>> @[<hov>%a@]" pr_present l ]
in
let print_fields ppf =
fun
[ Ovar_fields fields ->
print_list print_poly_variant
(fun ppf -> fprintf ppf "@;<1 -2>| ") ppf fields
| Ovar_name id tyl ->
fprintf ppf "@[%a%a@]" print_typargs tyl print_ident id ]
in
fprintf ppf "%s[%s@[<hv>@[<hv>%a@]%a]@]" (if non_gen then "_" else "")
(if closed then if tags = None then " " else "< "
else if tags = None then "> "
else "? ")
print_fields poly_variants print_present tags
| Otyp_alias _ _ | Otyp_arrow _ _ _ | Otyp_tuple _ as ty ->
fprintf ppf "@[<1>(%a)@]" print_out_type ty
| Otyp_abstract | Otyp_sum _ | Otyp_record _ | Otyp_manifest _ _ -> () ]
and print_fields rest ppf =
fun
[ [] ->
match rest with
[ Some non_gen -> fprintf ppf "%s.." (if non_gen then "_" else "")
| None -> () ]
| [(s, t)] -> do {
fprintf ppf "%s : %a" s print_out_type t;
match rest with
[ Some _ -> fprintf ppf ";@ "
| None -> () ];
print_fields rest ppf []
}
| [(s, t) :: l] ->
fprintf ppf "%s : %a;@ %a" s print_out_type t (print_fields rest) l ]
and print_poly_variant ppf (l, opt_amp, tyl) =
let pr_of ppf =
if opt_amp then fprintf ppf " of@ &@ "
else if tyl <> [] then fprintf ppf " of@ "
else fprintf ppf ""
in
fprintf ppf "@[<hv 2>`%s%t%a@]" l pr_of (print_typlist print_out_type " &")
tyl
and print_typlist print_elem sep ppf =
fun
[ [] -> ()
| [ty] -> print_elem ppf ty
| [ty :: tyl] ->
fprintf ppf "%a%s@ %a" print_elem ty sep (print_typlist print_elem sep)
tyl ]
and print_typargs ppf =
fun
[ [] -> ()
| [ty1] -> fprintf ppf "%a@ " print_simple_out_type ty1
| tyl ->
fprintf ppf "@[<1>(%a)@]@ " (print_typlist print_out_type ",") tyl ]
;
Signature items
value print_out_class_params ppf =
fun
[ [] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ "
(print_list (fun ppf x -> fprintf ppf "'%s" x)
(fun ppf -> fprintf ppf ", "))
tyl ]
;
value rec print_out_class_type ppf =
fun
[ Octy_constr id tyl ->
let pr_tyl ppf =
fun
[ [] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ " (print_typlist print_out_type ",")
tyl ]
in
fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id
| Octy_fun lab ty cty ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
print_out_type_2 ty print_out_class_type cty
| Octy_signature self_ty csil ->
let pr_param ppf =
fun
[ Some ty -> fprintf ppf "@ @[(%a)@]" print_out_type ty
| None -> () ]
in
fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty
(print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ "))
csil ]
and print_out_class_sig_item ppf =
fun
[ Ocsg_constraint ty1 ty2 ->
fprintf ppf "@[<2>constraint %a =@ %a@]" print_out_type ty1
print_out_type ty2
| Ocsg_method name priv virt ty ->
fprintf ppf "@[<2>method %s%s%s :@ %a@]"
(if priv then "private " else "") (if virt then "virtual " else "")
name print_out_type ty
| Ocsg_value name mut ty ->
fprintf ppf "@[<2>val %s%s :@ %a@]" (if mut then "mutable " else "")
name print_out_type ty ]
;
value rec print_out_module_type ppf =
fun
[ Omty_abstract -> ()
| Omty_functor name mty_arg mty_res ->
fprintf ppf "@[<2>functor@ (%s : %a) ->@ %a@]" name
print_out_module_type mty_arg print_out_module_type mty_res
| Omty_ident id -> fprintf ppf "%a" print_ident id
| Omty_signature sg ->
fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" print_signature_body sg ]
and print_signature_body ppf =
fun
[ [] -> ()
| [item] -> print_out_sig_item ppf item
| [item :: items] ->
fprintf ppf "%a@ %a" print_out_sig_item item print_signature_body
items ]
and print_out_sig_item ppf =
fun
[ Osig_class vir_flag name params clt ->
fprintf ppf "@[<2>class%s@ %a%s@ :@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name print_out_class_type clt
| Osig_class_type vir_flag name params clt ->
fprintf ppf "@[<2>class type%s@ %a%s@ =@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name print_out_class_type clt
| Osig_exception id tyl ->
fprintf ppf "@[<2>exception %a@]" print_out_constr (id, tyl)
| Osig_modtype name Omty_abstract ->
fprintf ppf "@[<2>module type %s@]" name
| Osig_modtype name mty ->
fprintf ppf "@[<2>module type %s =@ %a@]" name print_out_module_type mty
| Osig_module name mty ->
fprintf ppf "@[<2>module %s :@ %a@]" name print_out_module_type mty
| Osig_type tdl -> print_out_type_decl_list ppf tdl
| Osig_value name ty prims ->
let kwd = if prims = [] then "val" else "external" in
let pr_prims ppf =
fun
[ [] -> ()
| [s :: sl] -> do {
fprintf ppf "@ = \"%s\"" s;
List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl
} ]
in
fprintf ppf "@[<2>%s %a :@ %a%a@]" kwd value_ident name print_out_type
ty pr_prims prims ]
and print_out_type_decl_list ppf =
fun
[ [] -> ()
| [x] -> print_out_type_decl "type" ppf x
| [x :: l] -> do {
print_out_type_decl "type" ppf x;
List.iter (fun x -> fprintf ppf "@ %a" (print_out_type_decl "and") x) l
} ]
and print_out_type_decl kwd ppf (name, args, ty, constraints) =
let print_constraints ppf params =
List.iter
(fun (ty1, ty2) ->
fprintf ppf "@ @[<2>constraint %a =@ %a@]" print_out_type ty1
print_out_type ty2)
params
in
let type_parameter ppf (ty, (co, cn)) =
fprintf ppf "%s'%s" (if not cn then "+" else if not co then "-" else "")
ty
in
let type_defined ppf =
match args with
[ [] -> fprintf ppf "%s" name
| [arg] -> fprintf ppf "@[%a@ %s@]" type_parameter arg name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list type_parameter (fun ppf -> fprintf ppf ",@ ")) args
name ]
in
let print_manifest ppf =
fun
[ Otyp_manifest ty _ -> fprintf ppf " =@ %a" print_out_type ty
| _ -> () ]
in
let print_name_args ppf =
fprintf ppf "%s %t%a" kwd type_defined print_manifest ty
in
let ty =
match ty with
[ Otyp_manifest _ ty -> ty
| _ -> ty ]
in
match ty with
[ Otyp_abstract ->
fprintf ppf "@[<2>@[<hv 2>%t@]%a@]" print_name_args print_constraints
constraints
| Otyp_record lbls ->
fprintf ppf "@[<2>@[<hv 2>%t = {%a@;<1 -2>}@]@ %a@]" print_name_args
(print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls
print_constraints constraints
| Otyp_sum constrs ->
fprintf ppf "@[<2>@[<hv 2>%t =@;<1 2>%a@]%a@]" print_name_args
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | ")) constrs
print_constraints constraints
| ty ->
fprintf ppf "@[<2>@[<hv 2>%t =@ %a@]%a@]" print_name_args print_out_type
ty print_constraints constraints ]
and print_out_constr ppf (name, tyl) =
match tyl with
[ [] -> fprintf ppf "%s" name
| _ ->
fprintf ppf "@[<2>%s of@ %a@]" name
(print_typlist print_simple_out_type " *") tyl ]
and print_out_label ppf (name, mut, arg) =
fprintf ppf "@[<2>%s%s :@ %a@];" (if mut then "mutable " else "") name
print_out_type arg
;
Signature items
value print_out_class_params ppf =
fun
[ [] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ "
(print_list (fun ppf x -> fprintf ppf "'%s" x)
(fun ppf -> fprintf ppf ", "))
tyl ]
;
value rec print_out_class_type ppf =
fun
[ Octy_constr id tyl ->
let pr_tyl ppf =
fun
[ [] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ " (print_typlist print_out_type ",")
tyl ]
in
fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id
| Octy_fun lab ty cty ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
print_out_type_2 ty print_out_class_type cty
| Octy_signature self_ty csil ->
let pr_param ppf =
fun
[ Some ty -> fprintf ppf "@ @[(%a)@]" print_out_type ty
| None -> () ]
in
fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty
(print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ "))
csil ]
and print_out_class_sig_item ppf =
fun
[ Ocsg_constraint ty1 ty2 ->
fprintf ppf "@[<2>constraint %a =@ %a@]" print_out_type ty1
print_out_type ty2
| Ocsg_method name priv virt ty ->
fprintf ppf "@[<2>method %s%s%s :@ %a@]"
(if priv then "private " else "") (if virt then "virtual " else "")
name print_out_type ty
| Ocsg_value name mut ty ->
fprintf ppf "@[<2>val %s%s :@ %a@]" (if mut then "mutable " else "")
name print_out_type ty ]
;
value rec print_out_module_type ppf =
fun
[ Omty_abstract -> ()
| Omty_functor name mty_arg mty_res ->
fprintf ppf "@[<2>functor@ (%s : %a) ->@ %a@]" name
print_out_module_type mty_arg print_out_module_type mty_res
| Omty_ident id -> fprintf ppf "%a" print_ident id
| Omty_signature sg ->
fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" print_signature_body sg ]
and print_signature_body ppf =
fun
[ [] -> ()
| [item] -> print_out_sig_item ppf item
| [item :: items] ->
fprintf ppf "%a@ %a" print_out_sig_item item print_signature_body
items ]
and print_out_sig_item ppf =
fun
[ Osig_class vir_flag name params clt ->
fprintf ppf "@[<2>class%s@ %a%s@ :@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name print_out_class_type clt
| Osig_class_type vir_flag name params clt ->
fprintf ppf "@[<2>class type%s@ %a%s@ =@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name print_out_class_type clt
| Osig_exception id tyl ->
fprintf ppf "@[<2>exception %a@]" print_out_constr (id, tyl)
| Osig_modtype name Omty_abstract ->
fprintf ppf "@[<2>module type %s@]" name
| Osig_modtype name mty ->
fprintf ppf "@[<2>module type %s =@ %a@]" name print_out_module_type mty
| Osig_module name mty ->
fprintf ppf "@[<2>module %s :@ %a@]" name print_out_module_type mty
| Osig_type tdl -> print_out_type_decl_list ppf tdl
| Osig_value name ty prims ->
let kwd = if prims = [] then "val" else "external" in
let pr_prims ppf =
fun
[ [] -> ()
| [s :: sl] -> do {
fprintf ppf "@ = \"%s\"" s;
List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl
} ]
in
fprintf ppf "@[<2>%s %a :@ %a%a@]" kwd value_ident name print_out_type
ty pr_prims prims ]
and print_out_type_decl_list ppf =
fun
[ [] -> ()
| [x] -> print_out_type_decl "type" ppf x
| [x :: l] -> do {
print_out_type_decl "type" ppf x;
List.iter (fun x -> fprintf ppf "@ %a" (print_out_type_decl "and") x) l
} ]
and print_out_type_decl kwd ppf (name, args, ty, constraints) =
let print_constraints ppf params =
List.iter
(fun (ty1, ty2) ->
fprintf ppf "@ @[<2>constraint %a =@ %a@]" print_out_type ty1
print_out_type ty2)
params
in
let type_parameter ppf (ty, (co, cn)) =
fprintf ppf "%s'%s" (if not cn then "+" else if not co then "-" else "")
ty
in
let type_defined ppf =
match args with
[ [] -> fprintf ppf "%s" name
| [arg] -> fprintf ppf "@[%a@ %s@]" type_parameter arg name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list type_parameter (fun ppf -> fprintf ppf ",@ ")) args
name ]
in
let print_manifest ppf =
fun
[ Otyp_manifest ty _ -> fprintf ppf " =@ %a" print_out_type ty
| _ -> () ]
in
let print_name_args ppf =
fprintf ppf "%s %t%a" kwd type_defined print_manifest ty
in
let ty =
match ty with
[ Otyp_manifest _ ty -> ty
| _ -> ty ]
in
match ty with
[ Otyp_abstract ->
fprintf ppf "@[<2>@[<hv 2>%t@]%a@]" print_name_args print_constraints
constraints
| Otyp_record lbls ->
fprintf ppf "@[<2>@[<hv 2>%t = {%a@;<1 -2>}@]@ %a@]" print_name_args
(print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls
print_constraints constraints
| Otyp_sum constrs ->
fprintf ppf "@[<2>@[<hv 2>%t =@;<1 2>%a@]%a@]" print_name_args
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | ")) constrs
print_constraints constraints
| ty ->
fprintf ppf "@[<2>@[<hv 2>%t =@ %a@]%a@]" print_name_args print_out_type
ty print_constraints constraints ]
and print_out_constr ppf (name, tyl) =
match tyl with
[ [] -> fprintf ppf "%s" name
| _ ->
fprintf ppf "@[<2>%s of@ %a@]" name
(print_typlist print_simple_out_type " *") tyl ]
and print_out_label ppf (name, mut, arg) =
fprintf ppf "@[<2>%s%s :@ %a@];" (if mut then "mutable " else "") name
print_out_type arg
;
(* Phrases *)
value print_out_exception ppf exn outv =
match exn with
[ Sys.Break -> fprintf ppf "Interrupted.@."
| Out_of_memory -> fprintf ppf "Out of memory during evaluation.@."
| Stack_overflow ->
fprintf ppf "Stack overflow during evaluation (looping recursion?).@."
| _ ->
fprintf ppf "@[Exception:@ %a.@]@." Toploop.print_out_value.val outv ]
;
value rec print_items ppf =
fun
[ [] -> ()
| [(tree, valopt) :: items] -> do {
match valopt with
[ Some v ->
fprintf ppf "@[<2>%a =@ %a@]" Toploop.print_out_sig_item.val tree
Toploop.print_out_value.val v
| None -> fprintf ppf "@[%a@]" Toploop.print_out_sig_item.val tree ];
if items <> [] then fprintf ppf "@ %a" print_items items else ()
} ]
;
value print_out_phrase ppf =
fun
[ Ophr_eval outv ty ->
fprintf ppf "@[- : %a@ =@ %a@]@." Toploop.print_out_type.val ty
Toploop.print_out_value.val outv
| Ophr_signature [] -> ()
| Ophr_signature items -> fprintf ppf "@[<v>%a@]@." print_items items
| Ophr_exception (exn, outv) -> print_out_exception ppf exn outv ]
;
Toploop.print_out_value.val := print_out_value;
Toploop.print_out_type.val := print_out_type;
Toploop.print_out_sig_item.val := print_out_sig_item;
Toploop.print_out_phrase.val := print_out_phrase;
| null | https://raw.githubusercontent.com/camlp5/camlp5/15e03f56f55b2856dafe7dd3ca232799069f5dda/top/oprint.ml | ocaml | camlp5r
Values
Types
Phrases | oprint.ml , v
Copyright ( c ) INRIA 2007 - 2017
open Format;
open Outcometree;
exception Ellipsis;
value cautious f ppf arg =
try f ppf arg with [ Ellipsis -> fprintf ppf "..." ]
;
value rec print_ident ppf =
fun
[ Oide_ident s -> fprintf ppf "%s" s
| Oide_dot id s -> fprintf ppf "%a.%s" print_ident id s
| Oide_apply id1 id2 ->
fprintf ppf "%a(%a)" print_ident id1 print_ident id2 ]
;
value value_ident ppf name =
if List.mem name ["or"; "mod"; "land"; "lor"; "lxor"; "lsl"; "lsr"; "asr"]
then
fprintf ppf "( %s )" name
else
match name.[0] with
[ 'a'..'z' | '\223'..'\246' | '\248'..'\255' | '_' ->
fprintf ppf "%s" name
| _ -> fprintf ppf "( %s )" name ]
;
value print_out_value ppf tree =
let rec print_tree ppf =
fun
[ Oval_tuple tree_list ->
fprintf ppf "@[%a@]" (print_tree_list print_tree_1 ",") tree_list
| tree -> print_tree_1 ppf tree ]
and print_tree_1 ppf =
fun
[ Oval_constr name [param] ->
fprintf ppf "@[<1>%a@ %a@]" print_ident name print_simple_tree param
| Oval_constr name ([_ :: _] as params) ->
fprintf ppf "@[<1>%a@ (%a)@]" print_ident name
(print_tree_list print_tree_1 ",") params
| Oval_variant name (Some param) ->
fprintf ppf "@[<2>`%s@ %a@]" name print_simple_tree param
| tree -> print_simple_tree ppf tree ]
and print_simple_tree ppf =
fun
[ Oval_int i -> fprintf ppf "%i" i
| Oval_int32 i -> fprintf ppf "%li" i
| Oval_int64 i -> fprintf ppf "%Li" i
| Oval_nativeint i -> fprintf ppf "%ni" i
| Oval_float f -> fprintf ppf "%s" (string_of_float f)
| Oval_char c -> fprintf ppf "'%s'" (Char.escaped c)
| Oval_string s ->
try fprintf ppf "\"%s\"" (String.escaped s) with
[ Invalid_argument "String.create" -> fprintf ppf "<huge string>" ]
| Oval_list tl ->
fprintf ppf "@[<1>[%a]@]" (print_tree_list print_tree_1 ";") tl
| Oval_array tl ->
fprintf ppf "@[<2>[|%a|]@]" (print_tree_list print_tree_1 ";") tl
| Oval_constr name [] -> print_ident ppf name
| Oval_variant name None -> fprintf ppf "`%s" name
| Oval_stuff s -> fprintf ppf "%s" s
| Oval_record fel ->
fprintf ppf "@[<1>{%a}@]" (cautious (print_fields True)) fel
| Oval_ellipsis -> raise Ellipsis
| Oval_printer f -> f ppf
| tree -> fprintf ppf "@[<1>(%a)@]" (cautious print_tree) tree ]
and print_fields first ppf =
fun
[ [] -> ()
| [(name, tree) :: fields] -> do {
if not first then fprintf ppf ";@ " else ();
fprintf ppf "@[<1>%a@ =@ %a@]" print_ident name (cautious print_tree)
tree;
print_fields False ppf fields
} ]
and print_tree_list print_item sep ppf tree_list =
let rec print_list first ppf =
fun
[ [] -> ()
| [tree :: tree_list] -> do {
if not first then fprintf ppf "%s@ " sep else ();
print_item ppf tree;
print_list False ppf tree_list
} ]
in
cautious (print_list True) ppf tree_list
in
cautious print_tree ppf tree
;
value rec print_list_init pr sep ppf =
fun
[ [] -> ()
| [a :: l] -> do { sep ppf; pr ppf a; print_list_init pr sep ppf l } ]
;
value rec print_list pr sep ppf =
fun
[ [] -> ()
| [a] -> pr ppf a
| [a :: l] -> do { pr ppf a; sep ppf; print_list pr sep ppf l } ]
;
value pr_present =
print_list (fun ppf s -> fprintf ppf "`%s" s) (fun ppf -> fprintf ppf "@ ")
;
value rec print_out_type ppf =
fun
[ Otyp_alias ty s -> fprintf ppf "@[%a as '%s@]" print_out_type ty s
| ty -> print_out_type_1 ppf ty ]
and print_out_type_1 ppf =
fun
[ Otyp_arrow lab ty1 ty2 ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
print_out_type_2 ty1 print_out_type_1 ty2
| ty -> print_out_type_2 ppf ty ]
and print_out_type_2 ppf =
fun
[ Otyp_tuple tyl ->
fprintf ppf "@[<0>%a@]" (print_typlist print_simple_out_type " *") tyl
| ty -> print_simple_out_type ppf ty ]
and print_simple_out_type ppf =
fun
[ Otyp_class ng id tyl ->
fprintf ppf "@[%a%s#%a@]" print_typargs tyl (if ng then "_" else "")
print_ident id
| Otyp_constr id tyl ->
fprintf ppf "@[%a%a@]" print_typargs tyl print_ident id
| Otyp_object fields rest ->
fprintf ppf "@[<2>< %a >@]" (print_fields rest) fields
| Otyp_stuff s -> fprintf ppf "%s" s
| Otyp_var ng s -> fprintf ppf "'%s%s" (if ng then "_" else "") s
| Otyp_variant non_gen poly_variants closed tags ->
let print_present ppf =
fun
[ None | Some [] -> ()
| Some l -> fprintf ppf "@;<1 -2>> @[<hov>%a@]" pr_present l ]
in
let print_fields ppf =
fun
[ Ovar_fields fields ->
print_list print_poly_variant
(fun ppf -> fprintf ppf "@;<1 -2>| ") ppf fields
| Ovar_name id tyl ->
fprintf ppf "@[%a%a@]" print_typargs tyl print_ident id ]
in
fprintf ppf "%s[%s@[<hv>@[<hv>%a@]%a]@]" (if non_gen then "_" else "")
(if closed then if tags = None then " " else "< "
else if tags = None then "> "
else "? ")
print_fields poly_variants print_present tags
| Otyp_alias _ _ | Otyp_arrow _ _ _ | Otyp_tuple _ as ty ->
fprintf ppf "@[<1>(%a)@]" print_out_type ty
| Otyp_abstract | Otyp_sum _ | Otyp_record _ | Otyp_manifest _ _ -> () ]
and print_fields rest ppf =
fun
[ [] ->
match rest with
[ Some non_gen -> fprintf ppf "%s.." (if non_gen then "_" else "")
| None -> () ]
| [(s, t)] -> do {
fprintf ppf "%s : %a" s print_out_type t;
match rest with
[ Some _ -> fprintf ppf ";@ "
| None -> () ];
print_fields rest ppf []
}
| [(s, t) :: l] ->
fprintf ppf "%s : %a;@ %a" s print_out_type t (print_fields rest) l ]
and print_poly_variant ppf (l, opt_amp, tyl) =
let pr_of ppf =
if opt_amp then fprintf ppf " of@ &@ "
else if tyl <> [] then fprintf ppf " of@ "
else fprintf ppf ""
in
fprintf ppf "@[<hv 2>`%s%t%a@]" l pr_of (print_typlist print_out_type " &")
tyl
and print_typlist print_elem sep ppf =
fun
[ [] -> ()
| [ty] -> print_elem ppf ty
| [ty :: tyl] ->
fprintf ppf "%a%s@ %a" print_elem ty sep (print_typlist print_elem sep)
tyl ]
and print_typargs ppf =
fun
[ [] -> ()
| [ty1] -> fprintf ppf "%a@ " print_simple_out_type ty1
| tyl ->
fprintf ppf "@[<1>(%a)@]@ " (print_typlist print_out_type ",") tyl ]
;
Signature items
value print_out_class_params ppf =
fun
[ [] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ "
(print_list (fun ppf x -> fprintf ppf "'%s" x)
(fun ppf -> fprintf ppf ", "))
tyl ]
;
value rec print_out_class_type ppf =
fun
[ Octy_constr id tyl ->
let pr_tyl ppf =
fun
[ [] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ " (print_typlist print_out_type ",")
tyl ]
in
fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id
| Octy_fun lab ty cty ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
print_out_type_2 ty print_out_class_type cty
| Octy_signature self_ty csil ->
let pr_param ppf =
fun
[ Some ty -> fprintf ppf "@ @[(%a)@]" print_out_type ty
| None -> () ]
in
fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty
(print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ "))
csil ]
and print_out_class_sig_item ppf =
fun
[ Ocsg_constraint ty1 ty2 ->
fprintf ppf "@[<2>constraint %a =@ %a@]" print_out_type ty1
print_out_type ty2
| Ocsg_method name priv virt ty ->
fprintf ppf "@[<2>method %s%s%s :@ %a@]"
(if priv then "private " else "") (if virt then "virtual " else "")
name print_out_type ty
| Ocsg_value name mut ty ->
fprintf ppf "@[<2>val %s%s :@ %a@]" (if mut then "mutable " else "")
name print_out_type ty ]
;
value rec print_out_module_type ppf =
fun
[ Omty_abstract -> ()
| Omty_functor name mty_arg mty_res ->
fprintf ppf "@[<2>functor@ (%s : %a) ->@ %a@]" name
print_out_module_type mty_arg print_out_module_type mty_res
| Omty_ident id -> fprintf ppf "%a" print_ident id
| Omty_signature sg ->
fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" print_signature_body sg ]
and print_signature_body ppf =
fun
[ [] -> ()
| [item] -> print_out_sig_item ppf item
| [item :: items] ->
fprintf ppf "%a@ %a" print_out_sig_item item print_signature_body
items ]
and print_out_sig_item ppf =
fun
[ Osig_class vir_flag name params clt ->
fprintf ppf "@[<2>class%s@ %a%s@ :@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name print_out_class_type clt
| Osig_class_type vir_flag name params clt ->
fprintf ppf "@[<2>class type%s@ %a%s@ =@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name print_out_class_type clt
| Osig_exception id tyl ->
fprintf ppf "@[<2>exception %a@]" print_out_constr (id, tyl)
| Osig_modtype name Omty_abstract ->
fprintf ppf "@[<2>module type %s@]" name
| Osig_modtype name mty ->
fprintf ppf "@[<2>module type %s =@ %a@]" name print_out_module_type mty
| Osig_module name mty ->
fprintf ppf "@[<2>module %s :@ %a@]" name print_out_module_type mty
| Osig_type tdl -> print_out_type_decl_list ppf tdl
| Osig_value name ty prims ->
let kwd = if prims = [] then "val" else "external" in
let pr_prims ppf =
fun
[ [] -> ()
| [s :: sl] -> do {
fprintf ppf "@ = \"%s\"" s;
List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl
} ]
in
fprintf ppf "@[<2>%s %a :@ %a%a@]" kwd value_ident name print_out_type
ty pr_prims prims ]
and print_out_type_decl_list ppf =
fun
[ [] -> ()
| [x] -> print_out_type_decl "type" ppf x
| [x :: l] -> do {
print_out_type_decl "type" ppf x;
List.iter (fun x -> fprintf ppf "@ %a" (print_out_type_decl "and") x) l
} ]
and print_out_type_decl kwd ppf (name, args, ty, constraints) =
let print_constraints ppf params =
List.iter
(fun (ty1, ty2) ->
fprintf ppf "@ @[<2>constraint %a =@ %a@]" print_out_type ty1
print_out_type ty2)
params
in
let type_parameter ppf (ty, (co, cn)) =
fprintf ppf "%s'%s" (if not cn then "+" else if not co then "-" else "")
ty
in
let type_defined ppf =
match args with
[ [] -> fprintf ppf "%s" name
| [arg] -> fprintf ppf "@[%a@ %s@]" type_parameter arg name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list type_parameter (fun ppf -> fprintf ppf ",@ ")) args
name ]
in
let print_manifest ppf =
fun
[ Otyp_manifest ty _ -> fprintf ppf " =@ %a" print_out_type ty
| _ -> () ]
in
let print_name_args ppf =
fprintf ppf "%s %t%a" kwd type_defined print_manifest ty
in
let ty =
match ty with
[ Otyp_manifest _ ty -> ty
| _ -> ty ]
in
match ty with
[ Otyp_abstract ->
fprintf ppf "@[<2>@[<hv 2>%t@]%a@]" print_name_args print_constraints
constraints
| Otyp_record lbls ->
fprintf ppf "@[<2>@[<hv 2>%t = {%a@;<1 -2>}@]@ %a@]" print_name_args
(print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls
print_constraints constraints
| Otyp_sum constrs ->
fprintf ppf "@[<2>@[<hv 2>%t =@;<1 2>%a@]%a@]" print_name_args
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | ")) constrs
print_constraints constraints
| ty ->
fprintf ppf "@[<2>@[<hv 2>%t =@ %a@]%a@]" print_name_args print_out_type
ty print_constraints constraints ]
and print_out_constr ppf (name, tyl) =
match tyl with
[ [] -> fprintf ppf "%s" name
| _ ->
fprintf ppf "@[<2>%s of@ %a@]" name
(print_typlist print_simple_out_type " *") tyl ]
and print_out_label ppf (name, mut, arg) =
fprintf ppf "@[<2>%s%s :@ %a@];" (if mut then "mutable " else "") name
print_out_type arg
;
Signature items
value print_out_class_params ppf =
fun
[ [] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ "
(print_list (fun ppf x -> fprintf ppf "'%s" x)
(fun ppf -> fprintf ppf ", "))
tyl ]
;
value rec print_out_class_type ppf =
fun
[ Octy_constr id tyl ->
let pr_tyl ppf =
fun
[ [] -> ()
| tyl ->
fprintf ppf "@[<1>[%a]@]@ " (print_typlist print_out_type ",")
tyl ]
in
fprintf ppf "@[%a%a@]" pr_tyl tyl print_ident id
| Octy_fun lab ty cty ->
fprintf ppf "@[%s%a ->@ %a@]" (if lab <> "" then lab ^ ":" else "")
print_out_type_2 ty print_out_class_type cty
| Octy_signature self_ty csil ->
let pr_param ppf =
fun
[ Some ty -> fprintf ppf "@ @[(%a)@]" print_out_type ty
| None -> () ]
in
fprintf ppf "@[<hv 2>@[<2>object%a@]@ %a@;<1 -2>end@]" pr_param self_ty
(print_list print_out_class_sig_item (fun ppf -> fprintf ppf "@ "))
csil ]
and print_out_class_sig_item ppf =
fun
[ Ocsg_constraint ty1 ty2 ->
fprintf ppf "@[<2>constraint %a =@ %a@]" print_out_type ty1
print_out_type ty2
| Ocsg_method name priv virt ty ->
fprintf ppf "@[<2>method %s%s%s :@ %a@]"
(if priv then "private " else "") (if virt then "virtual " else "")
name print_out_type ty
| Ocsg_value name mut ty ->
fprintf ppf "@[<2>val %s%s :@ %a@]" (if mut then "mutable " else "")
name print_out_type ty ]
;
value rec print_out_module_type ppf =
fun
[ Omty_abstract -> ()
| Omty_functor name mty_arg mty_res ->
fprintf ppf "@[<2>functor@ (%s : %a) ->@ %a@]" name
print_out_module_type mty_arg print_out_module_type mty_res
| Omty_ident id -> fprintf ppf "%a" print_ident id
| Omty_signature sg ->
fprintf ppf "@[<hv 2>sig@ %a@;<1 -2>end@]" print_signature_body sg ]
and print_signature_body ppf =
fun
[ [] -> ()
| [item] -> print_out_sig_item ppf item
| [item :: items] ->
fprintf ppf "%a@ %a" print_out_sig_item item print_signature_body
items ]
and print_out_sig_item ppf =
fun
[ Osig_class vir_flag name params clt ->
fprintf ppf "@[<2>class%s@ %a%s@ :@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name print_out_class_type clt
| Osig_class_type vir_flag name params clt ->
fprintf ppf "@[<2>class type%s@ %a%s@ =@ %a@]"
(if vir_flag then " virtual" else "") print_out_class_params params
name print_out_class_type clt
| Osig_exception id tyl ->
fprintf ppf "@[<2>exception %a@]" print_out_constr (id, tyl)
| Osig_modtype name Omty_abstract ->
fprintf ppf "@[<2>module type %s@]" name
| Osig_modtype name mty ->
fprintf ppf "@[<2>module type %s =@ %a@]" name print_out_module_type mty
| Osig_module name mty ->
fprintf ppf "@[<2>module %s :@ %a@]" name print_out_module_type mty
| Osig_type tdl -> print_out_type_decl_list ppf tdl
| Osig_value name ty prims ->
let kwd = if prims = [] then "val" else "external" in
let pr_prims ppf =
fun
[ [] -> ()
| [s :: sl] -> do {
fprintf ppf "@ = \"%s\"" s;
List.iter (fun s -> fprintf ppf "@ \"%s\"" s) sl
} ]
in
fprintf ppf "@[<2>%s %a :@ %a%a@]" kwd value_ident name print_out_type
ty pr_prims prims ]
and print_out_type_decl_list ppf =
fun
[ [] -> ()
| [x] -> print_out_type_decl "type" ppf x
| [x :: l] -> do {
print_out_type_decl "type" ppf x;
List.iter (fun x -> fprintf ppf "@ %a" (print_out_type_decl "and") x) l
} ]
and print_out_type_decl kwd ppf (name, args, ty, constraints) =
let print_constraints ppf params =
List.iter
(fun (ty1, ty2) ->
fprintf ppf "@ @[<2>constraint %a =@ %a@]" print_out_type ty1
print_out_type ty2)
params
in
let type_parameter ppf (ty, (co, cn)) =
fprintf ppf "%s'%s" (if not cn then "+" else if not co then "-" else "")
ty
in
let type_defined ppf =
match args with
[ [] -> fprintf ppf "%s" name
| [arg] -> fprintf ppf "@[%a@ %s@]" type_parameter arg name
| _ ->
fprintf ppf "@[(@[%a)@]@ %s@]"
(print_list type_parameter (fun ppf -> fprintf ppf ",@ ")) args
name ]
in
let print_manifest ppf =
fun
[ Otyp_manifest ty _ -> fprintf ppf " =@ %a" print_out_type ty
| _ -> () ]
in
let print_name_args ppf =
fprintf ppf "%s %t%a" kwd type_defined print_manifest ty
in
let ty =
match ty with
[ Otyp_manifest _ ty -> ty
| _ -> ty ]
in
match ty with
[ Otyp_abstract ->
fprintf ppf "@[<2>@[<hv 2>%t@]%a@]" print_name_args print_constraints
constraints
| Otyp_record lbls ->
fprintf ppf "@[<2>@[<hv 2>%t = {%a@;<1 -2>}@]@ %a@]" print_name_args
(print_list_init print_out_label (fun ppf -> fprintf ppf "@ ")) lbls
print_constraints constraints
| Otyp_sum constrs ->
fprintf ppf "@[<2>@[<hv 2>%t =@;<1 2>%a@]%a@]" print_name_args
(print_list print_out_constr (fun ppf -> fprintf ppf "@ | ")) constrs
print_constraints constraints
| ty ->
fprintf ppf "@[<2>@[<hv 2>%t =@ %a@]%a@]" print_name_args print_out_type
ty print_constraints constraints ]
and print_out_constr ppf (name, tyl) =
match tyl with
[ [] -> fprintf ppf "%s" name
| _ ->
fprintf ppf "@[<2>%s of@ %a@]" name
(print_typlist print_simple_out_type " *") tyl ]
and print_out_label ppf (name, mut, arg) =
fprintf ppf "@[<2>%s%s :@ %a@];" (if mut then "mutable " else "") name
print_out_type arg
;
value print_out_exception ppf exn outv =
match exn with
[ Sys.Break -> fprintf ppf "Interrupted.@."
| Out_of_memory -> fprintf ppf "Out of memory during evaluation.@."
| Stack_overflow ->
fprintf ppf "Stack overflow during evaluation (looping recursion?).@."
| _ ->
fprintf ppf "@[Exception:@ %a.@]@." Toploop.print_out_value.val outv ]
;
value rec print_items ppf =
fun
[ [] -> ()
| [(tree, valopt) :: items] -> do {
match valopt with
[ Some v ->
fprintf ppf "@[<2>%a =@ %a@]" Toploop.print_out_sig_item.val tree
Toploop.print_out_value.val v
| None -> fprintf ppf "@[%a@]" Toploop.print_out_sig_item.val tree ];
if items <> [] then fprintf ppf "@ %a" print_items items else ()
} ]
;
value print_out_phrase ppf =
fun
[ Ophr_eval outv ty ->
fprintf ppf "@[- : %a@ =@ %a@]@." Toploop.print_out_type.val ty
Toploop.print_out_value.val outv
| Ophr_signature [] -> ()
| Ophr_signature items -> fprintf ppf "@[<v>%a@]@." print_items items
| Ophr_exception (exn, outv) -> print_out_exception ppf exn outv ]
;
Toploop.print_out_value.val := print_out_value;
Toploop.print_out_type.val := print_out_type;
Toploop.print_out_sig_item.val := print_out_sig_item;
Toploop.print_out_phrase.val := print_out_phrase;
|
14730416dca2882c35ce03f54a617ccc8a9a6433067089b5ef78f72041d599cd | jyp/lp-diagrams | Model.hs | module SMT.Model (readModel) where
import Text.ParserCombinators.Parsek.Position
import Data.Char (isSpace)
type P a = Parser a
tok :: String -> P ()
tok s = spaces >> string s >> return ()
many1 p = (:) <$> p <*> many p
parseDouble :: P Double
parseDouble = do
spaces
x <- many1 digit
string "."
y <- many1 digit
return $ read $ x ++ "." ++ y
parseValue = parseDouble <|> parens (parseDiv <|> parseNeg)
parseDiv = do
tok "/"
x <- parseValue
y <- parseValue
return (x/y)
parseNeg = do
tok "-"
x <- parseValue
return (negate x)
parseAssoc :: P (String,Double)
parseAssoc = parens $ do
tok "define-fun"
spaces
v <- many1 (satisfy (not . isSpace))
parens (return ())
tok "Real"
x <- parseValue
return (v,x)
parens :: Parser a -> Parser a
parens = between (tok "(") (tok")")
parseModel :: Parser [(String, Double)]
parseModel = parens $ do
_ <- optional (tok "model")
z3 < = 4.8.8 outputs the word " model "
z3 > = 4.8.10 does not
many parseAssoc
readModel :: String -> ParseResult SourcePos [(String, Double)]
readModel = parse "<model>" parseModel longestResult
| null | https://raw.githubusercontent.com/jyp/lp-diagrams/d334eee4343f340976c09d0da27431d5777a0266/SMT/Model.hs | haskell | module SMT.Model (readModel) where
import Text.ParserCombinators.Parsek.Position
import Data.Char (isSpace)
type P a = Parser a
tok :: String -> P ()
tok s = spaces >> string s >> return ()
many1 p = (:) <$> p <*> many p
parseDouble :: P Double
parseDouble = do
spaces
x <- many1 digit
string "."
y <- many1 digit
return $ read $ x ++ "." ++ y
parseValue = parseDouble <|> parens (parseDiv <|> parseNeg)
parseDiv = do
tok "/"
x <- parseValue
y <- parseValue
return (x/y)
parseNeg = do
tok "-"
x <- parseValue
return (negate x)
parseAssoc :: P (String,Double)
parseAssoc = parens $ do
tok "define-fun"
spaces
v <- many1 (satisfy (not . isSpace))
parens (return ())
tok "Real"
x <- parseValue
return (v,x)
parens :: Parser a -> Parser a
parens = between (tok "(") (tok")")
parseModel :: Parser [(String, Double)]
parseModel = parens $ do
_ <- optional (tok "model")
z3 < = 4.8.8 outputs the word " model "
z3 > = 4.8.10 does not
many parseAssoc
readModel :: String -> ParseResult SourcePos [(String, Double)]
readModel = parse "<model>" parseModel longestResult
| |
7be33b15034ccfca8bb0b101bf3b2081e212d3c1354cebb45d63a31402e748a0 | rescript-association/reanalyze | FindSourceFile.ml | (** Prepend nativeBuildTarget to fname when provided (-native-build-target) *)
let nativeFilePath fname =
match !Common.Cli.nativeBuildTarget with
| None -> fname
| Some nativeBuildTarget -> Filename.concat nativeBuildTarget fname
let rec interface items =
match items with
| {CL.Typedtree.sig_loc} :: rest -> (
match
not (Sys.file_exists (nativeFilePath sig_loc.loc_start.pos_fname))
with
| true -> interface rest
| false -> Some sig_loc.loc_start.pos_fname)
| [] -> None
let rec implementation items =
match items with
| {CL.Typedtree.str_loc} :: rest -> (
match
not (Sys.file_exists (nativeFilePath str_loc.loc_start.pos_fname))
with
| true -> implementation rest
| false -> Some str_loc.loc_start.pos_fname)
| [] -> None
let cmt cmt_annots =
match cmt_annots with
| CL.Cmt_format.Interface signature ->
if !Common.Cli.debug && signature.sig_items = [] then
Log_.item "Interface %d@." (signature.sig_items |> List.length);
interface signature.sig_items
| Implementation structure ->
if !Common.Cli.debug && structure.str_items = [] then
Log_.item "Implementation %d@." (structure.str_items |> List.length);
implementation structure.str_items
| _ -> None
| null | https://raw.githubusercontent.com/rescript-association/reanalyze/f98831c1cd5dabc1737f500515f0f3ae443a232b/src/FindSourceFile.ml | ocaml | * Prepend nativeBuildTarget to fname when provided (-native-build-target) | let nativeFilePath fname =
match !Common.Cli.nativeBuildTarget with
| None -> fname
| Some nativeBuildTarget -> Filename.concat nativeBuildTarget fname
let rec interface items =
match items with
| {CL.Typedtree.sig_loc} :: rest -> (
match
not (Sys.file_exists (nativeFilePath sig_loc.loc_start.pos_fname))
with
| true -> interface rest
| false -> Some sig_loc.loc_start.pos_fname)
| [] -> None
let rec implementation items =
match items with
| {CL.Typedtree.str_loc} :: rest -> (
match
not (Sys.file_exists (nativeFilePath str_loc.loc_start.pos_fname))
with
| true -> implementation rest
| false -> Some str_loc.loc_start.pos_fname)
| [] -> None
let cmt cmt_annots =
match cmt_annots with
| CL.Cmt_format.Interface signature ->
if !Common.Cli.debug && signature.sig_items = [] then
Log_.item "Interface %d@." (signature.sig_items |> List.length);
interface signature.sig_items
| Implementation structure ->
if !Common.Cli.debug && structure.str_items = [] then
Log_.item "Implementation %d@." (structure.str_items |> List.length);
implementation structure.str_items
| _ -> None
|
3fd022718e2444951de55fa59ae006a2953cc1cd8f5347157a1b35b3facf181b | nuprl/gradual-typing-performance | classes.rkt | (module classes typed/racket
(require ;racket/class
(prefix-in mred: typed/racket/gui)
(prefix-in util: "utils.rkt")
"typed-base.rkt" ; replace this with base, after defining interfaces
"constants.rkt"
"make-cards.rkt"
string-constants
"../show-help.rkt")
;; case-lambda bug
(require (only-in racket/base case-lambda))
( require / typed racket [ remq ( All ( a ) ( Any ( a ) - > ( a ) ) ) ] )
(require/typed "../show-scribbling.rkt" [show-scribbling (Module-Path String -> (-> Void))])
(provide pasteboard%
table%)
(define-type Pasteboard%
(Class #:implements mred:Pasteboard%
[only-front-selected (-> Void)]
[get-all-list (-> (Listof (Instance mred:Snip% #;Card%)))]
[get-full-box (-> (Values Real Real Real Real))]
[get-region-box (Region -> (Values Real Real Nonnegative-Real Nonnegative-Real))]
[add-region (-> Region Void)]
[remove-region (-> Region Void)]
[unhilite-region (Region -> Void)]
[hilite-region (-> Region Void)]
[set-double-click-action (-> (-> (Instance mred:Snip%) Void) Void)]
[set-single-click-action (-> (-> (Instance Card%) Void) Void)]
[set-button-action (-> (U 'left 'middle 'right) Symbol Void)]
(augment [after-select ((Instance mred:Snip%) Any -> Void)]
[on-interactive-move ((Instance mred:Mouse-Event%) -> Void)]
[after-interactive-move ((Instance mred:Mouse-Event%) -> Void)])))
(: pasteboard% Pasteboard%)
(define pasteboard%
(class mred:pasteboard%
(inherit begin-edit-sequence end-edit-sequence get-admin
invalidate-bitmap-cache
find-next-selected-snip find-first-snip find-snip
set-before set-after
add-selected is-selected? no-selected set-selected remove-selected
get-snip-location move-to
dc-location-to-editor-location
set-selection-visible)
(: select-one? Boolean)
(define select-one? #t)
(: select-backward? Boolean)
(define select-backward? #f)
(: raise-to-front? Boolean)
(define raise-to-front? #f)
(: button-map (Listof (List (U 'left 'middle 'right) Boolean Boolean Boolean)))
(define button-map '((left #f #f #t)
(middle #t #f #t)
(right #f #t #f)))
(: do-on-double-click (U 'flip ((Instance mred:Snip%) -> Void)))
(define do-on-double-click 'flip)
(: do-on-single-click ((Instance Card%) -> Void))
(define do-on-single-click void)
(: selecting? Boolean)
(define selecting? #f)
(: dragging? Boolean)
(define dragging? #f)
(: bg-click? Boolean)
(define bg-click? #f)
(: click-base (Option (Instance Card%)))
(define click-base #f)
(: last-click (Option Any))
(define last-click #f)
(: regions (Listof Region)) ; not sure if this is right, but a decent starting guess
(define regions null)
(: update-region (Region -> Void))
(: get-snip-bounds ((Instance mred:Snip%) -> (Values Real Real Real Real)))
(: get-reverse-selected-list (-> (Listof (Instance mred:Snip%))))
(: for-each-selected (-> (-> (Instance Card% #;mred:Snip%) Any) Void))
(: make-overlapping-list (-> (Instance mred:Snip%) (Listof (Instance mred:Snip%)) Any (Listof (Instance mred:Snip%))))
(private*
[get-snip-bounds
(lambda: ([s : (Instance mred:Snip%)])
(let: ([xbox : (Boxof Real) (box 0)]
[ybox : (Boxof Real) (box 0)])
(get-snip-location s xbox ybox #f)
(let ([l (unbox xbox)]
[t (unbox ybox)])
(get-snip-location s xbox ybox #t)
(values l t (unbox xbox) (unbox ybox)))))]
[for-each-selected
(lambda (f)
(let: loop : Void ([snip : (Option (Instance mred:Snip%)) (find-next-selected-snip #f)])
(when snip
(let ([snip : (Instance Card%) (cast snip (Instance Card%))])
(f snip)
(loop (find-next-selected-snip snip))))))]
[make-overlapping-list
(lambda ([s : (Instance mred:Snip%)] so-far behind?)
(let-values ([(sl st sr sb) (get-snip-bounds s)])
(let: loop : (Listof (Instance mred:Snip%)) ([t : (Option (Instance mred:Snip%)) (find-first-snip)] [so-far : (Listof (Instance mred:Snip%)) so-far] [get? : Boolean (not behind?)])
(cond
[(not t) so-far]
[(eq? s t) (if behind?
(loop (send t next) so-far #t)
so-far)]
[get?
(let ([l (if (and (not (memq t so-far))
(let-values ([(tl tt tr tb)
(get-snip-bounds t)])
(and (or (<= sl tl sr)
(<= sl tr sr))
(or (<= st tt sb)
(<= st tb sb)))))
(make-overlapping-list t ((inst cons (Instance mred:Snip%) (Listof (Instance mred:Snip%))) t so-far) behind?)
so-far)])
(loop (send t next) l #t))]
[else
(loop (send t next) so-far #f)]))))]
[get-reverse-selected-list
(lambda ()
(let: loop : (Listof (Instance mred:Snip%)) ([s (find-next-selected-snip #f)][l : (Listof (Instance mred:Snip%)) null])
(if s
(loop (find-next-selected-snip s) ((inst cons (Instance mred:Snip%) (Listof (Instance mred:Snip%))) s l))
l)))]
[shuffle
cards to shuffle in back->front order
(let* ([permuted-list : (Listof (Instance Card%))
(util:shuffle-list selected-list 7)]
[get-pos
(lambda ([s : (Instance mred:Snip%)])
(let ([xb : (Boxof Real) (box 0)]
[yb : (Boxof Real) (box 0)])
(get-snip-location s xb yb)
(cons (unbox xb) (unbox yb))))]
[sel-loc-list ((inst map (Pairof Real Real) (Instance mred:Snip%)) get-pos selected-list)]
[perm-loc-list ((inst map (Pairof Real Real) (Instance mred:Snip%)) get-pos permuted-list)])
((inst for-each (Instance Card%) (Pairof Real Real) (Pairof Real Real))
(lambda ([s : (Instance Card%)] [start-pos : (Pairof Real Real)] [end-pos : (Pairof Real Real)])
(let* ([sx : Real (car start-pos)]
[sy : Real (cdr start-pos)]
[ex : Real (car end-pos)]
[ey : Real (cdr end-pos)]
[steps (max 1 (floor (/ 50 (length selected-list))))])
(let: loop : Void ([i : Integer 1])
(unless (> i steps)
(let ([x (+ sx (* (/ i steps) (- ex sx)))]
[y (+ sy (* (/ i steps) (- ey sy)))])
(move-to s x y)
(mred:flush-display)
(loop (add1 i)))))))
permuted-list perm-loc-list sel-loc-list)
(let loop ([l permuted-list])
(unless (null? l)
(set-before (car l) #f)
(loop (cdr l))))
(no-selected)))]
[update-region
(lambda (region)
(let-values ([(sx sy sw sh) (get-region-box region)])
(invalidate-bitmap-cache sx sy sw sh)))])
(public*
[only-front-selected
(lambda ()
(let: loop : Void ([s : (Option (Instance mred:Snip%)) (find-next-selected-snip #f)][ok : (Option (Instance mred:Snip%)) (find-first-snip)])
(when s
(if (eq? s ok)
(loop (find-next-selected-snip s)
(send (assert ok) next))
(let: loop ([s : (Instance mred:Snip%) s][l : (Listof (Instance mred:Snip%)) (list s)])
(let ([next (find-next-selected-snip s)])
(if next
(loop next (cons s l))
(for-each (lambda: ([s : (Instance mred:Snip%)])
(remove-selected s))
l))))))))])
(override*
[on-paint
(lambda (before? dc l t r b dx dy caret)
(when before?
(for-each
(lambda: ([region : Region])
(when (region-paint-callback region)
(let-values ([(sx sy sw sh) (get-region-box region)])
((assert (region-paint-callback region)) dc (+ dx sx) (+ dy sy) sw sh)))
(when (region-label region)
(let ([old-b (send dc get-brush)]
[old-p (send dc get-pen)])
(let-values ([(sx sy sw sh) (get-region-box region)])
(send dc set-brush (assert white-brush))
(send dc set-pen no-pen)
(send dc draw-rectangle (+ dx sx) (+ dy sy) sw sh)
(send dc set-pen dark-gray-pen)
(draw-roundish-rectangle dc (+ dx sx) (+ dy sy) sw sh)
(let ([text (region-label region)])
(if (string? text)
(let ([old-f (send dc get-font)])
(send dc set-font nice-font)
(let-values ([(x y d a) (send dc get-text-extent text)])
(send dc draw-text text
(+ dx sx (/ (- sw x) 2))
(if (region-button? region)
;; Since we use size-in-pixels, the letters
should really be 12 pixels high ( including
;; the descender), but the space above the letter
can vary by font ; center on 12 , splitting
;; the difference for the descender
(+ dy sy (/ (- sh 12) 2) (- 12 y (/ d -2)))
(+ dy sy 5))))
(send dc set-font old-f))
(send dc draw-bitmap (assert text)
(+ dx sx (/ (- sw (send (assert text) get-width)) 2))
(+ dy sy (/ (- sh (send (assert text) get-height)) 2))
'solid black-color
(send (assert text) get-loaded-mask))))
(when (region-hilite? region)
(send dc set-brush (assert hilite-brush))
(send dc set-pen no-pen)
(send dc draw-rectangle (+ dx sx 1) (+ dy sy 1) (assert (- sw 2) (lambda: ([x : Real]) (>= x 0))) (assert (- sh 2) (lambda: ([x : Real]) (>= x 0))))))
(send dc set-brush old-b)
(send dc set-pen old-p))))
regions)))])
(augment*
[after-select
(lambda: ([s : (Instance mred:Snip%)] [on? : Any])
(inner (void) after-select s on?)
(unless (or (not on?) selecting?)
(set! selecting? #t)
(if select-one?
(when raise-to-front?
(set-before s #f))
(begin
(begin-edit-sequence)
(let ([l : (Listof (Instance mred:Snip%)) (make-overlapping-list s (list s) select-backward?)])
((inst for-each (Instance mred:Snip%)) (lambda: ([i : (Instance mred:Snip%)]) (add-selected i)) l))
(when raise-to-front?
(let loop ([snip (find-next-selected-snip #f)][prev : (Option (Instance mred:Snip%)) #f])
(when snip
(if prev
(set-after snip prev)
(set-before snip #f))
(loop (find-next-selected-snip (assert snip)) snip))))
(end-edit-sequence)))
(set! selecting? #f)))]
[on-interactive-move
(lambda (e)
(inner (void) on-interactive-move e)
(for-each (lambda: ([region : Region]) (set-region-decided-start?! region #f)) regions)
(for-each-selected (lambda: ([snip : (Instance Card% #;mred:Snip%)]) (send snip remember-location this)))
(set! dragging? #t))])
(override*
[interactive-adjust-move
(lambda: ([snip : (Instance mred:Snip%)] [xb : (Boxof Real)] [yb : (Boxof Real)])
(super interactive-adjust-move snip xb yb)
(let ([snip (cast snip (Instance Card%))])
(let-values: ([([l : Real] [t : Real] [r : Real] [b : Real]) (get-snip-bounds snip)])
(let-values: ([([rl : Real] [rt : Real] [rw : Real] [rh : Real])
(let: ([r : (Option Region) (send snip stay-in-region)])
(if r
(values (region-x r) (region-y r)
(region-w r) (region-h r))
(let: ([wb : (Boxof Real) (box 0)][hb : (Boxof Real) (box 0)])
(send (assert (get-admin)) get-view #f #f wb hb)
(values 0 0 (unbox wb) (unbox hb)))))])
(let ([max-x (- (+ rl rw) (- r l))]
[max-y (- (+ rt rh) (- b t))])
(when (< (unbox xb) rl)
(set-box! xb rl))
(when (> (unbox xb) max-x)
(set-box! xb max-x))
(when (< (unbox yb) rt)
(set-box! yb rt))
(when (> (unbox yb) max-y)
(set-box! yb max-y)))))))])
(: after-interactive-move ((Instance mred:Mouse-Event%) -> Void) #:augment ((Instance mred:Mouse-Event%) -> Void))
(augment*
[after-interactive-move
(lambda: ([e : (Instance mred:Mouse-Event%)])
(when dragging?
(set! dragging? #f)
(inner (void) after-interactive-move e)
(for-each-selected (lambda: ([snip : (Instance Card% #;mred:Snip%)]) (send snip back-to-original-location this)))
(let: ([cards : (Listof (Instance mred:Snip%)) (get-reverse-selected-list)])
(only-front-selected) ; in case overlap changed
(for-each
(lambda: ([region : Region])
(when (region-hilite? region)
(mred:queue-callback
; Call it outside the current edit sequence
(lambda ()
((assert (region-callback region)) cards)
(unhilite-region region)))))
regions))))])
(override*
[on-default-event
(lambda: ([e : (Instance mred:Mouse-Event%)])
(let: ([click : (Option (U 'left 'middle 'right)) (let: ([c : (Option (U 'left 'middle 'right)) (or (and (send e button-down? 'left) 'left)
(and (send e button-down? 'right) 'right)
(and (send e button-down? 'middle) 'middle))])
(cond
[(eq? c last-click) c]
[(not last-click) c]
;; Move/drag event has different mouse button,
;; and there was no mouse up. Don't accept the
;; click, yet.
[else #f]))])
(set! last-click click)
(when click
(let*: ([actions : (List Boolean Boolean Boolean) (cdr (assert (assoc click button-map)))]
[one? (list-ref actions 0)]
[backward? (list-ref actions 1)]
[raise? (list-ref actions 2)])
(unless (and (eq? backward? select-backward?)
(eq? one? select-one?)
(eq? raise? raise-to-front?))
(set! select-one? one?)
(set! select-backward? backward?)
(set! raise-to-front? raise?)
(no-selected))))
(let*-values ([(lx ly) (dc-location-to-editor-location
(send e get-x)
(send e get-y))]
[(s) (find-snip lx ly)])
; Clicking on a "selected" card unselects others
; in this interface
(when (send e button-down?)
(unless (or (not click-base) (not s) (eq? s click-base))
(no-selected))
there does n't seem to be a better way to get this to typecheck than to c - a - s - t s to a Card% instance
;; occurence typing should work here??
(when (and dragging? click-base (send (assert click-base) user-can-move))
(for-each
(lambda: ([region : Region])
(when (and (not (region-button? region))
(region-callback region)
(or (not (region-decided-start? region))
(region-can-select? region)))
(let-values ([(sx sy sw sh) (get-region-box region)])
(let ([in? (and (<= sx lx (+ sx sw))
(<= sy ly (+ sy sh)))])
(unless (region-decided-start? region)
(set-region-decided-start?! region #t)
(set-region-can-select?! region (not in?)))
(when (and (not (eq? in? (region-hilite? region)))
(region-can-select? region))
(set-region-hilite?! region in?)
(when (region-interactive-callback region)
((assert (region-interactive-callback region)) in? (get-reverse-selected-list)))
(invalidate-bitmap-cache sx sy sw sh))))))
regions))
; Can't move => no raise, either
(unless (or (not click-base) (send (assert click-base) user-can-move))
(set! raise-to-front? #f))
(let ([was-bg? bg-click?])
(if (send e button-down?)
(set! bg-click? (not s))
(when (and bg-click? (not (send e dragging?)))
(set! bg-click? #f)))
(unless bg-click?
(super on-default-event e))
(when (and bg-click? dragging?)
;; We didn't call super on-default-event, so we need
;; to explicitly end the drag:
(after-interactive-move e))
(when bg-click?
; Check for clicking on a button region:
(for-each
(lambda: ([region : Region])
(when (and (region-button? region)
(region-callback region))
(let-values ([(sx sy sw sh) (get-region-box region)])
(let ([in? (and (<= sx lx (+ sx sw))
(<= sy ly (+ sy sh)))])
(unless (region-decided-start? region)
(set-region-decided-start?! region #t)
(set-region-can-select?! region in?))
(when (and (not (eq? in? (region-hilite? region)))
(region-can-select? region))
(set-region-hilite?! region in?)
(invalidate-bitmap-cache sx sy sw sh))))))
regions))
(when (and was-bg? (not bg-click?))
; Callback hilighted button:
(for-each
(lambda: ([region : Region])
(when (region-button? region)
(set-region-decided-start?! region #f)
(when (region-hilite? region)
(mred:queue-callback
; Call it outside the current edit sequence
(lambda ()
((assert (region-callback region))) ; changing type in typed-base, but this is a bug based on documentation
(unhilite-region region))))))
regions)))
(when (and (send e button-down?)
click-base
(not (send (assert click-base) user-can-move)))
(no-selected)))
(when (and click click-base)
(do-on-single-click (assert click-base)))))]
[on-double-click
(lambda (s e)
(cond
[(eq? do-on-double-click 'flip)
(begin-edit-sequence)
(let ([l (get-reverse-selected-list)])
(for-each
(lambda: ([s : (Instance mred:Snip%)])
(let ([s (cast s (Instance Card%))])
(when (send s user-can-flip)
(send s flip))))
l)
(let loop ([l (reverse l)])
(unless (null? l)
(set-before (car l) #f)
(loop (cdr l)))))
(no-selected)
(end-edit-sequence)]
[do-on-double-click
((assert do-on-double-click (lambda (x) (not (symbol? x)))) s)]
[else (void)]))])
(public*
[get-all-list
(lambda ()
Card% ) ) ( [ t : ( Option ( Instance mred : Snip% ) ) ( find - first - snip)][accum : ( ( Instance mred : Snip% # ; Card% ) ) null ] )
(cond
[(not t) (reverse accum)]
[else (loop (send t next) (cons t #;(cast t (Instance Card%)) accum))])))]
[get-full-box
(lambda ()
(let: ([xb : (Boxof Real) (box 0)] [yb : (Boxof Real) (box 0)]
[wb : (Boxof Real) (box 0)] [hb : (Boxof Real) (box 0)])
(send (assert (get-admin)) get-view xb yb wb hb)
(values 0 0 (unbox wb) (unbox hb))))]
[get-region-box
(lambda: ([region : Region])
(values (region-x region)
(region-y region)
(region-w region)
(region-h region)))]
[add-region
(lambda: ([r : Region])
(set! regions (append regions (list r)))
(update-region r))]
[remove-region
(lambda: ([r : Region])
(set! regions (remq r regions))
(update-region r))]
[unhilite-region
(lambda: ([region : Region])
(set-region-hilite?! region #f)
(update-region region))]
[hilite-region
(lambda: ([region : Region])
(set-region-hilite?! region #t)
(update-region region))]
[set-double-click-action
(lambda: ([a : (U ((Instance mred:Snip%) -> Void) 'flip)])
(set! do-on-double-click a))]
[set-single-click-action
(lambda: ([a : ((Instance Card%) -> Void)])
(set! do-on-single-click a))]
[set-button-action
(lambda: ([button : (U 'left 'middle 'right)] [action : Symbol])
(let: ([map : (List Boolean Boolean Boolean)
(case action
[(drag/one) (list #t #f #f)]
[(drag-raise/one) (list #t #f #t)]
[(drag/above) (list #f #f #f)]
[(drag-raise/above) (list #f #f #t)]
[(drag/below) (list #f #t #f)]
[(drag-raise/below) (list #f #t #t)]
[else (error 'set-button-action "unknown action: ~s" action)])])
(set! button-map
(cons
(ann (cons button map) (List (U 'left 'right 'middle) Boolean Boolean Boolean))
come back to this remq does n't really have the right type I think
button-map)))))])
(super-new) ;(super-make-object)
(set-selection-visible #f)))
(define-type Table%
(Class #:implements mred:Frame%
(init
[title String]
[w Nonnegative-Real]
[h Nonnegative-Real]
[parent (Option (Instance mred:Frame%)) #:optional]
[width (Option Integer) #:optional]
[height (Option Integer) #:optional]
[x (Option Integer) #:optional]
[y (Option Integer) #:optional]
[enabled Any #:optional]
[border Natural #:optional]
[spacing Natural #:optional]
[alignment (List (U 'left 'center 'right)
(U 'top 'center 'bottom))
#:optional]
[min-width (Option Natural) #:optional]
[min-height (Option Natural) #:optional]
[stretchable-width Any #:optional]
[stretchable-height Any #:optional])
(augment [on-close (-> Void)])
[table-width (-> Real)]
[table-height (-> Real)]
[begin-card-sequence (-> Void)]
[end-card-sequence (-> Void)]
[add-card ((Instance Card%) Real Real -> Any)]
[add-cards (case-> ((Listof (Instance Card%)) Real Real -> Void)
((Listof (Instance Card%)) Real Real (Any -> (Values Real Real)) -> Void))]
[add-cards-to-region ((Listof (Instance Card%)) Region -> Void)]
[move-card (-> (Instance Card%) Real Real Void)]
[move-cards (case-> ((Listof (Instance Card%)) Real Real -> Void)
((Listof (Instance Card%)) Real Real (Any -> (Values Real Real)) -> Void))]
[move-cards-to-region (-> (Listof (Instance Card%)) Region Void)]
[card-location ((Instance Card%) -> (Values Real Real))]
[all-cards (-> (Listof (Instance mred:Snip%)))]
[remove-card ((Instance Card%) -> Void)]
[remove-cards ((Listof (Instance Card%)) -> Void)]
[flip-card ((Instance Card%) -> Void)]
[flip-cards ((Listof (Instance Card%)) -> Void)]
[rotate-card ((Instance Card%) Mode -> Void)]
[rotate-cards ((Listof (Instance Card%)) Mode -> Void)]
[card-face-up ((Instance Card%) -> Void)]
[cards-face-up ((Listof (Instance Card%)) -> Void)]
[card-face-down ((Instance Card%) -> Void)]
[cards-face-down ((Listof (Instance Card%)) -> Void)]
[card-to-front ((Instance Card%) -> Void)]
[card-to-back ((Instance Card%) -> Void)]
[stack-cards ((Listof (Instance Card%)) -> Void)]
[add-region (Region -> Void)]
[remove-region (Region -> Void)]
[hilite-region (Region -> Void)]
[unhilite-region (Region -> Void)]
[set-button-action ((U 'left 'middle 'right) Symbol -> Void)]
[set-double-click-action ((-> (Instance mred:Snip%) Void) -> Void)]
[set-single-click-action (-> (-> (Instance Card%) Void) Void)]
[pause (-> Real Void)]
[animated (case-> (-> Boolean)
(Any -> Void))]
[set-status (-> String Void)]
[create-status-pane (-> (Instance mred:Horizontal-Pane%))]
[add-help-button (-> (Instance mred:Area-Container<%>) (Listof String) String Any (Instance mred:Button%))]
[add-scribble-button (-> (Instance mred:Area-Container<%>) Module-Path String (Instance mred:Button%))] ; may need type for tag
))
(: table% Table%)
(define table%
(class mred:frame%
(init title w h)
(inherit reflow-container)
(augment*
[on-close
(lambda ()
(exit))])
(public*
[table-width (lambda ()
(reflow-container)
(let-values ([(x y w h) (send pb get-full-box)])
w))]
[table-height (lambda ()
(reflow-container)
(let-values ([(x y w h) (send pb get-full-box)])
h))]
[begin-card-sequence
(lambda ()
(set! in-sequence (add1 in-sequence))
(send pb begin-edit-sequence))]
[end-card-sequence
(lambda ()
(send pb end-edit-sequence)
(set! in-sequence (sub1 in-sequence)))]
[add-card
(lambda ([card : (Instance Card%)] [x : Real] [y : Real])
(position-cards (list card) x y (lambda (p) (values 0 0)) add-cards-callback))]
[add-cards
(lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset (lambda (p) (values 0 0))])
(position-cards cards x y offset add-cards-callback))]
[add-cards-to-region
(lambda ([cards : (Listof (Instance Card%))] [region : Region])
(position-cards-in-region cards region add-cards-callback))]
[move-card
(lambda ([card : (Instance Card%)] [x : Real] [y : Real])
(position-cards (list card) x y (lambda (p) (values 0 0)) move-cards-callback))]
[move-cards
(lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset (lambda (p) (values 0 0))])
(position-cards cards x y offset move-cards-callback))]
[move-cards-to-region
(lambda ([cards : (Listof (Instance Card%))] [region : Region])
(position-cards-in-region cards region (lambda ([c : (Instance Card%)] [x : Real] [y : Real]) (send pb move-to c x y))))]
[card-location
(lambda ([card : (Instance Card%)])
(let ([x : (Boxof Real) (box 0)]
[y : (Boxof Real) (box 0)])
(unless (send pb get-snip-location card x y)
(raise-mismatch-error 'card-location "card not on table: " card))
(values (unbox x) (unbox y))))]
[all-cards
(lambda ()
(send pb get-all-list))]
[remove-card
(lambda ([card : (Instance Card%)])
(remove-cards (list card)))]
[remove-cards
(lambda ([cards : (Listof (Instance Card%))])
(begin-card-sequence)
(for-each (lambda ([c : (Instance Card%)]) (send pb release-snip c)) cards)
(end-card-sequence))]
[flip-card
(lambda ([card : (Instance Card%)])
(flip-cards (list card)))]
[flip-cards
(lambda ([cards : (Listof (Instance Card%))])
(if (or (not animate?) (positive? in-sequence))
(for-each (lambda ([c : (Instance Card%)]) (send c flip)) cards)
(let ([flip-step
(lambda ([go : (-> Void)])
(let ([start (current-milliseconds)])
(begin-card-sequence)
(go)
(end-card-sequence)
(pause (max 0 (- (/ ANIMATION-TIME ANIMATION-STEPS)
(/ (- (current-milliseconds) start) 1000))))))])
(flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c semi-flip)) cards)))
(flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c flip)) cards)))
(flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c semi-flip)) cards))))))]
[rotate-card
(lambda ([card : (Instance Card%)] [mode : Mode]) (rotate-cards (list card) mode))]
[rotate-cards
(lambda ([cards : (Listof (Instance Card%))] [mode : Mode])
(begin-card-sequence)
(let ([tw (table-width)]
[th (table-height)])
(map (lambda ([c : (Instance Card%)])
(let ([w (send c card-width)]
[h (send c card-height)])
(send c rotate mode)
(let ([w2 (send c card-width)]
[h2 (send c card-height)]
[x : (Boxof Real) (box 0)]
[y : (Boxof Real) (box 0)])
(send pb get-snip-location c x y)
(send pb move-to c
(min (max 0 (+ (unbox x) (/ (- w w2) 2))) (- tw w2))
(min (max 0 (+ (unbox y) (/ (- h h2) 2))) (- th h2))))))
cards)
(end-card-sequence)))]
[card-face-up
(lambda ([card : (Instance Card%)])
(cards-face-up (list card)))]
[cards-face-up
(lambda (cards)
(flip-cards (filter (lambda ([c : (Instance Card%)]) (send c face-down?)) cards)))]
[card-face-down
(lambda ([card : (Instance Card%)])
(cards-face-down (list card)))]
[cards-face-down
(lambda ([cards : (Listof (Instance Card%))])
(flip-cards (filter (lambda ([c : (Instance Card%)]) (not (send c face-down?))) cards)))]
[card-to-front
(lambda ([card : (Instance Card%)])
(send pb set-before card #f))]
[card-to-back
(lambda ([card : (Instance Card%)])
(send pb set-after card #f))]
[stack-cards
(lambda ([cards : (Listof (Instance Card%))])
(unless (null? cards)
(send pb only-front-selected) ; in case overlap changes
(begin-card-sequence)
(let loop ([l (cdr cards)][behind (car cards)])
(unless (null? l)
(send pb set-after (car l) behind)
(loop (cdr l) (car l))))
(end-card-sequence)))]
[add-region
(lambda (r)
(send pb add-region r))]
[remove-region
(lambda (r)
(send pb remove-region r))]
[hilite-region
(lambda (r)
(send pb hilite-region r))]
[unhilite-region
(lambda (r)
(send pb unhilite-region r))]
[set-button-action
(lambda (button action)
(send pb set-button-action button action))]
[set-double-click-action
(lambda ([a : (-> (Instance mred:Snip%) Void)])
(send pb set-double-click-action a))]
[set-single-click-action
(lambda ([a : (-> (Instance Card%) Void)])
(send pb set-single-click-action a))]
[pause
(lambda ([duration : Real])
(let ([s (make-semaphore)]
[a (alarm-evt (+ (current-inexact-milliseconds)
(* duration 1000)))]
[enabled? (send c is-enabled?)])
;; Can't move the cards during this time:
(send c enable #f)
(mred:yield a)
(when enabled?
(send c enable #t))))]
[animated
(case-lambda
[() animate?]
[(on?) (set! animate? (and on? #t))])]
[create-status-pane
(lambda ()
(let ([p (make-object mred:horizontal-pane% this)])
(set! msg (new mred:message%
[parent p]
[label ""]
[stretchable-width #t]))
p))]
[set-status
(lambda ([str : String])
(when msg
(send (assert msg) set-label str)))]
[add-help-button
(lambda ([pane : (Instance mred:Area-Container<%>)] [where : (Listof String)] [title : String] [tt? : Any])
(new mred:button%
(parent pane)
(label (string-constant help-menu-label))
(callback
(let ([show-help (show-help where title tt?)])
(lambda x
(show-help))))))]
[add-scribble-button
(lambda ([pane : (Instance mred:Area-Container<%>)] [mod : Module-Path] [tag : String])
(new mred:button%
(parent pane)
(label (string-constant help-menu-label))
(callback
(let ([show-help (show-scribbling mod tag)])
(lambda x
(show-help))))))])
(begin
(: msg (Option (Instance mred:Button%)))
(define msg #f)
(: add-cards-callback (-> (Instance Card%) Real Real Void))
(define add-cards-callback
(lambda ([card : (Instance Card%)] [x : Real] [y : Real])
(send pb insert card #f x y)))
(: move-cards-callback (-> (Instance Card%) Real Real Boolean))
(define move-cards-callback
(lambda ([card : (Instance Card%)] [x : Real] [y : Real])
(send pb move-to card x y)
(send card remember-location pb))))
(begin
(define animate? #t)
(define in-sequence 0))
(: position-cards (-> (Listof (Instance Card%)) Real Real (-> Real (Values Real Real)) (-> (Instance Card%) Real Real Any) Void)) ; la
(: position-cards-in-region (-> (Listof (Instance Card%)) Region (-> (Instance Card%) Real Real Any) Void))
(private*
[position-cards
(lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset : (-> Real (Values Real Real))] set)
(let ([positions (let: loop : (Listof (Pairof Real Real)) ([l : (Listof (Instance Card%)) cards][n : Real 0])
(if (null? l)
null
(let-values ([(dx dy) (offset n)])
(cons (cons (+ x dx) (+ y dy))
(loop (cdr l) (add1 n))))))])
(if (or (not animate?) (positive? in-sequence) (eq? set add-cards-callback))
(begin
(begin-card-sequence)
(for-each (lambda ([c : (Instance Card%)] [p : (Pairof Real Real)]) (set c (car p) (cdr p))) cards positions)
(end-card-sequence))
(let-values ([(moving-cards
source-xs
source-ys
dest-xs
dest-ys)
(let: loop : (Values (Listof (Instance Card%)) (Listof Real) (Listof Real) (Listof Real) (Listof Real) ) ([cl : (Listof (Instance Card%)) cards][pl : (Listof (Pairof Real Real)) positions])
(if (null? cl)
(values null null null null null)
(let-values ([(mcl sxl syl dxl dyl) (loop (cdr cl) (cdr pl))]
[(card) (car cl)]
[(x y) (values (caar pl) (cdar pl))])
(let ([xb : (Boxof Real) (box 0)][yb : (Boxof Real) (box 0)])
(send pb get-snip-location card xb yb)
(let ([sx (unbox xb)][sy (unbox yb)])
(if (and (= x sx) (= y sy))
(values mcl sxl syl dxl dyl)
(values (cons card mcl)
(cons sx sxl)
(cons sy syl)
(cons x dxl)
(cons y dyl))))))))])
(let ([time-scale
;; An animation speed that looks good for
;; long moves looks too slow for short
;; moves. So scale the time back by as much
as 50 % if the max distance for all cards
;; is short.
(let ([max-delta (max (apply max 0 (map (lambda ([sx : Real] [dx : Real])
(abs (- sx dx)))
source-xs dest-xs))
(apply max 0 (map (lambda ([sy : Real] [dy : Real])
(abs (- sy dy)))
source-ys dest-ys)))])
(if (max-delta . < . 100)
(/ (+ max-delta 100) 200.0)
1))])
(let loop ([n 1])
(unless (> n ANIMATION-STEPS)
(let ([start (current-milliseconds)]
[scale (lambda ([s : Real] [d : Real])
(+ s (* (/ n ANIMATION-STEPS) (- d s))))])
(begin-card-sequence)
(for-each
(lambda ([c : (Instance Card%)] [sx : Real] [sy : Real] [dx : Real] [dy : Real])
(set c (scale sx dx) (scale sy dy)))
moving-cards
source-xs source-ys
dest-xs dest-ys)
(end-card-sequence)
(pause (max 0 (- (/ (* time-scale ANIMATION-TIME) ANIMATION-STEPS)
(/ (- (current-milliseconds) start) 1000))))
(loop (add1 n))))))))
;; In case overlap changed:
(send pb only-front-selected)))]
[position-cards-in-region
(lambda ([cards : (Listof (Instance Card%))] [r : Region] set)
(unless (null? cards)
(let-values ([(x y w h) (send pb get-region-box r)]
[(len) (sub1 (length cards))]
[(cw ch) (values (send (car cards) card-width)
(send (car cards) card-height))])
(let* ([pretty (lambda ([cw : Real]) (+ (* (add1 len) cw) (* len PRETTY-CARD-SEP-AMOUNT)))]
[pw (pretty cw)]
[ph (pretty ch)])
(let-values ([(x w) (if (> w pw)
(values (+ x (/ (- w pw) 2)) pw)
(values x w))]
[(y h) (if (> h ph)
(values (+ y (/ (- h ph) 2)) ph)
(values y h))])
(position-cards cards x y
(lambda ([p : Real])
(if (zero? len)
(values (/ (- w cw) 2)
(/ (- h ch) 2))
(values (* (- len p) (/ (- w cw) len))
(* (- len p) (/ (- h ch) len)))))
set))))))])
(super-new [label title] [style '(metal no-resize-border)])
(begin
(: c (Instance mred:Editor-Canvas%))
(define c (make-object mred:editor-canvas% this #f '(no-vscroll no-hscroll)))
(: pb (Instance Pasteboard%))
(define pb (make-object pasteboard%)))
(send c min-client-width (+ 10 (exact-floor (* w (send back get-width)))))
(send c min-client-height (+ 10 (exact-floor (* h (send back get-height)))))
(send c stretchable-width #f)
(send c stretchable-height #f)
(send this stretchable-width #f)
(send this stretchable-height #f)
(send c set-editor pb)))
(: draw-roundish-rectangle ((Instance mred:DC<%>) Real Real Real Real -> Void))
(define (draw-roundish-rectangle dc x y w h)
(send dc draw-line (+ x 1) y (+ x w -2) y)
(send dc draw-line (+ x 1) (+ y h -1) (+ x w -2) (+ y h -1))
(send dc draw-line x (+ y 1) x (+ y h -2))
(send dc draw-line (+ x w -1) (+ y 1) (+ x w -1) (+ y h -2))))
| null | https://raw.githubusercontent.com/nuprl/gradual-typing-performance/35442b3221299a9cadba6810573007736b0d65d4/pre-benchmark/ecoop/cards/cards/classes.rkt | racket | racket/class
replace this with base, after defining interfaces
case-lambda bug
Card%)))]
not sure if this is right, but a decent starting guess
mred:Snip%) Any) Void))
Since we use size-in-pixels, the letters
the descender), but the space above the letter
center on 12 , splitting
the difference for the descender
mred:Snip%)]) (send snip remember-location this)))
mred:Snip%)]) (send snip back-to-original-location this)))
in case overlap changed
Call it outside the current edit sequence
Move/drag event has different mouse button,
and there was no mouse up. Don't accept the
click, yet.
Clicking on a "selected" card unselects others
in this interface
occurence typing should work here??
Can't move => no raise, either
We didn't call super on-default-event, so we need
to explicitly end the drag:
Check for clicking on a button region:
Callback hilighted button:
Call it outside the current edit sequence
changing type in typed-base, but this is a bug based on documentation
Card% ) ) null ] )
(cast t (Instance Card%)) accum))])))]
(super-make-object)
may need type for tag
in case overlap changes
Can't move the cards during this time:
la
An animation speed that looks good for
long moves looks too slow for short
moves. So scale the time back by as much
is short.
In case overlap changed: | (module classes typed/racket
(prefix-in mred: typed/racket/gui)
(prefix-in util: "utils.rkt")
"constants.rkt"
"make-cards.rkt"
string-constants
"../show-help.rkt")
(require (only-in racket/base case-lambda))
( require / typed racket [ remq ( All ( a ) ( Any ( a ) - > ( a ) ) ) ] )
(require/typed "../show-scribbling.rkt" [show-scribbling (Module-Path String -> (-> Void))])
(provide pasteboard%
table%)
(define-type Pasteboard%
(Class #:implements mred:Pasteboard%
[only-front-selected (-> Void)]
[get-full-box (-> (Values Real Real Real Real))]
[get-region-box (Region -> (Values Real Real Nonnegative-Real Nonnegative-Real))]
[add-region (-> Region Void)]
[remove-region (-> Region Void)]
[unhilite-region (Region -> Void)]
[hilite-region (-> Region Void)]
[set-double-click-action (-> (-> (Instance mred:Snip%) Void) Void)]
[set-single-click-action (-> (-> (Instance Card%) Void) Void)]
[set-button-action (-> (U 'left 'middle 'right) Symbol Void)]
(augment [after-select ((Instance mred:Snip%) Any -> Void)]
[on-interactive-move ((Instance mred:Mouse-Event%) -> Void)]
[after-interactive-move ((Instance mred:Mouse-Event%) -> Void)])))
(: pasteboard% Pasteboard%)
(define pasteboard%
(class mred:pasteboard%
(inherit begin-edit-sequence end-edit-sequence get-admin
invalidate-bitmap-cache
find-next-selected-snip find-first-snip find-snip
set-before set-after
add-selected is-selected? no-selected set-selected remove-selected
get-snip-location move-to
dc-location-to-editor-location
set-selection-visible)
(: select-one? Boolean)
(define select-one? #t)
(: select-backward? Boolean)
(define select-backward? #f)
(: raise-to-front? Boolean)
(define raise-to-front? #f)
(: button-map (Listof (List (U 'left 'middle 'right) Boolean Boolean Boolean)))
(define button-map '((left #f #f #t)
(middle #t #f #t)
(right #f #t #f)))
(: do-on-double-click (U 'flip ((Instance mred:Snip%) -> Void)))
(define do-on-double-click 'flip)
(: do-on-single-click ((Instance Card%) -> Void))
(define do-on-single-click void)
(: selecting? Boolean)
(define selecting? #f)
(: dragging? Boolean)
(define dragging? #f)
(: bg-click? Boolean)
(define bg-click? #f)
(: click-base (Option (Instance Card%)))
(define click-base #f)
(: last-click (Option Any))
(define last-click #f)
(define regions null)
(: update-region (Region -> Void))
(: get-snip-bounds ((Instance mred:Snip%) -> (Values Real Real Real Real)))
(: get-reverse-selected-list (-> (Listof (Instance mred:Snip%))))
(: make-overlapping-list (-> (Instance mred:Snip%) (Listof (Instance mred:Snip%)) Any (Listof (Instance mred:Snip%))))
(private*
[get-snip-bounds
(lambda: ([s : (Instance mred:Snip%)])
(let: ([xbox : (Boxof Real) (box 0)]
[ybox : (Boxof Real) (box 0)])
(get-snip-location s xbox ybox #f)
(let ([l (unbox xbox)]
[t (unbox ybox)])
(get-snip-location s xbox ybox #t)
(values l t (unbox xbox) (unbox ybox)))))]
[for-each-selected
(lambda (f)
(let: loop : Void ([snip : (Option (Instance mred:Snip%)) (find-next-selected-snip #f)])
(when snip
(let ([snip : (Instance Card%) (cast snip (Instance Card%))])
(f snip)
(loop (find-next-selected-snip snip))))))]
[make-overlapping-list
(lambda ([s : (Instance mred:Snip%)] so-far behind?)
(let-values ([(sl st sr sb) (get-snip-bounds s)])
(let: loop : (Listof (Instance mred:Snip%)) ([t : (Option (Instance mred:Snip%)) (find-first-snip)] [so-far : (Listof (Instance mred:Snip%)) so-far] [get? : Boolean (not behind?)])
(cond
[(not t) so-far]
[(eq? s t) (if behind?
(loop (send t next) so-far #t)
so-far)]
[get?
(let ([l (if (and (not (memq t so-far))
(let-values ([(tl tt tr tb)
(get-snip-bounds t)])
(and (or (<= sl tl sr)
(<= sl tr sr))
(or (<= st tt sb)
(<= st tb sb)))))
(make-overlapping-list t ((inst cons (Instance mred:Snip%) (Listof (Instance mred:Snip%))) t so-far) behind?)
so-far)])
(loop (send t next) l #t))]
[else
(loop (send t next) so-far #f)]))))]
[get-reverse-selected-list
(lambda ()
(let: loop : (Listof (Instance mred:Snip%)) ([s (find-next-selected-snip #f)][l : (Listof (Instance mred:Snip%)) null])
(if s
(loop (find-next-selected-snip s) ((inst cons (Instance mred:Snip%) (Listof (Instance mred:Snip%))) s l))
l)))]
[shuffle
cards to shuffle in back->front order
(let* ([permuted-list : (Listof (Instance Card%))
(util:shuffle-list selected-list 7)]
[get-pos
(lambda ([s : (Instance mred:Snip%)])
(let ([xb : (Boxof Real) (box 0)]
[yb : (Boxof Real) (box 0)])
(get-snip-location s xb yb)
(cons (unbox xb) (unbox yb))))]
[sel-loc-list ((inst map (Pairof Real Real) (Instance mred:Snip%)) get-pos selected-list)]
[perm-loc-list ((inst map (Pairof Real Real) (Instance mred:Snip%)) get-pos permuted-list)])
((inst for-each (Instance Card%) (Pairof Real Real) (Pairof Real Real))
(lambda ([s : (Instance Card%)] [start-pos : (Pairof Real Real)] [end-pos : (Pairof Real Real)])
(let* ([sx : Real (car start-pos)]
[sy : Real (cdr start-pos)]
[ex : Real (car end-pos)]
[ey : Real (cdr end-pos)]
[steps (max 1 (floor (/ 50 (length selected-list))))])
(let: loop : Void ([i : Integer 1])
(unless (> i steps)
(let ([x (+ sx (* (/ i steps) (- ex sx)))]
[y (+ sy (* (/ i steps) (- ey sy)))])
(move-to s x y)
(mred:flush-display)
(loop (add1 i)))))))
permuted-list perm-loc-list sel-loc-list)
(let loop ([l permuted-list])
(unless (null? l)
(set-before (car l) #f)
(loop (cdr l))))
(no-selected)))]
[update-region
(lambda (region)
(let-values ([(sx sy sw sh) (get-region-box region)])
(invalidate-bitmap-cache sx sy sw sh)))])
(public*
[only-front-selected
(lambda ()
(let: loop : Void ([s : (Option (Instance mred:Snip%)) (find-next-selected-snip #f)][ok : (Option (Instance mred:Snip%)) (find-first-snip)])
(when s
(if (eq? s ok)
(loop (find-next-selected-snip s)
(send (assert ok) next))
(let: loop ([s : (Instance mred:Snip%) s][l : (Listof (Instance mred:Snip%)) (list s)])
(let ([next (find-next-selected-snip s)])
(if next
(loop next (cons s l))
(for-each (lambda: ([s : (Instance mred:Snip%)])
(remove-selected s))
l))))))))])
(override*
[on-paint
(lambda (before? dc l t r b dx dy caret)
(when before?
(for-each
(lambda: ([region : Region])
(when (region-paint-callback region)
(let-values ([(sx sy sw sh) (get-region-box region)])
((assert (region-paint-callback region)) dc (+ dx sx) (+ dy sy) sw sh)))
(when (region-label region)
(let ([old-b (send dc get-brush)]
[old-p (send dc get-pen)])
(let-values ([(sx sy sw sh) (get-region-box region)])
(send dc set-brush (assert white-brush))
(send dc set-pen no-pen)
(send dc draw-rectangle (+ dx sx) (+ dy sy) sw sh)
(send dc set-pen dark-gray-pen)
(draw-roundish-rectangle dc (+ dx sx) (+ dy sy) sw sh)
(let ([text (region-label region)])
(if (string? text)
(let ([old-f (send dc get-font)])
(send dc set-font nice-font)
(let-values ([(x y d a) (send dc get-text-extent text)])
(send dc draw-text text
(+ dx sx (/ (- sw x) 2))
(if (region-button? region)
should really be 12 pixels high ( including
(+ dy sy (/ (- sh 12) 2) (- 12 y (/ d -2)))
(+ dy sy 5))))
(send dc set-font old-f))
(send dc draw-bitmap (assert text)
(+ dx sx (/ (- sw (send (assert text) get-width)) 2))
(+ dy sy (/ (- sh (send (assert text) get-height)) 2))
'solid black-color
(send (assert text) get-loaded-mask))))
(when (region-hilite? region)
(send dc set-brush (assert hilite-brush))
(send dc set-pen no-pen)
(send dc draw-rectangle (+ dx sx 1) (+ dy sy 1) (assert (- sw 2) (lambda: ([x : Real]) (>= x 0))) (assert (- sh 2) (lambda: ([x : Real]) (>= x 0))))))
(send dc set-brush old-b)
(send dc set-pen old-p))))
regions)))])
(augment*
[after-select
(lambda: ([s : (Instance mred:Snip%)] [on? : Any])
(inner (void) after-select s on?)
(unless (or (not on?) selecting?)
(set! selecting? #t)
(if select-one?
(when raise-to-front?
(set-before s #f))
(begin
(begin-edit-sequence)
(let ([l : (Listof (Instance mred:Snip%)) (make-overlapping-list s (list s) select-backward?)])
((inst for-each (Instance mred:Snip%)) (lambda: ([i : (Instance mred:Snip%)]) (add-selected i)) l))
(when raise-to-front?
(let loop ([snip (find-next-selected-snip #f)][prev : (Option (Instance mred:Snip%)) #f])
(when snip
(if prev
(set-after snip prev)
(set-before snip #f))
(loop (find-next-selected-snip (assert snip)) snip))))
(end-edit-sequence)))
(set! selecting? #f)))]
[on-interactive-move
(lambda (e)
(inner (void) on-interactive-move e)
(for-each (lambda: ([region : Region]) (set-region-decided-start?! region #f)) regions)
(set! dragging? #t))])
(override*
[interactive-adjust-move
(lambda: ([snip : (Instance mred:Snip%)] [xb : (Boxof Real)] [yb : (Boxof Real)])
(super interactive-adjust-move snip xb yb)
(let ([snip (cast snip (Instance Card%))])
(let-values: ([([l : Real] [t : Real] [r : Real] [b : Real]) (get-snip-bounds snip)])
(let-values: ([([rl : Real] [rt : Real] [rw : Real] [rh : Real])
(let: ([r : (Option Region) (send snip stay-in-region)])
(if r
(values (region-x r) (region-y r)
(region-w r) (region-h r))
(let: ([wb : (Boxof Real) (box 0)][hb : (Boxof Real) (box 0)])
(send (assert (get-admin)) get-view #f #f wb hb)
(values 0 0 (unbox wb) (unbox hb)))))])
(let ([max-x (- (+ rl rw) (- r l))]
[max-y (- (+ rt rh) (- b t))])
(when (< (unbox xb) rl)
(set-box! xb rl))
(when (> (unbox xb) max-x)
(set-box! xb max-x))
(when (< (unbox yb) rt)
(set-box! yb rt))
(when (> (unbox yb) max-y)
(set-box! yb max-y)))))))])
(: after-interactive-move ((Instance mred:Mouse-Event%) -> Void) #:augment ((Instance mred:Mouse-Event%) -> Void))
(augment*
[after-interactive-move
(lambda: ([e : (Instance mred:Mouse-Event%)])
(when dragging?
(set! dragging? #f)
(inner (void) after-interactive-move e)
(let: ([cards : (Listof (Instance mred:Snip%)) (get-reverse-selected-list)])
(for-each
(lambda: ([region : Region])
(when (region-hilite? region)
(mred:queue-callback
(lambda ()
((assert (region-callback region)) cards)
(unhilite-region region)))))
regions))))])
(override*
[on-default-event
(lambda: ([e : (Instance mred:Mouse-Event%)])
(let: ([click : (Option (U 'left 'middle 'right)) (let: ([c : (Option (U 'left 'middle 'right)) (or (and (send e button-down? 'left) 'left)
(and (send e button-down? 'right) 'right)
(and (send e button-down? 'middle) 'middle))])
(cond
[(eq? c last-click) c]
[(not last-click) c]
[else #f]))])
(set! last-click click)
(when click
(let*: ([actions : (List Boolean Boolean Boolean) (cdr (assert (assoc click button-map)))]
[one? (list-ref actions 0)]
[backward? (list-ref actions 1)]
[raise? (list-ref actions 2)])
(unless (and (eq? backward? select-backward?)
(eq? one? select-one?)
(eq? raise? raise-to-front?))
(set! select-one? one?)
(set! select-backward? backward?)
(set! raise-to-front? raise?)
(no-selected))))
(let*-values ([(lx ly) (dc-location-to-editor-location
(send e get-x)
(send e get-y))]
[(s) (find-snip lx ly)])
(when (send e button-down?)
(unless (or (not click-base) (not s) (eq? s click-base))
(no-selected))
there does n't seem to be a better way to get this to typecheck than to c - a - s - t s to a Card% instance
(when (and dragging? click-base (send (assert click-base) user-can-move))
(for-each
(lambda: ([region : Region])
(when (and (not (region-button? region))
(region-callback region)
(or (not (region-decided-start? region))
(region-can-select? region)))
(let-values ([(sx sy sw sh) (get-region-box region)])
(let ([in? (and (<= sx lx (+ sx sw))
(<= sy ly (+ sy sh)))])
(unless (region-decided-start? region)
(set-region-decided-start?! region #t)
(set-region-can-select?! region (not in?)))
(when (and (not (eq? in? (region-hilite? region)))
(region-can-select? region))
(set-region-hilite?! region in?)
(when (region-interactive-callback region)
((assert (region-interactive-callback region)) in? (get-reverse-selected-list)))
(invalidate-bitmap-cache sx sy sw sh))))))
regions))
(unless (or (not click-base) (send (assert click-base) user-can-move))
(set! raise-to-front? #f))
(let ([was-bg? bg-click?])
(if (send e button-down?)
(set! bg-click? (not s))
(when (and bg-click? (not (send e dragging?)))
(set! bg-click? #f)))
(unless bg-click?
(super on-default-event e))
(when (and bg-click? dragging?)
(after-interactive-move e))
(when bg-click?
(for-each
(lambda: ([region : Region])
(when (and (region-button? region)
(region-callback region))
(let-values ([(sx sy sw sh) (get-region-box region)])
(let ([in? (and (<= sx lx (+ sx sw))
(<= sy ly (+ sy sh)))])
(unless (region-decided-start? region)
(set-region-decided-start?! region #t)
(set-region-can-select?! region in?))
(when (and (not (eq? in? (region-hilite? region)))
(region-can-select? region))
(set-region-hilite?! region in?)
(invalidate-bitmap-cache sx sy sw sh))))))
regions))
(when (and was-bg? (not bg-click?))
(for-each
(lambda: ([region : Region])
(when (region-button? region)
(set-region-decided-start?! region #f)
(when (region-hilite? region)
(mred:queue-callback
(lambda ()
(unhilite-region region))))))
regions)))
(when (and (send e button-down?)
click-base
(not (send (assert click-base) user-can-move)))
(no-selected)))
(when (and click click-base)
(do-on-single-click (assert click-base)))))]
[on-double-click
(lambda (s e)
(cond
[(eq? do-on-double-click 'flip)
(begin-edit-sequence)
(let ([l (get-reverse-selected-list)])
(for-each
(lambda: ([s : (Instance mred:Snip%)])
(let ([s (cast s (Instance Card%))])
(when (send s user-can-flip)
(send s flip))))
l)
(let loop ([l (reverse l)])
(unless (null? l)
(set-before (car l) #f)
(loop (cdr l)))))
(no-selected)
(end-edit-sequence)]
[do-on-double-click
((assert do-on-double-click (lambda (x) (not (symbol? x)))) s)]
[else (void)]))])
(public*
[get-all-list
(lambda ()
(cond
[(not t) (reverse accum)]
[get-full-box
(lambda ()
(let: ([xb : (Boxof Real) (box 0)] [yb : (Boxof Real) (box 0)]
[wb : (Boxof Real) (box 0)] [hb : (Boxof Real) (box 0)])
(send (assert (get-admin)) get-view xb yb wb hb)
(values 0 0 (unbox wb) (unbox hb))))]
[get-region-box
(lambda: ([region : Region])
(values (region-x region)
(region-y region)
(region-w region)
(region-h region)))]
[add-region
(lambda: ([r : Region])
(set! regions (append regions (list r)))
(update-region r))]
[remove-region
(lambda: ([r : Region])
(set! regions (remq r regions))
(update-region r))]
[unhilite-region
(lambda: ([region : Region])
(set-region-hilite?! region #f)
(update-region region))]
[hilite-region
(lambda: ([region : Region])
(set-region-hilite?! region #t)
(update-region region))]
[set-double-click-action
(lambda: ([a : (U ((Instance mred:Snip%) -> Void) 'flip)])
(set! do-on-double-click a))]
[set-single-click-action
(lambda: ([a : ((Instance Card%) -> Void)])
(set! do-on-single-click a))]
[set-button-action
(lambda: ([button : (U 'left 'middle 'right)] [action : Symbol])
(let: ([map : (List Boolean Boolean Boolean)
(case action
[(drag/one) (list #t #f #f)]
[(drag-raise/one) (list #t #f #t)]
[(drag/above) (list #f #f #f)]
[(drag-raise/above) (list #f #f #t)]
[(drag/below) (list #f #t #f)]
[(drag-raise/below) (list #f #t #t)]
[else (error 'set-button-action "unknown action: ~s" action)])])
(set! button-map
(cons
(ann (cons button map) (List (U 'left 'right 'middle) Boolean Boolean Boolean))
come back to this remq does n't really have the right type I think
button-map)))))])
(set-selection-visible #f)))
(define-type Table%
(Class #:implements mred:Frame%
(init
[title String]
[w Nonnegative-Real]
[h Nonnegative-Real]
[parent (Option (Instance mred:Frame%)) #:optional]
[width (Option Integer) #:optional]
[height (Option Integer) #:optional]
[x (Option Integer) #:optional]
[y (Option Integer) #:optional]
[enabled Any #:optional]
[border Natural #:optional]
[spacing Natural #:optional]
[alignment (List (U 'left 'center 'right)
(U 'top 'center 'bottom))
#:optional]
[min-width (Option Natural) #:optional]
[min-height (Option Natural) #:optional]
[stretchable-width Any #:optional]
[stretchable-height Any #:optional])
(augment [on-close (-> Void)])
[table-width (-> Real)]
[table-height (-> Real)]
[begin-card-sequence (-> Void)]
[end-card-sequence (-> Void)]
[add-card ((Instance Card%) Real Real -> Any)]
[add-cards (case-> ((Listof (Instance Card%)) Real Real -> Void)
((Listof (Instance Card%)) Real Real (Any -> (Values Real Real)) -> Void))]
[add-cards-to-region ((Listof (Instance Card%)) Region -> Void)]
[move-card (-> (Instance Card%) Real Real Void)]
[move-cards (case-> ((Listof (Instance Card%)) Real Real -> Void)
((Listof (Instance Card%)) Real Real (Any -> (Values Real Real)) -> Void))]
[move-cards-to-region (-> (Listof (Instance Card%)) Region Void)]
[card-location ((Instance Card%) -> (Values Real Real))]
[all-cards (-> (Listof (Instance mred:Snip%)))]
[remove-card ((Instance Card%) -> Void)]
[remove-cards ((Listof (Instance Card%)) -> Void)]
[flip-card ((Instance Card%) -> Void)]
[flip-cards ((Listof (Instance Card%)) -> Void)]
[rotate-card ((Instance Card%) Mode -> Void)]
[rotate-cards ((Listof (Instance Card%)) Mode -> Void)]
[card-face-up ((Instance Card%) -> Void)]
[cards-face-up ((Listof (Instance Card%)) -> Void)]
[card-face-down ((Instance Card%) -> Void)]
[cards-face-down ((Listof (Instance Card%)) -> Void)]
[card-to-front ((Instance Card%) -> Void)]
[card-to-back ((Instance Card%) -> Void)]
[stack-cards ((Listof (Instance Card%)) -> Void)]
[add-region (Region -> Void)]
[remove-region (Region -> Void)]
[hilite-region (Region -> Void)]
[unhilite-region (Region -> Void)]
[set-button-action ((U 'left 'middle 'right) Symbol -> Void)]
[set-double-click-action ((-> (Instance mred:Snip%) Void) -> Void)]
[set-single-click-action (-> (-> (Instance Card%) Void) Void)]
[pause (-> Real Void)]
[animated (case-> (-> Boolean)
(Any -> Void))]
[set-status (-> String Void)]
[create-status-pane (-> (Instance mred:Horizontal-Pane%))]
[add-help-button (-> (Instance mred:Area-Container<%>) (Listof String) String Any (Instance mred:Button%))]
))
(: table% Table%)
(define table%
(class mred:frame%
(init title w h)
(inherit reflow-container)
(augment*
[on-close
(lambda ()
(exit))])
(public*
[table-width (lambda ()
(reflow-container)
(let-values ([(x y w h) (send pb get-full-box)])
w))]
[table-height (lambda ()
(reflow-container)
(let-values ([(x y w h) (send pb get-full-box)])
h))]
[begin-card-sequence
(lambda ()
(set! in-sequence (add1 in-sequence))
(send pb begin-edit-sequence))]
[end-card-sequence
(lambda ()
(send pb end-edit-sequence)
(set! in-sequence (sub1 in-sequence)))]
[add-card
(lambda ([card : (Instance Card%)] [x : Real] [y : Real])
(position-cards (list card) x y (lambda (p) (values 0 0)) add-cards-callback))]
[add-cards
(lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset (lambda (p) (values 0 0))])
(position-cards cards x y offset add-cards-callback))]
[add-cards-to-region
(lambda ([cards : (Listof (Instance Card%))] [region : Region])
(position-cards-in-region cards region add-cards-callback))]
[move-card
(lambda ([card : (Instance Card%)] [x : Real] [y : Real])
(position-cards (list card) x y (lambda (p) (values 0 0)) move-cards-callback))]
[move-cards
(lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset (lambda (p) (values 0 0))])
(position-cards cards x y offset move-cards-callback))]
[move-cards-to-region
(lambda ([cards : (Listof (Instance Card%))] [region : Region])
(position-cards-in-region cards region (lambda ([c : (Instance Card%)] [x : Real] [y : Real]) (send pb move-to c x y))))]
[card-location
(lambda ([card : (Instance Card%)])
(let ([x : (Boxof Real) (box 0)]
[y : (Boxof Real) (box 0)])
(unless (send pb get-snip-location card x y)
(raise-mismatch-error 'card-location "card not on table: " card))
(values (unbox x) (unbox y))))]
[all-cards
(lambda ()
(send pb get-all-list))]
[remove-card
(lambda ([card : (Instance Card%)])
(remove-cards (list card)))]
[remove-cards
(lambda ([cards : (Listof (Instance Card%))])
(begin-card-sequence)
(for-each (lambda ([c : (Instance Card%)]) (send pb release-snip c)) cards)
(end-card-sequence))]
[flip-card
(lambda ([card : (Instance Card%)])
(flip-cards (list card)))]
[flip-cards
(lambda ([cards : (Listof (Instance Card%))])
(if (or (not animate?) (positive? in-sequence))
(for-each (lambda ([c : (Instance Card%)]) (send c flip)) cards)
(let ([flip-step
(lambda ([go : (-> Void)])
(let ([start (current-milliseconds)])
(begin-card-sequence)
(go)
(end-card-sequence)
(pause (max 0 (- (/ ANIMATION-TIME ANIMATION-STEPS)
(/ (- (current-milliseconds) start) 1000))))))])
(flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c semi-flip)) cards)))
(flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c flip)) cards)))
(flip-step (lambda () (for-each (lambda ([c : (Instance Card%)]) (send c semi-flip)) cards))))))]
[rotate-card
(lambda ([card : (Instance Card%)] [mode : Mode]) (rotate-cards (list card) mode))]
[rotate-cards
(lambda ([cards : (Listof (Instance Card%))] [mode : Mode])
(begin-card-sequence)
(let ([tw (table-width)]
[th (table-height)])
(map (lambda ([c : (Instance Card%)])
(let ([w (send c card-width)]
[h (send c card-height)])
(send c rotate mode)
(let ([w2 (send c card-width)]
[h2 (send c card-height)]
[x : (Boxof Real) (box 0)]
[y : (Boxof Real) (box 0)])
(send pb get-snip-location c x y)
(send pb move-to c
(min (max 0 (+ (unbox x) (/ (- w w2) 2))) (- tw w2))
(min (max 0 (+ (unbox y) (/ (- h h2) 2))) (- th h2))))))
cards)
(end-card-sequence)))]
[card-face-up
(lambda ([card : (Instance Card%)])
(cards-face-up (list card)))]
[cards-face-up
(lambda (cards)
(flip-cards (filter (lambda ([c : (Instance Card%)]) (send c face-down?)) cards)))]
[card-face-down
(lambda ([card : (Instance Card%)])
(cards-face-down (list card)))]
[cards-face-down
(lambda ([cards : (Listof (Instance Card%))])
(flip-cards (filter (lambda ([c : (Instance Card%)]) (not (send c face-down?))) cards)))]
[card-to-front
(lambda ([card : (Instance Card%)])
(send pb set-before card #f))]
[card-to-back
(lambda ([card : (Instance Card%)])
(send pb set-after card #f))]
[stack-cards
(lambda ([cards : (Listof (Instance Card%))])
(unless (null? cards)
(begin-card-sequence)
(let loop ([l (cdr cards)][behind (car cards)])
(unless (null? l)
(send pb set-after (car l) behind)
(loop (cdr l) (car l))))
(end-card-sequence)))]
[add-region
(lambda (r)
(send pb add-region r))]
[remove-region
(lambda (r)
(send pb remove-region r))]
[hilite-region
(lambda (r)
(send pb hilite-region r))]
[unhilite-region
(lambda (r)
(send pb unhilite-region r))]
[set-button-action
(lambda (button action)
(send pb set-button-action button action))]
[set-double-click-action
(lambda ([a : (-> (Instance mred:Snip%) Void)])
(send pb set-double-click-action a))]
[set-single-click-action
(lambda ([a : (-> (Instance Card%) Void)])
(send pb set-single-click-action a))]
[pause
(lambda ([duration : Real])
(let ([s (make-semaphore)]
[a (alarm-evt (+ (current-inexact-milliseconds)
(* duration 1000)))]
[enabled? (send c is-enabled?)])
(send c enable #f)
(mred:yield a)
(when enabled?
(send c enable #t))))]
[animated
(case-lambda
[() animate?]
[(on?) (set! animate? (and on? #t))])]
[create-status-pane
(lambda ()
(let ([p (make-object mred:horizontal-pane% this)])
(set! msg (new mred:message%
[parent p]
[label ""]
[stretchable-width #t]))
p))]
[set-status
(lambda ([str : String])
(when msg
(send (assert msg) set-label str)))]
[add-help-button
(lambda ([pane : (Instance mred:Area-Container<%>)] [where : (Listof String)] [title : String] [tt? : Any])
(new mred:button%
(parent pane)
(label (string-constant help-menu-label))
(callback
(let ([show-help (show-help where title tt?)])
(lambda x
(show-help))))))]
[add-scribble-button
(lambda ([pane : (Instance mred:Area-Container<%>)] [mod : Module-Path] [tag : String])
(new mred:button%
(parent pane)
(label (string-constant help-menu-label))
(callback
(let ([show-help (show-scribbling mod tag)])
(lambda x
(show-help))))))])
(begin
(: msg (Option (Instance mred:Button%)))
(define msg #f)
(: add-cards-callback (-> (Instance Card%) Real Real Void))
(define add-cards-callback
(lambda ([card : (Instance Card%)] [x : Real] [y : Real])
(send pb insert card #f x y)))
(: move-cards-callback (-> (Instance Card%) Real Real Boolean))
(define move-cards-callback
(lambda ([card : (Instance Card%)] [x : Real] [y : Real])
(send pb move-to card x y)
(send card remember-location pb))))
(begin
(define animate? #t)
(define in-sequence 0))
(: position-cards-in-region (-> (Listof (Instance Card%)) Region (-> (Instance Card%) Real Real Any) Void))
(private*
[position-cards
(lambda ([cards : (Listof (Instance Card%))] [x : Real] [y : Real] [offset : (-> Real (Values Real Real))] set)
(let ([positions (let: loop : (Listof (Pairof Real Real)) ([l : (Listof (Instance Card%)) cards][n : Real 0])
(if (null? l)
null
(let-values ([(dx dy) (offset n)])
(cons (cons (+ x dx) (+ y dy))
(loop (cdr l) (add1 n))))))])
(if (or (not animate?) (positive? in-sequence) (eq? set add-cards-callback))
(begin
(begin-card-sequence)
(for-each (lambda ([c : (Instance Card%)] [p : (Pairof Real Real)]) (set c (car p) (cdr p))) cards positions)
(end-card-sequence))
(let-values ([(moving-cards
source-xs
source-ys
dest-xs
dest-ys)
(let: loop : (Values (Listof (Instance Card%)) (Listof Real) (Listof Real) (Listof Real) (Listof Real) ) ([cl : (Listof (Instance Card%)) cards][pl : (Listof (Pairof Real Real)) positions])
(if (null? cl)
(values null null null null null)
(let-values ([(mcl sxl syl dxl dyl) (loop (cdr cl) (cdr pl))]
[(card) (car cl)]
[(x y) (values (caar pl) (cdar pl))])
(let ([xb : (Boxof Real) (box 0)][yb : (Boxof Real) (box 0)])
(send pb get-snip-location card xb yb)
(let ([sx (unbox xb)][sy (unbox yb)])
(if (and (= x sx) (= y sy))
(values mcl sxl syl dxl dyl)
(values (cons card mcl)
(cons sx sxl)
(cons sy syl)
(cons x dxl)
(cons y dyl))))))))])
(let ([time-scale
as 50 % if the max distance for all cards
(let ([max-delta (max (apply max 0 (map (lambda ([sx : Real] [dx : Real])
(abs (- sx dx)))
source-xs dest-xs))
(apply max 0 (map (lambda ([sy : Real] [dy : Real])
(abs (- sy dy)))
source-ys dest-ys)))])
(if (max-delta . < . 100)
(/ (+ max-delta 100) 200.0)
1))])
(let loop ([n 1])
(unless (> n ANIMATION-STEPS)
(let ([start (current-milliseconds)]
[scale (lambda ([s : Real] [d : Real])
(+ s (* (/ n ANIMATION-STEPS) (- d s))))])
(begin-card-sequence)
(for-each
(lambda ([c : (Instance Card%)] [sx : Real] [sy : Real] [dx : Real] [dy : Real])
(set c (scale sx dx) (scale sy dy)))
moving-cards
source-xs source-ys
dest-xs dest-ys)
(end-card-sequence)
(pause (max 0 (- (/ (* time-scale ANIMATION-TIME) ANIMATION-STEPS)
(/ (- (current-milliseconds) start) 1000))))
(loop (add1 n))))))))
(send pb only-front-selected)))]
[position-cards-in-region
(lambda ([cards : (Listof (Instance Card%))] [r : Region] set)
(unless (null? cards)
(let-values ([(x y w h) (send pb get-region-box r)]
[(len) (sub1 (length cards))]
[(cw ch) (values (send (car cards) card-width)
(send (car cards) card-height))])
(let* ([pretty (lambda ([cw : Real]) (+ (* (add1 len) cw) (* len PRETTY-CARD-SEP-AMOUNT)))]
[pw (pretty cw)]
[ph (pretty ch)])
(let-values ([(x w) (if (> w pw)
(values (+ x (/ (- w pw) 2)) pw)
(values x w))]
[(y h) (if (> h ph)
(values (+ y (/ (- h ph) 2)) ph)
(values y h))])
(position-cards cards x y
(lambda ([p : Real])
(if (zero? len)
(values (/ (- w cw) 2)
(/ (- h ch) 2))
(values (* (- len p) (/ (- w cw) len))
(* (- len p) (/ (- h ch) len)))))
set))))))])
(super-new [label title] [style '(metal no-resize-border)])
(begin
(: c (Instance mred:Editor-Canvas%))
(define c (make-object mred:editor-canvas% this #f '(no-vscroll no-hscroll)))
(: pb (Instance Pasteboard%))
(define pb (make-object pasteboard%)))
(send c min-client-width (+ 10 (exact-floor (* w (send back get-width)))))
(send c min-client-height (+ 10 (exact-floor (* h (send back get-height)))))
(send c stretchable-width #f)
(send c stretchable-height #f)
(send this stretchable-width #f)
(send this stretchable-height #f)
(send c set-editor pb)))
(: draw-roundish-rectangle ((Instance mred:DC<%>) Real Real Real Real -> Void))
(define (draw-roundish-rectangle dc x y w h)
(send dc draw-line (+ x 1) y (+ x w -2) y)
(send dc draw-line (+ x 1) (+ y h -1) (+ x w -2) (+ y h -1))
(send dc draw-line x (+ y 1) x (+ y h -2))
(send dc draw-line (+ x w -1) (+ y 1) (+ x w -1) (+ y h -2))))
|
320c535b9b895da4dcbb8e8fc9da0c68a5bc6932423f4563b0e3ce5638bce542 | microsoft/hash-modulo-alpha | Hash.hs | -- |
-- For example, have a look at example1:
--
> import
-- > showExpr example1
--
-- ((lam x ((add x) x)) (lam y ((add y) y)))
{-# LANGUAGE BangPatterns #-}
# LANGUAGE TemplateHaskell #
# LANGUAGE LambdaCase #
module Hash where
import Hedgehog hiding (Var)
import qualified Hedgehog.Gen as Gen
import Data.Char (ord)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Hashable (Hashable, hash)
import Data.Function (on)
import Data.List (groupBy, sortBy)
import Data.Ord (comparing)
import System.Random (Random, randomRIO, randomIO)
import Expr (Expr(Var, Lam, App), Path,
allHashResults, annotation, mapAnnotation)
import qualified AlphaHashInefficient
import qualified AlphaHashEfficient
import qualified AlphaHashEfficientHash
import qualified AlphaHashOptimizedHash
import AlphaHashEfficientHash (Hash, thenHash)
locallyNameless :: (Hashable a, Ord a) => Expr h a -> Expr Hash a
locallyNameless = mapAnnotation hash . locallyNamelessExplicit
locallyNamelessExplicit :: (Ord a, Hashable a) => Expr h a -> Expr Hash a
Decorates an expression with a
-- hash-code at every node
locallyNamelessExplicit (Var _ n) = Var (hash n) n
locallyNamelessExplicit (App _ e1 e2) = App h he1 he2
where
he1 = locallyNamelessExplicit e1
he2 = locallyNamelessExplicit e2
h = hash "App" `thenHash` annotation he1 `thenHash` annotation he2
locallyNamelessExplicit e_@(Lam _ n e) = Lam h n (locallyNamelessExplicit e)
where
h = hashOnly emptyEnv e_
Yikes ! A second full traversal of e
-- Does not return a decorated expression, only a hash code
-- All nested lambdas are dealt with via deBruijn
hashOnly env (Var _ n') = case lookupEnv env n' of
Just h' -> hash (3 :: Int) `thenHash` h'
Nothing -> hash (4 :: Int) `thenHash` hash n'
hashOnly env (App _ e1 e2) = hash "App" `thenHash` h1 `thenHash` h2
where h1 = hashOnly env e1
h2 = hashOnly env e2
hashOnly env (Lam _ n' e') = hash "Lam" `thenHash` h'
where !env' = (extendEnv env n')
h' = hashOnly env' e'
lookupEnv (_, env) n' = Map.lookup n' env
extendEnv (i, env) n'
= ((,) $! (i+1)) $! Map.insert n' (hash i) env
emptyEnv = (0 :: Int, Map.empty)
| ( Broken ) DeBruijin Algorithm from " Finding Identical
Subexpressions "
deBruijnHash :: (Hashable a, Ord a) => Expr h a -> Expr Hash a
deBruijnHash expr = es
where (_, es) = deBruijnHashExplicit Map.empty expr
deBruijnHashExplicit :: (Hashable a, Ord a)
=> Map.Map a Int
-> Expr h a
-> (Hash, Expr Hash a)
deBruijnHashExplicit = \env -> \case
Var _ x -> (hash', Var hash' x)
where !hash' = case dbLookupVar x env of
Nothing -> hash "free" `thenHash` x
Just i -> hash "bound" `thenHash` i
Lam _ x e -> (hash', Lam hash' x subExpressionHashesE)
where (hashE, subExpressionHashesE) =
deBruijnHashExplicit env' e
!hash' = hash "lam" `thenHash` hashE
!env' = dbAddVar x env
App _ f e -> (hash', App hash' lF lE)
where (hashF, lF) = deBruijnHashExplicit env f
(hashE, lE) = deBruijnHashExplicit env e
!hash' = hash "app" `thenHash` hashF `thenHash` hashE
dbAddVar :: Ord k => k -> Map k Int -> Map k Int
dbAddVar v env = Map.insert v (Map.size env) env
dbLookupVar :: Ord k => k -> Map k Int -> Maybe Int
dbLookupVar v env = fmap (Map.size env -) (Map.lookup v env)
structuralHashNested :: Hashable a => Expr h a -> Expr Hash a
structuralHashNested e = es
where (_, es) = structuralHashNestedExplicit e
structuralHashNestedExplicit :: Hashable a
=> Expr h a
-> (Hash, Expr Hash a)
structuralHashNestedExplicit = \case
Var _ x -> (thisHash, Var thisHash x)
where !thisHash = hash "Var" `thenHash` x
Lam _ x e -> (thisHash, Lam thisHash x subExpressionHashes)
where (h, subExpressionHashes) = structuralHashNestedExplicit e
!thisHash = hash "Lam" `thenHash` x `thenHash` h
App _ f e -> (thisHash, App thisHash subExpressionHashesL subExpressionHashesR)
where (hL, subExpressionHashesL) = structuralHashNestedExplicit f
(hR, subExpressionHashesR) = structuralHashNestedExplicit e
!thisHash = hash "App" `thenHash` hL `thenHash` hR
alphaEquivalentAccordingToHashExpr :: (Ord a, Hashable a)
=> Expr h a -> Expr h a -> Bool
alphaEquivalentAccordingToHashExpr = (==) `on` AlphaHashOptimizedHash.alphaHashTop
alphaEquivalentAccordingToSummariseExpr :: Ord name
=> Expr h name
-> Expr h name
-> Bool
alphaEquivalentAccordingToSummariseExpr = (==) `on` AlphaHashInefficient.summariseExpr
| Whether two expressions are alpha - equivalent , implemented using
-- 'uniquifyBinders'
alphaEquivalentAccordingToUniquifyBinders :: (Eq h, Ord a) => Expr h a -> Expr h a -> Bool
alphaEquivalentAccordingToUniquifyBinders = (==) `on` uniquifyBinders
-- | Makes binders unique whilst preserving alpha-equivalence. The
binders are replaced with integers starting from zero and
increasing in left - to - right depth - first order .
--
In consequence , two expressions are alpha - equivalent if they are
equal under @uniqifyBinders@.
uniquifyBinders :: Ord a => Expr h a -> Expr h (Either a Int)
uniquifyBinders = fst . uniquifyBindersExplicit Map.empty 0
-- | The internals of 'uniquifyBinders'
uniquifyBindersExplicit :: Ord a
=> Map.Map a Int
-> Int
-> Expr h a
-> (Expr h (Either a Int), Int)
uniquifyBindersExplicit m n = \case
Var h x -> case Map.lookup x m of
Nothing -> (Var h (Left x), n)
Just i -> (Var h (Right i), n)
Lam h x e -> (Lam h (Right n) e', n')
where (e', n') = uniquifyBindersExplicit (Map.insert x n m) (n+1) e
App h f x -> (App h f' x', n'')
where (f', n') = uniquifyBindersExplicit m n f
(x', n'') = uniquifyBindersExplicit m n' x
normalizedGroupedEquivalentSubexpressions
:: Ord hash => [(hash, Path, expr)] -> [[(Path, expr)]]
normalizedGroupedEquivalentSubexpressions =
sortBy (comparing (map fst))
. filter ((/= 1) . length)
. (map . map) (\(_, path, z) -> (path, z))
. groupBy ((==) `on` (\(x, _, _) -> x))
. sortBy (comparing (\(x, _, _) -> x))
-- | Generates random expressions for testing
genExprWithVarsTest :: MonadGen m => [v] -> m (Expr () v)
genExprWithVarsTest vars = genExprWithVars_vars
Hedgehog has an example for exactly this use case !
--
-- -1.0.2/docs/Hedgehog-Gen.html#v:recursive
where genExprWithVars_vars = Gen.recursive
Gen.choice
[ Var () <$> Gen.element vars ]
[ Gen.subtermM genExprWithVars_vars (\e -> Lam () <$> Gen.element vars <*> pure e)
, Gen.subterm2 genExprWithVars_vars genExprWithVars_vars (App ())
]
genExprWithVars :: (Random v, Integral v)
=> v -> IO (Expr () v)
genExprWithVars fresh = do
size <- randomRIO (0, 2000)
genExprWithVarsSize size fresh
genExprWithVarsSize :: (Random a, Integral a)
=> Int -> a -> IO (Expr () a)
genExprWithVarsSize size fresh =
if size <= 1
then Var () <$> vars
else do
app <- randomIO
if app
then do
sizeL <- randomRIO (1, size - 2)
let sizeR = size - sizeL - 1
App () <$> genExprWithVarsSize sizeL fresh
<*> genExprWithVarsSize sizeR fresh
else
Lam () <$> binders <*> genExprWithVarsSize (size - 1) (fresh + 1)
where vars = randomRIO (0, fresh - 1)
binders = pure fresh
genExprWithVarsUnbalancedSize :: (Random a, Integral a)
=> Int -> a -> IO (Expr () a)
genExprWithVarsUnbalancedSize size fresh =
if size <= 1
then Var () <$> vars
else App () <$> (Lam () <$> binders <*> e)
<*> (Var () <$> vars)
where vars = randomRIO (0, fresh - 1)
binders = pure fresh
e = genExprWithVarsUnbalancedSize (size - 3) (fresh + 1)
-- | Generates random expressions for testing
genExpr :: MonadGen m => m (Expr () Char)
genExpr = genExprWithVarsTest ['u'..'z']
genExprNumVars :: Int -> IO (Expr () Int)
genExprNumVars n = genExprWithVars (n+1)
genExprAdversarialPair :: Int -> IO (Expr () Int, Expr () Int)
genExprAdversarialPair size =
let wrapWithApp expr = App () expr (Var () 2)
wrapWithLam expr = Lam () size expr
baseExpr1 = Lam () 1 (App () (Var () 1) (App () (Var () 1) (Var () 1)))
baseExpr2 = Lam () 1 (App () (App () (Var () 1) (Var () 1)) (Var () 1))
in
if size <= 6
then pure (baseExpr1, baseExpr2)
else if size == 7
then pure (wrapWithLam baseExpr1, wrapWithLam baseExpr2)
else do
app <- randomIO
if app
then do
(expr1, expr2) <- genExprAdversarialPair (size - 2)
pure (wrapWithApp expr1, wrapWithApp expr2)
else do
(expr1, expr2) <- genExprAdversarialPair (size - 1)
pure (wrapWithLam expr1, wrapWithLam expr2)
testEverythingInFileStartingWith'prop_' :: IO ()
testEverythingInFileStartingWith'prop_' = checkParallel $$(discover) >> pure ()
numRandomTests :: TestLimit
numRandomTests = 100 * 100
-- | Some specific test cases that demonstrate how 'uniquifyBinders'
-- works. Please suggest more examples if you have ones that would be
-- helpful.
prop_uniquifyBindersExamples :: Property
prop_uniquifyBindersExamples = withTests 1 $ property $ do
let b = Right -- "bound"
f = Left -- "free"
examples = [ (Lam () "x" (Var () "x"),
Lam () (b 0) (Var () (b 0)))
, (Lam () "x" (Var () "y"),
Lam () (b 0) (Var () (f "y")))
, (Lam () "x" (Lam () "y" (Var () "x")),
Lam () (b 0) (Lam () (b 1) (Var () (b 0))))
, (Lam () "x" (Lam () "x" (Var () "x")),
Lam () (b 0) (Lam () (b 1) (Var () (b 1))))
, (Lam () "x" (App () (Var () "x") (Var () "x")),
Lam () (b 0) (App () (Var () (b 0)) (Var () (b 0))))
, (App () (Lam () "x" (Var () "x")) (Lam () "x" (Var () "x")),
App () (Lam () (b 0) (Var () (b 0))) (Lam () (b 1) (Var () (b 1))))
]
flip mapM_ examples $ \(expression, uniquified) ->
uniquifyBinders expression === uniquified
-- | Checks that the paths come out of the algorithms in the same
order ( which just so happens to be depth first preorder ) . This is
-- not an essential property of the algorithms, but it's nice that
-- they are thus normalised so that we can compare behaviour more
-- easily.
prop_stablePaths :: Property
prop_stablePaths = withTests numRandomTests $ property $ do
let paths = map (\(_, path, _) -> path) . allHashResults
expr <- forAll genExpr
let d = deBruijnHash expr
n = structuralHashNested expr
paths d === paths n
-- | A sanity check for uniquifyBinders: it should be idempotent
prop_uniquifyBindersIdempotent :: Property
prop_uniquifyBindersIdempotent = withTests numRandomTests $ property $ do
expr <- forAll genExpr
let uniquifyBinders_expr = uniquifyBinders expr
-- For fairly boring type system reasons the types coming out of
one iteration of uniquifyBinders are different from the types
coming out of two iterations .
--
-- We just need to convert 'Left x' to 'Left (Left x)' so they
-- types match.
massageVariables = fmap (either (Left . Left) Right)
massageVariables uniquifyBinders_expr === uniquifyBinders uniquifyBinders_expr
-- | A sanity check for both uniquifyBinders and castHashTop: uniquifying
-- binders should preserve alpha-equivalence and this equivalence
-- should be picked up by castHashTop.
prop_hashUniquifyBinders :: Property
prop_hashUniquifyBinders = withTests numRandomTests $ property $ do
expr <- forAll genExpr
let massageVariables = fmap Left
assert (alphaEquivalentAccordingToHashExpr (uniquifyBinders expr)
(massageVariables expr))
-- | A check for whether castHashTop respects alpha-equivalence (as
-- defined above) by checking it against alpha-equivalence in terms of
-- uniquifyBinders, which is presumably easier to get right.
prop_hashAlphaEquivalence :: Property
prop_hashAlphaEquivalence = withTests numRandomTests $ property $ do
expr1 <- forAll genExpr
expr2 <- forAll genExpr
Or can use Hedgehog 's " diff "
alphaEquivalentAccordingToUniquifyBinders expr1 expr2
=== alphaEquivalentAccordingToHashExpr expr1 expr2
prop_hashAlphaEquivalence2 :: Property
prop_hashAlphaEquivalence2 = withTests numRandomTests $ property $ do
expr1 <- forAll genExpr
expr2 <- forAll genExpr
Or can use Hedgehog 's " diff "
alphaEquivalentAccordingToUniquifyBinders expr1 expr2
=== alphaEquivalentAccordingToSummariseExpr expr1 expr2
propG_rebuild :: (Expr () Int -> t)
-> ((Int -> Int) -> Int -> t -> Expr () Int)
-> Property
propG_rebuild summariseExpr rebuild = withTests numRandomTests $ property $ do
expr1Char <- forAll genExpr
let expr1 = fmap ord expr1Char
esummary = summariseExpr expr1
expr2 = rebuild (+1) (0 :: Int) esummary
assert (alphaEquivalentAccordingToUniquifyBinders expr1 expr2)
prop_rebuild3 :: Property
prop_rebuild3 = propG_rebuild AlphaHashInefficient.summariseExpr AlphaHashInefficient.rebuild
prop_rebuildFastOrig :: Property
prop_rebuildFastOrig =
propG_rebuild AlphaHashEfficient.summariseExpr AlphaHashEfficient.rebuild
-- | Shows equivalence the algorithms
prop_equivCastFast :: Property
prop_equivCastFast = withTests numRandomTests $ property $ do
let n = normalizedGroupedEquivalentSubexpressions . allHashResults
expr <- forAll (fmap uniquifyBinders genExpr)
let locallyNameless_groups = n (locallyNameless expr)
alphaHashEfficientHash_groups = n (AlphaHashEfficientHash.alphaHash expr)
alphaHashFasterOrigHash_groups = n (AlphaHashOptimizedHash.alphaHash expr)
locallyNameless_groups === alphaHashEfficientHash_groups
locallyNameless_groups === alphaHashFasterOrigHash_groups
prop_rebuildSApp3_inverse :: Property
prop_rebuildSApp3_inverse =
AlphaHashInefficient.prop_rebuildSApp3_inverse genExpr numRandomTests
prop_rebuildSApp_inverse :: Property
prop_rebuildSApp_inverse =
AlphaHashEfficient.prop_rebuildSApp_inverse genExpr numRandomTests
prop_fastFaster :: Property
prop_fastFaster = withTests numRandomTests $ property $ do
expr <- forAll genExpr
AlphaHashEfficientHash.alphaHash expr === AlphaHashOptimizedHash.alphaHash expr
| null | https://raw.githubusercontent.com/microsoft/hash-modulo-alpha/7ff12dbee25595a141e197a4c0a3666c416abc4e/src/Hash.hs | haskell | |
For example, have a look at example1:
> showExpr example1
((lam x ((add x) x)) (lam y ((add y) y)))
# LANGUAGE BangPatterns #
hash-code at every node
Does not return a decorated expression, only a hash code
All nested lambdas are dealt with via deBruijn
'uniquifyBinders'
| Makes binders unique whilst preserving alpha-equivalence. The
| The internals of 'uniquifyBinders'
| Generates random expressions for testing
-1.0.2/docs/Hedgehog-Gen.html#v:recursive
| Generates random expressions for testing
| Some specific test cases that demonstrate how 'uniquifyBinders'
works. Please suggest more examples if you have ones that would be
helpful.
"bound"
"free"
| Checks that the paths come out of the algorithms in the same
not an essential property of the algorithms, but it's nice that
they are thus normalised so that we can compare behaviour more
easily.
| A sanity check for uniquifyBinders: it should be idempotent
For fairly boring type system reasons the types coming out of
We just need to convert 'Left x' to 'Left (Left x)' so they
types match.
| A sanity check for both uniquifyBinders and castHashTop: uniquifying
binders should preserve alpha-equivalence and this equivalence
should be picked up by castHashTop.
| A check for whether castHashTop respects alpha-equivalence (as
defined above) by checking it against alpha-equivalence in terms of
uniquifyBinders, which is presumably easier to get right.
| Shows equivalence the algorithms | > import
# LANGUAGE TemplateHaskell #
# LANGUAGE LambdaCase #
module Hash where
import Hedgehog hiding (Var)
import qualified Hedgehog.Gen as Gen
import Data.Char (ord)
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Hashable (Hashable, hash)
import Data.Function (on)
import Data.List (groupBy, sortBy)
import Data.Ord (comparing)
import System.Random (Random, randomRIO, randomIO)
import Expr (Expr(Var, Lam, App), Path,
allHashResults, annotation, mapAnnotation)
import qualified AlphaHashInefficient
import qualified AlphaHashEfficient
import qualified AlphaHashEfficientHash
import qualified AlphaHashOptimizedHash
import AlphaHashEfficientHash (Hash, thenHash)
locallyNameless :: (Hashable a, Ord a) => Expr h a -> Expr Hash a
locallyNameless = mapAnnotation hash . locallyNamelessExplicit
locallyNamelessExplicit :: (Ord a, Hashable a) => Expr h a -> Expr Hash a
Decorates an expression with a
locallyNamelessExplicit (Var _ n) = Var (hash n) n
locallyNamelessExplicit (App _ e1 e2) = App h he1 he2
where
he1 = locallyNamelessExplicit e1
he2 = locallyNamelessExplicit e2
h = hash "App" `thenHash` annotation he1 `thenHash` annotation he2
locallyNamelessExplicit e_@(Lam _ n e) = Lam h n (locallyNamelessExplicit e)
where
h = hashOnly emptyEnv e_
Yikes ! A second full traversal of e
hashOnly env (Var _ n') = case lookupEnv env n' of
Just h' -> hash (3 :: Int) `thenHash` h'
Nothing -> hash (4 :: Int) `thenHash` hash n'
hashOnly env (App _ e1 e2) = hash "App" `thenHash` h1 `thenHash` h2
where h1 = hashOnly env e1
h2 = hashOnly env e2
hashOnly env (Lam _ n' e') = hash "Lam" `thenHash` h'
where !env' = (extendEnv env n')
h' = hashOnly env' e'
lookupEnv (_, env) n' = Map.lookup n' env
extendEnv (i, env) n'
= ((,) $! (i+1)) $! Map.insert n' (hash i) env
emptyEnv = (0 :: Int, Map.empty)
| ( Broken ) DeBruijin Algorithm from " Finding Identical
Subexpressions "
deBruijnHash :: (Hashable a, Ord a) => Expr h a -> Expr Hash a
deBruijnHash expr = es
where (_, es) = deBruijnHashExplicit Map.empty expr
deBruijnHashExplicit :: (Hashable a, Ord a)
=> Map.Map a Int
-> Expr h a
-> (Hash, Expr Hash a)
deBruijnHashExplicit = \env -> \case
Var _ x -> (hash', Var hash' x)
where !hash' = case dbLookupVar x env of
Nothing -> hash "free" `thenHash` x
Just i -> hash "bound" `thenHash` i
Lam _ x e -> (hash', Lam hash' x subExpressionHashesE)
where (hashE, subExpressionHashesE) =
deBruijnHashExplicit env' e
!hash' = hash "lam" `thenHash` hashE
!env' = dbAddVar x env
App _ f e -> (hash', App hash' lF lE)
where (hashF, lF) = deBruijnHashExplicit env f
(hashE, lE) = deBruijnHashExplicit env e
!hash' = hash "app" `thenHash` hashF `thenHash` hashE
dbAddVar :: Ord k => k -> Map k Int -> Map k Int
dbAddVar v env = Map.insert v (Map.size env) env
dbLookupVar :: Ord k => k -> Map k Int -> Maybe Int
dbLookupVar v env = fmap (Map.size env -) (Map.lookup v env)
structuralHashNested :: Hashable a => Expr h a -> Expr Hash a
structuralHashNested e = es
where (_, es) = structuralHashNestedExplicit e
structuralHashNestedExplicit :: Hashable a
=> Expr h a
-> (Hash, Expr Hash a)
structuralHashNestedExplicit = \case
Var _ x -> (thisHash, Var thisHash x)
where !thisHash = hash "Var" `thenHash` x
Lam _ x e -> (thisHash, Lam thisHash x subExpressionHashes)
where (h, subExpressionHashes) = structuralHashNestedExplicit e
!thisHash = hash "Lam" `thenHash` x `thenHash` h
App _ f e -> (thisHash, App thisHash subExpressionHashesL subExpressionHashesR)
where (hL, subExpressionHashesL) = structuralHashNestedExplicit f
(hR, subExpressionHashesR) = structuralHashNestedExplicit e
!thisHash = hash "App" `thenHash` hL `thenHash` hR
alphaEquivalentAccordingToHashExpr :: (Ord a, Hashable a)
=> Expr h a -> Expr h a -> Bool
alphaEquivalentAccordingToHashExpr = (==) `on` AlphaHashOptimizedHash.alphaHashTop
alphaEquivalentAccordingToSummariseExpr :: Ord name
=> Expr h name
-> Expr h name
-> Bool
alphaEquivalentAccordingToSummariseExpr = (==) `on` AlphaHashInefficient.summariseExpr
| Whether two expressions are alpha - equivalent , implemented using
alphaEquivalentAccordingToUniquifyBinders :: (Eq h, Ord a) => Expr h a -> Expr h a -> Bool
alphaEquivalentAccordingToUniquifyBinders = (==) `on` uniquifyBinders
binders are replaced with integers starting from zero and
increasing in left - to - right depth - first order .
In consequence , two expressions are alpha - equivalent if they are
equal under @uniqifyBinders@.
uniquifyBinders :: Ord a => Expr h a -> Expr h (Either a Int)
uniquifyBinders = fst . uniquifyBindersExplicit Map.empty 0
uniquifyBindersExplicit :: Ord a
=> Map.Map a Int
-> Int
-> Expr h a
-> (Expr h (Either a Int), Int)
uniquifyBindersExplicit m n = \case
Var h x -> case Map.lookup x m of
Nothing -> (Var h (Left x), n)
Just i -> (Var h (Right i), n)
Lam h x e -> (Lam h (Right n) e', n')
where (e', n') = uniquifyBindersExplicit (Map.insert x n m) (n+1) e
App h f x -> (App h f' x', n'')
where (f', n') = uniquifyBindersExplicit m n f
(x', n'') = uniquifyBindersExplicit m n' x
normalizedGroupedEquivalentSubexpressions
:: Ord hash => [(hash, Path, expr)] -> [[(Path, expr)]]
normalizedGroupedEquivalentSubexpressions =
sortBy (comparing (map fst))
. filter ((/= 1) . length)
. (map . map) (\(_, path, z) -> (path, z))
. groupBy ((==) `on` (\(x, _, _) -> x))
. sortBy (comparing (\(x, _, _) -> x))
genExprWithVarsTest :: MonadGen m => [v] -> m (Expr () v)
genExprWithVarsTest vars = genExprWithVars_vars
Hedgehog has an example for exactly this use case !
where genExprWithVars_vars = Gen.recursive
Gen.choice
[ Var () <$> Gen.element vars ]
[ Gen.subtermM genExprWithVars_vars (\e -> Lam () <$> Gen.element vars <*> pure e)
, Gen.subterm2 genExprWithVars_vars genExprWithVars_vars (App ())
]
genExprWithVars :: (Random v, Integral v)
=> v -> IO (Expr () v)
genExprWithVars fresh = do
size <- randomRIO (0, 2000)
genExprWithVarsSize size fresh
genExprWithVarsSize :: (Random a, Integral a)
=> Int -> a -> IO (Expr () a)
genExprWithVarsSize size fresh =
if size <= 1
then Var () <$> vars
else do
app <- randomIO
if app
then do
sizeL <- randomRIO (1, size - 2)
let sizeR = size - sizeL - 1
App () <$> genExprWithVarsSize sizeL fresh
<*> genExprWithVarsSize sizeR fresh
else
Lam () <$> binders <*> genExprWithVarsSize (size - 1) (fresh + 1)
where vars = randomRIO (0, fresh - 1)
binders = pure fresh
genExprWithVarsUnbalancedSize :: (Random a, Integral a)
=> Int -> a -> IO (Expr () a)
genExprWithVarsUnbalancedSize size fresh =
if size <= 1
then Var () <$> vars
else App () <$> (Lam () <$> binders <*> e)
<*> (Var () <$> vars)
where vars = randomRIO (0, fresh - 1)
binders = pure fresh
e = genExprWithVarsUnbalancedSize (size - 3) (fresh + 1)
genExpr :: MonadGen m => m (Expr () Char)
genExpr = genExprWithVarsTest ['u'..'z']
genExprNumVars :: Int -> IO (Expr () Int)
genExprNumVars n = genExprWithVars (n+1)
genExprAdversarialPair :: Int -> IO (Expr () Int, Expr () Int)
genExprAdversarialPair size =
let wrapWithApp expr = App () expr (Var () 2)
wrapWithLam expr = Lam () size expr
baseExpr1 = Lam () 1 (App () (Var () 1) (App () (Var () 1) (Var () 1)))
baseExpr2 = Lam () 1 (App () (App () (Var () 1) (Var () 1)) (Var () 1))
in
if size <= 6
then pure (baseExpr1, baseExpr2)
else if size == 7
then pure (wrapWithLam baseExpr1, wrapWithLam baseExpr2)
else do
app <- randomIO
if app
then do
(expr1, expr2) <- genExprAdversarialPair (size - 2)
pure (wrapWithApp expr1, wrapWithApp expr2)
else do
(expr1, expr2) <- genExprAdversarialPair (size - 1)
pure (wrapWithLam expr1, wrapWithLam expr2)
testEverythingInFileStartingWith'prop_' :: IO ()
testEverythingInFileStartingWith'prop_' = checkParallel $$(discover) >> pure ()
numRandomTests :: TestLimit
numRandomTests = 100 * 100
prop_uniquifyBindersExamples :: Property
prop_uniquifyBindersExamples = withTests 1 $ property $ do
examples = [ (Lam () "x" (Var () "x"),
Lam () (b 0) (Var () (b 0)))
, (Lam () "x" (Var () "y"),
Lam () (b 0) (Var () (f "y")))
, (Lam () "x" (Lam () "y" (Var () "x")),
Lam () (b 0) (Lam () (b 1) (Var () (b 0))))
, (Lam () "x" (Lam () "x" (Var () "x")),
Lam () (b 0) (Lam () (b 1) (Var () (b 1))))
, (Lam () "x" (App () (Var () "x") (Var () "x")),
Lam () (b 0) (App () (Var () (b 0)) (Var () (b 0))))
, (App () (Lam () "x" (Var () "x")) (Lam () "x" (Var () "x")),
App () (Lam () (b 0) (Var () (b 0))) (Lam () (b 1) (Var () (b 1))))
]
flip mapM_ examples $ \(expression, uniquified) ->
uniquifyBinders expression === uniquified
order ( which just so happens to be depth first preorder ) . This is
prop_stablePaths :: Property
prop_stablePaths = withTests numRandomTests $ property $ do
let paths = map (\(_, path, _) -> path) . allHashResults
expr <- forAll genExpr
let d = deBruijnHash expr
n = structuralHashNested expr
paths d === paths n
prop_uniquifyBindersIdempotent :: Property
prop_uniquifyBindersIdempotent = withTests numRandomTests $ property $ do
expr <- forAll genExpr
let uniquifyBinders_expr = uniquifyBinders expr
one iteration of uniquifyBinders are different from the types
coming out of two iterations .
massageVariables = fmap (either (Left . Left) Right)
massageVariables uniquifyBinders_expr === uniquifyBinders uniquifyBinders_expr
prop_hashUniquifyBinders :: Property
prop_hashUniquifyBinders = withTests numRandomTests $ property $ do
expr <- forAll genExpr
let massageVariables = fmap Left
assert (alphaEquivalentAccordingToHashExpr (uniquifyBinders expr)
(massageVariables expr))
prop_hashAlphaEquivalence :: Property
prop_hashAlphaEquivalence = withTests numRandomTests $ property $ do
expr1 <- forAll genExpr
expr2 <- forAll genExpr
Or can use Hedgehog 's " diff "
alphaEquivalentAccordingToUniquifyBinders expr1 expr2
=== alphaEquivalentAccordingToHashExpr expr1 expr2
prop_hashAlphaEquivalence2 :: Property
prop_hashAlphaEquivalence2 = withTests numRandomTests $ property $ do
expr1 <- forAll genExpr
expr2 <- forAll genExpr
Or can use Hedgehog 's " diff "
alphaEquivalentAccordingToUniquifyBinders expr1 expr2
=== alphaEquivalentAccordingToSummariseExpr expr1 expr2
propG_rebuild :: (Expr () Int -> t)
-> ((Int -> Int) -> Int -> t -> Expr () Int)
-> Property
propG_rebuild summariseExpr rebuild = withTests numRandomTests $ property $ do
expr1Char <- forAll genExpr
let expr1 = fmap ord expr1Char
esummary = summariseExpr expr1
expr2 = rebuild (+1) (0 :: Int) esummary
assert (alphaEquivalentAccordingToUniquifyBinders expr1 expr2)
prop_rebuild3 :: Property
prop_rebuild3 = propG_rebuild AlphaHashInefficient.summariseExpr AlphaHashInefficient.rebuild
prop_rebuildFastOrig :: Property
prop_rebuildFastOrig =
propG_rebuild AlphaHashEfficient.summariseExpr AlphaHashEfficient.rebuild
prop_equivCastFast :: Property
prop_equivCastFast = withTests numRandomTests $ property $ do
let n = normalizedGroupedEquivalentSubexpressions . allHashResults
expr <- forAll (fmap uniquifyBinders genExpr)
let locallyNameless_groups = n (locallyNameless expr)
alphaHashEfficientHash_groups = n (AlphaHashEfficientHash.alphaHash expr)
alphaHashFasterOrigHash_groups = n (AlphaHashOptimizedHash.alphaHash expr)
locallyNameless_groups === alphaHashEfficientHash_groups
locallyNameless_groups === alphaHashFasterOrigHash_groups
prop_rebuildSApp3_inverse :: Property
prop_rebuildSApp3_inverse =
AlphaHashInefficient.prop_rebuildSApp3_inverse genExpr numRandomTests
prop_rebuildSApp_inverse :: Property
prop_rebuildSApp_inverse =
AlphaHashEfficient.prop_rebuildSApp_inverse genExpr numRandomTests
prop_fastFaster :: Property
prop_fastFaster = withTests numRandomTests $ property $ do
expr <- forAll genExpr
AlphaHashEfficientHash.alphaHash expr === AlphaHashOptimizedHash.alphaHash expr
|
eb74289c7f66427765866f4d10fbacc56d0f97197f611a6730d0bed19217ed25 | paurkedal/batyr | message.ml | Copyright ( C ) 2022 < >
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
*)
open Types
module Decode = Decoders_yojson.Basic.Decode
type attachment = {
ts: Ptime.t;
text: string option;
(* many more fields *)
}
let attachment_decoder =
let open Decode in
let* ts = field "ts" ptime_decoder in
let+ text = field_opt "text" string in
{ts; text}
type url = {
url: string;
headers: (string * string) list;
meta: (string * string) list;
(* parlsedUrl *)
}
let url_decoder =
let open Decode in
let* url = field "url" string in
let* headers = field_opt "headers" (key_value_pairs string) in
let+ meta = field_opt "meta" (key_value_pairs string) in
{ url; headers = Option.value ~default:[] headers;
meta = Option.value ~default:[] meta }
type t = {
id: string;
rid: string;
msg: string;
ts: Ptime.t;
u: User.t;
updated_at: Ptime.t;
edited_at: Ptime.t option;
edited_by: User.t option;
urls: url list;
attachments: attachment list;
alias: string option;
avatar: string option;
groupable: bool option;
parse_urls: bool option;
}
let decoder =
let open Decode in
let* id = field "_id" string in
let* rid = field "rid" string in
let* msg = field "msg" string in
let* ts = field "ts" ptime_decoder in
let* u = field "u" User.decoder in
let* updated_at = field "_updatedAt" ptime_decoder in
let* edited_at = field_opt "editedAt" ptime_decoder in
let* edited_by = field_opt "editedBy" User.decoder in
let* urls = field_opt "urls" (list url_decoder) in
let* attachments = field_opt "attachments" (list attachment_decoder) in
let* alias = field_opt "alias" string in
let* avatar = field_opt "avatar" string in
let* groupable = field_opt "groupable" bool in
let+ parse_urls = field_opt "parseUrls" bool in
let urls = Option.value ~default:[] urls in
let attachments = Option.value ~default:[] attachments in
{ id; rid; msg; ts; u; updated_at; edited_at; edited_by;
urls; attachments; alias; avatar; groupable; parse_urls }
| null | https://raw.githubusercontent.com/paurkedal/batyr/ade1853a93c32c79384eb5eec0d8c79401c1ca04/rockettime/lib/message.ml | ocaml | many more fields
parlsedUrl | Copyright ( C ) 2022 < >
*
* This program is free software : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation , either version 3 of the License , or
* ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU General Public License for more details .
*
* You should have received a copy of the GNU General Public License
* along with this program . If not , see < / > .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see </>.
*)
open Types
module Decode = Decoders_yojson.Basic.Decode
type attachment = {
ts: Ptime.t;
text: string option;
}
let attachment_decoder =
let open Decode in
let* ts = field "ts" ptime_decoder in
let+ text = field_opt "text" string in
{ts; text}
type url = {
url: string;
headers: (string * string) list;
meta: (string * string) list;
}
let url_decoder =
let open Decode in
let* url = field "url" string in
let* headers = field_opt "headers" (key_value_pairs string) in
let+ meta = field_opt "meta" (key_value_pairs string) in
{ url; headers = Option.value ~default:[] headers;
meta = Option.value ~default:[] meta }
type t = {
id: string;
rid: string;
msg: string;
ts: Ptime.t;
u: User.t;
updated_at: Ptime.t;
edited_at: Ptime.t option;
edited_by: User.t option;
urls: url list;
attachments: attachment list;
alias: string option;
avatar: string option;
groupable: bool option;
parse_urls: bool option;
}
let decoder =
let open Decode in
let* id = field "_id" string in
let* rid = field "rid" string in
let* msg = field "msg" string in
let* ts = field "ts" ptime_decoder in
let* u = field "u" User.decoder in
let* updated_at = field "_updatedAt" ptime_decoder in
let* edited_at = field_opt "editedAt" ptime_decoder in
let* edited_by = field_opt "editedBy" User.decoder in
let* urls = field_opt "urls" (list url_decoder) in
let* attachments = field_opt "attachments" (list attachment_decoder) in
let* alias = field_opt "alias" string in
let* avatar = field_opt "avatar" string in
let* groupable = field_opt "groupable" bool in
let+ parse_urls = field_opt "parseUrls" bool in
let urls = Option.value ~default:[] urls in
let attachments = Option.value ~default:[] attachments in
{ id; rid; msg; ts; u; updated_at; edited_at; edited_by;
urls; attachments; alias; avatar; groupable; parse_urls }
|
f37b9a3502c53a44118d3f31c2f90d2ad0b1d3d1f86523a521f84acefeee8cc5 | emina/rosette | raco.rkt | #lang racket/base
(require racket/cmdline
raco/command-name
"../util/module.rkt"
"compile.rkt"
"tool.rkt"
(only-in "record.rkt" filtering-threshold)
"renderer/trace.rkt"
"renderer/noop.rkt"
"renderer/heap.rkt"
"renderer/report.rkt")
;; raco symprofile (based on raco feature-profile)
;; profile the main submodule (if there is one), or the top-level module
(define renderer% (make-parameter make-report-renderer))
(define run-profiler? (make-parameter #t))
(define module-name (make-parameter 'main))
(define renderer-options (make-parameter (hash)))
(define pkgs-to-instrument (make-parameter '()))
(define file
(command-line #:program (short-program+command-name)
#:help-labels "" "Profiler modes"
#:once-any ; Profiler selections
["--trace" "Produce a complete execution trace"
(renderer% make-trace-renderer)]
["--report" "Produce an interactive report"
(renderer% make-report-renderer)]
["--stream" "Produce a streaming interactive report"
(renderer% make-report-stream-renderer)]
["--noop" "Produce no profile output (for testing)"
(renderer% make-noop-renderer)]
["--heap" "Profile a heap profile"
(renderer% make-heap-renderer)]
; Tool configuration
#:help-labels "" "Profiled code settings"
#:once-each
[("-l" "--compiler-only")
"Only install the compile handler; do not run the profiler"
(run-profiler? #f)]
[("-m" "--module") name
"Run submodule <name> (defaults to 'main')"
(module-name (string->symbol name))]
[("-r" "--racket")
"Instrument code in any language, not just `#lang rosette`"
(symbolic-profile-rosette-only? #f)]
#:multi
[("-p" "--pkg") pkg
"Instrument code in the given package"
(pkgs-to-instrument (cons pkg (pkgs-to-instrument)))]
#:help-labels "" "Profiling settings"
#:once-each
[("-t" "--threshold") t
"Threshold (in milliseconds) for pruning cheap function calls"
(let ([th (string->number t)])
(when (or (eq? th #f) (< th 0))
(raise-argument-error 'threshold "number >= 0" t))
(filtering-threshold th))]
; Renderer-specific configuration
#:help-labels "" "Mode-specific settings"
#:once-each
[("-d" "--delay") d
"Streaming report: delay between samples, in seconds"
(let ([de (string->number d)])
(when (or (eq? de #f) (<= de 0))
(raise-argument-error 'delay "number > 0" d))
(renderer-options (hash-set (renderer-options) 'interval de)))]
[("-s" "--symlink-html")
"Interactive reports: symlink template instead of copying"
(renderer-options (hash-set (renderer-options) 'symlink #t))]
#:help-labels ""
#:args (filename . args)
; pass all unused arguments to the file being run
(current-command-line-arguments (list->vector args))
filename))
; Set up the renderer
(define (renderer source-stx name)
((renderer%) source-stx name (renderer-options)))
(current-renderer renderer)
(collect-garbage)
(collect-garbage)
(collect-garbage)
(current-compile symbolic-profile-compile-handler)
(current-load/use-compiled (make-rosette-load/use-compiled
(pkgs-to-instrument)))
(define-values (mod mod-pretty)
(module->module-path file (module-name)))
(define (run)
(dynamic-require mod #f))
(if (run-profiler?)
(profile-thunk run #:source mod-pretty
#:name (format "~a" file))
(run))
| null | https://raw.githubusercontent.com/emina/rosette/b58652b26f110931638f0b78fa6bb301e6da2768/rosette/lib/profile/raco.rkt | racket | raco symprofile (based on raco feature-profile)
profile the main submodule (if there is one), or the top-level module
Profiler selections
Tool configuration
Renderer-specific configuration
pass all unused arguments to the file being run
Set up the renderer | #lang racket/base
(require racket/cmdline
raco/command-name
"../util/module.rkt"
"compile.rkt"
"tool.rkt"
(only-in "record.rkt" filtering-threshold)
"renderer/trace.rkt"
"renderer/noop.rkt"
"renderer/heap.rkt"
"renderer/report.rkt")
(define renderer% (make-parameter make-report-renderer))
(define run-profiler? (make-parameter #t))
(define module-name (make-parameter 'main))
(define renderer-options (make-parameter (hash)))
(define pkgs-to-instrument (make-parameter '()))
(define file
(command-line #:program (short-program+command-name)
#:help-labels "" "Profiler modes"
["--trace" "Produce a complete execution trace"
(renderer% make-trace-renderer)]
["--report" "Produce an interactive report"
(renderer% make-report-renderer)]
["--stream" "Produce a streaming interactive report"
(renderer% make-report-stream-renderer)]
["--noop" "Produce no profile output (for testing)"
(renderer% make-noop-renderer)]
["--heap" "Profile a heap profile"
(renderer% make-heap-renderer)]
#:help-labels "" "Profiled code settings"
#:once-each
[("-l" "--compiler-only")
"Only install the compile handler; do not run the profiler"
(run-profiler? #f)]
[("-m" "--module") name
"Run submodule <name> (defaults to 'main')"
(module-name (string->symbol name))]
[("-r" "--racket")
"Instrument code in any language, not just `#lang rosette`"
(symbolic-profile-rosette-only? #f)]
#:multi
[("-p" "--pkg") pkg
"Instrument code in the given package"
(pkgs-to-instrument (cons pkg (pkgs-to-instrument)))]
#:help-labels "" "Profiling settings"
#:once-each
[("-t" "--threshold") t
"Threshold (in milliseconds) for pruning cheap function calls"
(let ([th (string->number t)])
(when (or (eq? th #f) (< th 0))
(raise-argument-error 'threshold "number >= 0" t))
(filtering-threshold th))]
#:help-labels "" "Mode-specific settings"
#:once-each
[("-d" "--delay") d
"Streaming report: delay between samples, in seconds"
(let ([de (string->number d)])
(when (or (eq? de #f) (<= de 0))
(raise-argument-error 'delay "number > 0" d))
(renderer-options (hash-set (renderer-options) 'interval de)))]
[("-s" "--symlink-html")
"Interactive reports: symlink template instead of copying"
(renderer-options (hash-set (renderer-options) 'symlink #t))]
#:help-labels ""
#:args (filename . args)
(current-command-line-arguments (list->vector args))
filename))
(define (renderer source-stx name)
((renderer%) source-stx name (renderer-options)))
(current-renderer renderer)
(collect-garbage)
(collect-garbage)
(collect-garbage)
(current-compile symbolic-profile-compile-handler)
(current-load/use-compiled (make-rosette-load/use-compiled
(pkgs-to-instrument)))
(define-values (mod mod-pretty)
(module->module-path file (module-name)))
(define (run)
(dynamic-require mod #f))
(if (run-profiler?)
(profile-thunk run #:source mod-pretty
#:name (format "~a" file))
(run))
|
19177e8a21960035c6b50d4d9ab05a4111a1dcfd0e6e1a99260ed82f16b22025 | AeneasVerif/aeneas | TypesUtils.ml | open Types
include Charon.TypesUtils
module TA = TypesAnalysis
* Retuns true if the type contains borrows .
Note that we ca n't simply explore the type and look for regions : sometimes
we erase the lists of regions ( by replacing them with [ [ ] ] when using { ! } ,
and when a type uses ' static this region does n't appear in the region parameters .
Note that we can't simply explore the type and look for regions: sometimes
we erase the lists of regions (by replacing them with [[]] when using {!Types.ety},
and when a type uses 'static this region doesn't appear in the region parameters.
*)
let ty_has_borrows (infos : TA.type_infos) (ty : 'r ty) : bool =
let info = TA.analyze_ty infos ty in
info.TA.contains_borrow
* Retuns true if the type contains nested borrows .
Note that we ca n't simply explore the type and look for regions : sometimes
we erase the lists of regions ( by replacing them with [ [ ] ] when using { ! } ,
and when a type uses ' static this region does n't appear in the region parameters .
Note that we can't simply explore the type and look for regions: sometimes
we erase the lists of regions (by replacing them with [[]] when using {!Types.ety},
and when a type uses 'static this region doesn't appear in the region parameters.
*)
let ty_has_nested_borrows (infos : TA.type_infos) (ty : 'r ty) : bool =
let info = TA.analyze_ty infos ty in
info.TA.contains_nested_borrows
(** Retuns true if the type contains a borrow under a mutable borrow *)
let ty_has_borrow_under_mut (infos : TA.type_infos) (ty : 'r ty) : bool =
let info = TA.analyze_ty infos ty in
info.TA.contains_borrow_under_mut
| null | https://raw.githubusercontent.com/AeneasVerif/aeneas/d8d661d02cf0068753ae3963156896492dfde50a/compiler/TypesUtils.ml | ocaml | * Retuns true if the type contains a borrow under a mutable borrow | open Types
include Charon.TypesUtils
module TA = TypesAnalysis
* Retuns true if the type contains borrows .
Note that we ca n't simply explore the type and look for regions : sometimes
we erase the lists of regions ( by replacing them with [ [ ] ] when using { ! } ,
and when a type uses ' static this region does n't appear in the region parameters .
Note that we can't simply explore the type and look for regions: sometimes
we erase the lists of regions (by replacing them with [[]] when using {!Types.ety},
and when a type uses 'static this region doesn't appear in the region parameters.
*)
let ty_has_borrows (infos : TA.type_infos) (ty : 'r ty) : bool =
let info = TA.analyze_ty infos ty in
info.TA.contains_borrow
* Retuns true if the type contains nested borrows .
Note that we ca n't simply explore the type and look for regions : sometimes
we erase the lists of regions ( by replacing them with [ [ ] ] when using { ! } ,
and when a type uses ' static this region does n't appear in the region parameters .
Note that we can't simply explore the type and look for regions: sometimes
we erase the lists of regions (by replacing them with [[]] when using {!Types.ety},
and when a type uses 'static this region doesn't appear in the region parameters.
*)
let ty_has_nested_borrows (infos : TA.type_infos) (ty : 'r ty) : bool =
let info = TA.analyze_ty infos ty in
info.TA.contains_nested_borrows
let ty_has_borrow_under_mut (infos : TA.type_infos) (ty : 'r ty) : bool =
let info = TA.analyze_ty infos ty in
info.TA.contains_borrow_under_mut
|
4fee07d230ef6cac9ab2eebcafcbd829280eb7db35007de74e905dc45e396ef4 | janestreet/sexp | sexps.mli | open! Core
type t = Sexp.t Hash_set.t
val create : unit -> t
val of_list : Sexp.t list -> t
include Sexpable with type t := t
| null | https://raw.githubusercontent.com/janestreet/sexp/56e485b3cbf8a43e1a8d7647b0df31b27053febf/sexp_app/src/sexps.mli | ocaml | open! Core
type t = Sexp.t Hash_set.t
val create : unit -> t
val of_list : Sexp.t list -> t
include Sexpable with type t := t
| |
461aa09df122a4a6a10ec29c1e0b9f544ea2c2a347cca431539ce85e0360285c | RoadRunnr/dtlsex | dtlsex_session_cache.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 2008 - 2012 . All Rights Reserved .
%%
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
%% compliance with the License. You should have received a copy of the
%% Erlang Public License along with this software. If not, it can be
%% retrieved online at /.
%%
Software distributed under the License is distributed on an " AS IS "
%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%% the License for the specific language governing rights and limitations
%% under the License.
%%
%% %CopyrightEnd%
%%
%%
-module(dtlsex_session_cache).
-behaviour(dtlsex_session_cache_api).
-include("dtlsex_handshake.hrl").
-include("dtlsex_internal.hrl").
-export([init/1, terminate/1, lookup/2, update/3, delete/2, foldl/3,
select_session/2, size/1]).
%%--------------------------------------------------------------------
%% Description: Return table reference. Called by dtlsex_manager process.
%%--------------------------------------------------------------------
init(_) ->
ets:new(cache_name(), [ordered_set, protected]).
%%--------------------------------------------------------------------
%% Description: Handles cache table at termination of ssl manager.
%%--------------------------------------------------------------------
terminate(Cache) ->
ets:delete(Cache).
%%--------------------------------------------------------------------
Description : Looks up a cach entry . Should be callable from any
%% process.
%%--------------------------------------------------------------------
lookup(Cache, Key) ->
case ets:lookup(Cache, Key) of
[{Key, Session}] ->
Session;
[] ->
undefined
end.
%%--------------------------------------------------------------------
%% Description: Caches a new session or updates a already cached one.
%% Will only be called from the dtlsex_manager process.
%%--------------------------------------------------------------------
update(Cache, Key, Session) ->
ets:insert(Cache, {Key, Session}).
%%--------------------------------------------------------------------
%% Description: Delets a cache entry.
%% Will only be called from the dtlsex_manager process.
%%--------------------------------------------------------------------
delete(Cache, Key) ->
ets:delete(Cache, Key).
%%--------------------------------------------------------------------
Description : Calls Fun(Elem , AccIn ) on successive elements of the
cache , starting with AccIn = = Acc0 . Fun/2 must return a new
%% accumulator which is passed to the next call. The function returns
%% the final value of the accumulator. Acc0 is returned if the cache
%% is empty.Should be callable from any process
%%--------------------------------------------------------------------
foldl(Fun, Acc0, Cache) ->
ets:foldl(Fun, Acc0, Cache).
%%--------------------------------------------------------------------
%% Description: Selects a session that could be reused. Should be callable
%% from any process.
%%--------------------------------------------------------------------
select_session(Cache, PartialKey) ->
ets:select(Cache,
[{{{PartialKey,'_'}, '$1'},[],['$1']}]).
%%--------------------------------------------------------------------
%% Description: Returns the cache size
%%--------------------------------------------------------------------
size(Cache) ->
ets:info(Cache, size).
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
cache_name() ->
dtlsex_otp_session_cache.
| null | https://raw.githubusercontent.com/RoadRunnr/dtlsex/6cb9e52ff00ab0e5f33e0c4b54bf46eacddeb8e7/src/dtlsex_session_cache.erl | erlang |
%CopyrightBegin%
compliance with the License. You should have received a copy of the
Erlang Public License along with this software. If not, it can be
retrieved online at /.
basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
the License for the specific language governing rights and limitations
under the License.
%CopyrightEnd%
--------------------------------------------------------------------
Description: Return table reference. Called by dtlsex_manager process.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Handles cache table at termination of ssl manager.
--------------------------------------------------------------------
--------------------------------------------------------------------
process.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Caches a new session or updates a already cached one.
Will only be called from the dtlsex_manager process.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Delets a cache entry.
Will only be called from the dtlsex_manager process.
--------------------------------------------------------------------
--------------------------------------------------------------------
accumulator which is passed to the next call. The function returns
the final value of the accumulator. Acc0 is returned if the cache
is empty.Should be callable from any process
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Selects a session that could be reused. Should be callable
from any process.
--------------------------------------------------------------------
--------------------------------------------------------------------
Description: Returns the cache size
--------------------------------------------------------------------
--------------------------------------------------------------------
-------------------------------------------------------------------- | Copyright Ericsson AB 2008 - 2012 . All Rights Reserved .
The contents of this file are subject to the Erlang Public License ,
Version 1.1 , ( the " License " ) ; you may not use this file except in
Software distributed under the License is distributed on an " AS IS "
-module(dtlsex_session_cache).
-behaviour(dtlsex_session_cache_api).
-include("dtlsex_handshake.hrl").
-include("dtlsex_internal.hrl").
-export([init/1, terminate/1, lookup/2, update/3, delete/2, foldl/3,
select_session/2, size/1]).
init(_) ->
ets:new(cache_name(), [ordered_set, protected]).
terminate(Cache) ->
ets:delete(Cache).
Description : Looks up a cach entry . Should be callable from any
lookup(Cache, Key) ->
case ets:lookup(Cache, Key) of
[{Key, Session}] ->
Session;
[] ->
undefined
end.
update(Cache, Key, Session) ->
ets:insert(Cache, {Key, Session}).
delete(Cache, Key) ->
ets:delete(Cache, Key).
Description : Calls Fun(Elem , AccIn ) on successive elements of the
cache , starting with AccIn = = Acc0 . Fun/2 must return a new
foldl(Fun, Acc0, Cache) ->
ets:foldl(Fun, Acc0, Cache).
select_session(Cache, PartialKey) ->
ets:select(Cache,
[{{{PartialKey,'_'}, '$1'},[],['$1']}]).
size(Cache) ->
ets:info(Cache, size).
Internal functions
cache_name() ->
dtlsex_otp_session_cache.
|
d18e08c673c4b63197345cc104454f4e6d7f5e8cf12b67f7986055982d978ae4 | abhinav/pinch | FoldListSpec.hs | # LANGUAGE ScopedTypeVariables #
module Pinch.Internal.FoldListSpec (spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import qualified Data.Foldable as F
import qualified Data.IORef as IORef
import qualified Data.Vector as V
import qualified Pinch.Internal.FoldList as FL
spec :: Spec
spec = describe "FoldList" $ do
prop "is equal to itself" $ \(xs :: [Int]) ->
FL.fromFoldable xs === FL.fromFoldable xs
prop "is equal if the elements are the same" $ \(xs :: [Int]) ->
FL.fromFoldable xs === FL.fromFoldable (V.fromList xs)
prop "can convert to and from lists" $ \(xs :: [Int]) ->
F.toList (FL.fromFoldable xs) === xs
describe "replicate" $ do
it "can be empty" $
F.toList (FL.replicate 0 'a') `shouldBe` []
it "produces the requested number of duplicates" $
F.toList (FL.replicate 5 'a') `shouldBe` "aaaaa"
describe "replicateM" $
it "preserves order" $ do
ref <- IORef.newIORef (1 :: Int)
let get = IORef.atomicModifyIORef' ref (\a -> (a + 1, a))
result <- FL.replicateM 100 get
F.toList result `shouldBe` [1..100]
| null | https://raw.githubusercontent.com/abhinav/pinch/4b09f7960840f316b223bff9b9b44a6a51d3cccc/tests/Pinch/Internal/FoldListSpec.hs | haskell | # LANGUAGE ScopedTypeVariables #
module Pinch.Internal.FoldListSpec (spec) where
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import qualified Data.Foldable as F
import qualified Data.IORef as IORef
import qualified Data.Vector as V
import qualified Pinch.Internal.FoldList as FL
spec :: Spec
spec = describe "FoldList" $ do
prop "is equal to itself" $ \(xs :: [Int]) ->
FL.fromFoldable xs === FL.fromFoldable xs
prop "is equal if the elements are the same" $ \(xs :: [Int]) ->
FL.fromFoldable xs === FL.fromFoldable (V.fromList xs)
prop "can convert to and from lists" $ \(xs :: [Int]) ->
F.toList (FL.fromFoldable xs) === xs
describe "replicate" $ do
it "can be empty" $
F.toList (FL.replicate 0 'a') `shouldBe` []
it "produces the requested number of duplicates" $
F.toList (FL.replicate 5 'a') `shouldBe` "aaaaa"
describe "replicateM" $
it "preserves order" $ do
ref <- IORef.newIORef (1 :: Int)
let get = IORef.atomicModifyIORef' ref (\a -> (a + 1, a))
result <- FL.replicateM 100 get
F.toList result `shouldBe` [1..100]
| |
50c438c12dcb1b85108cf802dbfd89f2ae1c37a2eb1781699bb650ac75e6051b | msfm2018/Online-Service | utils.erl | -module(utils).
-include("common.hrl").
-compile(export_all).
% ets 为非关键字 的查询删除
del_player(So) ->
Key = ets:first(users),
case Key of
'$end_of_table' -> void;
_ ->
RT = ets:lookup(users, Key),
case RT of
[] -> void;
_ ->
[{_, _, _, _, B}] = RT,
case B == So of
true ->
ets:delete(users, Key);
false ->
nx(Key, So)
end
end
end.
nx(Keys, So) ->
Key1 = ets:next(users, Keys),
case Key1 of
'$end_of_table' -> void;
_ ->
RT = ets:lookup(users, Key1),
[{_, _, _, _, B}] = RT,
case B == So of
true ->
io : ~ n " ) ,
ets:delete(users, Key1);
false ->
%% io:format("next2~n"),
nx(Key1, So)
end
end.
%删除 代理IP
del_gateway_ip([], _OldVal, Vals) -> db:set_value("gateway_ip", Vals);
del_gateway_ip([H | T], OldVal, Vals) ->
case re:run(binary_to_list(H), OldVal) of
{match, _} ->
New = Vals;
_ -> case H of
<<>> -> New = Vals;
_ -> H1 = binary_to_list(H) ++ " ", New = [H1 | Vals]
end
end,
del_gateway_ip(T, OldVal, New).
local_port() ->
[{gc_gateway,[{port,Port},{acceptor_num,_}]}] = ets:lookup(?LocalCfg, gc_gateway), Port.
local_accetpnum() ->
[ { gc_gateway,[{port,_},{acceptor_num , Num},{localexternal_ip , _ } ] } ] = ets : lookup(?LocalCfg , ) , .
[{gc_gateway,[{port,_},{acceptor_num,Num}]}] = ets:lookup(?LocalCfg, gc_gateway),Num.
string_to_term(Str) ->
case catch erl_scan:string(Str ++ ". ") of
{ok, ScannedStr, _No} ->
case erl_parse:parse_term(ScannedStr) of
{ok, Term} ->
{ok, Term};
_Other ->
May be a PID , have to check this , since erl_scan
%% currently cannot handle this case... :-(
case catch list_to_pid(Str) of
Pid when is_pid(Pid) ->
{ok, Pid};
_Error ->
case get(error_msg_mode) of
normal ->
{error, {not_a_term, "Please enter a valid term!"}};
haiku ->
{error, {not_a_term, ["Aborted effort.",
"Reflect, repent and retype:",
"Enter valid term."]}}
end
end
end;
_Error ->
case get(error_msg_mode) of
normal ->
{error, {not_a_term, "Please enter a valid term!"}};
haiku ->
{error, {not_a_term, ["Aborted effort.",
"Reflect, repent and retype:",
"Enter valid term."]}}
end
end.
get_my_ip() ->
case init:get_argument(ip) of
{ok, [[Ip | _]]} ->
?TO_B(Ip);
_ ->
get_ip_by_node(node())
end.
get_local_ip() ->
[_, LocalIp] = string:tokens(atom_to_list(node()), "@"), LocalIp.
get_gateway_name() ->
[Name, _] = string:tokens(atom_to_list(node()), "@"), Name.
get_redis_host() ->
case init:get_argument(redis) of
{ok, [[Ip | _]]} ->
?TO_B(Ip);
_ ->
get_ip_by_node(node())
end.
get_ip_by_node(Node) ->
S = ?TO_L(Node),
[_, Ip] = string:tokens(S, "@"),
?TO_B(Ip).
ets_lookup_element(T, K, P) ->
case catch ets:lookup_element(T, K, P) of
{'EXIT', _} ->
?NULL;
R ->
R
end.
@doc 删除操作 不在乎顺序的删除
delete_list_member_no_order(Member, List) ->
delete_list_member_no_order(Member, List, []).
delete_list_member_no_order(_, [], RList) ->
RList;
delete_list_member_no_order(Member, [H | L], RList) ->
?IF(Member =:= H, delete_list_member_no_order(Member, L, RList), delete_list_member_no_order(Member, L, [H | RList])).
%% @doc 获取元组列表中对应k的v
get_v_by_k(K, L) ->
get_v_by_k(K, L, ?UNDEFINED).
get_v_by_k(K, L, Default) ->
case lists:keyfind(K, 1, L) of
{_, V} ->
V;
_ ->
Default
end.
@doc
quchong_no_order(L) ->
quchong1(L, []).
quchong1([], L1) ->
L1;
quchong1([H | L], L1) ->
case lists:member(H, L1) of
true -> quchong1(L, L1);
false -> quchong1(L, [H | L1])
end.
local_node() -> list_to_binary(atom_to_list(node())).
local_node_size() -> size(local_node()).
%% @doc get IP address string from Socket
ip(Socket) ->
{ok, {IP, _Port}} = inet:peername(Socket),
{Ip0, Ip1, Ip2, Ip3} = IP,
list_to_binary(integer_to_list(Ip0) ++ "." ++ integer_to_list(Ip1) ++ "." ++ integer_to_list(Ip2) ++ "." ++ integer_to_list(Ip3)).
%% @doc quick sort
sort([]) ->
[];
sort([H | T]) ->
sort([X || X <- T, X < H]) ++ [H] ++ sort([X || X <- T, X >= H]).
%% for
for(Max, Max, F) -> [F(Max)];
for(I, Max, F) -> [F(I) | for(I + 1, Max, F)].
@doc convert float to string , f2s(1.5678 ) - > 1.57
f2s(N) when is_integer(N) ->
integer_to_list(N) ++ ".00";
f2s(F) when is_float(F) ->
[A] = io_lib:format("~.2f", [F]),
A.
%% @doc convert other type to atom
to_atom(Msg) when is_atom(Msg) ->
Msg;
to_atom(Msg) when is_binary(Msg) ->
utils:list_to_atom2(binary_to_list(Msg));
to_atom(Msg) when is_list(Msg) ->
utils:list_to_atom2(Msg);
to_atom(_) ->
throw(other_value).
%% @doc convert other type to list
to_list(Msg) when is_list(Msg) ->
Msg;
to_list(Msg) when is_atom(Msg) ->
atom_to_list(Msg);
to_list(Msg) when is_binary(Msg) ->
binary_to_list(Msg);
to_list(Msg) when is_integer(Msg) ->
integer_to_list(Msg);
to_list(Msg) when is_float(Msg) ->
f2s(Msg);
to_list(Msg) when is_tuple(Msg) ->
tuple_to_list(Msg);
to_list(_) ->
throw(other_value).
%% @doc convert other type to binary
to_binary(Msg) when is_binary(Msg) ->
Msg;
to_binary(Msg) when is_atom(Msg) ->
list_to_binary(atom_to_list(Msg));
atom_to_binary(Msg , ) ;
to_binary(Msg) when is_list(Msg) ->
list_to_binary(Msg);
to_binary(Msg) when is_integer(Msg) ->
list_to_binary(integer_to_list(Msg));
to_binary(Msg) when is_float(Msg) ->
list_to_binary(f2s(Msg));
to_binary(_Msg) ->
throw(other_value).
%% @doc convert other type to float
to_float(Msg) ->
Msg2 = to_list(Msg),
list_to_float(Msg2).
%% @doc convert other type to integer
-spec to_integer(Msg :: any()) -> integer().
to_integer(Msg) when is_integer(Msg) ->
Msg;
to_integer(Msg) when is_binary(Msg) ->
Msg2 = binary_to_list(Msg),
list_to_integer(Msg2);
to_integer(Msg) when is_list(Msg) ->
list_to_integer(Msg);
to_integer(Msg) when is_float(Msg) ->
round(Msg);
to_integer(_Msg) ->
throw(other_value).
to_bool(D) when is_integer(D) ->
D =/= 0;
to_bool(D) when is_list(D) ->
length(D) =/= 0;
to_bool(D) when is_binary(D) ->
to_bool(binary_to_list(D));
to_bool(D) when is_boolean(D) ->
D;
to_bool(_D) ->
throw(other_value).
%% 不支持binary到tuple的直接转换 因为这种往往是直接从数据库取出来的<<"{1,2,3}">>等形式,单独做
to_tuple(D) when is_integer(D) ->
list_to_tuple(integer_to_list(D));
to_tuple(D) when is_list(D) ->
list_to_tuple(D);
to_tuple(D) when is_atom(D) ->
list_to_tuple(atom_to_list(D));
to_tuple(_D) ->
throw(other_value).
@doc get a random integer between and
random(Min, Max) ->
Min2 = Min - 1,
rand:uniform(Max - Min2) + Min2.
%% @doc 取整 大于X的最小整数
ceil(X) ->
T = trunc(X),
if
X - T == 0 ->
T;
true ->
if
X > 0 ->
T + 1;
true ->
T
end
end.
@doc 取整 小于X的最大整数
floor(X) ->
T = trunc(X),
if
X - T == 0 ->
T;
true ->
if
X > 0 ->
T;
true ->
T - 1
end
end.
md5(S) ->
Md5_bin = erlang:md5(S),
Md5_list = binary_to_list(Md5_bin),
lists:flatten(list_to_hex(Md5_list)).
list_to_hex(L) ->
lists:map(fun(X) -> int_to_hex(X) end, L).
int_to_hex(N) when N < 256 ->
[hex(N div 16), hex(N rem 16)].
hex(N) when N < 10 ->
$0 + N;
hex(N) when N >= 10, N < 16 ->
$a + (N - 10).
list_to_atom2(List) when is_list(List) ->
case catch (list_to_existing_atom(List)) of
{'EXIT', _} -> erlang:list_to_atom(List);
Atom when is_atom(Atom) -> Atom
end.
combine_lists(L1, L2) ->
Rtn =
lists:foldl(
fun(T, Acc) ->
case lists:member(T, Acc) of
true ->
Acc;
false ->
[T | Acc]
end
end, lists:reverse(L1), L2),
lists:reverse(Rtn).
get_process_info_and_zero_value(InfoName) ->
PList = erlang:processes(),
ZList = lists:filter(
fun(T) ->
case erlang:process_info(T, InfoName) of
{InfoName, 0} -> false;
_ -> true
end
end, PList),
ZZList = lists:map(
fun(T) -> {T, erlang:process_info(T, InfoName), erlang:process_info(T, registered_name)}
end, ZList),
[length(PList), InfoName, length(ZZList), ZZList].
get_process_info_and_large_than_value(InfoName, Value) ->
PList = erlang:processes(),
ZList = lists:filter(
fun(T) ->
case erlang:process_info(T, InfoName) of
{InfoName, VV} ->
if VV > Value -> true;
true -> false
end;
_ -> true
end
end, PList),
ZZList = lists:map(
fun(T) -> {T, erlang:process_info(T, InfoName), erlang:process_info(T, registered_name)}
end, ZList),
[length(PList), InfoName, Value, length(ZZList), ZZList].
get_msg_queue() ->
io:fwrite("process count:~p~n~p value is not 0 count:~p~nLists:~p~n",
get_process_info_and_zero_value(message_queue_len)).
get_memory() ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(memory, 1048576)).
get_memory(Value) ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(memory, Value)).
get_heap() ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(heap_size, 1048576)).
get_heap(Value) ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(heap_size, Value)).
get_processes() ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(memory, 0)).
list_to_term(String) ->
{ok, T, _} = erl_scan:string(String ++ "."),
case erl_parse:parse_term(T) of
{ok, Term} ->
Term;
{error, Error} ->
Error
end.
string_to_fun(S) ->
string_to_fun(S, []).
string_to_fun(S, Binding) ->
{ok, Ts, _} = erl_scan:string(S),
Ts1 = case lists:reverse(Ts) of
[{dot, _} | _] -> Ts;
TsR -> lists:reverse([{dot, 1} | TsR])
end,
{ok, Expr} = erl_parse:parse_exprs(Ts1),
{value, Fun, _} = erl_eval:exprs(Expr, Binding),
Fun.
substr_utf8(Utf8EncodedString, Length) ->
substr_utf8(Utf8EncodedString, 1, Length).
substr_utf8(Utf8EncodedString, Start, Length) ->
ByteLength = 2 * Length,
Ucs = xmerl_ucs:from_utf8(Utf8EncodedString),
Utf16Bytes = xmerl_ucs:to_utf16be(Ucs),
SubStringUtf16 = lists:sublist(Utf16Bytes, Start, ByteLength),
Ucs1 = xmerl_ucs:from_utf16be(SubStringUtf16),
xmerl_ucs:to_utf8(Ucs1).
ip_str(IP) ->
case IP of
{A, B, C, D} ->
lists:concat([A, ".", B, ".", C, ".", D]);
{A, B, C, D, E, F, G, H} ->
lists:concat([A, ":", B, ":", C, ":", D, ":", E, ":", F, ":", G, ":", H]);
Str when is_list(Str) ->
Str;
_ ->
[]
end.
去掉字符串空格
remove_string_black(L) ->
lists:reverse(remove_string_loop(L, [])).
remove_string_loop([], L) ->
L;
remove_string_loop([I | L], LS) ->
case I of
32 ->
remove_string_loop(L, LS);
_ ->
remove_string_loop(L, [I | LS])
end.
%%获取协议操作的时间戳,true->允许;false -> 直接丢弃该条数据
spec is_operate_ok/1 param : Type - > 添加的协议类型(atom ) ; return : true->允许;false - > 直接丢弃该条数据
is_operate_ok(Type, TimeStamp) ->
NowTime = util:unixtime(),
case get(Type) of
undefined ->
put(Type, NowTime),
true;
Value ->
case (NowTime - Value) >= TimeStamp of
true ->
put(Type, NowTime),
true;
false ->
false
end
end.
%%替换指定的列表的指定的位置N的元素
eg : replace([a , b , c , d ] , 2 , g ) - > [ a , g , c , d ]
replace(List, Key, NewElem) ->
NewList = lists:reverse(List),
Len = length(List),
case Key =< 0 orelse Key > Len of
true ->
List;
false ->
replace_elem(Len, [], NewList, Key, NewElem)
end.
replace_elem(0, List, _OldList, _Key, _NewElem) ->
List;
replace_elem(Num, List, [Elem | OldList], Key, NewElem) ->
NewList =
case Num =:= Key of
true ->
[NewElem | List];
false ->
[Elem | List]
end,
replace_elem(Num - 1, NewList, OldList, Key, NewElem).
| null | https://raw.githubusercontent.com/msfm2018/Online-Service/281c2db795f09c7e4dc6768d08d35bbe83350670/src/lib/utils.erl | erlang | ets 为非关键字 的查询删除
io:format("next2~n"),
删除 代理IP
currently cannot handle this case... :-(
@doc 获取元组列表中对应k的v
@doc get IP address string from Socket
@doc quick sort
for
@doc convert other type to atom
@doc convert other type to list
@doc convert other type to binary
@doc convert other type to float
@doc convert other type to integer
不支持binary到tuple的直接转换 因为这种往往是直接从数据库取出来的<<"{1,2,3}">>等形式,单独做
@doc 取整 大于X的最小整数
获取协议操作的时间戳,true->允许;false -> 直接丢弃该条数据
替换指定的列表的指定的位置N的元素 | -module(utils).
-include("common.hrl").
-compile(export_all).
del_player(So) ->
Key = ets:first(users),
case Key of
'$end_of_table' -> void;
_ ->
RT = ets:lookup(users, Key),
case RT of
[] -> void;
_ ->
[{_, _, _, _, B}] = RT,
case B == So of
true ->
ets:delete(users, Key);
false ->
nx(Key, So)
end
end
end.
nx(Keys, So) ->
Key1 = ets:next(users, Keys),
case Key1 of
'$end_of_table' -> void;
_ ->
RT = ets:lookup(users, Key1),
[{_, _, _, _, B}] = RT,
case B == So of
true ->
io : ~ n " ) ,
ets:delete(users, Key1);
false ->
nx(Key1, So)
end
end.
del_gateway_ip([], _OldVal, Vals) -> db:set_value("gateway_ip", Vals);
del_gateway_ip([H | T], OldVal, Vals) ->
case re:run(binary_to_list(H), OldVal) of
{match, _} ->
New = Vals;
_ -> case H of
<<>> -> New = Vals;
_ -> H1 = binary_to_list(H) ++ " ", New = [H1 | Vals]
end
end,
del_gateway_ip(T, OldVal, New).
local_port() ->
[{gc_gateway,[{port,Port},{acceptor_num,_}]}] = ets:lookup(?LocalCfg, gc_gateway), Port.
local_accetpnum() ->
[ { gc_gateway,[{port,_},{acceptor_num , Num},{localexternal_ip , _ } ] } ] = ets : lookup(?LocalCfg , ) , .
[{gc_gateway,[{port,_},{acceptor_num,Num}]}] = ets:lookup(?LocalCfg, gc_gateway),Num.
string_to_term(Str) ->
case catch erl_scan:string(Str ++ ". ") of
{ok, ScannedStr, _No} ->
case erl_parse:parse_term(ScannedStr) of
{ok, Term} ->
{ok, Term};
_Other ->
May be a PID , have to check this , since erl_scan
case catch list_to_pid(Str) of
Pid when is_pid(Pid) ->
{ok, Pid};
_Error ->
case get(error_msg_mode) of
normal ->
{error, {not_a_term, "Please enter a valid term!"}};
haiku ->
{error, {not_a_term, ["Aborted effort.",
"Reflect, repent and retype:",
"Enter valid term."]}}
end
end
end;
_Error ->
case get(error_msg_mode) of
normal ->
{error, {not_a_term, "Please enter a valid term!"}};
haiku ->
{error, {not_a_term, ["Aborted effort.",
"Reflect, repent and retype:",
"Enter valid term."]}}
end
end.
get_my_ip() ->
case init:get_argument(ip) of
{ok, [[Ip | _]]} ->
?TO_B(Ip);
_ ->
get_ip_by_node(node())
end.
get_local_ip() ->
[_, LocalIp] = string:tokens(atom_to_list(node()), "@"), LocalIp.
get_gateway_name() ->
[Name, _] = string:tokens(atom_to_list(node()), "@"), Name.
get_redis_host() ->
case init:get_argument(redis) of
{ok, [[Ip | _]]} ->
?TO_B(Ip);
_ ->
get_ip_by_node(node())
end.
get_ip_by_node(Node) ->
S = ?TO_L(Node),
[_, Ip] = string:tokens(S, "@"),
?TO_B(Ip).
ets_lookup_element(T, K, P) ->
case catch ets:lookup_element(T, K, P) of
{'EXIT', _} ->
?NULL;
R ->
R
end.
@doc 删除操作 不在乎顺序的删除
delete_list_member_no_order(Member, List) ->
delete_list_member_no_order(Member, List, []).
delete_list_member_no_order(_, [], RList) ->
RList;
delete_list_member_no_order(Member, [H | L], RList) ->
?IF(Member =:= H, delete_list_member_no_order(Member, L, RList), delete_list_member_no_order(Member, L, [H | RList])).
get_v_by_k(K, L) ->
get_v_by_k(K, L, ?UNDEFINED).
get_v_by_k(K, L, Default) ->
case lists:keyfind(K, 1, L) of
{_, V} ->
V;
_ ->
Default
end.
@doc
quchong_no_order(L) ->
quchong1(L, []).
quchong1([], L1) ->
L1;
quchong1([H | L], L1) ->
case lists:member(H, L1) of
true -> quchong1(L, L1);
false -> quchong1(L, [H | L1])
end.
local_node() -> list_to_binary(atom_to_list(node())).
local_node_size() -> size(local_node()).
ip(Socket) ->
{ok, {IP, _Port}} = inet:peername(Socket),
{Ip0, Ip1, Ip2, Ip3} = IP,
list_to_binary(integer_to_list(Ip0) ++ "." ++ integer_to_list(Ip1) ++ "." ++ integer_to_list(Ip2) ++ "." ++ integer_to_list(Ip3)).
sort([]) ->
[];
sort([H | T]) ->
sort([X || X <- T, X < H]) ++ [H] ++ sort([X || X <- T, X >= H]).
for(Max, Max, F) -> [F(Max)];
for(I, Max, F) -> [F(I) | for(I + 1, Max, F)].
@doc convert float to string , f2s(1.5678 ) - > 1.57
f2s(N) when is_integer(N) ->
integer_to_list(N) ++ ".00";
f2s(F) when is_float(F) ->
[A] = io_lib:format("~.2f", [F]),
A.
to_atom(Msg) when is_atom(Msg) ->
Msg;
to_atom(Msg) when is_binary(Msg) ->
utils:list_to_atom2(binary_to_list(Msg));
to_atom(Msg) when is_list(Msg) ->
utils:list_to_atom2(Msg);
to_atom(_) ->
throw(other_value).
to_list(Msg) when is_list(Msg) ->
Msg;
to_list(Msg) when is_atom(Msg) ->
atom_to_list(Msg);
to_list(Msg) when is_binary(Msg) ->
binary_to_list(Msg);
to_list(Msg) when is_integer(Msg) ->
integer_to_list(Msg);
to_list(Msg) when is_float(Msg) ->
f2s(Msg);
to_list(Msg) when is_tuple(Msg) ->
tuple_to_list(Msg);
to_list(_) ->
throw(other_value).
to_binary(Msg) when is_binary(Msg) ->
Msg;
to_binary(Msg) when is_atom(Msg) ->
list_to_binary(atom_to_list(Msg));
atom_to_binary(Msg , ) ;
to_binary(Msg) when is_list(Msg) ->
list_to_binary(Msg);
to_binary(Msg) when is_integer(Msg) ->
list_to_binary(integer_to_list(Msg));
to_binary(Msg) when is_float(Msg) ->
list_to_binary(f2s(Msg));
to_binary(_Msg) ->
throw(other_value).
to_float(Msg) ->
Msg2 = to_list(Msg),
list_to_float(Msg2).
-spec to_integer(Msg :: any()) -> integer().
to_integer(Msg) when is_integer(Msg) ->
Msg;
to_integer(Msg) when is_binary(Msg) ->
Msg2 = binary_to_list(Msg),
list_to_integer(Msg2);
to_integer(Msg) when is_list(Msg) ->
list_to_integer(Msg);
to_integer(Msg) when is_float(Msg) ->
round(Msg);
to_integer(_Msg) ->
throw(other_value).
to_bool(D) when is_integer(D) ->
D =/= 0;
to_bool(D) when is_list(D) ->
length(D) =/= 0;
to_bool(D) when is_binary(D) ->
to_bool(binary_to_list(D));
to_bool(D) when is_boolean(D) ->
D;
to_bool(_D) ->
throw(other_value).
to_tuple(D) when is_integer(D) ->
list_to_tuple(integer_to_list(D));
to_tuple(D) when is_list(D) ->
list_to_tuple(D);
to_tuple(D) when is_atom(D) ->
list_to_tuple(atom_to_list(D));
to_tuple(_D) ->
throw(other_value).
@doc get a random integer between and
random(Min, Max) ->
Min2 = Min - 1,
rand:uniform(Max - Min2) + Min2.
ceil(X) ->
T = trunc(X),
if
X - T == 0 ->
T;
true ->
if
X > 0 ->
T + 1;
true ->
T
end
end.
@doc 取整 小于X的最大整数
floor(X) ->
T = trunc(X),
if
X - T == 0 ->
T;
true ->
if
X > 0 ->
T;
true ->
T - 1
end
end.
md5(S) ->
Md5_bin = erlang:md5(S),
Md5_list = binary_to_list(Md5_bin),
lists:flatten(list_to_hex(Md5_list)).
list_to_hex(L) ->
lists:map(fun(X) -> int_to_hex(X) end, L).
int_to_hex(N) when N < 256 ->
[hex(N div 16), hex(N rem 16)].
hex(N) when N < 10 ->
$0 + N;
hex(N) when N >= 10, N < 16 ->
$a + (N - 10).
list_to_atom2(List) when is_list(List) ->
case catch (list_to_existing_atom(List)) of
{'EXIT', _} -> erlang:list_to_atom(List);
Atom when is_atom(Atom) -> Atom
end.
combine_lists(L1, L2) ->
Rtn =
lists:foldl(
fun(T, Acc) ->
case lists:member(T, Acc) of
true ->
Acc;
false ->
[T | Acc]
end
end, lists:reverse(L1), L2),
lists:reverse(Rtn).
get_process_info_and_zero_value(InfoName) ->
PList = erlang:processes(),
ZList = lists:filter(
fun(T) ->
case erlang:process_info(T, InfoName) of
{InfoName, 0} -> false;
_ -> true
end
end, PList),
ZZList = lists:map(
fun(T) -> {T, erlang:process_info(T, InfoName), erlang:process_info(T, registered_name)}
end, ZList),
[length(PList), InfoName, length(ZZList), ZZList].
get_process_info_and_large_than_value(InfoName, Value) ->
PList = erlang:processes(),
ZList = lists:filter(
fun(T) ->
case erlang:process_info(T, InfoName) of
{InfoName, VV} ->
if VV > Value -> true;
true -> false
end;
_ -> true
end
end, PList),
ZZList = lists:map(
fun(T) -> {T, erlang:process_info(T, InfoName), erlang:process_info(T, registered_name)}
end, ZList),
[length(PList), InfoName, Value, length(ZZList), ZZList].
get_msg_queue() ->
io:fwrite("process count:~p~n~p value is not 0 count:~p~nLists:~p~n",
get_process_info_and_zero_value(message_queue_len)).
get_memory() ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(memory, 1048576)).
get_memory(Value) ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(memory, Value)).
get_heap() ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(heap_size, 1048576)).
get_heap(Value) ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(heap_size, Value)).
get_processes() ->
io:fwrite("process count:~p~n~p value is large than ~p count:~p~nLists:~p~n",
get_process_info_and_large_than_value(memory, 0)).
list_to_term(String) ->
{ok, T, _} = erl_scan:string(String ++ "."),
case erl_parse:parse_term(T) of
{ok, Term} ->
Term;
{error, Error} ->
Error
end.
string_to_fun(S) ->
string_to_fun(S, []).
string_to_fun(S, Binding) ->
{ok, Ts, _} = erl_scan:string(S),
Ts1 = case lists:reverse(Ts) of
[{dot, _} | _] -> Ts;
TsR -> lists:reverse([{dot, 1} | TsR])
end,
{ok, Expr} = erl_parse:parse_exprs(Ts1),
{value, Fun, _} = erl_eval:exprs(Expr, Binding),
Fun.
substr_utf8(Utf8EncodedString, Length) ->
substr_utf8(Utf8EncodedString, 1, Length).
substr_utf8(Utf8EncodedString, Start, Length) ->
ByteLength = 2 * Length,
Ucs = xmerl_ucs:from_utf8(Utf8EncodedString),
Utf16Bytes = xmerl_ucs:to_utf16be(Ucs),
SubStringUtf16 = lists:sublist(Utf16Bytes, Start, ByteLength),
Ucs1 = xmerl_ucs:from_utf16be(SubStringUtf16),
xmerl_ucs:to_utf8(Ucs1).
ip_str(IP) ->
case IP of
{A, B, C, D} ->
lists:concat([A, ".", B, ".", C, ".", D]);
{A, B, C, D, E, F, G, H} ->
lists:concat([A, ":", B, ":", C, ":", D, ":", E, ":", F, ":", G, ":", H]);
Str when is_list(Str) ->
Str;
_ ->
[]
end.
去掉字符串空格
remove_string_black(L) ->
lists:reverse(remove_string_loop(L, [])).
remove_string_loop([], L) ->
L;
remove_string_loop([I | L], LS) ->
case I of
32 ->
remove_string_loop(L, LS);
_ ->
remove_string_loop(L, [I | LS])
end.
spec is_operate_ok/1 param : Type - > 添加的协议类型(atom ) ; return : true->允许;false - > 直接丢弃该条数据
is_operate_ok(Type, TimeStamp) ->
NowTime = util:unixtime(),
case get(Type) of
undefined ->
put(Type, NowTime),
true;
Value ->
case (NowTime - Value) >= TimeStamp of
true ->
put(Type, NowTime),
true;
false ->
false
end
end.
eg : replace([a , b , c , d ] , 2 , g ) - > [ a , g , c , d ]
replace(List, Key, NewElem) ->
NewList = lists:reverse(List),
Len = length(List),
case Key =< 0 orelse Key > Len of
true ->
List;
false ->
replace_elem(Len, [], NewList, Key, NewElem)
end.
replace_elem(0, List, _OldList, _Key, _NewElem) ->
List;
replace_elem(Num, List, [Elem | OldList], Key, NewElem) ->
NewList =
case Num =:= Key of
true ->
[NewElem | List];
false ->
[Elem | List]
end,
replace_elem(Num - 1, NewList, OldList, Key, NewElem).
|
2f6a529f4a7de687fad4c17a348314e3254c2d283bacf9b61a694b22a5cc8b9b | Enecuum/Node | Interpreters.hs | module Enecuum.Testing.Core.Interpreters
( module X
) where
import Enecuum.Testing.Core.Interpreters.Logger as X
import Enecuum.Testing.Core.Interpreters.CoreEffect as X
| null | https://raw.githubusercontent.com/Enecuum/Node/3dfbc6a39c84bd45dd5f4b881e067044dde0153a/test/test-framework/Enecuum/Testing/Core/Interpreters.hs | haskell | module Enecuum.Testing.Core.Interpreters
( module X
) where
import Enecuum.Testing.Core.Interpreters.Logger as X
import Enecuum.Testing.Core.Interpreters.CoreEffect as X
| |
e4f9159e577b47d7bf68859317acc3c959c004cd994c673eb19dd990ec252f6d | abdulapopoola/SICPBook | 3.02.scm | #lang planet neil/sicp
;; Looks like a spy function
(define (make-monitored proc)
(let ((counter 0))
(define (dispatch m)
(cond ((eq? m 'how-many-calls?) counter)
((eq? m 'reset)
(set! counter 0))
(else (set! counter (+ counter 1))
(proc m))))
dispatch))
(define s (make-monitored sqrt))
(s 100)
10
(s 9)
3
(s 'how-many-calls?)
2
(s 'reset)
(s 'how-many-calls?)
0 | null | https://raw.githubusercontent.com/abdulapopoola/SICPBook/c8a0228ebf66d9c1ddc5ef1fcc1d05d8684f090a/Chapter%203/3.1/3.02.scm | scheme | Looks like a spy function | #lang planet neil/sicp
(define (make-monitored proc)
(let ((counter 0))
(define (dispatch m)
(cond ((eq? m 'how-many-calls?) counter)
((eq? m 'reset)
(set! counter 0))
(else (set! counter (+ counter 1))
(proc m))))
dispatch))
(define s (make-monitored sqrt))
(s 100)
10
(s 9)
3
(s 'how-many-calls?)
2
(s 'reset)
(s 'how-many-calls?)
0 |
cddaa7196d147079fb3828c422d7b9dcecfb0c3f256732854d2311f3e4d44531 | janestreet/universe | client.mli | open Core
val command : command:string -> unit Or_error.t Api_call.t
val command_output : command:string -> string Or_error.t Api_call.t
val get_chan_info : chan:int -> Channel_info.t Or_error.t Api_call.t
val list_bufs : Buf.t list Or_error.t Api_call.t
val list_chans : Channel_info.t list Or_error.t Api_call.t
val get_current_buf : Buf.t Or_error.t Api_call.t
*
Calls many API methods atomically .
This has two main usages :
1 . To perform several requests from an async context
atomically , i.e. without interleaving redraws , RPC requests
from other clients , or user interactions ( however API
methods may trigger autocommands or event processing which
have such side - effects , e.g. |:sleep| may wake timers ) .
2 . To minimize RPC overhead ( roundtrips ) of a sequence of many
requests .
Parameters :
{ calls } an array of calls , where each call is described
by an array with two elements : the request name ,
and an array of arguments .
Return :
Array of two elements . The first is an array of return
values . The second is NIL if all calls succeeded . If a
call resulted in an error , it is a three - element array
with the zero - based index of the call which resulted in an
error , the error type and the error message . If an error
occurred , the values from all preceding calls will still
be returned .
Calls many API methods atomically.
This has two main usages:
1. To perform several requests from an async context
atomically, i.e. without interleaving redraws, RPC requests
from other clients, or user interactions (however API
methods may trigger autocommands or event processing which
have such side-effects, e.g. |:sleep| may wake timers).
2. To minimize RPC overhead (roundtrips) of a sequence of many
requests.
Parameters:
{calls} an array of calls, where each call is described
by an array with two elements: the request name,
and an array of arguments.
Return:
Array of two elements. The first is an array of return
values. The second is NIL if all calls succeeded. If a
call resulted in an error, it is a three-element array
with the zero-based index of the call which resulted in an
error, the error type and the error message. If an error
occurred, the values from all preceding calls will still
be returned.
*)
val call_atomic : calls:Msgpack.t list -> Msgpack.t list Or_error.t Api_call.t
val eval : expr:string -> Msgpack.t Or_error.t Api_call.t
val feedkeys
: keys:string
-> mode:string
-> escape_csi:bool
-> unit Or_error.t Api_call.t
module Untested : sig
val ui_attach
: width:int
-> height:int
-> options:(Msgpack.t * Msgpack.t) list
-> unit Or_error.t Api_call.t
val ui_detach : unit Or_error.t Api_call.t
val ui_try_resize : width:int -> height:int -> unit Or_error.t Api_call.t
val ui_set_option : name:string -> value:Msgpack.t -> unit Or_error.t Api_call.t
val get_hl_by_name
: name:string
-> rgb:bool
-> (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val get_hl_by_id
: hl_id:int
-> rgb:bool
-> (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val input : keys:string -> int Or_error.t Api_call.t
val replace_termcodes
: str:string
-> from_part:bool
-> do_lt:bool
-> special:bool
-> string Or_error.t Api_call.t
val execute_lua : code:string -> args:Msgpack.t list -> Msgpack.t Or_error.t Api_call.t
val call_function : fn:string -> args:Msgpack.t list -> Msgpack.t Or_error.t Api_call.t
val call_dict_function
: dict:Msgpack.t
-> fn:string
-> args:Msgpack.t list
-> Msgpack.t Or_error.t Api_call.t
val strwidth : text:string -> int Or_error.t Api_call.t
val list_runtime_paths : string list Or_error.t Api_call.t
val set_current_dir : dir:string -> unit Or_error.t Api_call.t
val get_current_line : string Or_error.t Api_call.t
val set_current_line : line:string -> unit Or_error.t Api_call.t
val del_current_line : unit Or_error.t Api_call.t
val get_var : name:string -> Msgpack.t Or_error.t Api_call.t
val set_var : name:string -> value:Msgpack.t -> unit Or_error.t Api_call.t
val del_var : name:string -> unit Or_error.t Api_call.t
val get_vvar : name:string -> Msgpack.t Or_error.t Api_call.t
val get_option : name:string -> Msgpack.t Or_error.t Api_call.t
val set_option : name:string -> value:Msgpack.t -> unit Or_error.t Api_call.t
val out_write : str:string -> unit Or_error.t Api_call.t
val err_write : str:string -> unit Or_error.t Api_call.t
val err_writeln : str:string -> unit Or_error.t Api_call.t
val set_current_buf : buffer:Buf.t -> unit Or_error.t Api_call.t
val list_wins : Window.t list Or_error.t Api_call.t
val get_current_win : Window.t Or_error.t Api_call.t
val set_current_win : window:Window.t -> unit Or_error.t Api_call.t
val list_tabpages : Tabpage.t list Or_error.t Api_call.t
val get_current_tabpage : Tabpage.t Or_error.t Api_call.t
val set_current_tabpage : tabpage:Tabpage.t -> unit Or_error.t Api_call.t
val subscribe : event:string -> unit Or_error.t Api_call.t
val unsubscribe : event:string -> unit Or_error.t Api_call.t
val get_color_by_name : name:string -> int Or_error.t Api_call.t
val get_color_map : (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val get_mode : (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val get_keymap : mode:string -> Keymap.t list Or_error.t Api_call.t
val get_commands
: opts:(Msgpack.t * Msgpack.t) list
-> Nvim_command.t String.Map.t Or_error.t Api_call.t
val get_api_info : Msgpack.t list Or_error.t Api_call.t
val set_client_info
: ?version:Client_info.Version.t
-> ?methods:Client_info.Client_method.t String.Map.t
-> ?attributes:string String.Map.t
-> name:string
-> type_:Client_info.Client_type.t
-> unit
-> unit Or_error.t Api_call.t
val parse_expression
: expr:string
-> flags:string
-> highlight:bool
-> (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val list_uis : Msgpack.t list Or_error.t Api_call.t
val get_proc_children : pid:int -> Msgpack.t list Or_error.t Api_call.t
val get_proc : pid:int -> Msgpack.t Or_error.t Api_call.t
val keymap
: lhs:string
-> rhs:string
-> mode:string
-> opts:bool String.Map.t
-> unit Or_error.t Api_call.t
end
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/vcaml/src/client.mli | ocaml | open Core
val command : command:string -> unit Or_error.t Api_call.t
val command_output : command:string -> string Or_error.t Api_call.t
val get_chan_info : chan:int -> Channel_info.t Or_error.t Api_call.t
val list_bufs : Buf.t list Or_error.t Api_call.t
val list_chans : Channel_info.t list Or_error.t Api_call.t
val get_current_buf : Buf.t Or_error.t Api_call.t
*
Calls many API methods atomically .
This has two main usages :
1 . To perform several requests from an async context
atomically , i.e. without interleaving redraws , RPC requests
from other clients , or user interactions ( however API
methods may trigger autocommands or event processing which
have such side - effects , e.g. |:sleep| may wake timers ) .
2 . To minimize RPC overhead ( roundtrips ) of a sequence of many
requests .
Parameters :
{ calls } an array of calls , where each call is described
by an array with two elements : the request name ,
and an array of arguments .
Return :
Array of two elements . The first is an array of return
values . The second is NIL if all calls succeeded . If a
call resulted in an error , it is a three - element array
with the zero - based index of the call which resulted in an
error , the error type and the error message . If an error
occurred , the values from all preceding calls will still
be returned .
Calls many API methods atomically.
This has two main usages:
1. To perform several requests from an async context
atomically, i.e. without interleaving redraws, RPC requests
from other clients, or user interactions (however API
methods may trigger autocommands or event processing which
have such side-effects, e.g. |:sleep| may wake timers).
2. To minimize RPC overhead (roundtrips) of a sequence of many
requests.
Parameters:
{calls} an array of calls, where each call is described
by an array with two elements: the request name,
and an array of arguments.
Return:
Array of two elements. The first is an array of return
values. The second is NIL if all calls succeeded. If a
call resulted in an error, it is a three-element array
with the zero-based index of the call which resulted in an
error, the error type and the error message. If an error
occurred, the values from all preceding calls will still
be returned.
*)
val call_atomic : calls:Msgpack.t list -> Msgpack.t list Or_error.t Api_call.t
val eval : expr:string -> Msgpack.t Or_error.t Api_call.t
val feedkeys
: keys:string
-> mode:string
-> escape_csi:bool
-> unit Or_error.t Api_call.t
module Untested : sig
val ui_attach
: width:int
-> height:int
-> options:(Msgpack.t * Msgpack.t) list
-> unit Or_error.t Api_call.t
val ui_detach : unit Or_error.t Api_call.t
val ui_try_resize : width:int -> height:int -> unit Or_error.t Api_call.t
val ui_set_option : name:string -> value:Msgpack.t -> unit Or_error.t Api_call.t
val get_hl_by_name
: name:string
-> rgb:bool
-> (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val get_hl_by_id
: hl_id:int
-> rgb:bool
-> (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val input : keys:string -> int Or_error.t Api_call.t
val replace_termcodes
: str:string
-> from_part:bool
-> do_lt:bool
-> special:bool
-> string Or_error.t Api_call.t
val execute_lua : code:string -> args:Msgpack.t list -> Msgpack.t Or_error.t Api_call.t
val call_function : fn:string -> args:Msgpack.t list -> Msgpack.t Or_error.t Api_call.t
val call_dict_function
: dict:Msgpack.t
-> fn:string
-> args:Msgpack.t list
-> Msgpack.t Or_error.t Api_call.t
val strwidth : text:string -> int Or_error.t Api_call.t
val list_runtime_paths : string list Or_error.t Api_call.t
val set_current_dir : dir:string -> unit Or_error.t Api_call.t
val get_current_line : string Or_error.t Api_call.t
val set_current_line : line:string -> unit Or_error.t Api_call.t
val del_current_line : unit Or_error.t Api_call.t
val get_var : name:string -> Msgpack.t Or_error.t Api_call.t
val set_var : name:string -> value:Msgpack.t -> unit Or_error.t Api_call.t
val del_var : name:string -> unit Or_error.t Api_call.t
val get_vvar : name:string -> Msgpack.t Or_error.t Api_call.t
val get_option : name:string -> Msgpack.t Or_error.t Api_call.t
val set_option : name:string -> value:Msgpack.t -> unit Or_error.t Api_call.t
val out_write : str:string -> unit Or_error.t Api_call.t
val err_write : str:string -> unit Or_error.t Api_call.t
val err_writeln : str:string -> unit Or_error.t Api_call.t
val set_current_buf : buffer:Buf.t -> unit Or_error.t Api_call.t
val list_wins : Window.t list Or_error.t Api_call.t
val get_current_win : Window.t Or_error.t Api_call.t
val set_current_win : window:Window.t -> unit Or_error.t Api_call.t
val list_tabpages : Tabpage.t list Or_error.t Api_call.t
val get_current_tabpage : Tabpage.t Or_error.t Api_call.t
val set_current_tabpage : tabpage:Tabpage.t -> unit Or_error.t Api_call.t
val subscribe : event:string -> unit Or_error.t Api_call.t
val unsubscribe : event:string -> unit Or_error.t Api_call.t
val get_color_by_name : name:string -> int Or_error.t Api_call.t
val get_color_map : (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val get_mode : (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val get_keymap : mode:string -> Keymap.t list Or_error.t Api_call.t
val get_commands
: opts:(Msgpack.t * Msgpack.t) list
-> Nvim_command.t String.Map.t Or_error.t Api_call.t
val get_api_info : Msgpack.t list Or_error.t Api_call.t
val set_client_info
: ?version:Client_info.Version.t
-> ?methods:Client_info.Client_method.t String.Map.t
-> ?attributes:string String.Map.t
-> name:string
-> type_:Client_info.Client_type.t
-> unit
-> unit Or_error.t Api_call.t
val parse_expression
: expr:string
-> flags:string
-> highlight:bool
-> (Msgpack.t * Msgpack.t) list Or_error.t Api_call.t
val list_uis : Msgpack.t list Or_error.t Api_call.t
val get_proc_children : pid:int -> Msgpack.t list Or_error.t Api_call.t
val get_proc : pid:int -> Msgpack.t Or_error.t Api_call.t
val keymap
: lhs:string
-> rhs:string
-> mode:string
-> opts:bool String.Map.t
-> unit Or_error.t Api_call.t
end
| |
115de62cd865056c863f189b44dbff04a8235ddf25d10515c4e4a4649930c6a3 | obsidiansystems/obelisk | Types.hs | {-# LANGUAGE ConstraintKinds #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE LambdaCase #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE StandaloneDeriving #
# LANGUAGE UndecidableInstances #
module Obelisk.CliApp.Types where
import Control.Concurrent.MVar (MVar)
import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
import Control.Monad.Fail (MonadFail)
import Control.Monad.Log (LoggingT(..), MonadLog, Severity (..), WithSeverity (..), logMessage)
import Control.Monad.Reader (MonadIO, ReaderT (..), MonadReader (..), ask, mapReaderT)
import Control.Monad.Writer (WriterT)
import Control.Monad.State (StateT)
import Control.Monad.Except (ExceptT, MonadError (..))
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans (MonadTrans, lift)
import Data.IORef (IORef)
import Data.Text (Text)
import System.Exit (ExitCode (..), exitWith)
import Obelisk.CliApp.TerminalString (TerminalString)
import Obelisk.CliApp.Theme (CliTheme)
--------------------------------------------------------------------------------
data Output
= Output_Log (WithSeverity Text) -- Regular logging message (with colors and newlines)
| Output_LogRaw (WithSeverity Text) -- Like `Output_Log` but without the implicit newline added.
Render and write a TerminalString using putstrLn
Overwrite the current line ( i.e. \r followed by ` putStr ` )
| Output_ClearLine -- Clear the line
deriving (Eq, Show, Ord)
type CliLog m = MonadLog Output m
type CliThrow e m = MonadError e m
-- | Log a message to the console.
--
-- Logs safely even if there are ongoing spinners.
putLog :: CliLog m => Severity -> Text -> m ()
putLog sev = logMessage . Output_Log . WithSeverity sev
newtype DieT e m a = DieT { unDieT :: ReaderT (e -> (Text, Int)) (LoggingT Output m) a }
deriving
( Functor, Applicative, Monad, MonadIO, MonadFail
, MonadThrow, MonadCatch, MonadMask
, MonadLog Output
)
instance MonadTrans (DieT e) where
lift = DieT . lift . lift
| Error printer is private to DieT
instance MonadReader r m => MonadReader r (DieT e m) where
ask = DieT $ lift $ ask
local = (\f (DieT a) -> DieT $ f a) . mapReaderT . local
reader = DieT . lift . lift . reader
TODO generalize to bigger error types
instance MonadIO m => MonadError e (DieT e m) where
throwError e = do
handler <- DieT ask
let (output, exitCode) = handler e
putLog Alert output
liftIO $ exitWith $ ExitFailure exitCode
-- Cannot catch
catchError m _ = m
--------------------------------------------------------------------------------
data CliConfig e = CliConfig
{ -- | We are capable of changing the log level at runtime
_cliConfig_logLevel :: IORef Severity
, -- | Disallow coloured output
_cliConfig_noColor :: Bool
, -- | Disallow spinners
_cliConfig_noSpinner :: Bool
, -- | Whether the last message was an Overwrite output
_cliConfig_lock :: MVar Bool
, -- | Whether the user tip (to make verbose) was already displayed
_cliConfig_tipDisplayed :: IORef Bool
, -- | Stack of logs from nested spinners
_cliConfig_spinnerStack :: IORef ([Bool], [TerminalString])
, -- | Failure handler. How to log error and what exit status to use.
_cliConfig_errorLogExitCode :: e -> (Text, Int)
, -- | Theme strings for spinners
_cliConfig_theme :: CliTheme
}
class Monad m => HasCliConfig e m | m -> e where
getCliConfig :: m (CliConfig e)
instance HasCliConfig e m => HasCliConfig e (ReaderT r m) where
getCliConfig = lift getCliConfig
instance (Monoid w, HasCliConfig e m) => HasCliConfig e (WriterT w m) where
getCliConfig = lift getCliConfig
instance HasCliConfig e m => HasCliConfig e (StateT s m) where
getCliConfig = lift getCliConfig
instance HasCliConfig e m => HasCliConfig e (ExceptT e m) where
getCliConfig = lift getCliConfig
--------------------------------------------------------------------------------
newtype CliT e m a = CliT
{ unCliT :: ReaderT (CliConfig e) (DieT e m) a
}
deriving
( Functor, Applicative, Monad, MonadIO, MonadFail
, MonadThrow, MonadCatch, MonadMask
, MonadLog Output -- CliLog
CliThrow
HasCliConfig
)
instance MonadTrans (CliT e) where
lift = CliT . lift . lift
instance Monad m => HasCliConfig e (CliT e m)where
getCliConfig = ask
| null | https://raw.githubusercontent.com/obsidiansystems/obelisk/9127921ab7cd1e67f6869ee814491a5a7aafb698/lib/cliapp/src/Obelisk/CliApp/Types.hs | haskell | # LANGUAGE ConstraintKinds #
# LANGUAGE OverloadedStrings #
------------------------------------------------------------------------------
Regular logging message (with colors and newlines)
Like `Output_Log` but without the implicit newline added.
Clear the line
| Log a message to the console.
Logs safely even if there are ongoing spinners.
Cannot catch
------------------------------------------------------------------------------
| We are capable of changing the log level at runtime
| Disallow coloured output
| Disallow spinners
| Whether the last message was an Overwrite output
| Whether the user tip (to make verbose) was already displayed
| Stack of logs from nested spinners
| Failure handler. How to log error and what exit status to use.
| Theme strings for spinners
------------------------------------------------------------------------------
CliLog | # LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE LambdaCase #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE StandaloneDeriving #
# LANGUAGE UndecidableInstances #
module Obelisk.CliApp.Types where
import Control.Concurrent.MVar (MVar)
import Control.Monad.Catch (MonadCatch, MonadMask, MonadThrow)
import Control.Monad.Fail (MonadFail)
import Control.Monad.Log (LoggingT(..), MonadLog, Severity (..), WithSeverity (..), logMessage)
import Control.Monad.Reader (MonadIO, ReaderT (..), MonadReader (..), ask, mapReaderT)
import Control.Monad.Writer (WriterT)
import Control.Monad.State (StateT)
import Control.Monad.Except (ExceptT, MonadError (..))
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans (MonadTrans, lift)
import Data.IORef (IORef)
import Data.Text (Text)
import System.Exit (ExitCode (..), exitWith)
import Obelisk.CliApp.TerminalString (TerminalString)
import Obelisk.CliApp.Theme (CliTheme)
data Output
Render and write a TerminalString using putstrLn
Overwrite the current line ( i.e. \r followed by ` putStr ` )
deriving (Eq, Show, Ord)
type CliLog m = MonadLog Output m
type CliThrow e m = MonadError e m
putLog :: CliLog m => Severity -> Text -> m ()
putLog sev = logMessage . Output_Log . WithSeverity sev
newtype DieT e m a = DieT { unDieT :: ReaderT (e -> (Text, Int)) (LoggingT Output m) a }
deriving
( Functor, Applicative, Monad, MonadIO, MonadFail
, MonadThrow, MonadCatch, MonadMask
, MonadLog Output
)
instance MonadTrans (DieT e) where
lift = DieT . lift . lift
| Error printer is private to DieT
instance MonadReader r m => MonadReader r (DieT e m) where
ask = DieT $ lift $ ask
local = (\f (DieT a) -> DieT $ f a) . mapReaderT . local
reader = DieT . lift . lift . reader
TODO generalize to bigger error types
instance MonadIO m => MonadError e (DieT e m) where
throwError e = do
handler <- DieT ask
let (output, exitCode) = handler e
putLog Alert output
liftIO $ exitWith $ ExitFailure exitCode
catchError m _ = m
data CliConfig e = CliConfig
_cliConfig_logLevel :: IORef Severity
_cliConfig_noColor :: Bool
_cliConfig_noSpinner :: Bool
_cliConfig_lock :: MVar Bool
_cliConfig_tipDisplayed :: IORef Bool
_cliConfig_spinnerStack :: IORef ([Bool], [TerminalString])
_cliConfig_errorLogExitCode :: e -> (Text, Int)
_cliConfig_theme :: CliTheme
}
class Monad m => HasCliConfig e m | m -> e where
getCliConfig :: m (CliConfig e)
instance HasCliConfig e m => HasCliConfig e (ReaderT r m) where
getCliConfig = lift getCliConfig
instance (Monoid w, HasCliConfig e m) => HasCliConfig e (WriterT w m) where
getCliConfig = lift getCliConfig
instance HasCliConfig e m => HasCliConfig e (StateT s m) where
getCliConfig = lift getCliConfig
instance HasCliConfig e m => HasCliConfig e (ExceptT e m) where
getCliConfig = lift getCliConfig
newtype CliT e m a = CliT
{ unCliT :: ReaderT (CliConfig e) (DieT e m) a
}
deriving
( Functor, Applicative, Monad, MonadIO, MonadFail
, MonadThrow, MonadCatch, MonadMask
CliThrow
HasCliConfig
)
instance MonadTrans (CliT e) where
lift = CliT . lift . lift
instance Monad m => HasCliConfig e (CliT e m)where
getCliConfig = ask
|
c45081196fb88a14c8b6622f19e1561a3d275abe2e2940ecf2e9e0252d6d7ff8 | Opetushallitus/aipal | vastaajatunnus_test.clj | (ns aipal.arkisto.vastaajatunnus-test
(:require [aipal.arkisto.vastaajatunnus :refer :all])
(:use clojure.test))
(deftest tunnukset-ovat-keskenaan-yksilollisia
(testing "Tarkistetaan että funktio osaa luoda vain keskenään uniikkien tunnusten joukon kun mahdolliset merkit loppuvat."
(let [merkkien-lkm (count sallitut-merkit)
haetut-tunnukset (take (+ 100 merkkien-lkm) (luo-tunnuksia 1))]
(is (distinct? haetut-tunnukset)))))
| null | https://raw.githubusercontent.com/Opetushallitus/aipal/767bd14ec7153dc97fdf688443b9687cdb70082f/aipal/test/clj/aipal/arkisto/vastaajatunnus_test.clj | clojure | (ns aipal.arkisto.vastaajatunnus-test
(:require [aipal.arkisto.vastaajatunnus :refer :all])
(:use clojure.test))
(deftest tunnukset-ovat-keskenaan-yksilollisia
(testing "Tarkistetaan että funktio osaa luoda vain keskenään uniikkien tunnusten joukon kun mahdolliset merkit loppuvat."
(let [merkkien-lkm (count sallitut-merkit)
haetut-tunnukset (take (+ 100 merkkien-lkm) (luo-tunnuksia 1))]
(is (distinct? haetut-tunnukset)))))
| |
0fff322052f545081fd02cec1b65c1e44d3db27c9a05097736b03f224c6a7875 | wilbowma/cur | issue-60.rkt | #lang cur
(require
cur/stdlib/sugar
cur/stdlib/prop
rackunit/turnstile+)
(typecheck-fail/toplvl
(define-datatype Nat : Type
(z : Nat)
(s : (-> (-> (-> Nat False) False) Nat)))
#:with-msg "does not satisfy strict positivity")
| null | https://raw.githubusercontent.com/wilbowma/cur/e039c98941b3d272c6e462387df22846e10b0128/cur-test/cur/tests/issue-60.rkt | racket | #lang cur
(require
cur/stdlib/sugar
cur/stdlib/prop
rackunit/turnstile+)
(typecheck-fail/toplvl
(define-datatype Nat : Type
(z : Nat)
(s : (-> (-> (-> Nat False) False) Nat)))
#:with-msg "does not satisfy strict positivity")
| |
2cf9a4919c1fed7448983d8ca722acdbf2bd063d80d1fd054b9fe14a3a91794d | ghc/testsuite | tc219.hs | {-# LANGUAGE ImplicitParams, NoMonomorphismRestriction #-}
module ShouldCompile where
c.f . , only no type signature here
-- Instead, the NoMonomorphismRestriction language
bar = show ?c
foo1 = let { ?c = 'x' } in bar
foo2 = let { ?c = True } in bar
| null | https://raw.githubusercontent.com/ghc/testsuite/998a816ae89c4fd573f4abd7c6abb346cf7ee9af/tests/typecheck/should_compile/tc219.hs | haskell | # LANGUAGE ImplicitParams, NoMonomorphismRestriction #
Instead, the NoMonomorphismRestriction language |
module ShouldCompile where
c.f . , only no type signature here
bar = show ?c
foo1 = let { ?c = 'x' } in bar
foo2 = let { ?c = True } in bar
|
a5aabb232c70494782a1b274c7d49f241d189cef57ed72e40b3486e87fe37354 | HunterYIboHu/htdp2-solution | ex75-ufo.rkt | The first three lines of this file were inserted by . They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-beginner-reader.ss" "lang")((modname 5.6-ufo) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t write repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
(define-struct vel [deltax deltay])
A is a structure : ( make - vel Number Number )
; interpretation
; (make-vel dx dy) means a velocity of dx pixels [per tick]
; along the horizontal and dy pixels along the vertical direction
(define-struct ufo [loc vel])
; A UFO is a structure: (make-ufo Posn Vel)
; interpretation (make-ufo p v) is at location p moving at
velocity v. For , see above .
(define v1 (make-vel 8 -3))
(define v2 (make-vel -5 -3))
(define p1 (make-posn 22 80))
(define p2 (make-posn 30 77))
(define u1 (make-ufo p1 v1))
(define u2 (make-ufo p1 v2))
(define u3 (make-ufo p2 v1))
(define u4 (make-ufo p2 v2))
; adds v to p
; examples:
(check-expect (posn+ p1 v1) p2)
(check-expect (posn+ p1 v2) (make-posn 17 77))
(define (posn+ p v)
(make-posn (+ (posn-x p) (vel-deltax v))
(+ (posn-y p) (vel-deltay v))))
; UFO -> UFO
determines where u moves in one clock tick ;
; leaves the velocity as is
(check-expect (ufo-move-1 u1) u3)
; change the position, not the velocity
(check-expect (ufo-move-1 u2) (make-ufo (make-posn 17 77) v2))
; change the position, not the velocity. But write the result of
; posn
(define (ufo-move-1 u)
(make-ufo (posn+ (ufo-loc u) (ufo-vel u))
(ufo-vel u)))
| null | https://raw.githubusercontent.com/HunterYIboHu/htdp2-solution/6182b4c2ef650ac7059f3c143f639d09cd708516/Chapter1/Section5/ex75-ufo.rkt | racket | about the language level of this file in a form that our tools can easily process.
interpretation
(make-vel dx dy) means a velocity of dx pixels [per tick]
along the horizontal and dy pixels along the vertical direction
A UFO is a structure: (make-ufo Posn Vel)
interpretation (make-ufo p v) is at location p moving at
adds v to p
examples:
UFO -> UFO
leaves the velocity as is
change the position, not the velocity
change the position, not the velocity. But write the result of
posn | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-beginner-reader.ss" "lang")((modname 5.6-ufo) (read-case-sensitive #t) (teachpacks ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp"))) (htdp-settings #(#t write repeating-decimal #f #t none #f ((lib "image.rkt" "teachpack" "2htdp") (lib "universe.rkt" "teachpack" "2htdp")) #f)))
(define-struct vel [deltax deltay])
A is a structure : ( make - vel Number Number )
(define-struct ufo [loc vel])
velocity v. For , see above .
(define v1 (make-vel 8 -3))
(define v2 (make-vel -5 -3))
(define p1 (make-posn 22 80))
(define p2 (make-posn 30 77))
(define u1 (make-ufo p1 v1))
(define u2 (make-ufo p1 v2))
(define u3 (make-ufo p2 v1))
(define u4 (make-ufo p2 v2))
(check-expect (posn+ p1 v1) p2)
(check-expect (posn+ p1 v2) (make-posn 17 77))
(define (posn+ p v)
(make-posn (+ (posn-x p) (vel-deltax v))
(+ (posn-y p) (vel-deltay v))))
(check-expect (ufo-move-1 u1) u3)
(check-expect (ufo-move-1 u2) (make-ufo (make-posn 17 77) v2))
(define (ufo-move-1 u)
(make-ufo (posn+ (ufo-loc u) (ufo-vel u))
(ufo-vel u)))
|
f6b63a34eb375c82022fedb697b4dd6e1a760a73f47b626725053760eeea3126 | gabebw/croniker | Root.hs | module Handler.Root
( getRootR
) where
import Import
import Yesod.Auth.OAuth (twitterUrl)
getRootR :: Handler Html
getRootR = do
maid <- maybeAuthId
case maid of
Nothing -> defaultLayout $ do
setTitle "Croniker"
$(widgetFile "root")
(Just _) -> redirect ProfileR
| null | https://raw.githubusercontent.com/gabebw/croniker/89f081738c229a3302af3b0123fea208bccbda11/Handler/Root.hs | haskell | module Handler.Root
( getRootR
) where
import Import
import Yesod.Auth.OAuth (twitterUrl)
getRootR :: Handler Html
getRootR = do
maid <- maybeAuthId
case maid of
Nothing -> defaultLayout $ do
setTitle "Croniker"
$(widgetFile "root")
(Just _) -> redirect ProfileR
| |
c7e6310648563e81b33e82c0236b36d8e1adf7d19706f3a8afc56234698ae35c | ivarref/double-trouble | counter_str.clj | (ns com.github.ivarref.double-trouble.counter-str
(:require [datomic.api :as d])
(:import (datomic.db DbId)))
(defn counter-str [db counter-name tempid attr]
(assert (string? counter-name) "counter-name must be a string")
(assert (or (instance? DbId tempid) (string? tempid)) "tempid must be a string or datomic.db.DbId")
(assert (keyword? attr) "attr must be a keyword")
(let [next-val (or (some->> (d/q '[:find ?val .
:in $ ?counter-name
:where
[?e :com.github.ivarref.double-trouble/counter-name ?counter-name]
[?e :com.github.ivarref.double-trouble/counter-value ?val]]
db counter-name)
(inc))
1)]
[{:com.github.ivarref.double-trouble/counter-name counter-name
:com.github.ivarref.double-trouble/counter-value next-val}
[:db/add tempid attr (str next-val)]]))
| null | https://raw.githubusercontent.com/ivarref/double-trouble/a8ebc58758c21b1a6f4e5faa0128bb034526a26d/src/com/github/ivarref/double_trouble/counter_str.clj | clojure | (ns com.github.ivarref.double-trouble.counter-str
(:require [datomic.api :as d])
(:import (datomic.db DbId)))
(defn counter-str [db counter-name tempid attr]
(assert (string? counter-name) "counter-name must be a string")
(assert (or (instance? DbId tempid) (string? tempid)) "tempid must be a string or datomic.db.DbId")
(assert (keyword? attr) "attr must be a keyword")
(let [next-val (or (some->> (d/q '[:find ?val .
:in $ ?counter-name
:where
[?e :com.github.ivarref.double-trouble/counter-name ?counter-name]
[?e :com.github.ivarref.double-trouble/counter-value ?val]]
db counter-name)
(inc))
1)]
[{:com.github.ivarref.double-trouble/counter-name counter-name
:com.github.ivarref.double-trouble/counter-value next-val}
[:db/add tempid attr (str next-val)]]))
| |
e6051adae19483e7c4aa44ba5730a4110b6e4ca0542b20eab85217a8e25d2b8e | unison-code/unison | ImplementFrameOperations.hs | |
Copyright : Copyright ( c ) 2016 , RISE SICS AB
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2016, RISE SICS AB
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
This file is part of Unison , see -code.github.io
Main authors:
Roberto Castaneda Lozano <>
This file is part of Unison, see -code.github.io
-}
module Unison.Tools.Import.ImplementFrameOperations (implementFrameOperations) where
import Unison
import Unison.Target.API
implementFrameOperations implementFrames f @ Function {fCode = code} target =
let iff = implementFrame target
code' = map (implementFrameOperationsInBlock implementFrames iff) code
in f {fCode = code'}
implementFrameOperationsInBlock implementFrames iff b @ Block {bCode = code} =
let code' = concatMap (implementFrameOperation implementFrames iff) code
in b {bCode = code'}
implementFrameOperation implementFrames iff o
| implementFrames && (isFrameSetup o || isFrameDestroy o) = iff o
| otherwise = [o]
| null | https://raw.githubusercontent.com/unison-code/unison/9f8caf78230f956a57b50a327f8d1dca5839bf64/src/unison/src/Unison/Tools/Import/ImplementFrameOperations.hs | haskell | |
Copyright : Copyright ( c ) 2016 , RISE SICS AB
License : BSD3 ( see the LICENSE file )
Maintainer :
Copyright : Copyright (c) 2016, RISE SICS AB
License : BSD3 (see the LICENSE file)
Maintainer :
-}
Main authors :
< >
This file is part of Unison , see -code.github.io
Main authors:
Roberto Castaneda Lozano <>
This file is part of Unison, see -code.github.io
-}
module Unison.Tools.Import.ImplementFrameOperations (implementFrameOperations) where
import Unison
import Unison.Target.API
implementFrameOperations implementFrames f @ Function {fCode = code} target =
let iff = implementFrame target
code' = map (implementFrameOperationsInBlock implementFrames iff) code
in f {fCode = code'}
implementFrameOperationsInBlock implementFrames iff b @ Block {bCode = code} =
let code' = concatMap (implementFrameOperation implementFrames iff) code
in b {bCode = code'}
implementFrameOperation implementFrames iff o
| implementFrames && (isFrameSetup o || isFrameDestroy o) = iff o
| otherwise = [o]
| |
ef3654911438d2d154875cab1bfd3c8b0102545e88fdcd2b816189261dc901dd | osener/bonsai_revery | color.mli | exception Color_hex_parse_exception of string
type t = Revery.Color.t
val rgba : float -> float -> float -> float -> t
val rgb : float -> float -> float -> t
val rgba_int : int -> int -> int -> int -> t
val rgb_int : int -> int -> int -> t
(** @raise Color_hex_parse_exception on invalid hex color strings *)
val hex : string -> t
val multiply_alpha : float -> t -> t
val mix : start:t -> stop:t -> amount:float -> t
val opposite : t -> t
val to_rgba : t -> float * float * float * float
val get_alpha : t -> float
val equals : t -> t -> bool
val to_string : t -> string
val to_skia : t -> Skia.Color.t
| null | https://raw.githubusercontent.com/osener/bonsai_revery/754346997c21d2c4f91e6a7e7e6ce9f18df09056/src/color.mli | ocaml | * @raise Color_hex_parse_exception on invalid hex color strings | exception Color_hex_parse_exception of string
type t = Revery.Color.t
val rgba : float -> float -> float -> float -> t
val rgb : float -> float -> float -> t
val rgba_int : int -> int -> int -> int -> t
val rgb_int : int -> int -> int -> t
val hex : string -> t
val multiply_alpha : float -> t -> t
val mix : start:t -> stop:t -> amount:float -> t
val opposite : t -> t
val to_rgba : t -> float * float * float * float
val get_alpha : t -> float
val equals : t -> t -> bool
val to_string : t -> string
val to_skia : t -> Skia.Color.t
|
70b0e3e20cdb927df9a81949e7e1e1276146b3905de5bdd131a2d513166b3f76 | fjames86/schannel | ffi.lisp | Copyright ( c ) 2019 < >
This code is licensed under the MIT license .
(in-package #:schannel)
(define-foreign-library secur32
(:windows "Secur32.dll"))
(use-foreign-library secur32)
(define-foreign-library crypt32
(:windows "Crypt32.dll"))
(use-foreign-library crypt32)
;; ---------------------- Useful utilities -----------------------
(defun memset (ptr count &optional (val 0))
(dotimes (i count)
(setf (mem-aref ptr :uint8 i) val)))
(defun copyout (ptr count)
(let ((arr (make-array count :element-type '(unsigned-byte 8))))
(dotimes (i count)
(setf (aref arr i) (mem-aref ptr :uint8 i)))
arr))
(defun copyin (ptr arr &optional (start 0) end)
(let ((count (- (or end (length arr)) start)))
(dotimes (i count)
(setf (mem-aref ptr :uint8 i) (aref arr (+ start i))))
ptr))
;; ----------------------------------------------------------------
;; typedef struct _CERT_CONTEXT {
DWORD dwCertEncodingType ;
;; BYTE *pbCertEncoded;
DWORD cbCertEncoded ;
;; PCERT_INFO pCertInfo;
hCertStore ;
;; } CERT_CONTEXT, *PCERT_CONTEXT;
(defcstruct cert-context
(encoding-type :uint32)
(encoded :pointer)
(cencoded :uint32)
(info :pointer)
(store :pointer))
;; typedef struct _CRYPTOAPI_BLOB {
DWORD cbData ;
BYTE * ;
;; }
(defcstruct crypt-blob
(count :uint32)
(ptr :pointer))
;; typedef struct _CRYPT_ALGORITHM_IDENTIFIER {
LPSTR pszObjId ;
;; CRYPT_OBJID_BLOB Parameters;
} CRYPT_ALGORITHM_IDENTIFIER , * PCRYPT_ALGORITHM_IDENTIFIER ;
(defcstruct alg-id
(name :pointer)
(blob (:struct crypt-blob)))
typedef struct _ CRYPT_BIT_BLOB {
DWORD cbData ;
BYTE * ;
DWORD cUnusedBits ;
} CRYPT_BIT_BLOB , * PCRYPT_BIT_BLOB ;
(defcstruct crypt-bit-blob
(count :uint32)
(ptr :uint32)
(unused :uint32))
;; typedef struct _CERT_PUBLIC_KEY_INFO {
CRYPT_ALGORITHM_IDENTIFIER Algorithm ;
CRYPT_BIT_BLOB PublicKey ;
;; }
(defcstruct crypt-key-info
(algid (:struct alg-id))
(bitblob (:struct crypt-bit-blob)))
;; typedef struct _CERT_INFO {
;; DWORD dwVersion;
CRYPT_INTEGER_BLOB SerialNumber ;
CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm ;
CERT_NAME_BLOB Issuer ;
FILETIME NotBefore ;
FILETIME ;
;; CERT_NAME_BLOB Subject;
CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo ;
CRYPT_BIT_BLOB IssuerUniqueId ;
CRYPT_BIT_BLOB SubjectUniqueId ;
;; DWORD cExtension;
;; PCERT_EXTENSION rgExtension;
;; } CERT_INFO, *PCERT_INFO;
(defcstruct cert-info
(version :uint32)
(blob (:struct crypt-blob))
(algid (:struct alg-id))
(name (:struct crypt-blob))
(notbefore :uint64)
(notafter :uint64)
(subject (:struct crypt-blob))
(keyinfo (:struct crypt-key-info))
(issuerid (:struct crypt-blob))
(subjectid (:struct crypt-blob))
(extension :uint32)
(pext :pointer))
;; SECURITY_STATUS SEC_ENTRY
;; FreeContextBuffer(
;; _Inout_ PVOID pvContextBuffer // buffer to free
;; );
(defcfun (%free-context-buffer "FreeContextBuffer" :convention :stdcall) :uint32
(buffer :pointer))
(defun free-context-buffer (ptr)
(%free-context-buffer ptr)
nil)
;; PCCERT_CONTEXT CertCreateCertificateContext(
DWORD dwCertEncodingType ,
const BYTE * pbCertEncoded ,
;; DWORD cbCertEncoded
;; );
(defcfun (%cert-create-certificate-context "CertCreateCertificateContext" :convention :stdcall) :pointer
(encoding-type :uint32)
(encoded :pointer)
(count :uint32))
(defun create-certificate-context (data &key (start 0) end)
(let ((count (- (or end (length data)) start)))
(with-foreign-object (buf :uint8 count)
(copyin buf data start end)
(let ((hcert (%cert-create-certificate-context 1
buf
count)))
(if (null-pointer-p hcert)
(error "Failed to create certificate context")
hcert)))))
;; BOOL
WINAPI
CertFreeCertificateContext (
_ _ PCCERT_CONTEXT pCertContext
;; );
(defcfun (%cert-free-certificate-context "CertFreeCertificateContext" :convention :stdcall) :boolean
(hcert :pointer))
(defun free-certificate-context (hcert)
(%cert-free-certificate-context hcert))
(defun certificate-string (&rest component-names)
"common-name locality-name
organization-name organization-unit-name
email country-name state-or-province
street-address title given-name
initials surname domain-component
"
(with-output-to-string (s)
(let ((sep ""))
(do ((cnames component-names (cddr cnames)))
((null cnames))
(format s "~A~A=\"~A\""
sep
(ecase (car cnames)
(:common-name "CN")
(:locality-name "L")
(:organization-name "O")
(:organization-unit-name "OU")
(:email "E")
(:country-name "C")
(:state-or-province "S")
(:street-address "STREET")
(:title "T")
(:given-name "G")
(:initials "I")
(:surname "SN")
(:domain-component "DC"))
(cadr cnames))
(setf sep ",")))))
BOOL CertStrToNameA (
DWORD dwCertEncodingType ,
LPCSTR pszX500 ,
DWORD dwStrType ,
;; void *pvReserved,
BYTE * pbEncoded ,
DWORD * pcbEncoded ,
LPCSTR * ppszError
;; );
(defcfun (%cert-str-to-name "CertStrToNameA" :convention :stdcall) :boolean
(enctype :uint32)
(str :pointer)
(strtype :uint32)
(reserved :pointer)
(encoded :pointer)
(count :pointer)
(errorstr :pointer))
(defun cert-string-to-name (string)
(with-foreign-string (pstr string)
(with-foreign-objects ((buf :uint8 1024)
(count :uint32))
(setf (mem-aref count :uint32) 1024)
(let ((sts (%cert-str-to-name 1 ;; x509
pstr
oid name
(null-pointer)
buf
count
(null-pointer))))
(unless sts
(error "Failed to parse string"))
(copyout buf (mem-aref count :uint32))))))
DWORD
WINAPI
;; CertNameToStrA(
_ In _ DWORD dwCertEncodingType ,
_ In _ PCERT_NAME_BLOB pName ,
;; _In_ DWORD dwStrType,
_ , return ) LPSTR psz ,
_ In _ DWORD csz
;; );
(defcfun (%cert-name-to-string "CertNameToStrW" :convention :stdcall) :uint32
(encoding :uint32)
(blob :pointer)
(strtype :uint32)
(str :pointer)
(size :uint32))
(defun cert-name-to-string (pblob)
(with-foreign-object (str :uint16 512)
(let ((sts (%cert-name-to-string 1 ;; x509
pblob
1 ;; 1=CERT_SIMPLE_NAME_STR 3=CERT_X500_NAME_STR
str
512)))
(unless (= sts 0)
(foreign-string-to-lisp str :encoding :ucs-2le)))))
PCCERT_CONTEXT CertCreateSelfSignCertificate (
HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProvOrNCryptKey ,
PCERT_NAME_BLOB pSubjectIssuerBlob ,
;; DWORD dwFlags,
;; PCRYPT_KEY_PROV_INFO pKeyProvInfo,
;; PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
PSYSTEMTIME pStartTime ,
PSYSTEMTIME pEndTime ,
;; PCERT_EXTENSIONS pExtensions
;; );
(defcfun (%cert-create-self-signed-certificate "CertCreateSelfSignCertificate" :convention :stdcall) :pointer
(cryptprov :pointer)
(issuer-blob :pointer)
(flags :uint32)
(keyprovinfo :pointer)
(sigalg :pointer)
(starttime :pointer)
(endtime :pointer)
(extensions :pointer))
(defcstruct cert-name-blob
(count :uint32)
(pblob :pointer))
(defun create-self-signed-certificate (&key certificate-name-components)
(let ((buf (cert-string-to-name (apply #'certificate-string certificate-name-components))))
(with-foreign-objects ((pbuf :uint8 (length buf))
(pblob '(:struct cert-name-blob)))
(copyin pbuf buf)
(setf (foreign-slot-value pblob '(:struct cert-name-blob) 'count)
(length buf)
(foreign-slot-value pblob '(:struct cert-name-blob) 'pblob)
pbuf)
(let ((ret (%cert-create-self-signed-certificate (null-pointer)
pblob
0
(null-pointer)
(null-pointer)
(null-pointer)
(null-pointer)
(null-pointer))))
(when (null-pointer-p ret)
(error "Failed"))
ret))))
;; HCERTSTORE
WINAPI
;; CertOpenStore(
_ In _ LPCSTR lpszStoreProvider ,
_ In _ DWORD dwEncodingType ,
_ _ HCRYPTPROV_LEGACY hCryptProv ,
;; _In_ DWORD dwFlags,
;; _In_opt_ const void *pvPara
;; );
(defcfun (%cert-open-store "CertOpenStore" :convention :stdcall) :pointer
(storeprov :pointer)
(encoding :uint32)
(hprov :pointer)
(flags :uint32)
(para :pointer))
(defun cert-open-file-store (filename)
(with-foreign-string (pfname filename :encoding :ucs-2)
(let ((res (%cert-open-store (make-pointer +cert-store-prov-filename-w+)
1 ;; x509
(null-pointer)
+cert-store-open-existing-flag+
pfname)))
(if (null-pointer-p res)
(error "Failed to open certificate store")
res))))
(defun cert-open-memory-store ()
(let ((hstore (%cert-open-store (make-pointer +cert-store-prov-memory+)
0
(null-pointer)
0
(null-pointer))))
(if (null-pointer-p hstore)
(error "Failed to open memory store")
hstore)))
;; HCERTSTORE CertOpenSystemStoreW(
HCRYPTPROV_LEGACY hProv ,
;; LPCWSTR szSubsystemProtocol
;; );
(defcfun (%cert-open-system-store "CertOpenSystemStoreW" :convention :stdcall) :pointer
(prov :pointer)
(prot :pointer))
(defun cert-open-system-store (&optional subsystem)
(with-foreign-string (str (or subsystem "MY") :encoding :ucs-2)
(let ((res (%cert-open-system-store (null-pointer) str)))
(if (null-pointer-p res)
(error "Failed to open system store")
res))))
;; BOOL CertCloseStore(
hCertStore ,
DWORD dwFlags
;; );
(defcfun (%cert-close-store "CertCloseStore" :convention :stdcall) :boolean
(hstore :pointer)
(flags :uint32))
(defun cert-close-store (hstore)
(%cert-close-store hstore 0)
nil)
;; PCCERT_CONTEXT CertFindCertificateInStore(
hCertStore ,
DWORD dwCertEncodingType ,
DWORD dwFindFlags ,
DWORD dwFindType ,
;; const void *pvFindPara,
;; PCCERT_CONTEXT pPrevCertContext
;; );
(defcfun (%cert-find-certificate-in-store "CertFindCertificateInStore" :convention :stdcall) :pointer
(hstore :pointer)
(encoding :uint32)
(flags :uint32)
(type :uint32)
(para :pointer)
(prev :pointer))
(defconstant +cert-find-any+ 0)
(defconstant +cert-find-subject-name+ (logior (ash 2 16) 7))
(defconstant +cert-find-subject-str+ (logior (ash 8 16) 7))
(defun find-certificate-in-store (hstore &key subject-name)
(with-foreign-string (ppara (or subject-name "") :encoding :ucs-2)
(let ((res (%cert-find-certificate-in-store hstore
1 ;; x509 encoding
0 ;; flags not used
(if subject-name +cert-find-subject-str+ +cert-find-any+)
(if subject-name ppara (null-pointer))
(null-pointer))))
(if (null-pointer-p res)
nil
res))))
;; PCCERT_CONTEXT CertEnumCertificatesInStore(
hCertStore ,
;; PCCERT_CONTEXT pPrevCertContext
;; );
(defcfun (%cert-enum-certificates-in-store "CertEnumCertificatesInStore" :convention :stdcall) :pointer
(hstore :pointer)
(prev :pointer))
(defun enum-certificates-in-store (hstore)
(do ((hcert (%cert-enum-certificates-in-store hstore (null-pointer))
(%cert-enum-certificates-in-store hstore hcert))
(cert-names nil))
((null-pointer-p hcert) cert-names)
(let ((pinfo (foreign-slot-value hcert '(:struct cert-context) 'info)))
(let ((psubject (foreign-slot-pointer pinfo '(:struct cert-info) 'subject)))
(push (cert-name-to-string psubject) cert-names)))))
;; BOOL CertAddCertificateContextToStore(
hCertStore ,
;; PCCERT_CONTEXT pCertContext,
DWORD dwAddDisposition ,
;; PCCERT_CONTEXT *ppStoreContext
;; );
(defcfun (%cert-add-certificate-context-to-store "CertAddCertificateContextToStore" :convention :stdcall) :boolean
(hstore :pointer)
(hcert :pointer)
(flags :uint32)
(phcert :pointer))
(defun add-certificate-to-store (hstore hcert)
(let ((b (%cert-add-certificate-context-to-store hstore
hcert
3 ;; CERT_STORE_ADD_REPLACE_EXISTING
(null-pointer))))
(if b
nil
(error "Failed to add certificate to store"))))
;; BOOL PFXExportCertStoreEx(
;; HCERTSTORE hStore,
CRYPT_DATA_BLOB * pPFX ,
;; LPCWSTR szPassword,
;; void *pvPara,
DWORD dwFlags
;; );
(defcfun (%pfx-export-cert-store "PFXExportCertStoreEx" :convention :stdcall) :boolean
(hstore :pointer)
(blob :pointer)
(password :pointer)
(para :pointer)
(flags :uint32))
(defun pfx-export-cert-store (hstore password)
(with-foreign-objects ((pblob '(:struct crypt-blob)))
(with-foreign-string (wstr password :encoding :ucs-2)
(memset pblob (foreign-type-size '(:struct crypt-blob)))
(let ((b (%pfx-export-cert-store hstore pblob wstr (null-pointer) #x4)))
(unless b (error "PFXExportCertStore failed"))
(let ((count (foreign-slot-value pblob '(:struct crypt-blob) 'count)))
(with-foreign-object (buf :uint8 count)
(setf (foreign-slot-value pblob '(:struct crypt-blob) 'ptr) buf)
(let ((b2 (%pfx-export-cert-store hstore pblob wstr (null-pointer) #x4)))
(unless b2 (error "PFXExportCertStore failed2"))
(copyout buf count))))))))
;; HCERTSTORE PFXImportCertStore(
CRYPT_DATA_BLOB * pPFX ,
;; LPCWSTR szPassword,
DWORD dwFlags
;; );
(defcfun (%pfx-import-cert-store "PFXImportCertStore" :convention :stdcall) :pointer
(blob :pointer)
(password :pointer)
(flags :uint32))
(defun pfx-import-cert-store (data password &key (start 0) end)
(let ((count (- (or end (length data)) start)))
(with-foreign-objects ((blob '(:struct crypt-blob))
(buf :uint8 count))
(with-foreign-string (wstr password :encoding :ucs-2)
(setf (foreign-slot-value blob '(:struct crypt-blob) 'count) count
(foreign-slot-value blob '(:struct crypt-blob) 'ptr) buf)
(let ((hstore (%pfx-import-cert-store blob wstr 0)))
(if (null-pointer-p hstore)
(error "Failed to import cert store")
hstore))))))
;; BOOL CertSerializeCertificateStoreElement(
;; PCCERT_CONTEXT pCertContext,
DWORD dwFlags ,
;; BYTE *pbElement,
DWORD * pcbElement
;; );
(defcfun (%cert-serialize-certificate "CertSerializeCertificateStoreElement" :convention :stdcall) :boolean
(hcert :pointer)
(flags :uint32)
(buf :pointer)
(count :pointer))
(defun cert-serialize-certificate (hcert)
(with-foreign-object (count :uint32)
(setf (mem-aref count :uint32) 0)
(let ((b (%cert-serialize-certificate hcert 0 (null-pointer) count)))
(when b
(with-foreign-object (buf :uint8 (mem-aref count :uint32))
(let ((b2 (%cert-serialize-certificate hcert 0 buf count)))
(when b2
(copyout buf (mem-aref count :uint32)))))))))
;; BOOL CertAddSerializedElementToStore(
hCertStore ,
const BYTE * pbElement ,
;; DWORD cbElement,
DWORD dwAddDisposition ,
;; DWORD dwFlags,
DWORD dwContextTypeFlags ,
;; DWORD *pdwContextType,
;; const void **ppvContext
;; );
(defcfun (%cert-add-serialized-element-to-store "CertAddSerializedElementToStore" :convention :stdcall) :boolean
(hstore :pointer)
(buf :pointer)
(count :uint32)
(disposition :uint32)
(flags :uint32)
(cxttypeflags :uint32)
(cxttype :pointer)
(cxt :pointer))
(defun cert-add-serialized-element-to-store (hstore buf &key (start 0) end)
(let ((count (- (or end (length buf)) start)))
(with-foreign-objects ((pbuf :uint8 count)
(phcert :pointer))
(let ((b (%cert-add-serialized-element-to-store
hstore
pbuf
count
3 ;; CERT_STORE_ADD_REPLACE_EXISTING
0
#xffffffff ;; CERT_STORE_ALL_CONTEXT_FLAG
(null-pointer)
phcert)))
(if b
(mem-aref phcert :pointer)
(error "CertAddSerializedElementToStore failed"))))))
;; typedef struct _SCHANNEL_CRED
;; {
DWORD dwVersion ; // always SCHANNEL_CRED_VERSION
DWORD ;
;; PCCERT_CONTEXT *paCred;
;; HCERTSTORE hRootStore;
DWORD cMappers ;
;; struct _HMAPPER **aphMappers;
DWORD cSupportedAlgs ;
ALG_ID * palgSupportedAlgs ;
DWORD grbitEnabledProtocols ;
DWORD dwMinimumCipherStrength ;
DWORD dwMaximumCipherStrength ;
DWORD dwSessionLifespan ;
DWORD dwFlags ;
DWORD ;
;; } SCHANNEL_CRED, *PSCHANNEL_CRED;
(defcstruct schannel-cred
(version :uint32)
(ccreds :uint32)
(creds :pointer)
(certstore :pointer)
(cmappers :uint32)
(mappers :pointer)
(calgs :uint32)
(algs :pointer)
(enabled-protocols :uint32)
(min-cipher-strength :uint32)
(max-cipher-strength :uint32)
(session-lifespan :uint32)
(flags :uint32)
(cred-format :uint32))
;; typedef struct _SecHandle
;; {
;; ULONG_PTR dwLower ;
;; ULONG_PTR dwUpper ;
} SecHandle , * PSecHandle ;
(defcstruct sec-handle
(lower :pointer)
(upper :pointer))
SECURITY_STATUS SEC_Entry (
_ In_opt _ SEC_CHAR * ,
;; _In_ SEC_CHAR *pszPackage,
_ In _ ULONG fCredentialUse ,
;; _In_opt_ PLUID pvLogonID,
;; _In_opt_ PVOID pAuthData,
;; _In_opt_ SEC_GET_KEY_FN pGetKeyFn,
;; _In_opt_ PVOID pvGetKeyArgument,
;; _Out_ PCredHandle phCredential,
_ Out_opt _ PTimeStamp ptsExpiry
;; );
(defcfun (%acquire-credentials-handle "AcquireCredentialsHandleW" :convention :stdcall) :uint32
(principal :pointer)
(package :pointer)
(fcreduse :uint32)
(logonid :pointer)
(authdata :pointer)
(keyfn :pointer)
(keyfnarg :pointer)
(cred :pointer)
(expiry :pointer))
(defun acquire-credentials-handle (&key serverp ignore-certificates-p hcert)
(with-foreign-objects ((credp '(:struct schannel-cred))
(hcredp '(:struct sec-handle))
(certcxtp :pointer))
(with-foreign-string (unisp-name *unisp-name* :encoding :ucs-2)
setup
(memset credp (foreign-type-size '(:struct schannel-cred)))
(setf (foreign-slot-value credp '(:struct schannel-cred) 'version)
+schannel-cred-version+
(foreign-slot-value credp '(:struct schannel-cred) 'enabled-protocols)
(if serverp
(logior +tls1-server+ +tls1-1-server+ +tls1-2-server+)
(logior +tls1-client+ +tls1-1-client+ +tls1-2-client+))
(foreign-slot-value credp '(:struct schannel-cred) 'flags)
(let ((flags 0))
(when ignore-certificates-p (setf flags (logior flags #x8))) ;; SCH_CRED_MANUAL_CRED_VALIDATION
flags))
(when serverp
(unless hcert (error "hcert certificate context required for servers")))
(when hcert
(setf (foreign-slot-value credp '(:struct schannel-cred) 'ccreds)
1
(foreign-slot-value credp '(:struct schannel-cred) 'creds)
certcxtp
(mem-aref certcxtp :pointer)
hcert))
(let ((sts (%acquire-credentials-handle (null-pointer)
unisp-name
(if serverp +cred-inbound+ +cred-outbound+)
(null-pointer)
credp
(null-pointer)
(null-pointer)
hcredp
(null-pointer))))
(unless (= sts 0) (win-error sts))
(mem-aref hcredp '(:struct sec-handle))))))
KSECDDDECLSPEC SECURITY_STATUS SEC_ENTRY FreeCredentialsHandle (
;; PCredHandle phCredential
;; );
(defcfun (%free-credentials-handle "FreeCredentialsHandle" :convention :stdcall) :uint32
(hcred :pointer))
(defun free-credentials-handle (hcred)
(with-foreign-object (p '(:struct sec-handle))
(setf (mem-aref p '(:struct sec-handle)) hcred)
(let ((sts (%free-credentials-handle p)))
(unless (= sts 0) (win-error sts))
nil)))
;; typedef struct _SecBufferDesc {
;; unsigned long ulVersion;
;; unsigned long cBuffers;
;; PSecBuffer pBuffers;
;; } SecBufferDesc, *PSecBufferDesc;
(defcstruct sec-buffer-desc
SECBUFFER_VERSION=0
(cbuffers :uint32)
(buffers :pointer))
(defun init-sec-buffer-desc (ptr buffers count)
(setf (foreign-slot-value ptr '(:struct sec-buffer-desc) 'version)
0
(foreign-slot-value ptr '(:struct sec-buffer-desc) 'cbuffers)
count
(foreign-slot-value ptr '(:struct sec-buffer-desc) 'buffers)
buffers)
ptr)
;; typedef struct _SecBuffer {
;; unsigned long cbBuffer;
unsigned long BufferType ;
;; char *pvBuffer;
;; } SecBuffer, *PSecBuffer;
(defcstruct sec-buffer
(cbuffer :uint32)
(type :uint32)
(buffer :pointer))
(defun init-sec-buffer (ptr count buf type)
(setf (foreign-slot-value ptr '(:struct sec-buffer) 'cbuffer)
count
(foreign-slot-value ptr '(:struct sec-buffer) 'type)
type
(foreign-slot-value ptr '(:struct sec-buffer) 'buffer)
buf)
ptr)
;; ------------------ context initializtion functions ---------------------
(defconstant +default-isc-req-flags+
(logior +ISC-REQ-SEQUENCE-DETECT+
+ISC-REQ-REPLAY-DETECT+
+ISC-REQ-CONFIDENTIALITY+
+ISC-REQ-ALLOCATE-MEMORY+
+ISC-REQ-STREAM+))
SECURITY_STATUS SEC_Entry InitializeSecurityContext (
;; _In_opt_ PCredHandle phCredential,
;; _In_opt_ PCtxtHandle phContext,
;; _In_opt_ SEC_CHAR *pszTargetName,
_ In _ ULONG fContextReq ,
_ In _ ULONG Reserved1 ,
_ In _ ULONG TargetDataRep ,
_ In_opt _ PSecBufferDesc pInput ,
_ In _ ULONG Reserved2 ,
;; _Inout_opt_ PCtxtHandle phNewContext,
;; _Inout_opt_ PSecBufferDesc pOutput,
;; _Out_ PULONG pfContextAttr,
_ Out_opt _ PTimeStamp ptsExpiry
;; );
(defcfun (%initialize-security-context "InitializeSecurityContextW" :convention :stdcall) :uint32
(hcred :pointer)
(pcxt :pointer)
(targetname :pointer)
(fcontextreq :uint32)
(reserved1 :uint32)
(targetdatarep :uint32)
(input :pointer)
(reserved2 :uint32)
(newcontext :pointer)
(output :pointer)
(contextattr :pointer)
(expiry :pointer))
(defun initialize-security-context-init (hcred hostname)
"Called on first to initialize security context. Returns values hcontext token"
(with-foreign-objects ((phcred '(:struct sec-handle))
(pnewcxt '(:struct sec-handle))
(pcxtattr :uint32)
(poutput '(:struct sec-buffer-desc))
(poutputbufs '(:struct sec-buffer)))
(with-foreign-string (phostname hostname :encoding :ucs-2)
(setf (mem-aref phcred '(:struct sec-handle)) hcred)
(init-sec-buffer poutputbufs 0 (null-pointer) +secbuffer-empty+)
(init-sec-buffer-desc poutput poutputbufs 1)
(let ((sts (%initialize-security-context phcred
(null-pointer)
phostname ;; targetname
+default-isc-req-flags+ ;; fcontextreq?
0
0
(null-pointer)
0
pnewcxt
poutput
pcxtattr
(null-pointer))))
(cond
((= sts +continue-needed+)
(let* ((obufp (foreign-slot-value poutputbufs '(:struct sec-buffer) 'buffer))
(rtok (copyout obufp
(foreign-slot-value poutputbufs '(:struct sec-buffer) 'cbuffer)))
(extra-bytes nil))
(free-context-buffer obufp)
(when (= (foreign-slot-value (mem-aptr poutputbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr poutputbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
(values (mem-aref pnewcxt '(:struct sec-handle))
rtok
(mem-aref pcxtattr :uint32)
extra-bytes
nil)))
((= sts +incomplete-message+)
(values nil nil nil nil t))
(t (win-error sts)))))))
(defun initialize-security-context-continue (hcred hostname hcxt token cxtattr token-start token-end)
(with-foreign-objects ((phcred '(:struct sec-handle))
(phcxt '(:struct sec-handle))
(psecbuf '(:struct sec-buffer-desc))
(secbuffers '(:struct sec-buffer) 2)
(pcxtattr :uint32)
(ptoken :uint8 (- token-end token-start))
(poutput '(:struct sec-buffer-desc))
(poutputbufs '(:struct sec-buffer)))
(with-foreign-string (phostname hostname :encoding :ucs-2)
(setf (mem-aref phcred '(:struct sec-handle))
hcred
(mem-aref phcxt '(:struct sec-handle))
hcxt)
(copyin ptoken token token-start token-end)
(init-sec-buffer (mem-aptr secbuffers '(:struct sec-buffer) 0)
(- token-end token-start)
ptoken
+secbuffer-token+)
(init-sec-buffer (mem-aptr secbuffers '(:struct sec-buffer) 1)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer-desc psecbuf secbuffers 2)
(init-sec-buffer poutputbufs 0 (null-pointer) +secbuffer-empty+)
(init-sec-buffer-desc poutput poutputbufs 1)
(let ((sts (%initialize-security-context phcred
phcxt
phostname ;; targetname
cxtattr ;; +default-isc-req-flags+ ;; fcontextreq?
0
0
psecbuf
0
(null-pointer)
poutput
pcxtattr
(null-pointer))))
(cond
((= sts 0)
;; success
(let ((extra-bytes nil))
(when (= (foreign-slot-value (mem-aptr poutputbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr poutputbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
(values nil (mem-aref pcxtattr :uint32) extra-bytes nil)))
((or (= sts +incomplete-message+) #+nil(= sts +invalid-token+))
(values nil nil nil t))
((= sts +continue-needed+)
(let* ((obufp (foreign-slot-value poutputbufs '(:struct sec-buffer) 'buffer))
(rtok (copyout obufp (foreign-slot-value poutputbufs '(:struct sec-buffer) 'cbuffer)))
(extra-bytes nil))
(free-context-buffer obufp)
(when (= (foreign-slot-value (mem-aptr secbuffers '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr secbuffers '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
(values rtok
(mem-aref pcxtattr :uint32)
extra-bytes
nil)))
(t (win-error sts)))))))
SECURITY_STATUS SEC_Entry AcceptSecurityContext (
;; _In_opt_ PCredHandle phCredential,
;; _Inout_opt_ PCtxtHandle phContext,
_ In_opt _ PSecBufferDesc pInput ,
_ In _ ULONG fContextReq ,
_ In _ ULONG TargetDataRep ,
;; _Inout_opt_ PCtxtHandle phNewContext,
;; _Inout_opt_ PSecBufferDesc pOutput,
;; _Out_ PULONG pfContextAttr,
;; _Out_opt_ PTimeStamp ptsTimeStamp
;; );
(defcfun (%accept-security-context "AcceptSecurityContext" :convention :stdcall) :uint32
(hcred :pointer)
(pcxt :pointer)
(input :pointer)
(fcontextreq :uint32)
(targetdatarep :uint32)
(newcontext :pointer)
(output :pointer)
(contextattr :pointer)
(timestamp :pointer))
(defconstant +default-asc-req-flags+
(logior +asc-req-allocate-memory+
+asc-req-stream+
+asc-req-confidentiality+
+asc-req-sequence-detect+
+asc-req-replay-detect+))
(defun accept-security-context-init (hcred token token-start token-end &key require-client-certificate)
(with-foreign-objects ((phcred '(:struct sec-handle))
(phcxt '(:struct sec-handle))
(isecbufdesc '(:struct sec-buffer-desc))
(isecbufs '(:struct sec-buffer) 2)
(ptokbuf :uint8 (length token))
(osecbufdesc '(:struct sec-buffer-desc))
(osecbufs '(:struct sec-buffer))
(pcxtattr :uint32))
(setf (mem-aref phcred '(:struct sec-handle)) hcred)
;; input buffers
(copyin ptokbuf token token-start token-end)
(init-sec-buffer (mem-aptr isecbufs '(:struct sec-buffer) 0)
(- token-end token-start)
ptokbuf
+secbuffer-token+)
(init-sec-buffer (mem-aptr isecbufs '(:struct sec-buffer) 1)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer-desc isecbufdesc isecbufs 2)
;; output buffers
(init-sec-buffer osecbufs 0 (null-pointer) +secbuffer-empty+)
(init-sec-buffer-desc osecbufdesc osecbufs 1)
(let ((sts (%accept-security-context phcred
(null-pointer)
isecbufdesc
(logior +default-asc-req-flags+
(if require-client-certificate +asc-req-mutual-auth+ 0))
0
phcxt
osecbufdesc
pcxtattr
(null-pointer))))
(cond
((= sts +continue-needed+)
(let ((tok nil)
(extra-bytes nil))
;; look for extra bytes in input buffer
(when (= (foreign-slot-value (mem-aptr isecbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr isecbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
;; copy out the token buffer
(setf tok
(copyout (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer)
(foreign-slot-value osecbufs
'(:struct sec-buffer)
'cbuffer)))
;; free the allocate token buffer
(free-context-buffer (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer))
(values (mem-aref phcxt '(:struct sec-handle))
tok
extra-bytes
(mem-aref pcxtattr :uint32)
nil)))
((= sts +incomplete-message+)
(values nil nil nil nil t))
(t (win-error sts))))))
SECURITY_STATUS SEC_ENTRY CompleteAuthToken (
;; [in] PCtxtHandle phContext,
;; [in] PSecBufferDesc pToken
;; );
(defcfun (%complete-auth-token "CompleteAuthToken" :convention :stdcall) :uint32
(pcxt :pointer)
(pbuf :pointer))
(defun complete-auth-token (phcxt psecbufdesc)
(let ((sts (%complete-auth-token phcxt psecbufdesc)))
(if (zerop sts)
nil
(win-error sts))))
(defun accept-security-context-continue (hcred hcxt token cxtattr token-start token-end)
(with-foreign-objects ((phcred '(:struct sec-handle))
(phcxt '(:struct sec-handle))
(isecbufdesc '(:struct sec-buffer-desc))
(isecbufs '(:struct sec-buffer) 2)
(ptokbuf :uint8 (length token))
(osecbufdesc '(:struct sec-buffer-desc))
(osecbufs '(:struct sec-buffer))
(pcxtattr :uint32))
(setf (mem-aref phcred '(:struct sec-handle)) hcred
(mem-aref phcxt '(:struct sec-handle)) hcxt)
;; input buffers
(copyin ptokbuf token token-start token-end)
(init-sec-buffer (mem-aptr isecbufs '(:struct sec-buffer) 0)
(- token-end token-start)
ptokbuf
+secbuffer-token+)
(init-sec-buffer (mem-aptr isecbufs '(:struct sec-buffer) 1)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer-desc isecbufdesc isecbufs 2)
;; output buffers
(init-sec-buffer osecbufs 0 (null-pointer) +secbuffer-empty+)
(init-sec-buffer-desc osecbufdesc osecbufs 1)
(let ((sts (%accept-security-context phcred
phcxt
isecbufdesc
cxtattr
0
(null-pointer)
osecbufdesc
pcxtattr
(null-pointer))))
(cond
((or (= sts 0)
(= sts +continue-needed+))
(let ((tok nil)
(extra-bytes nil))
;; look for extra bytes in input buffer
(when (= (foreign-slot-value (mem-aptr isecbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr isecbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
;; copy out the token buffer
(setf tok
(copyout (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer)
(foreign-slot-value osecbufs
'(:struct sec-buffer)
'cbuffer)))
;; free the allocate token buffer
(free-context-buffer (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer))
(values tok extra-bytes (mem-aref pcxtattr :uint32) nil (= sts +continue-needed+))))
((= sts +incomplete-message+)
(values nil nil nil t nil))
((= sts +complete-needed+)
complete the context , need to call CompleteAuthToken
(complete-auth-token phcxt osecbufdesc)
;; free the allocate token buffer
(free-context-buffer (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer))
(values nil nil (mem-aref pcxtattr :uint32) nil nil))
(t (win-error sts))))))
;; SECURITY_STATUS SEC_Entry QueryContextAttributes(
_ In _ PCtxtHandle phContext ,
_ In _ ULONG ulAttribute ,
;; _Out_ PVOID pBuffer
;; );
(defcfun (%query-context-attributes "QueryContextAttributesW" :convention :stdcall) :uint32
(pcxt :pointer)
(attr :uint32)
(buffer :pointer))
(defun query-stream-sizes (hcxt)
(with-foreign-objects ((phcxt '(:struct sec-handle))
(buf :uint32 5))
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt)
(let ((sts (%query-context-attributes phcxt
SECPKG_ATTR_STREAM_SIZES
buf)))
(unless (= sts 0) (win-error sts))
(list :header (mem-aref buf :uint32 0)
:trailer (mem-aref buf :uint32 1)
:max-message (mem-aref buf :uint32 2)
:max-buffers (mem-aref buf :uint32 3)
:block-size (mem-aref buf :uint32 4)))))
(defstruct certificate-info
name
encoding-type
encoded)
(defun query-remote-certificate (hcxt)
(with-foreign-objects ((phcxt '(:struct sec-handle))
(buf :pointer))
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt)
(let ((sts (%query-context-attributes phcxt
SECPKG_ATTR_REMOTE_CERT_CONTEXT
buf)))
(unless (= sts 0) (win-error sts))
(let* ((pcert (mem-aref buf :pointer))
(pinfo (foreign-slot-value pcert '(:struct cert-context) 'info))
(psubject (foreign-slot-pointer pinfo '(:struct cert-info) 'subject))
(count (foreign-slot-value pcert '(:struct cert-context) 'cencoded))
(encoded (foreign-slot-value pcert '(:struct cert-context) 'encoded))
(encoded-buf (make-array count :element-type '(unsigned-byte 8)))
(encoding-type (foreign-slot-value pcert '(:struct cert-context) 'encoding-type)))
(dotimes (i count)
(setf (aref encoded-buf i) (mem-aref encoded :uint8 i)))
(make-certificate-info :name (cert-name-to-string psubject)
:encoding-type (cond
((= encoding-type +x509-asn-encoding+ ) :x509-asn-encoding)
((= encoding-type +pkcs-7-asn-encoding+) :pkcs-7-asn-encoding)
(t (error (format nil "Unknown encoding type ~A" encoding-type))))
:encoded encoded-buf)))))
;; -------------- not sure if we need these functions ----------------
;; SECURITY_STATUS SEC_ENTRY QueryCredentialsAttributesW(
;; PCredHandle phCredential,
unsigned long ulAttribute ,
;; void *pBuffer
;; );
( defcfun ( % query - credentials - attributes " QueryCredentialsAttributesW " : convention : stdcall ) : uint32
;; (pcred :pointer)
( attr : )
;; (buffer :pointer))
;; SECURITY_STATUS SEC_ENTRY SetCredentialsAttributesW(
;; _In_ PCredHandle phCredential, // Credential to Set
;; _In_ unsigned long ulAttribute, // Attribute to Set
;; _In_reads_bytes_(cbBuffer) void * pBuffer, // Buffer for attributes
;; _In_ unsigned long cbBuffer // Size (in bytes) of Buffer
;; );
( defcfun ( % set - credentials - attributes " SetCredentialsAttributesW " : convention : stdcall ) : uint32
;; (pcred :pointer)
( attr : )
;; (buffer :pointer)
( count : ) )
;; -------------------------------------------------------------------
KSECDDDECLSPEC SECURITY_STATUS SEC_ENTRY ApplyControlToken (
;; PCtxtHandle phContext,
PSecBufferDesc
;; );
(defcfun (%apply-control-token "ApplyControlToken" :convention :stdcall) :uint32
(pcxt :pointer)
(input :pointer))
(defun apply-shutdown-token (hcxt)
(with-foreign-objects ((secbufdesc '(:struct sec-buffer-desc))
(secbuf '(:struct sec-buffer))
(ctrltok :uint32)
(phcxt '(:struct sec-handle)))
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt
(mem-aref ctrltok :uint32) +schannel-shutdown+)
(init-sec-buffer secbuf 4 ctrltok +secbuffer-token+)
(init-sec-buffer-desc secbufdesc secbuf 1)
(let ((sts (%apply-control-token phcxt secbufdesc)))
(unless (= sts 0) (win-error sts))
nil)))
SECURITY_STATUS SEC_Entry DecryptMessage (
;; _In_ PCtxtHandle phContext,
;; _Inout_ PSecBufferDesc pMessage,
_ In _ ULONG ,
_ Out _ PULONG pfQOP
;; );
(defcfun (%decrypt-message "DecryptMessage" :convention :stdcall) :uint32
(pcxt :pointer)
(buffer :pointer)
(seqno :uint32)
(pqop :pointer))
(defun decrypt-message-1 (hcxt buf &key (start 0) end)
"Decrypt message. Sets buf contents to decrypted plaintext.
Returns values bend extra-start incomplete-p
bend is buffer end index and extra-start is starting index of first extra byte."
(let ((count (- (or end (length buf)) start)))
(with-foreign-objects ((phcxt '(:struct sec-handle))
(pbuf :uint8 count)
(secbufdesc '(:struct sec-buffer-desc))
(secbufs '(:struct sec-buffer) 4))
(dotimes (i count)
(setf (mem-aref pbuf :uint8 i) (aref buf (+ start i))))
(init-sec-buffer-desc secbufdesc secbufs 4)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 0)
count
pbuf
+secbuffer-data+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 1)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 2)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 3)
0
(null-pointer)
+secbuffer-empty+)
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt)
(let ((sts (%decrypt-message phcxt secbufdesc 0 (null-pointer)))
(bend 0)
(extra-start nil))
(cond
((= sts 0)
(dotimes (i 4)
(let ((btype (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'type)))
(cond
((= btype +secbuffer-data+)
;; copy back out
(let ((dcount (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'cbuffer))
(bptr (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'buffer)))
(dotimes (i dcount)
(setf (aref buf (+ start i)) (mem-aref bptr :uint8 i)))
(setf bend (+ start dcount))))
((= btype +secbuffer-extra+)
get index of first extra byte
(setf extra-start
(- count (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'cbuffer)))))))
(values bend extra-start nil))
((or (= sts +incomplete-message+) #+nil(= sts +invalid-token+))
(values nil nil t))
(t (win-error sts)))))))
SECURITY_STATUS SEC_Entry EncryptMessage (
;; _In_ PCtxtHandle phContext,
_ In _ ULONG fQOP ,
;; _Inout_ PSecBufferDesc pMessage,
_ In _ ULONG
;; );
(defcfun (%encrypt-message "EncryptMessage" :convention :stdcall) :uint32
(pcxt :pointer)
(fqop :uint32)
(buffer :pointer)
(seqno :uint32))
(defun encrypt-message-1 (hcxt buf &key (start 0) end)
"Returns end index"
(let ((count (- (or end (length buf)) start))
(ssizes (query-stream-sizes hcxt)))
(with-foreign-objects ((pbuf :uint8 (+ count
(getf ssizes :header)
(getf ssizes :trailer)))
(secbufdesc '(:struct sec-buffer-desc))
(secbufs '(:struct sec-buffer) 4)
(phcxt '(:struct sec-handle)))
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt)
;; copy data into input buffer
(dotimes (i count)
(setf (mem-aref pbuf :uint8 (+ (getf ssizes :header) i))
(aref buf (+ start i))))
(init-sec-buffer-desc secbufdesc secbufs 4)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 0)
(getf ssizes :header)
pbuf
+secbuffer-stream-header+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 1)
count
(mem-aptr pbuf :uint8 (getf ssizes :header))
+secbuffer-data+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 2)
(getf ssizes :trailer)
(mem-aptr pbuf :uint8 (+ (getf ssizes :header) count))
+secbuffer-stream-trailer+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 3)
0
(null-pointer)
+secbuffer-empty+)
(let ((sts (%encrypt-message phcxt 0 secbufdesc 0)))
(cond
((= sts 0)
(let ((bcount (loop :for i :below 3
:sum (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'cbuffer))))
(dotimes (i bcount)
(setf (aref buf (+ start i)) (mem-aref pbuf :uint8 i)))
(+ start bcount)))
(t (win-error sts)))))))
;; SECURITY_STATUS SEC_ENTRY
DeleteSecurityContext (
;; _In_ PCtxtHandle phContext // Context to delete
;; );
(defcfun (%delete-security-context "DeleteSecurityContext" :convention :stdcall) :uint32
(pcxt :pointer))
(defun delete-security-context (cxt)
(with-foreign-object (pcxt '(:struct sec-handle))
(setf (mem-aref pcxt '(:struct sec-handle)) cxt)
(let ((sts (%delete-security-context pcxt)))
(unless (= sts 0) (win-error sts))))
nil)
KSECDDDECLSPEC SECURITY_STATUS SEC_ENTRY (
[ in ] PCtxtHandle phContext ,
;; [out] void **Token
;; );
(defcfun (%query-security-context-token "QuerySecurityContextToken" :convention :stdcall)
:uint32
(pcxt :pointer)
(tok :pointer))
(defun query-security-context-token (cxt)
(with-foreign-objects ((pcxt '(:struct sec-handle))
(ptok :pointer))
(setf (mem-aref pcxt '(:struct sec-handle)) cxt)
(let ((sts (%query-security-context-token pcxt ptok)))
(unless (= sts 0) (win-error sts))
(mem-aref ptok :pointer))))
| null | https://raw.githubusercontent.com/fjames86/schannel/95182848e672065e6a679175dc843ec06bcf154e/ffi.lisp | lisp | ---------------------- Useful utilities -----------------------
----------------------------------------------------------------
typedef struct _CERT_CONTEXT {
BYTE *pbCertEncoded;
PCERT_INFO pCertInfo;
} CERT_CONTEXT, *PCERT_CONTEXT;
typedef struct _CRYPTOAPI_BLOB {
}
typedef struct _CRYPT_ALGORITHM_IDENTIFIER {
CRYPT_OBJID_BLOB Parameters;
typedef struct _CERT_PUBLIC_KEY_INFO {
}
typedef struct _CERT_INFO {
DWORD dwVersion;
CERT_NAME_BLOB Subject;
DWORD cExtension;
PCERT_EXTENSION rgExtension;
} CERT_INFO, *PCERT_INFO;
SECURITY_STATUS SEC_ENTRY
FreeContextBuffer(
_Inout_ PVOID pvContextBuffer // buffer to free
);
PCCERT_CONTEXT CertCreateCertificateContext(
DWORD cbCertEncoded
);
BOOL
);
void *pvReserved,
);
x509
CertNameToStrA(
_In_ DWORD dwStrType,
);
x509
1=CERT_SIMPLE_NAME_STR 3=CERT_X500_NAME_STR
DWORD dwFlags,
PCRYPT_KEY_PROV_INFO pKeyProvInfo,
PCRYPT_ALGORITHM_IDENTIFIER pSignatureAlgorithm,
PCERT_EXTENSIONS pExtensions
);
HCERTSTORE
CertOpenStore(
_In_ DWORD dwFlags,
_In_opt_ const void *pvPara
);
x509
HCERTSTORE CertOpenSystemStoreW(
LPCWSTR szSubsystemProtocol
);
BOOL CertCloseStore(
);
PCCERT_CONTEXT CertFindCertificateInStore(
const void *pvFindPara,
PCCERT_CONTEXT pPrevCertContext
);
x509 encoding
flags not used
PCCERT_CONTEXT CertEnumCertificatesInStore(
PCCERT_CONTEXT pPrevCertContext
);
BOOL CertAddCertificateContextToStore(
PCCERT_CONTEXT pCertContext,
PCCERT_CONTEXT *ppStoreContext
);
CERT_STORE_ADD_REPLACE_EXISTING
BOOL PFXExportCertStoreEx(
HCERTSTORE hStore,
LPCWSTR szPassword,
void *pvPara,
);
HCERTSTORE PFXImportCertStore(
LPCWSTR szPassword,
);
BOOL CertSerializeCertificateStoreElement(
PCCERT_CONTEXT pCertContext,
BYTE *pbElement,
);
BOOL CertAddSerializedElementToStore(
DWORD cbElement,
DWORD dwFlags,
DWORD *pdwContextType,
const void **ppvContext
);
CERT_STORE_ADD_REPLACE_EXISTING
CERT_STORE_ALL_CONTEXT_FLAG
typedef struct _SCHANNEL_CRED
{
// always SCHANNEL_CRED_VERSION
PCCERT_CONTEXT *paCred;
HCERTSTORE hRootStore;
struct _HMAPPER **aphMappers;
} SCHANNEL_CRED, *PSCHANNEL_CRED;
typedef struct _SecHandle
{
ULONG_PTR dwLower ;
ULONG_PTR dwUpper ;
_In_ SEC_CHAR *pszPackage,
_In_opt_ PLUID pvLogonID,
_In_opt_ PVOID pAuthData,
_In_opt_ SEC_GET_KEY_FN pGetKeyFn,
_In_opt_ PVOID pvGetKeyArgument,
_Out_ PCredHandle phCredential,
);
SCH_CRED_MANUAL_CRED_VALIDATION
PCredHandle phCredential
);
typedef struct _SecBufferDesc {
unsigned long ulVersion;
unsigned long cBuffers;
PSecBuffer pBuffers;
} SecBufferDesc, *PSecBufferDesc;
typedef struct _SecBuffer {
unsigned long cbBuffer;
char *pvBuffer;
} SecBuffer, *PSecBuffer;
------------------ context initializtion functions ---------------------
_In_opt_ PCredHandle phCredential,
_In_opt_ PCtxtHandle phContext,
_In_opt_ SEC_CHAR *pszTargetName,
_Inout_opt_ PCtxtHandle phNewContext,
_Inout_opt_ PSecBufferDesc pOutput,
_Out_ PULONG pfContextAttr,
);
targetname
fcontextreq?
targetname
+default-isc-req-flags+ ;; fcontextreq?
success
_In_opt_ PCredHandle phCredential,
_Inout_opt_ PCtxtHandle phContext,
_Inout_opt_ PCtxtHandle phNewContext,
_Inout_opt_ PSecBufferDesc pOutput,
_Out_ PULONG pfContextAttr,
_Out_opt_ PTimeStamp ptsTimeStamp
);
input buffers
output buffers
look for extra bytes in input buffer
copy out the token buffer
free the allocate token buffer
[in] PCtxtHandle phContext,
[in] PSecBufferDesc pToken
);
input buffers
output buffers
look for extra bytes in input buffer
copy out the token buffer
free the allocate token buffer
free the allocate token buffer
SECURITY_STATUS SEC_Entry QueryContextAttributes(
_Out_ PVOID pBuffer
);
-------------- not sure if we need these functions ----------------
SECURITY_STATUS SEC_ENTRY QueryCredentialsAttributesW(
PCredHandle phCredential,
void *pBuffer
);
(pcred :pointer)
(buffer :pointer))
SECURITY_STATUS SEC_ENTRY SetCredentialsAttributesW(
_In_ PCredHandle phCredential, // Credential to Set
_In_ unsigned long ulAttribute, // Attribute to Set
_In_reads_bytes_(cbBuffer) void * pBuffer, // Buffer for attributes
_In_ unsigned long cbBuffer // Size (in bytes) of Buffer
);
(pcred :pointer)
(buffer :pointer)
-------------------------------------------------------------------
PCtxtHandle phContext,
);
_In_ PCtxtHandle phContext,
_Inout_ PSecBufferDesc pMessage,
);
copy back out
_In_ PCtxtHandle phContext,
_Inout_ PSecBufferDesc pMessage,
);
copy data into input buffer
SECURITY_STATUS SEC_ENTRY
_In_ PCtxtHandle phContext // Context to delete
);
[out] void **Token
); | Copyright ( c ) 2019 < >
This code is licensed under the MIT license .
(in-package #:schannel)
(define-foreign-library secur32
(:windows "Secur32.dll"))
(use-foreign-library secur32)
(define-foreign-library crypt32
(:windows "Crypt32.dll"))
(use-foreign-library crypt32)
(defun memset (ptr count &optional (val 0))
(dotimes (i count)
(setf (mem-aref ptr :uint8 i) val)))
(defun copyout (ptr count)
(let ((arr (make-array count :element-type '(unsigned-byte 8))))
(dotimes (i count)
(setf (aref arr i) (mem-aref ptr :uint8 i)))
arr))
(defun copyin (ptr arr &optional (start 0) end)
(let ((count (- (or end (length arr)) start)))
(dotimes (i count)
(setf (mem-aref ptr :uint8 i) (aref arr (+ start i))))
ptr))
(defcstruct cert-context
(encoding-type :uint32)
(encoded :pointer)
(cencoded :uint32)
(info :pointer)
(store :pointer))
(defcstruct crypt-blob
(count :uint32)
(ptr :pointer))
(defcstruct alg-id
(name :pointer)
(blob (:struct crypt-blob)))
typedef struct _ CRYPT_BIT_BLOB {
(defcstruct crypt-bit-blob
(count :uint32)
(ptr :uint32)
(unused :uint32))
(defcstruct crypt-key-info
(algid (:struct alg-id))
(bitblob (:struct crypt-bit-blob)))
(defcstruct cert-info
(version :uint32)
(blob (:struct crypt-blob))
(algid (:struct alg-id))
(name (:struct crypt-blob))
(notbefore :uint64)
(notafter :uint64)
(subject (:struct crypt-blob))
(keyinfo (:struct crypt-key-info))
(issuerid (:struct crypt-blob))
(subjectid (:struct crypt-blob))
(extension :uint32)
(pext :pointer))
(defcfun (%free-context-buffer "FreeContextBuffer" :convention :stdcall) :uint32
(buffer :pointer))
(defun free-context-buffer (ptr)
(%free-context-buffer ptr)
nil)
DWORD dwCertEncodingType ,
const BYTE * pbCertEncoded ,
(defcfun (%cert-create-certificate-context "CertCreateCertificateContext" :convention :stdcall) :pointer
(encoding-type :uint32)
(encoded :pointer)
(count :uint32))
(defun create-certificate-context (data &key (start 0) end)
(let ((count (- (or end (length data)) start)))
(with-foreign-object (buf :uint8 count)
(copyin buf data start end)
(let ((hcert (%cert-create-certificate-context 1
buf
count)))
(if (null-pointer-p hcert)
(error "Failed to create certificate context")
hcert)))))
WINAPI
CertFreeCertificateContext (
_ _ PCCERT_CONTEXT pCertContext
(defcfun (%cert-free-certificate-context "CertFreeCertificateContext" :convention :stdcall) :boolean
(hcert :pointer))
(defun free-certificate-context (hcert)
(%cert-free-certificate-context hcert))
(defun certificate-string (&rest component-names)
"common-name locality-name
organization-name organization-unit-name
email country-name state-or-province
street-address title given-name
initials surname domain-component
"
(with-output-to-string (s)
(let ((sep ""))
(do ((cnames component-names (cddr cnames)))
((null cnames))
(format s "~A~A=\"~A\""
sep
(ecase (car cnames)
(:common-name "CN")
(:locality-name "L")
(:organization-name "O")
(:organization-unit-name "OU")
(:email "E")
(:country-name "C")
(:state-or-province "S")
(:street-address "STREET")
(:title "T")
(:given-name "G")
(:initials "I")
(:surname "SN")
(:domain-component "DC"))
(cadr cnames))
(setf sep ",")))))
BOOL CertStrToNameA (
DWORD dwCertEncodingType ,
LPCSTR pszX500 ,
DWORD dwStrType ,
BYTE * pbEncoded ,
DWORD * pcbEncoded ,
LPCSTR * ppszError
(defcfun (%cert-str-to-name "CertStrToNameA" :convention :stdcall) :boolean
(enctype :uint32)
(str :pointer)
(strtype :uint32)
(reserved :pointer)
(encoded :pointer)
(count :pointer)
(errorstr :pointer))
(defun cert-string-to-name (string)
(with-foreign-string (pstr string)
(with-foreign-objects ((buf :uint8 1024)
(count :uint32))
(setf (mem-aref count :uint32) 1024)
pstr
oid name
(null-pointer)
buf
count
(null-pointer))))
(unless sts
(error "Failed to parse string"))
(copyout buf (mem-aref count :uint32))))))
DWORD
WINAPI
_ In _ DWORD dwCertEncodingType ,
_ In _ PCERT_NAME_BLOB pName ,
_ , return ) LPSTR psz ,
_ In _ DWORD csz
(defcfun (%cert-name-to-string "CertNameToStrW" :convention :stdcall) :uint32
(encoding :uint32)
(blob :pointer)
(strtype :uint32)
(str :pointer)
(size :uint32))
(defun cert-name-to-string (pblob)
(with-foreign-object (str :uint16 512)
pblob
str
512)))
(unless (= sts 0)
(foreign-string-to-lisp str :encoding :ucs-2le)))))
PCCERT_CONTEXT CertCreateSelfSignCertificate (
HCRYPTPROV_OR_NCRYPT_KEY_HANDLE hCryptProvOrNCryptKey ,
PCERT_NAME_BLOB pSubjectIssuerBlob ,
PSYSTEMTIME pStartTime ,
PSYSTEMTIME pEndTime ,
(defcfun (%cert-create-self-signed-certificate "CertCreateSelfSignCertificate" :convention :stdcall) :pointer
(cryptprov :pointer)
(issuer-blob :pointer)
(flags :uint32)
(keyprovinfo :pointer)
(sigalg :pointer)
(starttime :pointer)
(endtime :pointer)
(extensions :pointer))
(defcstruct cert-name-blob
(count :uint32)
(pblob :pointer))
(defun create-self-signed-certificate (&key certificate-name-components)
(let ((buf (cert-string-to-name (apply #'certificate-string certificate-name-components))))
(with-foreign-objects ((pbuf :uint8 (length buf))
(pblob '(:struct cert-name-blob)))
(copyin pbuf buf)
(setf (foreign-slot-value pblob '(:struct cert-name-blob) 'count)
(length buf)
(foreign-slot-value pblob '(:struct cert-name-blob) 'pblob)
pbuf)
(let ((ret (%cert-create-self-signed-certificate (null-pointer)
pblob
0
(null-pointer)
(null-pointer)
(null-pointer)
(null-pointer)
(null-pointer))))
(when (null-pointer-p ret)
(error "Failed"))
ret))))
WINAPI
_ In _ LPCSTR lpszStoreProvider ,
_ In _ DWORD dwEncodingType ,
_ _ HCRYPTPROV_LEGACY hCryptProv ,
(defcfun (%cert-open-store "CertOpenStore" :convention :stdcall) :pointer
(storeprov :pointer)
(encoding :uint32)
(hprov :pointer)
(flags :uint32)
(para :pointer))
(defun cert-open-file-store (filename)
(with-foreign-string (pfname filename :encoding :ucs-2)
(let ((res (%cert-open-store (make-pointer +cert-store-prov-filename-w+)
(null-pointer)
+cert-store-open-existing-flag+
pfname)))
(if (null-pointer-p res)
(error "Failed to open certificate store")
res))))
(defun cert-open-memory-store ()
(let ((hstore (%cert-open-store (make-pointer +cert-store-prov-memory+)
0
(null-pointer)
0
(null-pointer))))
(if (null-pointer-p hstore)
(error "Failed to open memory store")
hstore)))
HCRYPTPROV_LEGACY hProv ,
(defcfun (%cert-open-system-store "CertOpenSystemStoreW" :convention :stdcall) :pointer
(prov :pointer)
(prot :pointer))
(defun cert-open-system-store (&optional subsystem)
(with-foreign-string (str (or subsystem "MY") :encoding :ucs-2)
(let ((res (%cert-open-system-store (null-pointer) str)))
(if (null-pointer-p res)
(error "Failed to open system store")
res))))
hCertStore ,
DWORD dwFlags
(defcfun (%cert-close-store "CertCloseStore" :convention :stdcall) :boolean
(hstore :pointer)
(flags :uint32))
(defun cert-close-store (hstore)
(%cert-close-store hstore 0)
nil)
hCertStore ,
DWORD dwCertEncodingType ,
DWORD dwFindFlags ,
DWORD dwFindType ,
(defcfun (%cert-find-certificate-in-store "CertFindCertificateInStore" :convention :stdcall) :pointer
(hstore :pointer)
(encoding :uint32)
(flags :uint32)
(type :uint32)
(para :pointer)
(prev :pointer))
(defconstant +cert-find-any+ 0)
(defconstant +cert-find-subject-name+ (logior (ash 2 16) 7))
(defconstant +cert-find-subject-str+ (logior (ash 8 16) 7))
(defun find-certificate-in-store (hstore &key subject-name)
(with-foreign-string (ppara (or subject-name "") :encoding :ucs-2)
(let ((res (%cert-find-certificate-in-store hstore
(if subject-name +cert-find-subject-str+ +cert-find-any+)
(if subject-name ppara (null-pointer))
(null-pointer))))
(if (null-pointer-p res)
nil
res))))
hCertStore ,
(defcfun (%cert-enum-certificates-in-store "CertEnumCertificatesInStore" :convention :stdcall) :pointer
(hstore :pointer)
(prev :pointer))
(defun enum-certificates-in-store (hstore)
(do ((hcert (%cert-enum-certificates-in-store hstore (null-pointer))
(%cert-enum-certificates-in-store hstore hcert))
(cert-names nil))
((null-pointer-p hcert) cert-names)
(let ((pinfo (foreign-slot-value hcert '(:struct cert-context) 'info)))
(let ((psubject (foreign-slot-pointer pinfo '(:struct cert-info) 'subject)))
(push (cert-name-to-string psubject) cert-names)))))
hCertStore ,
DWORD dwAddDisposition ,
(defcfun (%cert-add-certificate-context-to-store "CertAddCertificateContextToStore" :convention :stdcall) :boolean
(hstore :pointer)
(hcert :pointer)
(flags :uint32)
(phcert :pointer))
(defun add-certificate-to-store (hstore hcert)
(let ((b (%cert-add-certificate-context-to-store hstore
hcert
(null-pointer))))
(if b
nil
(error "Failed to add certificate to store"))))
CRYPT_DATA_BLOB * pPFX ,
DWORD dwFlags
(defcfun (%pfx-export-cert-store "PFXExportCertStoreEx" :convention :stdcall) :boolean
(hstore :pointer)
(blob :pointer)
(password :pointer)
(para :pointer)
(flags :uint32))
(defun pfx-export-cert-store (hstore password)
(with-foreign-objects ((pblob '(:struct crypt-blob)))
(with-foreign-string (wstr password :encoding :ucs-2)
(memset pblob (foreign-type-size '(:struct crypt-blob)))
(let ((b (%pfx-export-cert-store hstore pblob wstr (null-pointer) #x4)))
(unless b (error "PFXExportCertStore failed"))
(let ((count (foreign-slot-value pblob '(:struct crypt-blob) 'count)))
(with-foreign-object (buf :uint8 count)
(setf (foreign-slot-value pblob '(:struct crypt-blob) 'ptr) buf)
(let ((b2 (%pfx-export-cert-store hstore pblob wstr (null-pointer) #x4)))
(unless b2 (error "PFXExportCertStore failed2"))
(copyout buf count))))))))
CRYPT_DATA_BLOB * pPFX ,
DWORD dwFlags
(defcfun (%pfx-import-cert-store "PFXImportCertStore" :convention :stdcall) :pointer
(blob :pointer)
(password :pointer)
(flags :uint32))
(defun pfx-import-cert-store (data password &key (start 0) end)
(let ((count (- (or end (length data)) start)))
(with-foreign-objects ((blob '(:struct crypt-blob))
(buf :uint8 count))
(with-foreign-string (wstr password :encoding :ucs-2)
(setf (foreign-slot-value blob '(:struct crypt-blob) 'count) count
(foreign-slot-value blob '(:struct crypt-blob) 'ptr) buf)
(let ((hstore (%pfx-import-cert-store blob wstr 0)))
(if (null-pointer-p hstore)
(error "Failed to import cert store")
hstore))))))
DWORD dwFlags ,
DWORD * pcbElement
(defcfun (%cert-serialize-certificate "CertSerializeCertificateStoreElement" :convention :stdcall) :boolean
(hcert :pointer)
(flags :uint32)
(buf :pointer)
(count :pointer))
(defun cert-serialize-certificate (hcert)
(with-foreign-object (count :uint32)
(setf (mem-aref count :uint32) 0)
(let ((b (%cert-serialize-certificate hcert 0 (null-pointer) count)))
(when b
(with-foreign-object (buf :uint8 (mem-aref count :uint32))
(let ((b2 (%cert-serialize-certificate hcert 0 buf count)))
(when b2
(copyout buf (mem-aref count :uint32)))))))))
hCertStore ,
const BYTE * pbElement ,
DWORD dwAddDisposition ,
DWORD dwContextTypeFlags ,
(defcfun (%cert-add-serialized-element-to-store "CertAddSerializedElementToStore" :convention :stdcall) :boolean
(hstore :pointer)
(buf :pointer)
(count :uint32)
(disposition :uint32)
(flags :uint32)
(cxttypeflags :uint32)
(cxttype :pointer)
(cxt :pointer))
(defun cert-add-serialized-element-to-store (hstore buf &key (start 0) end)
(let ((count (- (or end (length buf)) start)))
(with-foreign-objects ((pbuf :uint8 count)
(phcert :pointer))
(let ((b (%cert-add-serialized-element-to-store
hstore
pbuf
count
0
(null-pointer)
phcert)))
(if b
(mem-aref phcert :pointer)
(error "CertAddSerializedElementToStore failed"))))))
(defcstruct schannel-cred
(version :uint32)
(ccreds :uint32)
(creds :pointer)
(certstore :pointer)
(cmappers :uint32)
(mappers :pointer)
(calgs :uint32)
(algs :pointer)
(enabled-protocols :uint32)
(min-cipher-strength :uint32)
(max-cipher-strength :uint32)
(session-lifespan :uint32)
(flags :uint32)
(cred-format :uint32))
(defcstruct sec-handle
(lower :pointer)
(upper :pointer))
SECURITY_STATUS SEC_Entry (
_ In_opt _ SEC_CHAR * ,
_ In _ ULONG fCredentialUse ,
_ Out_opt _ PTimeStamp ptsExpiry
(defcfun (%acquire-credentials-handle "AcquireCredentialsHandleW" :convention :stdcall) :uint32
(principal :pointer)
(package :pointer)
(fcreduse :uint32)
(logonid :pointer)
(authdata :pointer)
(keyfn :pointer)
(keyfnarg :pointer)
(cred :pointer)
(expiry :pointer))
(defun acquire-credentials-handle (&key serverp ignore-certificates-p hcert)
(with-foreign-objects ((credp '(:struct schannel-cred))
(hcredp '(:struct sec-handle))
(certcxtp :pointer))
(with-foreign-string (unisp-name *unisp-name* :encoding :ucs-2)
setup
(memset credp (foreign-type-size '(:struct schannel-cred)))
(setf (foreign-slot-value credp '(:struct schannel-cred) 'version)
+schannel-cred-version+
(foreign-slot-value credp '(:struct schannel-cred) 'enabled-protocols)
(if serverp
(logior +tls1-server+ +tls1-1-server+ +tls1-2-server+)
(logior +tls1-client+ +tls1-1-client+ +tls1-2-client+))
(foreign-slot-value credp '(:struct schannel-cred) 'flags)
(let ((flags 0))
flags))
(when serverp
(unless hcert (error "hcert certificate context required for servers")))
(when hcert
(setf (foreign-slot-value credp '(:struct schannel-cred) 'ccreds)
1
(foreign-slot-value credp '(:struct schannel-cred) 'creds)
certcxtp
(mem-aref certcxtp :pointer)
hcert))
(let ((sts (%acquire-credentials-handle (null-pointer)
unisp-name
(if serverp +cred-inbound+ +cred-outbound+)
(null-pointer)
credp
(null-pointer)
(null-pointer)
hcredp
(null-pointer))))
(unless (= sts 0) (win-error sts))
(mem-aref hcredp '(:struct sec-handle))))))
KSECDDDECLSPEC SECURITY_STATUS SEC_ENTRY FreeCredentialsHandle (
(defcfun (%free-credentials-handle "FreeCredentialsHandle" :convention :stdcall) :uint32
(hcred :pointer))
(defun free-credentials-handle (hcred)
(with-foreign-object (p '(:struct sec-handle))
(setf (mem-aref p '(:struct sec-handle)) hcred)
(let ((sts (%free-credentials-handle p)))
(unless (= sts 0) (win-error sts))
nil)))
(defcstruct sec-buffer-desc
SECBUFFER_VERSION=0
(cbuffers :uint32)
(buffers :pointer))
(defun init-sec-buffer-desc (ptr buffers count)
(setf (foreign-slot-value ptr '(:struct sec-buffer-desc) 'version)
0
(foreign-slot-value ptr '(:struct sec-buffer-desc) 'cbuffers)
count
(foreign-slot-value ptr '(:struct sec-buffer-desc) 'buffers)
buffers)
ptr)
(defcstruct sec-buffer
(cbuffer :uint32)
(type :uint32)
(buffer :pointer))
(defun init-sec-buffer (ptr count buf type)
(setf (foreign-slot-value ptr '(:struct sec-buffer) 'cbuffer)
count
(foreign-slot-value ptr '(:struct sec-buffer) 'type)
type
(foreign-slot-value ptr '(:struct sec-buffer) 'buffer)
buf)
ptr)
(defconstant +default-isc-req-flags+
(logior +ISC-REQ-SEQUENCE-DETECT+
+ISC-REQ-REPLAY-DETECT+
+ISC-REQ-CONFIDENTIALITY+
+ISC-REQ-ALLOCATE-MEMORY+
+ISC-REQ-STREAM+))
SECURITY_STATUS SEC_Entry InitializeSecurityContext (
_ In _ ULONG fContextReq ,
_ In _ ULONG Reserved1 ,
_ In _ ULONG TargetDataRep ,
_ In_opt _ PSecBufferDesc pInput ,
_ In _ ULONG Reserved2 ,
_ Out_opt _ PTimeStamp ptsExpiry
(defcfun (%initialize-security-context "InitializeSecurityContextW" :convention :stdcall) :uint32
(hcred :pointer)
(pcxt :pointer)
(targetname :pointer)
(fcontextreq :uint32)
(reserved1 :uint32)
(targetdatarep :uint32)
(input :pointer)
(reserved2 :uint32)
(newcontext :pointer)
(output :pointer)
(contextattr :pointer)
(expiry :pointer))
(defun initialize-security-context-init (hcred hostname)
"Called on first to initialize security context. Returns values hcontext token"
(with-foreign-objects ((phcred '(:struct sec-handle))
(pnewcxt '(:struct sec-handle))
(pcxtattr :uint32)
(poutput '(:struct sec-buffer-desc))
(poutputbufs '(:struct sec-buffer)))
(with-foreign-string (phostname hostname :encoding :ucs-2)
(setf (mem-aref phcred '(:struct sec-handle)) hcred)
(init-sec-buffer poutputbufs 0 (null-pointer) +secbuffer-empty+)
(init-sec-buffer-desc poutput poutputbufs 1)
(let ((sts (%initialize-security-context phcred
(null-pointer)
0
0
(null-pointer)
0
pnewcxt
poutput
pcxtattr
(null-pointer))))
(cond
((= sts +continue-needed+)
(let* ((obufp (foreign-slot-value poutputbufs '(:struct sec-buffer) 'buffer))
(rtok (copyout obufp
(foreign-slot-value poutputbufs '(:struct sec-buffer) 'cbuffer)))
(extra-bytes nil))
(free-context-buffer obufp)
(when (= (foreign-slot-value (mem-aptr poutputbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr poutputbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
(values (mem-aref pnewcxt '(:struct sec-handle))
rtok
(mem-aref pcxtattr :uint32)
extra-bytes
nil)))
((= sts +incomplete-message+)
(values nil nil nil nil t))
(t (win-error sts)))))))
(defun initialize-security-context-continue (hcred hostname hcxt token cxtattr token-start token-end)
(with-foreign-objects ((phcred '(:struct sec-handle))
(phcxt '(:struct sec-handle))
(psecbuf '(:struct sec-buffer-desc))
(secbuffers '(:struct sec-buffer) 2)
(pcxtattr :uint32)
(ptoken :uint8 (- token-end token-start))
(poutput '(:struct sec-buffer-desc))
(poutputbufs '(:struct sec-buffer)))
(with-foreign-string (phostname hostname :encoding :ucs-2)
(setf (mem-aref phcred '(:struct sec-handle))
hcred
(mem-aref phcxt '(:struct sec-handle))
hcxt)
(copyin ptoken token token-start token-end)
(init-sec-buffer (mem-aptr secbuffers '(:struct sec-buffer) 0)
(- token-end token-start)
ptoken
+secbuffer-token+)
(init-sec-buffer (mem-aptr secbuffers '(:struct sec-buffer) 1)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer-desc psecbuf secbuffers 2)
(init-sec-buffer poutputbufs 0 (null-pointer) +secbuffer-empty+)
(init-sec-buffer-desc poutput poutputbufs 1)
(let ((sts (%initialize-security-context phcred
phcxt
0
0
psecbuf
0
(null-pointer)
poutput
pcxtattr
(null-pointer))))
(cond
((= sts 0)
(let ((extra-bytes nil))
(when (= (foreign-slot-value (mem-aptr poutputbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr poutputbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
(values nil (mem-aref pcxtattr :uint32) extra-bytes nil)))
((or (= sts +incomplete-message+) #+nil(= sts +invalid-token+))
(values nil nil nil t))
((= sts +continue-needed+)
(let* ((obufp (foreign-slot-value poutputbufs '(:struct sec-buffer) 'buffer))
(rtok (copyout obufp (foreign-slot-value poutputbufs '(:struct sec-buffer) 'cbuffer)))
(extra-bytes nil))
(free-context-buffer obufp)
(when (= (foreign-slot-value (mem-aptr secbuffers '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr secbuffers '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
(values rtok
(mem-aref pcxtattr :uint32)
extra-bytes
nil)))
(t (win-error sts)))))))
SECURITY_STATUS SEC_Entry AcceptSecurityContext (
_ In_opt _ PSecBufferDesc pInput ,
_ In _ ULONG fContextReq ,
_ In _ ULONG TargetDataRep ,
(defcfun (%accept-security-context "AcceptSecurityContext" :convention :stdcall) :uint32
(hcred :pointer)
(pcxt :pointer)
(input :pointer)
(fcontextreq :uint32)
(targetdatarep :uint32)
(newcontext :pointer)
(output :pointer)
(contextattr :pointer)
(timestamp :pointer))
(defconstant +default-asc-req-flags+
(logior +asc-req-allocate-memory+
+asc-req-stream+
+asc-req-confidentiality+
+asc-req-sequence-detect+
+asc-req-replay-detect+))
(defun accept-security-context-init (hcred token token-start token-end &key require-client-certificate)
(with-foreign-objects ((phcred '(:struct sec-handle))
(phcxt '(:struct sec-handle))
(isecbufdesc '(:struct sec-buffer-desc))
(isecbufs '(:struct sec-buffer) 2)
(ptokbuf :uint8 (length token))
(osecbufdesc '(:struct sec-buffer-desc))
(osecbufs '(:struct sec-buffer))
(pcxtattr :uint32))
(setf (mem-aref phcred '(:struct sec-handle)) hcred)
(copyin ptokbuf token token-start token-end)
(init-sec-buffer (mem-aptr isecbufs '(:struct sec-buffer) 0)
(- token-end token-start)
ptokbuf
+secbuffer-token+)
(init-sec-buffer (mem-aptr isecbufs '(:struct sec-buffer) 1)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer-desc isecbufdesc isecbufs 2)
(init-sec-buffer osecbufs 0 (null-pointer) +secbuffer-empty+)
(init-sec-buffer-desc osecbufdesc osecbufs 1)
(let ((sts (%accept-security-context phcred
(null-pointer)
isecbufdesc
(logior +default-asc-req-flags+
(if require-client-certificate +asc-req-mutual-auth+ 0))
0
phcxt
osecbufdesc
pcxtattr
(null-pointer))))
(cond
((= sts +continue-needed+)
(let ((tok nil)
(extra-bytes nil))
(when (= (foreign-slot-value (mem-aptr isecbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr isecbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
(setf tok
(copyout (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer)
(foreign-slot-value osecbufs
'(:struct sec-buffer)
'cbuffer)))
(free-context-buffer (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer))
(values (mem-aref phcxt '(:struct sec-handle))
tok
extra-bytes
(mem-aref pcxtattr :uint32)
nil)))
((= sts +incomplete-message+)
(values nil nil nil nil t))
(t (win-error sts))))))
SECURITY_STATUS SEC_ENTRY CompleteAuthToken (
(defcfun (%complete-auth-token "CompleteAuthToken" :convention :stdcall) :uint32
(pcxt :pointer)
(pbuf :pointer))
(defun complete-auth-token (phcxt psecbufdesc)
(let ((sts (%complete-auth-token phcxt psecbufdesc)))
(if (zerop sts)
nil
(win-error sts))))
(defun accept-security-context-continue (hcred hcxt token cxtattr token-start token-end)
(with-foreign-objects ((phcred '(:struct sec-handle))
(phcxt '(:struct sec-handle))
(isecbufdesc '(:struct sec-buffer-desc))
(isecbufs '(:struct sec-buffer) 2)
(ptokbuf :uint8 (length token))
(osecbufdesc '(:struct sec-buffer-desc))
(osecbufs '(:struct sec-buffer))
(pcxtattr :uint32))
(setf (mem-aref phcred '(:struct sec-handle)) hcred
(mem-aref phcxt '(:struct sec-handle)) hcxt)
(copyin ptokbuf token token-start token-end)
(init-sec-buffer (mem-aptr isecbufs '(:struct sec-buffer) 0)
(- token-end token-start)
ptokbuf
+secbuffer-token+)
(init-sec-buffer (mem-aptr isecbufs '(:struct sec-buffer) 1)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer-desc isecbufdesc isecbufs 2)
(init-sec-buffer osecbufs 0 (null-pointer) +secbuffer-empty+)
(init-sec-buffer-desc osecbufdesc osecbufs 1)
(let ((sts (%accept-security-context phcred
phcxt
isecbufdesc
cxtattr
0
(null-pointer)
osecbufdesc
pcxtattr
(null-pointer))))
(cond
((or (= sts 0)
(= sts +continue-needed+))
(let ((tok nil)
(extra-bytes nil))
(when (= (foreign-slot-value (mem-aptr isecbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'type)
+secbuffer-extra+)
(setf extra-bytes
(foreign-slot-value (mem-aptr isecbufs '(:struct sec-buffer) 1)
'(:struct sec-buffer)
'cbuffer)))
(setf tok
(copyout (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer)
(foreign-slot-value osecbufs
'(:struct sec-buffer)
'cbuffer)))
(free-context-buffer (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer))
(values tok extra-bytes (mem-aref pcxtattr :uint32) nil (= sts +continue-needed+))))
((= sts +incomplete-message+)
(values nil nil nil t nil))
((= sts +complete-needed+)
complete the context , need to call CompleteAuthToken
(complete-auth-token phcxt osecbufdesc)
(free-context-buffer (foreign-slot-value osecbufs
'(:struct sec-buffer)
'buffer))
(values nil nil (mem-aref pcxtattr :uint32) nil nil))
(t (win-error sts))))))
_ In _ PCtxtHandle phContext ,
_ In _ ULONG ulAttribute ,
(defcfun (%query-context-attributes "QueryContextAttributesW" :convention :stdcall) :uint32
(pcxt :pointer)
(attr :uint32)
(buffer :pointer))
(defun query-stream-sizes (hcxt)
(with-foreign-objects ((phcxt '(:struct sec-handle))
(buf :uint32 5))
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt)
(let ((sts (%query-context-attributes phcxt
SECPKG_ATTR_STREAM_SIZES
buf)))
(unless (= sts 0) (win-error sts))
(list :header (mem-aref buf :uint32 0)
:trailer (mem-aref buf :uint32 1)
:max-message (mem-aref buf :uint32 2)
:max-buffers (mem-aref buf :uint32 3)
:block-size (mem-aref buf :uint32 4)))))
(defstruct certificate-info
name
encoding-type
encoded)
(defun query-remote-certificate (hcxt)
(with-foreign-objects ((phcxt '(:struct sec-handle))
(buf :pointer))
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt)
(let ((sts (%query-context-attributes phcxt
SECPKG_ATTR_REMOTE_CERT_CONTEXT
buf)))
(unless (= sts 0) (win-error sts))
(let* ((pcert (mem-aref buf :pointer))
(pinfo (foreign-slot-value pcert '(:struct cert-context) 'info))
(psubject (foreign-slot-pointer pinfo '(:struct cert-info) 'subject))
(count (foreign-slot-value pcert '(:struct cert-context) 'cencoded))
(encoded (foreign-slot-value pcert '(:struct cert-context) 'encoded))
(encoded-buf (make-array count :element-type '(unsigned-byte 8)))
(encoding-type (foreign-slot-value pcert '(:struct cert-context) 'encoding-type)))
(dotimes (i count)
(setf (aref encoded-buf i) (mem-aref encoded :uint8 i)))
(make-certificate-info :name (cert-name-to-string psubject)
:encoding-type (cond
((= encoding-type +x509-asn-encoding+ ) :x509-asn-encoding)
((= encoding-type +pkcs-7-asn-encoding+) :pkcs-7-asn-encoding)
(t (error (format nil "Unknown encoding type ~A" encoding-type))))
:encoded encoded-buf)))))
unsigned long ulAttribute ,
( defcfun ( % query - credentials - attributes " QueryCredentialsAttributesW " : convention : stdcall ) : uint32
( attr : )
( defcfun ( % set - credentials - attributes " SetCredentialsAttributesW " : convention : stdcall ) : uint32
( attr : )
( count : ) )
KSECDDDECLSPEC SECURITY_STATUS SEC_ENTRY ApplyControlToken (
PSecBufferDesc
(defcfun (%apply-control-token "ApplyControlToken" :convention :stdcall) :uint32
(pcxt :pointer)
(input :pointer))
(defun apply-shutdown-token (hcxt)
(with-foreign-objects ((secbufdesc '(:struct sec-buffer-desc))
(secbuf '(:struct sec-buffer))
(ctrltok :uint32)
(phcxt '(:struct sec-handle)))
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt
(mem-aref ctrltok :uint32) +schannel-shutdown+)
(init-sec-buffer secbuf 4 ctrltok +secbuffer-token+)
(init-sec-buffer-desc secbufdesc secbuf 1)
(let ((sts (%apply-control-token phcxt secbufdesc)))
(unless (= sts 0) (win-error sts))
nil)))
SECURITY_STATUS SEC_Entry DecryptMessage (
_ In _ ULONG ,
_ Out _ PULONG pfQOP
(defcfun (%decrypt-message "DecryptMessage" :convention :stdcall) :uint32
(pcxt :pointer)
(buffer :pointer)
(seqno :uint32)
(pqop :pointer))
(defun decrypt-message-1 (hcxt buf &key (start 0) end)
"Decrypt message. Sets buf contents to decrypted plaintext.
Returns values bend extra-start incomplete-p
bend is buffer end index and extra-start is starting index of first extra byte."
(let ((count (- (or end (length buf)) start)))
(with-foreign-objects ((phcxt '(:struct sec-handle))
(pbuf :uint8 count)
(secbufdesc '(:struct sec-buffer-desc))
(secbufs '(:struct sec-buffer) 4))
(dotimes (i count)
(setf (mem-aref pbuf :uint8 i) (aref buf (+ start i))))
(init-sec-buffer-desc secbufdesc secbufs 4)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 0)
count
pbuf
+secbuffer-data+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 1)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 2)
0
(null-pointer)
+secbuffer-empty+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 3)
0
(null-pointer)
+secbuffer-empty+)
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt)
(let ((sts (%decrypt-message phcxt secbufdesc 0 (null-pointer)))
(bend 0)
(extra-start nil))
(cond
((= sts 0)
(dotimes (i 4)
(let ((btype (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'type)))
(cond
((= btype +secbuffer-data+)
(let ((dcount (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'cbuffer))
(bptr (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'buffer)))
(dotimes (i dcount)
(setf (aref buf (+ start i)) (mem-aref bptr :uint8 i)))
(setf bend (+ start dcount))))
((= btype +secbuffer-extra+)
get index of first extra byte
(setf extra-start
(- count (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'cbuffer)))))))
(values bend extra-start nil))
((or (= sts +incomplete-message+) #+nil(= sts +invalid-token+))
(values nil nil t))
(t (win-error sts)))))))
SECURITY_STATUS SEC_Entry EncryptMessage (
_ In _ ULONG fQOP ,
_ In _ ULONG
(defcfun (%encrypt-message "EncryptMessage" :convention :stdcall) :uint32
(pcxt :pointer)
(fqop :uint32)
(buffer :pointer)
(seqno :uint32))
(defun encrypt-message-1 (hcxt buf &key (start 0) end)
"Returns end index"
(let ((count (- (or end (length buf)) start))
(ssizes (query-stream-sizes hcxt)))
(with-foreign-objects ((pbuf :uint8 (+ count
(getf ssizes :header)
(getf ssizes :trailer)))
(secbufdesc '(:struct sec-buffer-desc))
(secbufs '(:struct sec-buffer) 4)
(phcxt '(:struct sec-handle)))
(setf (mem-aref phcxt '(:struct sec-handle)) hcxt)
(dotimes (i count)
(setf (mem-aref pbuf :uint8 (+ (getf ssizes :header) i))
(aref buf (+ start i))))
(init-sec-buffer-desc secbufdesc secbufs 4)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 0)
(getf ssizes :header)
pbuf
+secbuffer-stream-header+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 1)
count
(mem-aptr pbuf :uint8 (getf ssizes :header))
+secbuffer-data+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 2)
(getf ssizes :trailer)
(mem-aptr pbuf :uint8 (+ (getf ssizes :header) count))
+secbuffer-stream-trailer+)
(init-sec-buffer (mem-aptr secbufs '(:struct sec-buffer) 3)
0
(null-pointer)
+secbuffer-empty+)
(let ((sts (%encrypt-message phcxt 0 secbufdesc 0)))
(cond
((= sts 0)
(let ((bcount (loop :for i :below 3
:sum (foreign-slot-value (mem-aptr secbufs '(:struct sec-buffer) i)
'(:struct sec-buffer)
'cbuffer))))
(dotimes (i bcount)
(setf (aref buf (+ start i)) (mem-aref pbuf :uint8 i)))
(+ start bcount)))
(t (win-error sts)))))))
DeleteSecurityContext (
(defcfun (%delete-security-context "DeleteSecurityContext" :convention :stdcall) :uint32
(pcxt :pointer))
(defun delete-security-context (cxt)
(with-foreign-object (pcxt '(:struct sec-handle))
(setf (mem-aref pcxt '(:struct sec-handle)) cxt)
(let ((sts (%delete-security-context pcxt)))
(unless (= sts 0) (win-error sts))))
nil)
KSECDDDECLSPEC SECURITY_STATUS SEC_ENTRY (
[ in ] PCtxtHandle phContext ,
(defcfun (%query-security-context-token "QuerySecurityContextToken" :convention :stdcall)
:uint32
(pcxt :pointer)
(tok :pointer))
(defun query-security-context-token (cxt)
(with-foreign-objects ((pcxt '(:struct sec-handle))
(ptok :pointer))
(setf (mem-aref pcxt '(:struct sec-handle)) cxt)
(let ((sts (%query-security-context-token pcxt ptok)))
(unless (= sts 0) (win-error sts))
(mem-aref ptok :pointer))))
|
44823815d0e2fd06f54ec07c9acd43236cf8c1cb2166df286efec359edcd7a9c | merijn/Belewitte | RunConfig.hs | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE GeneralisedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE QuasiQuotes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Schema.RunConfig where
import Data.String.Interpolate.IsString (i)
import Database.Persist.Sql (Unique)
import Pretty.Fields.Persistent
import Schema.Utils
( Entity
, EntityDef
, Int64
, MonadLogger
, MonadSql
, MonadThrow
, Transaction
, (.>)
, (.=)
)
import qualified Schema.Utils as Utils
import Types
Schema version for RunConfig table initialisation
import qualified Schema.Platform.V1 as Platform.V1
-- Schema version for current schema
import Schema.Algorithm (AlgorithmId)
import qualified Schema.Algorithm as Algorithm
import Schema.Dataset (DatasetId)
import qualified Schema.Dataset as Dataset
import Schema.Platform (PlatformId)
import qualified Schema.Platform as Platform
import qualified Schema.RunConfig.V0 as V0
Utils.mkEntitiesWith "schema"
[Algorithm.schema, Dataset.schema, Platform.schema] [Utils.mkSchema|
RunConfig
algorithmId AlgorithmId
platformId PlatformId
datasetId DatasetId
algorithmVersion CommitId
repeats Int
UniqRunConfig algorithmId platformId datasetId algorithmVersion
deriving Eq Show
|]
deriving instance Show (Unique RunConfig)
instance PrettyFields (Entity RunConfig) where
prettyFieldInfo = ("Id", idField RunConfigId) :|
[ ("Algorithm", namedIdField RunConfigAlgorithmId)
, ("Platform", namedIdField RunConfigPlatformId)
, ("Dataset", namedIdField RunConfigDatasetId)
, ("Repeats", RunConfigRepeats `fieldVia` prettyShow)
, ("Algorithm Commit", RunConfigAlgorithmVersion `fieldVia` getCommitId)
]
migrations
:: (MonadLogger m, MonadSql m, MonadThrow m)
=> Int64 -> Transaction m [EntityDef]
migrations = Utils.mkMigrationLookup
[ 6 .> V0.schema $ do
Utils.createTableFromSchema
[ Algorithm.schema
, Dataset.schema
, Platform.V1.schema
, schema
]
Utils.executeSql [i|
INSERT INTO "RunConfig"
SELECT ROW_NUMBER() OVER (ORDER BY algorithmId, platformId, datasetId)
, algorithmId
, platformId
, datasetId
, "Unknown"
, 0
FROM (
SELECT DISTINCT Variant.algorithmId, TotalTimer.platformId, Graph.datasetId
FROM TotalTimer
INNER JOIN Variant
ON Variant.id = TotalTimer.variantId
INNER JOIN Graph
ON Graph.id = Variant.graphId
)
|]
, 16 .= schema
]
| null | https://raw.githubusercontent.com/merijn/Belewitte/cab6010a2bc54acfc4f4b169c95799fe455799ef/benchmark-analysis/src/Schema/RunConfig.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
Schema version for current schema | # LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE GeneralisedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuasiQuotes #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Schema.RunConfig where
import Data.String.Interpolate.IsString (i)
import Database.Persist.Sql (Unique)
import Pretty.Fields.Persistent
import Schema.Utils
( Entity
, EntityDef
, Int64
, MonadLogger
, MonadSql
, MonadThrow
, Transaction
, (.>)
, (.=)
)
import qualified Schema.Utils as Utils
import Types
Schema version for RunConfig table initialisation
import qualified Schema.Platform.V1 as Platform.V1
import Schema.Algorithm (AlgorithmId)
import qualified Schema.Algorithm as Algorithm
import Schema.Dataset (DatasetId)
import qualified Schema.Dataset as Dataset
import Schema.Platform (PlatformId)
import qualified Schema.Platform as Platform
import qualified Schema.RunConfig.V0 as V0
Utils.mkEntitiesWith "schema"
[Algorithm.schema, Dataset.schema, Platform.schema] [Utils.mkSchema|
RunConfig
algorithmId AlgorithmId
platformId PlatformId
datasetId DatasetId
algorithmVersion CommitId
repeats Int
UniqRunConfig algorithmId platformId datasetId algorithmVersion
deriving Eq Show
|]
deriving instance Show (Unique RunConfig)
instance PrettyFields (Entity RunConfig) where
prettyFieldInfo = ("Id", idField RunConfigId) :|
[ ("Algorithm", namedIdField RunConfigAlgorithmId)
, ("Platform", namedIdField RunConfigPlatformId)
, ("Dataset", namedIdField RunConfigDatasetId)
, ("Repeats", RunConfigRepeats `fieldVia` prettyShow)
, ("Algorithm Commit", RunConfigAlgorithmVersion `fieldVia` getCommitId)
]
migrations
:: (MonadLogger m, MonadSql m, MonadThrow m)
=> Int64 -> Transaction m [EntityDef]
migrations = Utils.mkMigrationLookup
[ 6 .> V0.schema $ do
Utils.createTableFromSchema
[ Algorithm.schema
, Dataset.schema
, Platform.V1.schema
, schema
]
Utils.executeSql [i|
INSERT INTO "RunConfig"
SELECT ROW_NUMBER() OVER (ORDER BY algorithmId, platformId, datasetId)
, algorithmId
, platformId
, datasetId
, "Unknown"
, 0
FROM (
SELECT DISTINCT Variant.algorithmId, TotalTimer.platformId, Graph.datasetId
FROM TotalTimer
INNER JOIN Variant
ON Variant.id = TotalTimer.variantId
INNER JOIN Graph
ON Graph.id = Variant.graphId
)
|]
, 16 .= schema
]
|
2bed73dbf4a9bbc6de0901f51790d55a81dcc1113ea8a246ceb59ab5f9f2c884 | w01fe/sniper | snarf.clj | (ns sniper.snarf
"Snarf in namespaces and extract sniper.core/Forms with dependency info.
Main entry point is `classpath-ns-forms`."
(:use plumbing.core)
(:require
[clojure.java.classpath :as classpath]
[clojure.java.io :as java-io]
[clojure.tools.analyzer.ast :as ast]
[clojure.tools.analyzer.env :as env]
[clojure.tools.analyzer.jvm :as jvm]
[clojure.tools.analyzer.jvm.utils :as jvm-utils]
[clojure.tools.namespace.find :as namespace-find]
[clojure.tools.reader :as reader]
[clojure.tools.reader.reader-types :as reader-types]
[schema.core :as s]
[sniper.core :as sniper]))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Copied and modified from tools.analyzer.jvm master
(defn try-analyze [form env opts]
(try (jvm/analyze form env opts)
(catch Throwable t
(println t)
(println "WARNING: skipping form: " form))))
(defn analyze-ns
"Analyzes a whole namespace. returns a vector of the ASTs for all the
top-level ASTs of that file.
Evaluates all the forms.
Disables wrong-tag-handler, and fixes bug with opts shadowing,
and doesn't eval."
([ns] (analyze-ns ns (jvm/empty-env)))
([ns env] (analyze-ns ns env {:passes-opts
(merge
jvm/default-passes-opts
{:validate/wrong-tag-handler
(fn [_ ast]
#_(println "Wrong tag: " (-> ast :name meta :tag)
" in def: " (:name ast)))})}))
([ns env opts]
(println "Analyzing ns" ns)
(env/ensure
(jvm/global-env)
(let [res ^java.net.URL (jvm-utils/ns-url ns)]
(assert res (str "Can't find " ns " in classpath"))
(let [filename (str res)
path (.getPath res)]
(when-not (get-in (env/deref-env) [::analyzed-clj path])
(binding [*ns* (the-ns ns)
*file* filename]
(with-open [rdr (java-io/reader res)]
(let [pbr (reader-types/indexing-push-back-reader
(java.io.PushbackReader. rdr) 1 filename)
eof (Object.)
read-opts {:eof eof :features #{:clj :t.a.jvm}}
read-opts (if (.endsWith filename "cljc")
(assoc read-opts :read-cond :allow)
read-opts)]
(loop [ret []]
(let [form (reader/read read-opts pbr)]
;;(println "\n\n" form)
(if (identical? form eof)
(remove nil? ret)
(recur
(conj ret (try-analyze form (assoc env :ns (ns-name *ns*)) opts)))))))))))))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Private helpers: extracting definitions and references from forms
(defn class-name [^Class c] (.getName c))
(defn gen-interface-class [f]
(when (= (first f) 'clojure.core/gen-interface)
[(name (nth f 2))]))
(defn protocol-gen-interface-form [node]
(when (= (:type node) :class) (-> node :raw-forms first)))
(defnk class-defs
[op :as node]
(case op
(:deftype) [(class-name (safe-get node :class-name))]
possibly definterface
(:const) (-> node protocol-gen-interface-form gen-interface-class) ;; possibly defprotocol
nil))
(defnk class-refs [op :as node]
(case op
(:const) (when (= (:type node) :class) [(class-name (safe-get node :val))])
nil))
(defn var->symbol [v]
(letk [[ns [:name :as var-name]] (meta v)]
(symbol (name (ns-name ns)) (name var-name))))
(defn defprotocol-vars [f ns]
(when (= (first f) 'clojure.core/gen-interface)
(for [[m] (nth f 4)]
(symbol (name ns) (name m)))))
(defnk var-defs [op :as node]
(case op
(:def) [(var->symbol (safe-get node :var))]
(:const) (-> node protocol-gen-interface-form (defprotocol-vars (safe-get-in node [:env :ns])))
(:instance-call) (when (and (= 'addMethod (:method node)) ;; defmethod is part of multi var def.
(= clojure.lang.MultiFn (:class node)))
[(var->symbol (safe-get-in node [:instance :var]))])
nil))
(defnk var-refs [op :as node]
(case op
(:var :the-var) [(var->symbol (safe-get node :var))]
nil))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Public
(s/defn ^:always-validate normalized-form :- (s/maybe sniper/Form)
"Convert a top-level analyzer AST node into a sniper/Form.
May return nil for comment forms (which are often missing source info)."
[ast-node]
(let [nodes (ast/nodes ast-node)
unique (fn [f] (sort-by str (distinct (mapcat f nodes))))]
(if-not (get-in ast-node [:env :line])
(do (assert (= (ffirst (:raw-forms ast-node)) 'comment)
(str "MISSING line" (:raw-forms ast-node) (:env ast-node)))
nil)
{:source-info (select-keys (:env ast-node) [:file :ns :line :column :end-column :end-line])
:class-defs (unique class-defs)
:class-refs (unique class-refs)
:var-defs (unique var-defs)
:var-refs (unique var-refs)
:shadow? false})))
(def +analysis-cache-file+ ".sniper-analysis-cache.clj")
(defonce +analysis-cache+
(atom (try (read-string (slurp +analysis-cache-file+)) (catch Exception e {}))))
(defn cached-ns-forms
[ns]
(let [c (slurp (jvm-utils/ns-url ns))]
(or (@+analysis-cache+ c)
(let [res (vec (keep normalized-form (analyze-ns ns)))]
(swap! +analysis-cache+ assoc c res)
res))))
(s/defn ns-forms :- [sniper/Form]
"Get a flat sequence of forms for all namespaces in nss."
[& nss :- [clojure.lang.Symbol]]
(apply concat (pmap cached-ns-forms nss)))
(defn classpath-namespaces [dir-regex]
"Get a sequence of all namespaces on classpath that match dir-regex."
(->> (classpath/classpath)
(mapcat file-seq)
distinct
(filter (fn [^java.io.File f]
(and (.isDirectory f)
(re-find dir-regex (.getPath f)))))
(mapcat #(namespace-find/find-namespaces-in-dir %))
distinct
sort))
(s/defn classpath-ns-forms :- [sniper/Form]
[dir-regex]
"Get a flat sequence of forms for all namespaces on the classpath matching
dir-regex."
(let [nss (classpath-namespaces dir-regex)]
(println "Requiring" nss)
(apply require nss)
(let [res (apply ns-forms nss)]
(future (spit +analysis-cache-file+ @+analysis-cache+))
res)))
| null | https://raw.githubusercontent.com/w01fe/sniper/cdfadbef08bf41aea2cf6b0c854de6497ca52022/src/sniper/snarf.clj | clojure |
(println "\n\n" form)
Private helpers: extracting definitions and references from forms
possibly defprotocol
defmethod is part of multi var def.
Public | (ns sniper.snarf
"Snarf in namespaces and extract sniper.core/Forms with dependency info.
Main entry point is `classpath-ns-forms`."
(:use plumbing.core)
(:require
[clojure.java.classpath :as classpath]
[clojure.java.io :as java-io]
[clojure.tools.analyzer.ast :as ast]
[clojure.tools.analyzer.env :as env]
[clojure.tools.analyzer.jvm :as jvm]
[clojure.tools.analyzer.jvm.utils :as jvm-utils]
[clojure.tools.namespace.find :as namespace-find]
[clojure.tools.reader :as reader]
[clojure.tools.reader.reader-types :as reader-types]
[schema.core :as s]
[sniper.core :as sniper]))
Copied and modified from tools.analyzer.jvm master
(defn try-analyze [form env opts]
(try (jvm/analyze form env opts)
(catch Throwable t
(println t)
(println "WARNING: skipping form: " form))))
(defn analyze-ns
"Analyzes a whole namespace. returns a vector of the ASTs for all the
top-level ASTs of that file.
Evaluates all the forms.
Disables wrong-tag-handler, and fixes bug with opts shadowing,
and doesn't eval."
([ns] (analyze-ns ns (jvm/empty-env)))
([ns env] (analyze-ns ns env {:passes-opts
(merge
jvm/default-passes-opts
{:validate/wrong-tag-handler
(fn [_ ast]
#_(println "Wrong tag: " (-> ast :name meta :tag)
" in def: " (:name ast)))})}))
([ns env opts]
(println "Analyzing ns" ns)
(env/ensure
(jvm/global-env)
(let [res ^java.net.URL (jvm-utils/ns-url ns)]
(assert res (str "Can't find " ns " in classpath"))
(let [filename (str res)
path (.getPath res)]
(when-not (get-in (env/deref-env) [::analyzed-clj path])
(binding [*ns* (the-ns ns)
*file* filename]
(with-open [rdr (java-io/reader res)]
(let [pbr (reader-types/indexing-push-back-reader
(java.io.PushbackReader. rdr) 1 filename)
eof (Object.)
read-opts {:eof eof :features #{:clj :t.a.jvm}}
read-opts (if (.endsWith filename "cljc")
(assoc read-opts :read-cond :allow)
read-opts)]
(loop [ret []]
(let [form (reader/read read-opts pbr)]
(if (identical? form eof)
(remove nil? ret)
(recur
(conj ret (try-analyze form (assoc env :ns (ns-name *ns*)) opts)))))))))))))))
(defn class-name [^Class c] (.getName c))
(defn gen-interface-class [f]
(when (= (first f) 'clojure.core/gen-interface)
[(name (nth f 2))]))
(defn protocol-gen-interface-form [node]
(when (= (:type node) :class) (-> node :raw-forms first)))
(defnk class-defs
[op :as node]
(case op
(:deftype) [(class-name (safe-get node :class-name))]
possibly definterface
nil))
(defnk class-refs [op :as node]
(case op
(:const) (when (= (:type node) :class) [(class-name (safe-get node :val))])
nil))
(defn var->symbol [v]
(letk [[ns [:name :as var-name]] (meta v)]
(symbol (name (ns-name ns)) (name var-name))))
(defn defprotocol-vars [f ns]
(when (= (first f) 'clojure.core/gen-interface)
(for [[m] (nth f 4)]
(symbol (name ns) (name m)))))
(defnk var-defs [op :as node]
(case op
(:def) [(var->symbol (safe-get node :var))]
(:const) (-> node protocol-gen-interface-form (defprotocol-vars (safe-get-in node [:env :ns])))
(= clojure.lang.MultiFn (:class node)))
[(var->symbol (safe-get-in node [:instance :var]))])
nil))
(defnk var-refs [op :as node]
(case op
(:var :the-var) [(var->symbol (safe-get node :var))]
nil))
(s/defn ^:always-validate normalized-form :- (s/maybe sniper/Form)
"Convert a top-level analyzer AST node into a sniper/Form.
May return nil for comment forms (which are often missing source info)."
[ast-node]
(let [nodes (ast/nodes ast-node)
unique (fn [f] (sort-by str (distinct (mapcat f nodes))))]
(if-not (get-in ast-node [:env :line])
(do (assert (= (ffirst (:raw-forms ast-node)) 'comment)
(str "MISSING line" (:raw-forms ast-node) (:env ast-node)))
nil)
{:source-info (select-keys (:env ast-node) [:file :ns :line :column :end-column :end-line])
:class-defs (unique class-defs)
:class-refs (unique class-refs)
:var-defs (unique var-defs)
:var-refs (unique var-refs)
:shadow? false})))
(def +analysis-cache-file+ ".sniper-analysis-cache.clj")
(defonce +analysis-cache+
(atom (try (read-string (slurp +analysis-cache-file+)) (catch Exception e {}))))
(defn cached-ns-forms
[ns]
(let [c (slurp (jvm-utils/ns-url ns))]
(or (@+analysis-cache+ c)
(let [res (vec (keep normalized-form (analyze-ns ns)))]
(swap! +analysis-cache+ assoc c res)
res))))
(s/defn ns-forms :- [sniper/Form]
"Get a flat sequence of forms for all namespaces in nss."
[& nss :- [clojure.lang.Symbol]]
(apply concat (pmap cached-ns-forms nss)))
(defn classpath-namespaces [dir-regex]
"Get a sequence of all namespaces on classpath that match dir-regex."
(->> (classpath/classpath)
(mapcat file-seq)
distinct
(filter (fn [^java.io.File f]
(and (.isDirectory f)
(re-find dir-regex (.getPath f)))))
(mapcat #(namespace-find/find-namespaces-in-dir %))
distinct
sort))
(s/defn classpath-ns-forms :- [sniper/Form]
[dir-regex]
"Get a flat sequence of forms for all namespaces on the classpath matching
dir-regex."
(let [nss (classpath-namespaces dir-regex)]
(println "Requiring" nss)
(apply require nss)
(let [res (apply ns-forms nss)]
(future (spit +analysis-cache-file+ @+analysis-cache+))
res)))
|
c563318325dce187eb8601b69083158100eb586a13a2a0ff7c80402ac94c2900 | bmeurer/ocamljit2 | multimatch.ml | (* Simple example *)
let f x =
(multimatch x with `A -> 1 | `B -> true),
(multimatch x with `A -> 1. | `B -> "1");;
(* OK *)
module M : sig
val f :
[< `A & 'a = int & 'b = float | `B & 'b =string & 'a = bool] -> 'a * 'b
end = struct let f = f end;;
(* Bad *)
module M : sig
val f :
[< `A & 'a = int & 'b = float | `B & 'b =string & 'a = int] -> 'a * 'b
end = struct let f = f end;;
(* Should be good! *)
module M : sig
val f :
[< `A & 'a = int * float | `B & 'a = bool * string] -> 'a
end = struct let f = f end;;
let f = multifun `A|`B as x -> f x;;
Two - level example
let f = multifun
`A -> (multifun `C -> 1 | `D -> 1.)
| `B -> (multifun `C -> true | `D -> "1");;
(* OK *)
module M : sig
val f :
[< `A & 'b = [< `C & 'a = int | `D & 'a = float & 'c = bool] -> 'a
| `B & 'b = [< `C & 'c = bool | `D & 'c = string] -> 'c] -> 'b
end = struct let f = f end;;
(* Bad *)
module M : sig
val f :
[< `A & 'b = [< `C & 'a = int | `D & 'a = bool] -> 'a
| `B & 'b = [< `C & 'c = bool | `D & 'c = string] -> 'c] -> 'b
end = struct let f = f end;;
module M : sig
val f :
[< `A & 'b = [< `C & 'a = int | `D] -> 'a
| `B & 'b = [< `C & 'c = bool | `D & 'c = string] -> 'c] -> 'b
end = struct let f = f end;;
(* Examples with hidden sharing *)
let r = ref []
let f = multifun `A -> 1 | `B -> true
let g x = r := [f x];;
(* Bad! *)
module M : sig
val g : [< `A & 'a = int | `B & 'a = bool] -> unit
end = struct let g = g end;;
let r = ref []
let f = multifun `A -> r | `B -> ref [];;
(* Now OK *)
module M : sig
val f : [< `A & 'b = int list ref | `B & 'b = 'c list ref] -> 'b
end = struct let f = f end;;
(* Still OK *)
let l : int list ref = r;;
module M : sig
val f : [< `A & 'b = int list ref | `B & 'b = 'c list ref] -> 'b
end = struct let f = f end;;
(* Examples that would need unification *)
let f = multifun `A -> (1, []) | `B -> (true, [])
let g x = fst (f x);;
(* Didn't work, now Ok *)
module M : sig
val g : [< `A & 'a * 'b = int * bool | `B & 'a * 'b = bool * int] -> 'a
end = struct let g = g end;;
let g = multifun (`A|`B) as x -> g x;;
(* Other examples *)
let f x =
let a = multimatch x with `A -> 1 | `B -> "1" in
(multifun `A -> print_int | `B -> print_string) x a
;;
let f = multifun (`A|`B) as x -> f x;;
type unit_op = [`Set of int | `Move of int]
type int_op = [`Get]
let op r =
multifun
`Get -> !r
| `Set x -> r := x
| `Move dx -> r := !r + dx
;;
let rec trace r = function
[] -> []
| op1 :: ops ->
multimatch op1 with
#int_op as op1 ->
let x = op r op1 in
x :: trace r ops
| #unit_op as op1 ->
op r op1;
trace r ops
;;
class point x = object
val mutable x : int = x
method get = x
method set y = x <- y
method move dx = x <- x + dx
end;;
let poly sort coeffs x =
let add, mul, zero =
multimatch sort with
`Int -> (+), ( * ), 0
| `Float -> (+.), ( *. ), 0.
in
let rec compute = function
[] -> zero
| c :: cs -> add c (mul x (compute cs))
in
compute coeffs
;;
module M : sig
val poly : [< `Int & 'a = int | `Float & 'a = float] -> 'a list -> 'a -> 'a
end = struct let poly = poly end;;
type ('a,'b) num_sort =
'b constraint 'b = [< `Int & 'a = int | `Float & 'a = float]
module M : sig
val poly : ('a,_) num_sort -> 'a list -> 'a -> 'a
end = struct let poly = poly end;;
(* type dispatch *)
type num = [ `Int | `Float ]
let print0 = multifun
`Int -> print_int
| `Float -> print_float
;;
let print1 = multifun
#num as x -> print0 x
| `List t -> List.iter (print0 t)
| `Pair(t1,t2) -> (fun (x,y) -> print0 t1 x; print0 t2 y)
;;
print1 (`Pair(`Int,`Float)) (1,1.0);;
| null | https://raw.githubusercontent.com/bmeurer/ocamljit2/ef06db5c688c1160acc1de1f63c29473bcd0055c/testlabl/multimatch.ml | ocaml | Simple example
OK
Bad
Should be good!
OK
Bad
Examples with hidden sharing
Bad!
Now OK
Still OK
Examples that would need unification
Didn't work, now Ok
Other examples
type dispatch | let f x =
(multimatch x with `A -> 1 | `B -> true),
(multimatch x with `A -> 1. | `B -> "1");;
module M : sig
val f :
[< `A & 'a = int & 'b = float | `B & 'b =string & 'a = bool] -> 'a * 'b
end = struct let f = f end;;
module M : sig
val f :
[< `A & 'a = int & 'b = float | `B & 'b =string & 'a = int] -> 'a * 'b
end = struct let f = f end;;
module M : sig
val f :
[< `A & 'a = int * float | `B & 'a = bool * string] -> 'a
end = struct let f = f end;;
let f = multifun `A|`B as x -> f x;;
Two - level example
let f = multifun
`A -> (multifun `C -> 1 | `D -> 1.)
| `B -> (multifun `C -> true | `D -> "1");;
module M : sig
val f :
[< `A & 'b = [< `C & 'a = int | `D & 'a = float & 'c = bool] -> 'a
| `B & 'b = [< `C & 'c = bool | `D & 'c = string] -> 'c] -> 'b
end = struct let f = f end;;
module M : sig
val f :
[< `A & 'b = [< `C & 'a = int | `D & 'a = bool] -> 'a
| `B & 'b = [< `C & 'c = bool | `D & 'c = string] -> 'c] -> 'b
end = struct let f = f end;;
module M : sig
val f :
[< `A & 'b = [< `C & 'a = int | `D] -> 'a
| `B & 'b = [< `C & 'c = bool | `D & 'c = string] -> 'c] -> 'b
end = struct let f = f end;;
let r = ref []
let f = multifun `A -> 1 | `B -> true
let g x = r := [f x];;
module M : sig
val g : [< `A & 'a = int | `B & 'a = bool] -> unit
end = struct let g = g end;;
let r = ref []
let f = multifun `A -> r | `B -> ref [];;
module M : sig
val f : [< `A & 'b = int list ref | `B & 'b = 'c list ref] -> 'b
end = struct let f = f end;;
let l : int list ref = r;;
module M : sig
val f : [< `A & 'b = int list ref | `B & 'b = 'c list ref] -> 'b
end = struct let f = f end;;
let f = multifun `A -> (1, []) | `B -> (true, [])
let g x = fst (f x);;
module M : sig
val g : [< `A & 'a * 'b = int * bool | `B & 'a * 'b = bool * int] -> 'a
end = struct let g = g end;;
let g = multifun (`A|`B) as x -> g x;;
let f x =
let a = multimatch x with `A -> 1 | `B -> "1" in
(multifun `A -> print_int | `B -> print_string) x a
;;
let f = multifun (`A|`B) as x -> f x;;
type unit_op = [`Set of int | `Move of int]
type int_op = [`Get]
let op r =
multifun
`Get -> !r
| `Set x -> r := x
| `Move dx -> r := !r + dx
;;
let rec trace r = function
[] -> []
| op1 :: ops ->
multimatch op1 with
#int_op as op1 ->
let x = op r op1 in
x :: trace r ops
| #unit_op as op1 ->
op r op1;
trace r ops
;;
class point x = object
val mutable x : int = x
method get = x
method set y = x <- y
method move dx = x <- x + dx
end;;
let poly sort coeffs x =
let add, mul, zero =
multimatch sort with
`Int -> (+), ( * ), 0
| `Float -> (+.), ( *. ), 0.
in
let rec compute = function
[] -> zero
| c :: cs -> add c (mul x (compute cs))
in
compute coeffs
;;
module M : sig
val poly : [< `Int & 'a = int | `Float & 'a = float] -> 'a list -> 'a -> 'a
end = struct let poly = poly end;;
type ('a,'b) num_sort =
'b constraint 'b = [< `Int & 'a = int | `Float & 'a = float]
module M : sig
val poly : ('a,_) num_sort -> 'a list -> 'a -> 'a
end = struct let poly = poly end;;
type num = [ `Int | `Float ]
let print0 = multifun
`Int -> print_int
| `Float -> print_float
;;
let print1 = multifun
#num as x -> print0 x
| `List t -> List.iter (print0 t)
| `Pair(t1,t2) -> (fun (x,y) -> print0 t1 x; print0 t2 y)
;;
print1 (`Pair(`Int,`Float)) (1,1.0);;
|
ec7b882f907af1bfd1df93fc60f612e6c040a2faa463e7f5a2be3608da9fc6ff | jumarko/clojure-experiments | day-03.clj | (ns clojure-experiments.advent-of-code.advent-2020.day-03
"
Input: "
(:require [clojure-experiments.advent-of-code.advent-2020.utils :refer [read-input]]
[clojure.string :as str]))
(def sample-input
(->
"..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#
"
(str/split #"\n")))
(def test-input (read-input 3 identity))
;; ... but computing indices using module is much simpler
(defn valid-positions
"Given current position computes next position after moving
`right` steps to the right and `down` steps down."
[a-map [right down :as _slope]]
(let [map-height (count a-map)
map-width (count (first a-map))]
(->> [0 0]
(iterate (fn [[x y]]
[(+ x down)
(rem (+ y right) map-width)])) (take-while (fn [[x y]] ;; until we reach the bommot-most row on our map
(< x map-height))))))
(valid-positions sample-input [3 1])
= > ( [ 0 0 ] [ 1 3 ] [ 2 6 ] [ 3 9 ] [ 4 1 ] [ 5 4 ] [ 6 7 ] [ 7 10 ] [ 8 2 ] [ 9 5 ] [ 10 8 ] )
(defn count-trees [a-map slope]
(->> (valid-positions a-map slope)
(map (fn [coords] (get-in a-map coords)))
(filter #{\#})
count))
(count-trees sample-input [3 1])
= > 7
(count-trees test-input [3 1])
= > 292
(comment
(valid-positions test-input [3 1])
(map #(get-in test-input %) (valid-positions test-input [3 1])))
Part 2 - multiply number of steps using each of given slopes
(def slopes [[1 1] [3 1] [5 1] [7 1] [1 2]])
(map #(count-trees test-input %)
slopes)
= > ( 81 292 89 101 44 )
(apply * (map #(count-trees test-input %)
slopes))
= > 9354744432
| null | https://raw.githubusercontent.com/jumarko/clojure-experiments/f0f9c091959e7f54c3fb13d0585a793ebb09e4f9/src/clojure_experiments/advent_of_code/advent_2020/day-03.clj | clojure | ... but computing indices using module is much simpler
until we reach the bommot-most row on our map | (ns clojure-experiments.advent-of-code.advent-2020.day-03
"
Input: "
(:require [clojure-experiments.advent-of-code.advent-2020.utils :refer [read-input]]
[clojure.string :as str]))
(def sample-input
(->
"..##.......
#...#...#..
.#....#..#.
..#.#...#.#
.#...##..#.
..#.##.....
.#.#.#....#
.#........#
#.##...#...
#...##....#
.#..#...#.#
"
(str/split #"\n")))
(def test-input (read-input 3 identity))
(defn valid-positions
"Given current position computes next position after moving
`right` steps to the right and `down` steps down."
[a-map [right down :as _slope]]
(let [map-height (count a-map)
map-width (count (first a-map))]
(->> [0 0]
(iterate (fn [[x y]]
[(+ x down)
(< x map-height))))))
(valid-positions sample-input [3 1])
= > ( [ 0 0 ] [ 1 3 ] [ 2 6 ] [ 3 9 ] [ 4 1 ] [ 5 4 ] [ 6 7 ] [ 7 10 ] [ 8 2 ] [ 9 5 ] [ 10 8 ] )
(defn count-trees [a-map slope]
(->> (valid-positions a-map slope)
(map (fn [coords] (get-in a-map coords)))
(filter #{\#})
count))
(count-trees sample-input [3 1])
= > 7
(count-trees test-input [3 1])
= > 292
(comment
(valid-positions test-input [3 1])
(map #(get-in test-input %) (valid-positions test-input [3 1])))
Part 2 - multiply number of steps using each of given slopes
(def slopes [[1 1] [3 1] [5 1] [7 1] [1 2]])
(map #(count-trees test-input %)
slopes)
= > ( 81 292 89 101 44 )
(apply * (map #(count-trees test-input %)
slopes))
= > 9354744432
|
0c0abaf726801aceccc8aa0cc7d1823a7f011dd57218ea15b101dc2fd5466a14 | Helium4Haskell/helium | SimilarFunction2.hs | module SimilarFunction2 where
keerPi :: Float -> Float
keerPi x = pi * x
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/simple/typeerrors/Heuristics/SimilarFunction2.hs | haskell | module SimilarFunction2 where
keerPi :: Float -> Float
keerPi x = pi * x
| |
68e742c912316a282c08606a24750ba771493b4ed73237ef5faf8d7b779118d3 | didierverna/declt | package.lisp | package.lisp --- Declt package definition
Copyright ( C ) 2010 - 2013 , 2015 , 2017 , 2021 , 2022
Author : < >
This file is part of Declt .
;; 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.
THIS 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.
;;; Commentary:
;;; Code:
(in-package :cl-user)
(defpackage :net.didierverna.declt
(:documentation "The Declt library's package.")
(:use :cl :net.didierverna.declt.setup :net.didierverna.declt.assess)
(:export
;; From the :net.didierverna.declt.setup package:
;; - setup/src/version.lisp:
:*copyright-years*
:*release-major-level*
:*release-minor-level*
:*release-status*
:*release-status-level*
:*release-name*
:version
From the : net.didierverna.declt.assess package :
;; - assess/src/definition.lisp:
:definition :uid :source-file :foreignp
:name :docstring :public-definitions :private-definitions
;; - assess/src/symbol.lisp:
:symbol-definition :definition-symbol :home-package
:symbol-definition-p :publicp
:varoid-definition
:variable-definition :constant-definition :special-definition
:symbol-macro-definition
:funcoid-definition :funcoid :setfp :lambda-list
:setfable-funcoid-definition :expander-for :expanders-to
:accessor-mixin :target-slot
:macro-definition :macro
:compiler-macro-definition :definition-compiler-macro
:type-definition :expander
:expander-definition :expander :standalone-reader
:short-expander-definition :standalone-writer :short-expander-definition-p
:long-expander-definition
:function-definition :definition-function
:ordinary-function-definition
:ordinary-accessor-definition
:ordinary-reader-definition :ordinary-writer-definition
:generic-function-definition :generic :methods
:combination :combination-options
:generic-accessor-definition
:generic-reader-definition :generic-writer-definition
:combination-definition :combination :clients
:short-combination-definition :standalone-combinator
:identity-with-one-argument
:long-combination-definition
:method-definition :definition-method :owner :specializers
:method-definition-p :qualifiers
:accessor-method-definition
:reader-method-definition :reader-method-definition-p
:writer-method-definition :writer-method-definition-p
:classoid-definition :classoid :direct-slots
:clos-classoid-mixin :direct-superclassoids :direct-subclassoids
:direct-methods :direct-default-initargs
:condition-definition :definition-condition
:direct-superconditions :direct-subconditions
:class-definition :definition-class :direct-superclasses :direct-subclasses
:structure-definition :definition-structure
:clos-structure-definition :direct-superstructures :direct-substructures
:typed-structure-definition :structure-type :element-type
:slot-definition :slot :owner :readers :writers :value-type
:clos-slot-definition :allocation :initform :initargs
:typed-structure-slot-definition
:alias-definition :setfp :referee
:macro-alias-definition
:compiler-macro-alias-definition
:function-alias-definition
;; - assess/src/package.lisp:
:package-definition :definition-package
:use-list :used-by-list :definitions :nicknames
:package-definition-p
;; - assess/src/asdf.lisp:
:component-definition :component :location :parent :dependencies
:component-definition-p
:description :long-description :definition-version :if-feature
:file-definition :file :file-definition-p :extension
:source-file-definition
:lisp-file-definition :definitions :lisp-file-definition-p
:c-file-definition
:java-file-definition
:static-file-definition
:doc-file-definition
:html-file-definition
:cl-source-file.asd
:system-file-definition
:module-definition :module :children :module-definition-p
:system-definition :system :maintainers :authors :defsystem-dependencies
:system-definition-p
:long-name :mailto :homepage :source-control :bug-tracker :license-name
;; - assess/src/assess.lisp:
:report :system-name :library-name :tagline :library-version :contacts
:copyright-years :license
:introduction :conclusion
:definitions
:assess
From package.lisp ( this file ):
:nickname-package
;; From src/declt.lisp:
:declt))
(in-package :net.didierverna.declt)
(defun nickname-package (&optional (nickname :declt))
"Add NICKNAME (:DECLT by default) to the :NET.DIDIERVERNA.DECLT package."
(rename-package :net.didierverna.declt
(package-name :net.didierverna.declt)
(adjoin nickname (package-nicknames :net.didierverna.declt)
:test #'string-equal)))
;;; package.lisp ends here
| null | https://raw.githubusercontent.com/didierverna/declt/2b81350102d78b8122be908b8619f43fbf87da57/core/package.lisp | lisp | 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.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
Commentary:
Code:
From the :net.didierverna.declt.setup package:
- setup/src/version.lisp:
- assess/src/definition.lisp:
- assess/src/symbol.lisp:
- assess/src/package.lisp:
- assess/src/asdf.lisp:
- assess/src/assess.lisp:
From src/declt.lisp:
package.lisp ends here | package.lisp --- Declt package definition
Copyright ( C ) 2010 - 2013 , 2015 , 2017 , 2021 , 2022
Author : < >
This file is part of Declt .
THIS SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
(in-package :cl-user)
(defpackage :net.didierverna.declt
(:documentation "The Declt library's package.")
(:use :cl :net.didierverna.declt.setup :net.didierverna.declt.assess)
(:export
:*copyright-years*
:*release-major-level*
:*release-minor-level*
:*release-status*
:*release-status-level*
:*release-name*
:version
From the : net.didierverna.declt.assess package :
:definition :uid :source-file :foreignp
:name :docstring :public-definitions :private-definitions
:symbol-definition :definition-symbol :home-package
:symbol-definition-p :publicp
:varoid-definition
:variable-definition :constant-definition :special-definition
:symbol-macro-definition
:funcoid-definition :funcoid :setfp :lambda-list
:setfable-funcoid-definition :expander-for :expanders-to
:accessor-mixin :target-slot
:macro-definition :macro
:compiler-macro-definition :definition-compiler-macro
:type-definition :expander
:expander-definition :expander :standalone-reader
:short-expander-definition :standalone-writer :short-expander-definition-p
:long-expander-definition
:function-definition :definition-function
:ordinary-function-definition
:ordinary-accessor-definition
:ordinary-reader-definition :ordinary-writer-definition
:generic-function-definition :generic :methods
:combination :combination-options
:generic-accessor-definition
:generic-reader-definition :generic-writer-definition
:combination-definition :combination :clients
:short-combination-definition :standalone-combinator
:identity-with-one-argument
:long-combination-definition
:method-definition :definition-method :owner :specializers
:method-definition-p :qualifiers
:accessor-method-definition
:reader-method-definition :reader-method-definition-p
:writer-method-definition :writer-method-definition-p
:classoid-definition :classoid :direct-slots
:clos-classoid-mixin :direct-superclassoids :direct-subclassoids
:direct-methods :direct-default-initargs
:condition-definition :definition-condition
:direct-superconditions :direct-subconditions
:class-definition :definition-class :direct-superclasses :direct-subclasses
:structure-definition :definition-structure
:clos-structure-definition :direct-superstructures :direct-substructures
:typed-structure-definition :structure-type :element-type
:slot-definition :slot :owner :readers :writers :value-type
:clos-slot-definition :allocation :initform :initargs
:typed-structure-slot-definition
:alias-definition :setfp :referee
:macro-alias-definition
:compiler-macro-alias-definition
:function-alias-definition
:package-definition :definition-package
:use-list :used-by-list :definitions :nicknames
:package-definition-p
:component-definition :component :location :parent :dependencies
:component-definition-p
:description :long-description :definition-version :if-feature
:file-definition :file :file-definition-p :extension
:source-file-definition
:lisp-file-definition :definitions :lisp-file-definition-p
:c-file-definition
:java-file-definition
:static-file-definition
:doc-file-definition
:html-file-definition
:cl-source-file.asd
:system-file-definition
:module-definition :module :children :module-definition-p
:system-definition :system :maintainers :authors :defsystem-dependencies
:system-definition-p
:long-name :mailto :homepage :source-control :bug-tracker :license-name
:report :system-name :library-name :tagline :library-version :contacts
:copyright-years :license
:introduction :conclusion
:definitions
:assess
From package.lisp ( this file ):
:nickname-package
:declt))
(in-package :net.didierverna.declt)
(defun nickname-package (&optional (nickname :declt))
"Add NICKNAME (:DECLT by default) to the :NET.DIDIERVERNA.DECLT package."
(rename-package :net.didierverna.declt
(package-name :net.didierverna.declt)
(adjoin nickname (package-nicknames :net.didierverna.declt)
:test #'string-equal)))
|
26248cdcc41898431a05d5df75df57a83948201547109d048e085d60fcb5b062 | nikita-volkov/rerebase | STM.hs | module Control.Concurrent.STM
(
module Rebase.Control.Concurrent.STM
)
where
import Rebase.Control.Concurrent.STM
| null | https://raw.githubusercontent.com/nikita-volkov/rerebase/25895e6d8b0c515c912c509ad8dd8868780a74b6/library/Control/Concurrent/STM.hs | haskell | module Control.Concurrent.STM
(
module Rebase.Control.Concurrent.STM
)
where
import Rebase.Control.Concurrent.STM
| |
68f69e40e59aa927c3677f31b46c8a3b1d4473894e7badb4764a5d69746ea632 | csabahruska/jhc-components | Real.hs | module Jhc.Class.Real(Real(..),Integral(..),Fractional(..),Rational) where
import Jhc.Basics
import Jhc.Class.Num
import Jhc.Class.Ord
import Jhc.Enum
import Jhc.Inst.Num
import Jhc.Type.Float
infixl 7 /, `quot`, `rem`, `div`, `mod`
type Rational = Ratio Integer
class (Num a, Ord a) => Real a where
toRational :: a -> Rational
toDouble :: a -> Double
toDouble x = rationalToDouble (toRational x) where
rationalToDouble (x:%y) = fid x `divideDouble` fid y
foreign import primitive "FDiv" divideDouble :: Double -> Double -> Double
foreign import primitive "I2F" fid :: Integer -> Double
class (Real a, Enum a) => Integral a where
quot, rem :: a -> a -> a
div, mod :: a -> a -> a
quotRem, divMod :: a -> a -> (a,a)
toInteger :: a -> Integer
toInt :: a -> Int
-- Minimal complete definition:
-- quotRem, toInteger
n `quot` d = q where (q,r) = quotRem n d
n `rem` d = r where (q,r) = quotRem n d
n `div` d = q where (q,r) = divMod n d
n `mod` d = r where (q,r) = divMod n d
divMod n d = n `seq` d `seq` if signum r == - signum d then (q-1, r+d) else qr
where qr@(q,r) = quotRem n d
quotRem n d = (n `quot` d, n `rem` d)
toInteger x = toInteger (toInt x)
toInt x = toInt (toInteger x)
class (Num a) => Fractional a where
(/) :: a -> a -> a
recip :: a -> a
fromRational :: Rational -> a
fromDouble :: Double -> a
-- Minimal complete definition:
-- fromRational and (recip or (/))
recip x = 1 / x
x / y = x * recip y
x = fromRational ( doubleToRational x )
| null | https://raw.githubusercontent.com/csabahruska/jhc-components/a7dace481d017f5a83fbfc062bdd2d099133adf1/lib/jhc/Jhc/Class/Real.hs | haskell | Minimal complete definition:
quotRem, toInteger
Minimal complete definition:
fromRational and (recip or (/)) | module Jhc.Class.Real(Real(..),Integral(..),Fractional(..),Rational) where
import Jhc.Basics
import Jhc.Class.Num
import Jhc.Class.Ord
import Jhc.Enum
import Jhc.Inst.Num
import Jhc.Type.Float
infixl 7 /, `quot`, `rem`, `div`, `mod`
type Rational = Ratio Integer
class (Num a, Ord a) => Real a where
toRational :: a -> Rational
toDouble :: a -> Double
toDouble x = rationalToDouble (toRational x) where
rationalToDouble (x:%y) = fid x `divideDouble` fid y
foreign import primitive "FDiv" divideDouble :: Double -> Double -> Double
foreign import primitive "I2F" fid :: Integer -> Double
class (Real a, Enum a) => Integral a where
quot, rem :: a -> a -> a
div, mod :: a -> a -> a
quotRem, divMod :: a -> a -> (a,a)
toInteger :: a -> Integer
toInt :: a -> Int
n `quot` d = q where (q,r) = quotRem n d
n `rem` d = r where (q,r) = quotRem n d
n `div` d = q where (q,r) = divMod n d
n `mod` d = r where (q,r) = divMod n d
divMod n d = n `seq` d `seq` if signum r == - signum d then (q-1, r+d) else qr
where qr@(q,r) = quotRem n d
quotRem n d = (n `quot` d, n `rem` d)
toInteger x = toInteger (toInt x)
toInt x = toInt (toInteger x)
class (Num a) => Fractional a where
(/) :: a -> a -> a
recip :: a -> a
fromRational :: Rational -> a
fromDouble :: Double -> a
recip x = 1 / x
x / y = x * recip y
x = fromRational ( doubleToRational x )
|
3301e1e67c0a24f271664ef9f32892aa77602fb928f79cd20d04d07d67033703 | mdedwards/slippery-chicken | reeling-trains.lsp | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; File: reeling-trains.lsp
;;;
Class Hierarchy : None
;;;
Version : 1.0
;;;
;;; Project: slippery chicken (algorithmic composition)
;;;
;;; Purpose: Lisp example code to accompany trains.html
;;;
Author :
;;;
;;; Creation date: 1st December 2012
;;;
$ $ Last modified : 22:47:17 Fri May 17 2013 BST
;;;
SVN ID : $ I d : reeling-trains.lsp 3538 2013 - 05 - 18 08:29:15Z medward2 $
;;;
;;; ****
Licence : Copyright ( c ) 2012
;;;
;;; This file is part of slippery-chicken
;;;
;;; slippery-chicken 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.
;;;
;;; slippery-chicken 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 slippery-chicken; if not, write to the
Free Software Foundation , Inc. , 59 Temple Place , Suite
330 , Boston , MA 02111 - 1307 USA
;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; A function to place dynamics on random notes in the score
(defun place-dyns (event)
(when (equalp (start-time event) 0.0)
(random-rep 10 t))
(unless (is-rest event)
(when (> (random-rep 100) 67)
(setf (marks event)
(list (nth (random-rep 8) '(ppp pp p mp mf f ff fff)))))))
;; A function to place articulations (accent or staccato) on random notes in
;; the score
(defun place-arts (event)
(when (equalp (start-time event) 0.0)
(random-rep 10 t))
(unless (is-rest event)
(when (> (random-rep 100) 67)
(setf (marks event)
(list (nth (random-rep 5) '(a s)))))))
;; Disabling the chord function on the string instruments (no double-stops)
(loop for i in '(violin viola cello)
do
(set-slot 'chords
nil
i
+slippery-chicken-standard-instrument-palette+))
;; Changing the chord function for the piano instruments
(loop for i in '(piano piano-lh)
do
(set-slot 'chord-function
'chord-fun1
i
+slippery-chicken-standard-instrument-palette+))
(let* ((num-seqs 137) ; The number of sequences in the rthm-chain to be made
;; Defining the rthm-chain object
(rch
(make-rthm-chain
'test-rch
num-seqs
the 1 - beat fragments : 4 in total
(- s (s) (s) s -)
({ 3 (te) - te te - })
((e.) s))
(({ 3 (te) te (te) }) ; what we transition to
({ 3 - te (te) te - })
({ 3 (te) - te te - })
({ 3 (te) (te) te }))
the second transition
(- s e s -)
({ 3 te (tq) })
(s (e.)))
the third transition
(- s s s - (s))
((32) 32 (e.))
((q))))
the 2/4 bars : 4 total
((q) q)
((q) q)
((q) (s) e.))
(({ 3 te te +te te +te te }) ; what we transition to
(q - s e. -)
(q (s) e.)
(q (s) - s e -))
the second transition
((e) e +e e)
(q - s (e) s -)
((s) e. +s e.)))
the 3/4 bars : 4 total
(- e e - (e) e (q))
(- e. s - - +e e - (q))
(q (e.) s (q)))
(({ 3 (te) (te) te +te te +te } (q)) ; what we transition to
(- e. s - (q) (s) - s e -)
({ 3 te te +te } (q) q)
({ 3 - te +te te - } (e) e { 3 (te) (te) te }))
the second transition
(q +q (q))
(- e e - +q (q))
(s (e.) (q) (q)))))
;; The probabilty of rests or sounding notes in each passage
:activity-curve '(0 5 20 7 30 8 50 3 70 5 80 8 100 10)
;; The durations to be used for the inserted rests
:rests '(s e s q)
;; The durations to be used for the inserted rhythms
:sticking-rthms '(e h e. w s e h s)
;; The activity-curve for the sticking rhythms
:sticking-curve '(0 2 20 3 30 5 50 8 80 10 100 2)
;; The number of times each sticking rhythm is repeated
:sticking-repeats '(3 5 3 5 8)
;; The number of consecutive sequences that have the same
;; harmonic set
:harmonic-rthm-curve '(0 1 10 2 30 3 40 1 50 2 80 4 90 5 100 1)
The min and beat duration of bars generated ; beat taken from
;; the given time signature.
:split-data '(4 7)
The IDs for the original two players
:players '(fl cl))))
Adding new voices based on the content of the original two , these with
;; offsets however to avoid completely identical voices.
(add-voice rch '(1 fl) 'ob 1)
(add-voice rch '(1 cl) 'bn 1)
(add-voice rch '(1 fl) 'pnr 2)
(add-voice rch '(1 cl) 'pnl 2)
(add-voice rch '(1 fl) 'vn 3)
(add-voice rch '(1 fl) 'va 4)
(add-voice rch '(1 cl) 'vc 3)
(add-voice rch '(1 cl) 'vb 4)
;; Creating automatically generated pitch-seq palettes for the rthm-seqs made
(create-psps (palette rch))
;; A series of variables for the make-slippery-chicken function, starting
;; with the definition of the set-palette
(let* ((sp '((1 ((c3 cs3 d3 e3 fs3 g3 c4 cs4 e4 c5 gs5 cs6 d6
ds6)))
(2 ((b2 c3 fs3 gs3 ds4 e4 d5 ds5 cs6)))
(3 ((af2 f3 fs3 d4 e4 fs4 a4 d5 e5 c6 af6)))
(4 ((b2 c3 df3 f3 af3 c4 e4 d5 c6)))
(5 ((bf2 g3 e4 ef5 d6)))
(6 ((f3 ef4 a4 d5 e5 df6)))
(7 ((a2 b2 af3 f4 ef5 e5 c6)))
(8 ((e4 a4 c5 g5 af5 e6)))
(9 ((e4 df5 bf5)))
(10 ((b1 a2 g3 e4 df5 a5)))
(11 ((ef3 bf3 e4 b4 d5 f5 c6 ef6)))
(12 ((f3 df4 e4 b4 e5 f5 c6 g6)))
(13 ((e4 b4 df5)))
(14 ((d4 ef4 bf4)))
(15 ((df4 bf4 a5 fs6)))
(16 ((d4 ef4 f4 g4)))
(17 ((g1 bf1 fs2 af2 f3 fs3 e4)))
(18 ((ef1 df2 b2 a3 e4 f4 fs4 d5 a5 bf5)))
(19 ((e4 f4 g4 b4 c5 g5 af5 e6 f6)))
(20 ((bf3 b3 e4 f4 bf4)))
(21 ((e3 f3 df4 d4 ds4 f4 df5 d5 b5)))
(22 ((d3 g3 a3 e4 af4 ef5 df5)))
(23 ((g4 af4 df5 d5 af5 df6 d6)))
(24 ((af3 e4 a4 e5 bf5)))
(25 ((df2 a2 e3 ef4 d5 af5)))
(26 ((b2 ef3 df4 e4 c5 g5 ef6)))
(27 ((d1 a1 ef2 c3 a3 f4)))
(28 ((df3 g3 c4 df4 d4 e4)))
(29 ((c3 b3 e4 df5 b5)))
(30 ((ds1 ef2 b2 c3 g3 af3 d4 e4 b4 fs5 d6)))
(31 ((d1 ef2 a2 ef3 bf3 e4 d5 bf5 g6)))))
;; Creating the set-palette using the procession algorithm
(sm (procession (num-rthm-seqs rch) (length sp)))
;; Determining the high and low pitches for each instrument for each
;; harmonic set. Every time the same set occurs, the same instruments
;; will have the same limits.
(sls '((fl ((1 gs5 c7) (2 d5 c7) (3 e5 c7) (4 d5 c7) (5 ef5 c7)
(6 e5 c7) (7 ef5 c7) (8 g5 c7) (9 df5 c7) (10 df5 c7)
(11 d5 c7) (12 e5 c7) (13 df5 c7) (14 bf4 c7) (15 a5 c7)
(16 g4 c7) (17 e4 c7) (18 d5 c7) (19 g5 c7) (20 bf4 c7)
(21 df5 c7) (22 ef5 c7) (23 af5 c7) (24 e5 c7)
(25 d5 c7) (26 g5 c7) (27 f4 c7) (28 e4 c7) (29 df5 c7)
(30 fs5 c7) (31 d5 c7)))
(ob ((1 g4 a5) (2 g4 a5) (3 g4 a5) (4 g4 a5) (5 g4 a5)
(6 g4 a5) (7 g4 a5) (8 g4 a5) (9 g4 a5) (10 g4 a5)
(11 g4 a5) (12 g4 a5) (13 g4 a5) (14 g4 a5) (15 g4 a5)
(16 g4 a5) (17 e4 a5) (18 g4 a5) (19 g4 a5) (20 g4 a5)
(21 g4 a5) (22 g4 a5) (23 g4 a5) (24 g4 a5) (25 g4 a5)
(26 g4 a5) (27 f4 a5) (28 e4 a5) (29 g4 a5) (30 g4 a5)
(31 g4 a5)))
(cl ((1 b4 c6) (2 b4 c6) (3 b4 c6) (4 b4 c6) (5 b4 c6)
(6 b4 c6) (7 b4 c6) (8 b4 c6) (9 b4 c6) (10 b4 c6)
(11 b4 c6) (12 b4 c6) (13 b4 c6) (14 bf4 c6) (15 b4 c6)
(16 g4 c6) (17 e4 c6) (18 b4 c6) (19 b4 c6) (20 bf4 c6)
(21 b4 c6) (22 b4 c6) (23 b4 c6) (24 b4 c6) (25 b4 c6)
(26 b4 c6) (27 f4 c6) (28 e4 c6) (29 b4 c6) (30 b4 c6)
(31 b4 c6)))
(bn ((1 a2 d4) (2 a2 d4) (3 a2 d4) (4 a2 d4) (5 a2 d4)
(6 a2 d4) (7 a2 d4) (8 a2 e4) (9 a2 e4) (10 a2 d4)
(11 a2 d4) (12 a2 d4) (13 a2 e4) (14 a2 d4) (15 a2 d4)
(16 a2 d4) (17 a2 d4) (18 a2 d4) (19 a2 e4) (20 a2 d4)
(21 a2 d4) (22 a2 d4) (23 a2 g4) (24 a2 d4) (25 a2 d4)
(26 a2 d4) (27 a2 d4) (28 a2 d4) (29 a2 d4) (30 a2 d4)
(31 a2 d4)))
(vb ((1 c4 f6) (2 c4 f6) (3 c4 f6) (4 c4 f6) (5 c4 f6)
(6 c4 f6) (7 c4 f6) (8 c4 f6) (9 c4 f6) (10 c4 f6)
(11 c4 f6) (12 c4 f6) (13 c4 f6) (14 c4 f6) (15 c4 f6)
(16 c4 f6) (17 c4 f6) (18 c4 f6) (19 c4 f6) (20 c4 f6)
(21 c4 f6) (22 c4 f6) (23 c4 f6) (24 c4 f6) (25 c4 f6)
(26 c4 f6) (27 c4 f6) (28 c4 f6) (29 c4 f6) (30 c4 f6)
(31 c4 f6)))
(pnr ((1 c4 c8) (2 c4 c8) (3 c4 c8) (4 c4 c8) (5 c4 c8)
(6 c4 c8) (7 c4 c8) (8 g5 c8) (9 df5 c8) (10 c4 c8)
(11 c4 c8) (12 c4 c8) (13 b4 c8) (14 ef4 c8) (15 a5 c8)
(16 f4 c8) (17 f3 c8) (18 c4 c8) (19 c5 c8)
(20 e4 c8) (21 df5 c8) (22 c4 c8) (23 af5 c8) (24 a4 c8)
(25 c4 c8) (26 c4 c8) (27 a3 c8) (28 c4 c8) (29 c4 c8)
(30 c4 c8) (31 c4 c8)))
(pnl ((1 a0 b3) (2 a0 b3) (3 a0 b3) (4 a0 b3) (5 a0 b3)
(6 a0 b3) (7 a0 b3) (8 a0 c5) (9 a0 e4) (10 a0 b3)
(11 a0 b3) (12 a0 b3) (13 a0 e4) (14 a0 d4)
(15 a0 bf4) (16 a0 ef4) (17 a0 af2) (18 a0 b3)
(19 a0 b4) (20 a0 b3) (21 a0 ds4) (22 a0 b3) (23 a0 d5)
(24 a0 e4) (25 a0 b3) (26 a0 b3) (27 a0 c3) (28 a0 b3)
(29 a0 b3) (30 a0 b3) (31 a0 b3)))
(vn ((1 a4 c7) (2 a4 c7) (3 a4 c7) (4 a4 c7) (5 a4 c7)
(6 a4 c7) (7 a4 c7) (8 a4 c7) (9 a4 c7) (10 a4 c7)
(11 a4 c7) (12 a4 c7) (13 a4 c7) (14 a4 c7) (15 a4 c7)
(16 f4 c7) (17 e4 c7) (18 a4 c7) (19 a4 c7) (20 f4 c7)
(21 a4 c7) (22 a4 c7) (23 a4 c7) (24 a4 c7) (25 a4 c7)
(26 a4 c7) (27 a3 c7) (28 d4 c7) (29 a4 c7) (30 a4 c7)
(31 a4 c7)))
(va ((1 g3 gs4) (2 g3 gs4) (3 g3 gs4) (4 g3 gs4) (5 g3 gs4)
(6 g3 gs4) (7 g3 gs4) (8 g3 gs4) (9 g3 gs4)
(10 g3 gs4) (11 g3 gs4) (12 g3 gs4) (13 g3 gs4)
(14 g3 gs4) (15 g3 gs4) (16 g3 gs4) (17 g3 gs4)
(18 g3 gs4) (19 g3 gs4) (20 g3 gs4) (21 g3 gs4)
(22 g3 gs4) (23 g3 gs4) (24 g3 gs4) (25 g3 gs4)
(26 g3 gs4) (27 g3 gs4) (28 g3 gs4) (29 g3 gs4)
(30 g3 gs4) (31 g3 gs4)))
(vc ((1 c2 fs3) (2 c2 fs3) (3 c2 fs3) (4 c2 fs3) (5 c2 fs3)
(6 c2 fs3) (7 c2 fs3) (8 c2 e4) (9 c2 e4)
(10 c2 fs3) (11 c2 fs3) (12 c2 fs3) (13 c2 e4)
(14 c2 d4) (15 c2 df4) (16 c2 d4) (17 c2 fs3)
(18 c2 fs3) (19 c2 e4) (20 c2 b3) (21 c2 fs3)
(22 c2 fs3) (23 c2 g4) (24 c2 af3) (25 c2 fs3)
(26 c2 fs3) (27 c2 fs3) (28 c2 fs3) (29 c2 fs3)
(30 c2 fs3) (31 c2 fs3)))))
;; Creating a list for just the low set-limits, with consecutive
;; integers as x-values so there are equal number of breakpoint pairs
;; as sets in the set-palette
(sll (loop for p in sls
collect
(list (first p)
(loop for s in sm
for i from 1
collect i
collect (second (nth (1- s) (second p)))))))
;; Creating a list for just the high set-limits, with consecutive
;; integers as x-values so there are equal number of breakpoint pairs
;; as sets in the set-palette
(slh (loop for p in sls
collect
(list (first p)
(loop for s in sm
for i from 1
collect i
collect (third (nth (1- s) (second p)))))))
;; Creating the sc object
(reeling-trains
(make-slippery-chicken
'+reeling-trains+
:title "reeling trains"
:ensemble '(((fl (flute :midi-channel 1))
(ob (oboe :midi-channel 2))
(cl (b-flat-clarinet :midi-channel 3))
(bn (bassoon :midi-channel 4))
(vb (vibraphone :midi-channel 5))
(pnr (piano :midi-channel 6))
(pnl (piano-lh :midi-channel 7))
(vn (violin :midi-channel 8))
(va (viola :midi-channel 9))
(vc (cello :midi-channel 11))))
:staff-groupings '(4 1 2 3)
:set-palette sp
:set-map `((1 ,sm))
:set-limits-low sll
:set-limits-high slh
:tempo-map '((1 (q 72)))
;; The rs palette and map can be taken directly from the rthm-chain
;; object.
:rthm-seq-palette (palette rch)
:rthm-seq-map rch)))
;; add random dynamics
(process-events-by-time reeling-trains #'place-dyns)
;; add random articulations
(process-events-by-time reeling-trains #'place-arts)
;; remove repeated dynamics
(remove-extraneous-dynamics reeling-trains)
;; remove specific marks
(loop for pm in '((1 1 (cl bn vb pnr pnl vc) s) (2 1 vc ppp)
(2 2 (vn vc) s) (2 3 vc ff) (3 1 va p) (3 2 (ob va) s)
(3 2 vc fff) (5 3 ob f) (5 2 vn mf) (6 3 bn p) (8 4 ob s)
(9 1 fl s) (12 1 vn s) (17 1 ob ff) (17 2 fl ppp)
(19 3 vc mf) (20 2 cl s) (26 2 vn s) (26 2 va p)
(27 1 bn p) (27 2 va s) (28 3 ob ff) (35 1 vn s)
(38 2 bn fff) (42 2 vc f) (44 1 bn s) (47 2 ob mp)
(47 3 bn ppp) (51 1 pnr s) (53 1 (fl vb) s)
(53 2 (vb vc) s) (53 2 pnl mf) (54 2 vn s) (58 1 vc pp)
(61 1 bn s) (61 4 (ob pnr va) (mf fff ppp)) (62 1 ob s)
(62 2 va s) (63 2 va s) (65 1 pnr s) (66 1 ob pp)
(66 3 ob s) (66 3 fl s) (70 2 fl mf) (72 1 va p)
(73 2 vn s) (74 2 vn fff) (75 3 cl pp) (76 2 ob s)
(77 2 ob s) (85 1 bn s) (85 3 vb ff) (85 4 bn s)
(85 5 cl p) (85 5 bn a) (85 5 vc a)
(86 3 (bn vc) (pp fff)) (86 4 vc s) (86 5 vb f)
(87 2 ob s) (90 2 vb mf) (90 3 bn ff) (96 2 ob pp)
(97 1 fl pp) (98 4 vn mf) (100 1 ob mf) (101 1 fl p)
(101 1 vn s) (101 2 vn p) (102 1 vn s) (103 1 ob s)
(103 1 vc mf) (105 1 vn s) (105 1 vb mp) (106 2 va fff)
(106 2 vc s) (106 3 vb s) (106 3 vn f) (106 5 vb ff)
(106 5 pnl ff) (106 5 vc p) (110 2 vn s) (110 3 va s)
(110 3 vn mp) (110 2 va ppp) (111 2 ob fff)
(114 2 vn fff) (114 2 ob mp) (114 3 pnr ppp)
(116 3 vb mp) (118 2 pnr s) (118 2 vn mf) (120 2 va s)
(120 2 cl pp) (120 3 pnr mp) (125 3 fl f) (125 3 va p)
(125 3 va mp) (131 2 vn mf) (132 1 fl mp) (134 1 va ppp)
(137 1 vn s) (137 2 fl fff) (138 2 pnr p) (139 1 va mp)
(139 3 vn p) (142 2 vn s) (143 1 vn f) (144 1 pnr ff)
(151 3 ob f) (153 1 bn s) (156 1 pnl s) (156 2 bn fff)
(156 3 vb pp) (156 3 pnl fff) (156 3 va f) (156 5 vc a)
(156 6 vb mf) (158 3 pnr ff) (163 2 fl p) (163 2 vn mp)
(163 3 ob fff) (166 1 (fl va) (p mf)) (166 2 ob p)
(167 1 cl f) (169 3 ob mp) (170 2 vn mf) (172 3 pnr s)
(172 3 vn pp) (173 1 pnr s) (173 1 vb ff) (173 3 vn mp)
(175 4 pnr mf) (175 4 vn ff) (175 4 va p) (176 2 cl s)
(178 2 pnr pp) (178 2 va ff))
do
(rm-marks-from-notes reeling-trains
(first pm)
(second pm)
(third pm)
(fourth pm)))
;; add diminuendo marks
(loop for pdcr in '((pnr 2 2 4 1) (pnl 2 4 4 1) (vn 2 2 2 3) (bn 5 1 5 2)
(bn 14 1 14 2) (fl 17 1 18 1) (ob 26 1 27 2)
(fl 26 2 27 2) (ob 54 1 54 3) (vn 81 1 81 2)
(ob 103 1 103 2) (bn 102 2 103 2) (vb 102 2 103 2)
(va 107 1 107 2) (va 118 1 118 3) (va 169 1 169 3)
(vn 172 2 172 4) (va 176 1 176 2))
do
(add-mark-to-note reeling-trains
(second pdcr)
(third pdcr)
(first pdcr)
'dim-beg)
(add-mark-to-note reeling-trains
(fourth pdcr)
(fifth pdcr)
(first pdcr)
'dim-end))
;; add crescendo marks
(loop for pdcr in '((va 2 2 4 3) (va 10 1 10 3) (cl 14 1 14 2)
(va 17 2 18 1) (va 26 1 27 1) (fl 35 1 35 3)
(ob 48 1 48 3) (vb 53 1 53 3) (pnl 54 1 54 2)
(pnr 57 1 57 3) (fl 65 2 66 2) (bn 67 1 67 2)
(va 66 3 67 1) (fl 77 3 78 1) (va 83 1 83 2)
(fl 93 1 94 1) (va 93 2 94 1) (va 98 3 98 5)
(pnr 106 1 106 3) (ob 110 1 110 3) (fl 142 2 143 2)
(cl 145 1 145 3) (cl 164 1 164 2) (vb 170 1 170 2)
(vn 175 3 175 5) (vc 176 1 176 2))
do
(add-mark-to-note reeling-trains
(second pdcr)
(third pdcr)
(first pdcr)
'cresc-beg)
(add-mark-to-note reeling-trains
(fourth pdcr)
(fifth pdcr)
(first pdcr)
'cresc-end))
;; consolidate sounding durations
(map-over-bars reeling-trains 1 nil nil #'consolidate-notes)
make the first dynamic forte
(loop for p in '(fl ob cl bn vb pnr pnl vn va vc)
do
(add-mark-to-note reeling-trains 1 1 p 'f))
;; auto-slur
(auto-slur reeling-trains '(fl ob cl bn vb pnr pnl vn va vc)
:over-accents nil
:rm-staccatos nil)
;; output
(midi-play reeling-trains :midi-file "/tmp/reeling-trains.mid")
(cmn-display reeling-trains
:file "/tmp/reeling-trains.eps"
:size 14
:auto-clefs nil
:in-c t)
(write-lp-data-for-all reeling-trains
:auto-clefs nil
:in-c t)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
EOF
| null | https://raw.githubusercontent.com/mdedwards/slippery-chicken/c1c11fadcdb40cd869d5b29091ba5e53c5270e04/doc/examples/reeling-trains.lsp | lisp |
File: reeling-trains.lsp
Project: slippery chicken (algorithmic composition)
Purpose: Lisp example code to accompany trains.html
Creation date: 1st December 2012
****
This file is part of slippery-chicken
slippery-chicken is free software; you can redistribute it
and/or modify it under the terms of the GNU General
either version 3 of the License , or ( at your
option) any later version.
slippery-chicken 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.
License along with slippery-chicken; if not, write to the
A function to place dynamics on random notes in the score
A function to place articulations (accent or staccato) on random notes in
the score
Disabling the chord function on the string instruments (no double-stops)
Changing the chord function for the piano instruments
The number of sequences in the rthm-chain to be made
Defining the rthm-chain object
what we transition to
what we transition to
what we transition to
The probabilty of rests or sounding notes in each passage
The durations to be used for the inserted rests
The durations to be used for the inserted rhythms
The activity-curve for the sticking rhythms
The number of times each sticking rhythm is repeated
The number of consecutive sequences that have the same
harmonic set
beat taken from
the given time signature.
offsets however to avoid completely identical voices.
Creating automatically generated pitch-seq palettes for the rthm-seqs made
A series of variables for the make-slippery-chicken function, starting
with the definition of the set-palette
Creating the set-palette using the procession algorithm
Determining the high and low pitches for each instrument for each
harmonic set. Every time the same set occurs, the same instruments
will have the same limits.
Creating a list for just the low set-limits, with consecutive
integers as x-values so there are equal number of breakpoint pairs
as sets in the set-palette
Creating a list for just the high set-limits, with consecutive
integers as x-values so there are equal number of breakpoint pairs
as sets in the set-palette
Creating the sc object
The rs palette and map can be taken directly from the rthm-chain
object.
add random dynamics
add random articulations
remove repeated dynamics
remove specific marks
add diminuendo marks
add crescendo marks
consolidate sounding durations
auto-slur
output
| Class Hierarchy : None
Version : 1.0
Author :
$ $ Last modified : 22:47:17 Fri May 17 2013 BST
SVN ID : $ I d : reeling-trains.lsp 3538 2013 - 05 - 18 08:29:15Z medward2 $
Licence : Copyright ( c ) 2012
Public License as published by the Free Software
You should have received a copy of the GNU General Public
Free Software Foundation , Inc. , 59 Temple Place , Suite
330 , Boston , MA 02111 - 1307 USA
(defun place-dyns (event)
(when (equalp (start-time event) 0.0)
(random-rep 10 t))
(unless (is-rest event)
(when (> (random-rep 100) 67)
(setf (marks event)
(list (nth (random-rep 8) '(ppp pp p mp mf f ff fff)))))))
(defun place-arts (event)
(when (equalp (start-time event) 0.0)
(random-rep 10 t))
(unless (is-rest event)
(when (> (random-rep 100) 67)
(setf (marks event)
(list (nth (random-rep 5) '(a s)))))))
(loop for i in '(violin viola cello)
do
(set-slot 'chords
nil
i
+slippery-chicken-standard-instrument-palette+))
(loop for i in '(piano piano-lh)
do
(set-slot 'chord-function
'chord-fun1
i
+slippery-chicken-standard-instrument-palette+))
(rch
(make-rthm-chain
'test-rch
num-seqs
the 1 - beat fragments : 4 in total
(- s (s) (s) s -)
({ 3 (te) - te te - })
((e.) s))
({ 3 - te (te) te - })
({ 3 (te) - te te - })
({ 3 (te) (te) te }))
the second transition
(- s e s -)
({ 3 te (tq) })
(s (e.)))
the third transition
(- s s s - (s))
((32) 32 (e.))
((q))))
the 2/4 bars : 4 total
((q) q)
((q) q)
((q) (s) e.))
(q - s e. -)
(q (s) e.)
(q (s) - s e -))
the second transition
((e) e +e e)
(q - s (e) s -)
((s) e. +s e.)))
the 3/4 bars : 4 total
(- e e - (e) e (q))
(- e. s - - +e e - (q))
(q (e.) s (q)))
(- e. s - (q) (s) - s e -)
({ 3 te te +te } (q) q)
({ 3 - te +te te - } (e) e { 3 (te) (te) te }))
the second transition
(q +q (q))
(- e e - +q (q))
(s (e.) (q) (q)))))
:activity-curve '(0 5 20 7 30 8 50 3 70 5 80 8 100 10)
:rests '(s e s q)
:sticking-rthms '(e h e. w s e h s)
:sticking-curve '(0 2 20 3 30 5 50 8 80 10 100 2)
:sticking-repeats '(3 5 3 5 8)
:harmonic-rthm-curve '(0 1 10 2 30 3 40 1 50 2 80 4 90 5 100 1)
:split-data '(4 7)
The IDs for the original two players
:players '(fl cl))))
Adding new voices based on the content of the original two , these with
(add-voice rch '(1 fl) 'ob 1)
(add-voice rch '(1 cl) 'bn 1)
(add-voice rch '(1 fl) 'pnr 2)
(add-voice rch '(1 cl) 'pnl 2)
(add-voice rch '(1 fl) 'vn 3)
(add-voice rch '(1 fl) 'va 4)
(add-voice rch '(1 cl) 'vc 3)
(add-voice rch '(1 cl) 'vb 4)
(create-psps (palette rch))
(let* ((sp '((1 ((c3 cs3 d3 e3 fs3 g3 c4 cs4 e4 c5 gs5 cs6 d6
ds6)))
(2 ((b2 c3 fs3 gs3 ds4 e4 d5 ds5 cs6)))
(3 ((af2 f3 fs3 d4 e4 fs4 a4 d5 e5 c6 af6)))
(4 ((b2 c3 df3 f3 af3 c4 e4 d5 c6)))
(5 ((bf2 g3 e4 ef5 d6)))
(6 ((f3 ef4 a4 d5 e5 df6)))
(7 ((a2 b2 af3 f4 ef5 e5 c6)))
(8 ((e4 a4 c5 g5 af5 e6)))
(9 ((e4 df5 bf5)))
(10 ((b1 a2 g3 e4 df5 a5)))
(11 ((ef3 bf3 e4 b4 d5 f5 c6 ef6)))
(12 ((f3 df4 e4 b4 e5 f5 c6 g6)))
(13 ((e4 b4 df5)))
(14 ((d4 ef4 bf4)))
(15 ((df4 bf4 a5 fs6)))
(16 ((d4 ef4 f4 g4)))
(17 ((g1 bf1 fs2 af2 f3 fs3 e4)))
(18 ((ef1 df2 b2 a3 e4 f4 fs4 d5 a5 bf5)))
(19 ((e4 f4 g4 b4 c5 g5 af5 e6 f6)))
(20 ((bf3 b3 e4 f4 bf4)))
(21 ((e3 f3 df4 d4 ds4 f4 df5 d5 b5)))
(22 ((d3 g3 a3 e4 af4 ef5 df5)))
(23 ((g4 af4 df5 d5 af5 df6 d6)))
(24 ((af3 e4 a4 e5 bf5)))
(25 ((df2 a2 e3 ef4 d5 af5)))
(26 ((b2 ef3 df4 e4 c5 g5 ef6)))
(27 ((d1 a1 ef2 c3 a3 f4)))
(28 ((df3 g3 c4 df4 d4 e4)))
(29 ((c3 b3 e4 df5 b5)))
(30 ((ds1 ef2 b2 c3 g3 af3 d4 e4 b4 fs5 d6)))
(31 ((d1 ef2 a2 ef3 bf3 e4 d5 bf5 g6)))))
(sm (procession (num-rthm-seqs rch) (length sp)))
(sls '((fl ((1 gs5 c7) (2 d5 c7) (3 e5 c7) (4 d5 c7) (5 ef5 c7)
(6 e5 c7) (7 ef5 c7) (8 g5 c7) (9 df5 c7) (10 df5 c7)
(11 d5 c7) (12 e5 c7) (13 df5 c7) (14 bf4 c7) (15 a5 c7)
(16 g4 c7) (17 e4 c7) (18 d5 c7) (19 g5 c7) (20 bf4 c7)
(21 df5 c7) (22 ef5 c7) (23 af5 c7) (24 e5 c7)
(25 d5 c7) (26 g5 c7) (27 f4 c7) (28 e4 c7) (29 df5 c7)
(30 fs5 c7) (31 d5 c7)))
(ob ((1 g4 a5) (2 g4 a5) (3 g4 a5) (4 g4 a5) (5 g4 a5)
(6 g4 a5) (7 g4 a5) (8 g4 a5) (9 g4 a5) (10 g4 a5)
(11 g4 a5) (12 g4 a5) (13 g4 a5) (14 g4 a5) (15 g4 a5)
(16 g4 a5) (17 e4 a5) (18 g4 a5) (19 g4 a5) (20 g4 a5)
(21 g4 a5) (22 g4 a5) (23 g4 a5) (24 g4 a5) (25 g4 a5)
(26 g4 a5) (27 f4 a5) (28 e4 a5) (29 g4 a5) (30 g4 a5)
(31 g4 a5)))
(cl ((1 b4 c6) (2 b4 c6) (3 b4 c6) (4 b4 c6) (5 b4 c6)
(6 b4 c6) (7 b4 c6) (8 b4 c6) (9 b4 c6) (10 b4 c6)
(11 b4 c6) (12 b4 c6) (13 b4 c6) (14 bf4 c6) (15 b4 c6)
(16 g4 c6) (17 e4 c6) (18 b4 c6) (19 b4 c6) (20 bf4 c6)
(21 b4 c6) (22 b4 c6) (23 b4 c6) (24 b4 c6) (25 b4 c6)
(26 b4 c6) (27 f4 c6) (28 e4 c6) (29 b4 c6) (30 b4 c6)
(31 b4 c6)))
(bn ((1 a2 d4) (2 a2 d4) (3 a2 d4) (4 a2 d4) (5 a2 d4)
(6 a2 d4) (7 a2 d4) (8 a2 e4) (9 a2 e4) (10 a2 d4)
(11 a2 d4) (12 a2 d4) (13 a2 e4) (14 a2 d4) (15 a2 d4)
(16 a2 d4) (17 a2 d4) (18 a2 d4) (19 a2 e4) (20 a2 d4)
(21 a2 d4) (22 a2 d4) (23 a2 g4) (24 a2 d4) (25 a2 d4)
(26 a2 d4) (27 a2 d4) (28 a2 d4) (29 a2 d4) (30 a2 d4)
(31 a2 d4)))
(vb ((1 c4 f6) (2 c4 f6) (3 c4 f6) (4 c4 f6) (5 c4 f6)
(6 c4 f6) (7 c4 f6) (8 c4 f6) (9 c4 f6) (10 c4 f6)
(11 c4 f6) (12 c4 f6) (13 c4 f6) (14 c4 f6) (15 c4 f6)
(16 c4 f6) (17 c4 f6) (18 c4 f6) (19 c4 f6) (20 c4 f6)
(21 c4 f6) (22 c4 f6) (23 c4 f6) (24 c4 f6) (25 c4 f6)
(26 c4 f6) (27 c4 f6) (28 c4 f6) (29 c4 f6) (30 c4 f6)
(31 c4 f6)))
(pnr ((1 c4 c8) (2 c4 c8) (3 c4 c8) (4 c4 c8) (5 c4 c8)
(6 c4 c8) (7 c4 c8) (8 g5 c8) (9 df5 c8) (10 c4 c8)
(11 c4 c8) (12 c4 c8) (13 b4 c8) (14 ef4 c8) (15 a5 c8)
(16 f4 c8) (17 f3 c8) (18 c4 c8) (19 c5 c8)
(20 e4 c8) (21 df5 c8) (22 c4 c8) (23 af5 c8) (24 a4 c8)
(25 c4 c8) (26 c4 c8) (27 a3 c8) (28 c4 c8) (29 c4 c8)
(30 c4 c8) (31 c4 c8)))
(pnl ((1 a0 b3) (2 a0 b3) (3 a0 b3) (4 a0 b3) (5 a0 b3)
(6 a0 b3) (7 a0 b3) (8 a0 c5) (9 a0 e4) (10 a0 b3)
(11 a0 b3) (12 a0 b3) (13 a0 e4) (14 a0 d4)
(15 a0 bf4) (16 a0 ef4) (17 a0 af2) (18 a0 b3)
(19 a0 b4) (20 a0 b3) (21 a0 ds4) (22 a0 b3) (23 a0 d5)
(24 a0 e4) (25 a0 b3) (26 a0 b3) (27 a0 c3) (28 a0 b3)
(29 a0 b3) (30 a0 b3) (31 a0 b3)))
(vn ((1 a4 c7) (2 a4 c7) (3 a4 c7) (4 a4 c7) (5 a4 c7)
(6 a4 c7) (7 a4 c7) (8 a4 c7) (9 a4 c7) (10 a4 c7)
(11 a4 c7) (12 a4 c7) (13 a4 c7) (14 a4 c7) (15 a4 c7)
(16 f4 c7) (17 e4 c7) (18 a4 c7) (19 a4 c7) (20 f4 c7)
(21 a4 c7) (22 a4 c7) (23 a4 c7) (24 a4 c7) (25 a4 c7)
(26 a4 c7) (27 a3 c7) (28 d4 c7) (29 a4 c7) (30 a4 c7)
(31 a4 c7)))
(va ((1 g3 gs4) (2 g3 gs4) (3 g3 gs4) (4 g3 gs4) (5 g3 gs4)
(6 g3 gs4) (7 g3 gs4) (8 g3 gs4) (9 g3 gs4)
(10 g3 gs4) (11 g3 gs4) (12 g3 gs4) (13 g3 gs4)
(14 g3 gs4) (15 g3 gs4) (16 g3 gs4) (17 g3 gs4)
(18 g3 gs4) (19 g3 gs4) (20 g3 gs4) (21 g3 gs4)
(22 g3 gs4) (23 g3 gs4) (24 g3 gs4) (25 g3 gs4)
(26 g3 gs4) (27 g3 gs4) (28 g3 gs4) (29 g3 gs4)
(30 g3 gs4) (31 g3 gs4)))
(vc ((1 c2 fs3) (2 c2 fs3) (3 c2 fs3) (4 c2 fs3) (5 c2 fs3)
(6 c2 fs3) (7 c2 fs3) (8 c2 e4) (9 c2 e4)
(10 c2 fs3) (11 c2 fs3) (12 c2 fs3) (13 c2 e4)
(14 c2 d4) (15 c2 df4) (16 c2 d4) (17 c2 fs3)
(18 c2 fs3) (19 c2 e4) (20 c2 b3) (21 c2 fs3)
(22 c2 fs3) (23 c2 g4) (24 c2 af3) (25 c2 fs3)
(26 c2 fs3) (27 c2 fs3) (28 c2 fs3) (29 c2 fs3)
(30 c2 fs3) (31 c2 fs3)))))
(sll (loop for p in sls
collect
(list (first p)
(loop for s in sm
for i from 1
collect i
collect (second (nth (1- s) (second p)))))))
(slh (loop for p in sls
collect
(list (first p)
(loop for s in sm
for i from 1
collect i
collect (third (nth (1- s) (second p)))))))
(reeling-trains
(make-slippery-chicken
'+reeling-trains+
:title "reeling trains"
:ensemble '(((fl (flute :midi-channel 1))
(ob (oboe :midi-channel 2))
(cl (b-flat-clarinet :midi-channel 3))
(bn (bassoon :midi-channel 4))
(vb (vibraphone :midi-channel 5))
(pnr (piano :midi-channel 6))
(pnl (piano-lh :midi-channel 7))
(vn (violin :midi-channel 8))
(va (viola :midi-channel 9))
(vc (cello :midi-channel 11))))
:staff-groupings '(4 1 2 3)
:set-palette sp
:set-map `((1 ,sm))
:set-limits-low sll
:set-limits-high slh
:tempo-map '((1 (q 72)))
:rthm-seq-palette (palette rch)
:rthm-seq-map rch)))
(process-events-by-time reeling-trains #'place-dyns)
(process-events-by-time reeling-trains #'place-arts)
(remove-extraneous-dynamics reeling-trains)
(loop for pm in '((1 1 (cl bn vb pnr pnl vc) s) (2 1 vc ppp)
(2 2 (vn vc) s) (2 3 vc ff) (3 1 va p) (3 2 (ob va) s)
(3 2 vc fff) (5 3 ob f) (5 2 vn mf) (6 3 bn p) (8 4 ob s)
(9 1 fl s) (12 1 vn s) (17 1 ob ff) (17 2 fl ppp)
(19 3 vc mf) (20 2 cl s) (26 2 vn s) (26 2 va p)
(27 1 bn p) (27 2 va s) (28 3 ob ff) (35 1 vn s)
(38 2 bn fff) (42 2 vc f) (44 1 bn s) (47 2 ob mp)
(47 3 bn ppp) (51 1 pnr s) (53 1 (fl vb) s)
(53 2 (vb vc) s) (53 2 pnl mf) (54 2 vn s) (58 1 vc pp)
(61 1 bn s) (61 4 (ob pnr va) (mf fff ppp)) (62 1 ob s)
(62 2 va s) (63 2 va s) (65 1 pnr s) (66 1 ob pp)
(66 3 ob s) (66 3 fl s) (70 2 fl mf) (72 1 va p)
(73 2 vn s) (74 2 vn fff) (75 3 cl pp) (76 2 ob s)
(77 2 ob s) (85 1 bn s) (85 3 vb ff) (85 4 bn s)
(85 5 cl p) (85 5 bn a) (85 5 vc a)
(86 3 (bn vc) (pp fff)) (86 4 vc s) (86 5 vb f)
(87 2 ob s) (90 2 vb mf) (90 3 bn ff) (96 2 ob pp)
(97 1 fl pp) (98 4 vn mf) (100 1 ob mf) (101 1 fl p)
(101 1 vn s) (101 2 vn p) (102 1 vn s) (103 1 ob s)
(103 1 vc mf) (105 1 vn s) (105 1 vb mp) (106 2 va fff)
(106 2 vc s) (106 3 vb s) (106 3 vn f) (106 5 vb ff)
(106 5 pnl ff) (106 5 vc p) (110 2 vn s) (110 3 va s)
(110 3 vn mp) (110 2 va ppp) (111 2 ob fff)
(114 2 vn fff) (114 2 ob mp) (114 3 pnr ppp)
(116 3 vb mp) (118 2 pnr s) (118 2 vn mf) (120 2 va s)
(120 2 cl pp) (120 3 pnr mp) (125 3 fl f) (125 3 va p)
(125 3 va mp) (131 2 vn mf) (132 1 fl mp) (134 1 va ppp)
(137 1 vn s) (137 2 fl fff) (138 2 pnr p) (139 1 va mp)
(139 3 vn p) (142 2 vn s) (143 1 vn f) (144 1 pnr ff)
(151 3 ob f) (153 1 bn s) (156 1 pnl s) (156 2 bn fff)
(156 3 vb pp) (156 3 pnl fff) (156 3 va f) (156 5 vc a)
(156 6 vb mf) (158 3 pnr ff) (163 2 fl p) (163 2 vn mp)
(163 3 ob fff) (166 1 (fl va) (p mf)) (166 2 ob p)
(167 1 cl f) (169 3 ob mp) (170 2 vn mf) (172 3 pnr s)
(172 3 vn pp) (173 1 pnr s) (173 1 vb ff) (173 3 vn mp)
(175 4 pnr mf) (175 4 vn ff) (175 4 va p) (176 2 cl s)
(178 2 pnr pp) (178 2 va ff))
do
(rm-marks-from-notes reeling-trains
(first pm)
(second pm)
(third pm)
(fourth pm)))
(loop for pdcr in '((pnr 2 2 4 1) (pnl 2 4 4 1) (vn 2 2 2 3) (bn 5 1 5 2)
(bn 14 1 14 2) (fl 17 1 18 1) (ob 26 1 27 2)
(fl 26 2 27 2) (ob 54 1 54 3) (vn 81 1 81 2)
(ob 103 1 103 2) (bn 102 2 103 2) (vb 102 2 103 2)
(va 107 1 107 2) (va 118 1 118 3) (va 169 1 169 3)
(vn 172 2 172 4) (va 176 1 176 2))
do
(add-mark-to-note reeling-trains
(second pdcr)
(third pdcr)
(first pdcr)
'dim-beg)
(add-mark-to-note reeling-trains
(fourth pdcr)
(fifth pdcr)
(first pdcr)
'dim-end))
(loop for pdcr in '((va 2 2 4 3) (va 10 1 10 3) (cl 14 1 14 2)
(va 17 2 18 1) (va 26 1 27 1) (fl 35 1 35 3)
(ob 48 1 48 3) (vb 53 1 53 3) (pnl 54 1 54 2)
(pnr 57 1 57 3) (fl 65 2 66 2) (bn 67 1 67 2)
(va 66 3 67 1) (fl 77 3 78 1) (va 83 1 83 2)
(fl 93 1 94 1) (va 93 2 94 1) (va 98 3 98 5)
(pnr 106 1 106 3) (ob 110 1 110 3) (fl 142 2 143 2)
(cl 145 1 145 3) (cl 164 1 164 2) (vb 170 1 170 2)
(vn 175 3 175 5) (vc 176 1 176 2))
do
(add-mark-to-note reeling-trains
(second pdcr)
(third pdcr)
(first pdcr)
'cresc-beg)
(add-mark-to-note reeling-trains
(fourth pdcr)
(fifth pdcr)
(first pdcr)
'cresc-end))
(map-over-bars reeling-trains 1 nil nil #'consolidate-notes)
make the first dynamic forte
(loop for p in '(fl ob cl bn vb pnr pnl vn va vc)
do
(add-mark-to-note reeling-trains 1 1 p 'f))
(auto-slur reeling-trains '(fl ob cl bn vb pnr pnl vn va vc)
:over-accents nil
:rm-staccatos nil)
(midi-play reeling-trains :midi-file "/tmp/reeling-trains.mid")
(cmn-display reeling-trains
:file "/tmp/reeling-trains.eps"
:size 14
:auto-clefs nil
:in-c t)
(write-lp-data-for-all reeling-trains
:auto-clefs nil
:in-c t)))
EOF
|
f033efe8376c5d30b678300c9684fcfb3e1827678698439215829b9db8793db3 | uim/uim | hangul2.scm | ;;;
Copyright ( c ) 2003 - 2013 uim Project
;;;
;;; All rights reserved.
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
3 . Neither the name of authors nor the names of its contributors
;;; may be used to endorse or promote products derived from this software
;;; without specific prior written permission.
;;;
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
;;; ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
;;; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
;;; OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
;;; LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
;;; OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
;;; SUCH DAMAGE.
;;;;
(define hangul2-rule
'(
((("E" ))("ㄸ"))
((("E" "h" ))("또"))
((("E" "h" "d" ))("똥"))
((("E" "h" "f" ))("똘"))
((("E" "h" "k" ))("똬"))
((("E" "h" "k" "f" ))("똴"))
((("E" "h" "l" ))("뙤"))
((("E" "h" "l" "s" ))("뙨"))
((("E" "h" "o" ))("뙈"))
((("E" "h" "r" ))("똑"))
((("E" "h" "s" ))("똔"))
((("E" "j" ))("떠"))
((("E" "j" "T" ))("떴"))
((("E" "j" "a" ))("떰"))
((("E" "j" "d" ))("떵"))
((("E" "j" "f" ))("떨"))
((("E" "j" "f" "a" ))("떪"))
((("E" "j" "f" "q" ))("떫"))
((("E" "j" "g" ))("떻"))
((("E" "j" "q" ))("떱"))
((("E" "j" "r" ))("떡"))
((("E" "j" "s" ))("떤"))
((("E" "j" "t" ))("떳"))
((("E" "k" ))("따"))
((("E" "k" "T" ))("땄"))
((("E" "k" "a" ))("땀"))
((("E" "k" "d" ))("땅"))
((("E" "k" "f" ))("딸"))
((("E" "k" "g" ))("땋"))
((("E" "k" "q" ))("땁"))
((("E" "k" "r" ))("딱"))
((("E" "k" "s" ))("딴"))
((("E" "k" "t" ))("땃"))
((("E" "l" ))("띠"))
((("E" "l" "a" ))("띰"))
((("E" "l" "d" ))("띵"))
((("E" "l" "f" ))("띨"))
((("E" "l" "q" ))("띱"))
((("E" "l" "s" ))("띤"))
((("E" "l" "t" ))("띳"))
((("E" "m" ))("뜨"))
((("E" "m" "a" ))("뜸"))
((("E" "m" "e" ))("뜯"))
((("E" "m" "f" ))("뜰"))
((("E" "m" "l" ))("띄"))
((("E" "m" "l" "a" ))("띔"))
((("E" "m" "l" "f" ))("띌"))
((("E" "m" "l" "q" ))("띕"))
((("E" "m" "l" "s" ))("띈"))
((("E" "m" "q" ))("뜹"))
((("E" "m" "r" ))("뜩"))
((("E" "m" "s" ))("뜬"))
((("E" "m" "t" ))("뜻"))
((("E" "n" ))("뚜"))
((("E" "n" "a" ))("뚬"))
((("E" "n" "d" ))("뚱"))
((("E" "n" "f" ))("뚤"))
((("E" "n" "f" "g" ))("뚫"))
((("E" "n" "l" ))("뛰"))
((("E" "n" "l" "a" ))("뜀"))
((("E" "n" "l" "d" ))("뜅"))
((("E" "n" "l" "f" ))("뛸"))
((("E" "n" "l" "q" ))("뜁"))
((("E" "n" "l" "s" ))("뛴"))
((("E" "n" "p" ))("뛔"))
((("E" "n" "r" ))("뚝"))
((("E" "n" "s" ))("뚠"))
((("E" "o" ))("때"))
((("E" "o" "T" ))("땠"))
((("E" "o" "a" ))("땜"))
((("E" "o" "d" ))("땡"))
((("E" "o" "f" ))("땔"))
((("E" "o" "q" ))("땝"))
((("E" "o" "r" ))("땍"))
((("E" "o" "s" ))("땐"))
((("E" "o" "t" ))("땟"))
((("E" "p" ))("떼"))
((("E" "p" "T" ))("뗐"))
((("E" "p" "a" ))("뗌"))
((("E" "p" "d" ))("뗑"))
((("E" "p" "f" ))("뗄"))
((("E" "p" "q" ))("뗍"))
((("E" "p" "r" ))("떽"))
((("E" "p" "s" ))("뗀"))
((("E" "p" "t" ))("뗏"))
((("E" "u" ))("뗘"))
((("E" "u" "T" ))("뗬"))
((("H" "." ))("ㆍ"))
((("H" "." "l" ))("ㆎ"))
((("H" "D" ))("ㆀ"))
((("H" "G" ))("ㆅ"))
((("H" "Q" "d" ))("ㅹ"))
((("H" "S" ))("ㅥ"))
((("H" "T" ))("ㅿ"))
((("H" "a" "T" ))("ㅰ"))
((("H" "a" "d" ))("ㅱ"))
((("H" "a" "q" ))("ㅮ"))
((("H" "a" "t" ))("ㅯ"))
((("H" "b" "P" ))("ㆋ"))
((("H" "b" "l" ))("ㆌ"))
((("H" "b" "u" ))("ㆊ"))
((("H" "d" ))("ㆁ"))
((("H" "d" "T" ))("ㆃ"))
((("H" "d" "w" ))("ㆂ"))
((("H" "f" "G" ))("ㅭ"))
((("H" "f" "T" ))("ㅬ"))
((("H" "f" "e" ))("ㅪ"))
((("H" "f" "q" "t" ))("ㅫ"))
((("H" "f" "r" "t" ))("ㅩ"))
((("H" "g" ))("ㆆ"))
((("H" "q" "d" ))("ㅸ"))
((("H" "q" "e" ))("ㅳ"))
((("H" "q" "r" ))("ㅲ"))
((("H" "q" "t" "e" ))("ㅵ"))
((("H" "q" "t" "r" ))("ㅴ"))
((("H" "q" "w" ))("ㅶ"))
((("H" "q" "x" ))("ㅷ"))
((("H" "s" "T" ))("ㅨ"))
((("H" "s" "e" ))("ㅦ"))
((("H" "s" "t" ))("ㅧ"))
((("H" "t" "e" ))("ㅼ"))
((("H" "t" "q" ))("ㅽ"))
((("H" "t" "r" ))("ㅺ"))
((("H" "t" "s" ))("ㅻ"))
((("H" "t" "w" ))("ㅾ"))
((("H" "v" "d" ))("ㆄ"))
((("H" "y" "O" ))("ㆈ"))
((("H" "y" "i" ))("ㆇ"))
((("H" "y" "l" ))("ㆉ"))
((("O" ))("ㅒ"))
((("O" "T" ))("쟀"))
((("O" "a" ))("잼"))
((("O" "d" ))("쟁"))
((("O" "f" ))("잴"))
((("O" "q" ))("잽"))
((("O" "r" ))("잭"))
((("O" "s" ))("잰"))
((("O" "t" ))("잿"))
((("P" ))("ㅖ"))
((("Q" ))("ㅃ"))
((("Q" "b" ))("쀼"))
((("Q" "b" "d" ))("쁑"))
((("Q" "h" ))("뽀"))
((("Q" "h" "a" ))("뽐"))
((("Q" "h" "d" ))("뽕"))
((("Q" "h" "f" ))("뽈"))
((("Q" "h" "l" ))("뾔"))
((("Q" "h" "q" ))("뽑"))
((("Q" "h" "r" ))("뽁"))
((("Q" "h" "s" ))("뽄"))
((("Q" "i" ))("뺘"))
((("Q" "i" "a" ))("뺨"))
((("Q" "i" "r" ))("뺙"))
((("Q" "j" ))("뻐"))
((("Q" "j" "T" ))("뻤"))
((("Q" "j" "a" ))("뻠"))
((("Q" "j" "d" ))("뻥"))
((("Q" "j" "e" ))("뻗"))
((("Q" "j" "f" ))("뻘"))
((("Q" "j" "r" ))("뻑"))
((("Q" "j" "s" ))("뻔"))
((("Q" "j" "t" ))("뻣"))
((("Q" "k" ))("빠"))
((("Q" "k" "T" ))("빴"))
((("Q" "k" "a" ))("빰"))
((("Q" "k" "d" ))("빵"))
((("Q" "k" "f" ))("빨"))
((("Q" "k" "f" "a" ))("빪"))
((("Q" "k" "g" ))("빻"))
((("Q" "k" "q" ))("빱"))
((("Q" "k" "r" ))("빡"))
((("Q" "k" "s" ))("빤"))
((("Q" "k" "t" ))("빳"))
((("Q" "l" ))("삐"))
((("Q" "l" "a" ))("삠"))
((("Q" "l" "d" ))("삥"))
((("Q" "l" "f" ))("삘"))
((("Q" "l" "q" ))("삡"))
((("Q" "l" "r" ))("삑"))
((("Q" "l" "s" ))("삔"))
((("Q" "l" "t" ))("삣"))
((("Q" "m" ))("쁘"))
((("Q" "m" "a" ))("쁨"))
((("Q" "m" "f" ))("쁠"))
((("Q" "m" "q" ))("쁩"))
((("Q" "m" "s" ))("쁜"))
((("Q" "n" ))("뿌"))
((("Q" "n" "a" ))("뿜"))
((("Q" "n" "d" ))("뿡"))
((("Q" "n" "f" ))("뿔"))
((("Q" "n" "r" ))("뿍"))
((("Q" "n" "s" ))("뿐"))
((("Q" "n" "t" ))("뿟"))
((("Q" "o" ))("빼"))
((("Q" "o" "T" ))("뺐"))
((("Q" "o" "a" ))("뺌"))
((("Q" "o" "d" ))("뺑"))
((("Q" "o" "f" ))("뺄"))
((("Q" "o" "q" ))("뺍"))
((("Q" "o" "r" ))("빽"))
((("Q" "o" "s" ))("뺀"))
((("Q" "o" "t" ))("뺏"))
((("Q" "p" ))("뻬"))
((("Q" "p" "d" ))("뼁"))
((("Q" "u" ))("뼈"))
((("Q" "u" "T" ))("뼜"))
((("Q" "u" "a" ))("뼘"))
((("Q" "u" "d" ))("뼝"))
((("Q" "u" "q" ))("뼙"))
((("Q" "u" "r" ))("뼉"))
((("Q" "u" "t" ))("뼛"))
((("Q" "y" ))("뾰"))
((("Q" "y" "d" ))("뿅"))
((("R" ))("ㄲ"))
((("R" "P" ))("꼐"))
((("R" "b" ))("뀨"))
((("R" "h" ))("꼬"))
((("R" "h" "a" ))("꼼"))
((("R" "h" "c" ))("꽃"))
((("R" "h" "d" ))("꽁"))
((("R" "h" "f" ))("꼴"))
((("R" "h" "k" ))("꽈"))
((("R" "h" "k" "T" ))("꽜"))
((("R" "h" "k" "d" ))("꽝"))
((("R" "h" "k" "f" ))("꽐"))
((("R" "h" "k" "r" ))("꽉"))
((("R" "h" "l" ))("꾀"))
((("R" "h" "l" "a" ))("꾐"))
((("R" "h" "l" "d" ))("꾕"))
((("R" "h" "l" "f" ))("꾈"))
((("R" "h" "l" "q" ))("꾑"))
((("R" "h" "l" "s" ))("꾄"))
((("R" "h" "o" ))("꽤"))
((("R" "h" "o" "d" ))("꽹"))
((("R" "h" "o" "r" ))("꽥"))
((("R" "h" "q" ))("꼽"))
((("R" "h" "r" ))("꼭"))
((("R" "h" "s" ))("꼰"))
((("R" "h" "s" "g" ))("꼲"))
((("R" "h" "t" ))("꼿"))
((("R" "h" "w" ))("꽂"))
((("R" "i" ))("꺄"))
((("R" "i" "f" ))("꺌"))
((("R" "i" "r" ))("꺅"))
((("R" "j" ))("꺼"))
((("R" "j" "R" ))("꺾"))
((("R" "j" "T" ))("껐"))
((("R" "j" "a" ))("껌"))
((("R" "j" "d" ))("껑"))
((("R" "j" "f" ))("껄"))
((("R" "j" "q" ))("껍"))
((("R" "j" "r" ))("꺽"))
((("R" "j" "s" ))("껀"))
((("R" "j" "t" ))("껏"))
((("R" "k" ))("까"))
((("R" "k" "R" ))("깎"))
((("R" "k" "T" ))("깠"))
((("R" "k" "a" ))("깜"))
((("R" "k" "d" ))("깡"))
((("R" "k" "f" ))("깔"))
((("R" "k" "f" "a" ))("깖"))
((("R" "k" "q" ))("깝"))
((("R" "k" "r" ))("깍"))
((("R" "k" "s" ))("깐"))
((("R" "k" "t" ))("깟"))
((("R" "k" "x" ))("깥"))
((("R" "l" ))("끼"))
((("R" "l" "a" ))("낌"))
((("R" "l" "d" ))("낑"))
((("R" "l" "f" ))("낄"))
((("R" "l" "q" ))("낍"))
((("R" "l" "r" ))("끽"))
((("R" "l" "s" ))("낀"))
((("R" "l" "t" ))("낏"))
((("R" "m" ))("끄"))
((("R" "m" "a" ))("끔"))
((("R" "m" "d" ))("끙"))
((("R" "m" "f" ))("끌"))
((("R" "m" "f" "a" ))("끎"))
((("R" "m" "f" "g" ))("끓"))
((("R" "m" "q" ))("끕"))
((("R" "m" "r" ))("끅"))
((("R" "m" "s" ))("끈"))
((("R" "m" "s" "g" ))("끊"))
((("R" "m" "t" ))("끗"))
((("R" "m" "x" ))("끝"))
((("R" "n" ))("꾸"))
((("R" "n" "a" ))("꿈"))
((("R" "n" "d" ))("꿍"))
((("R" "n" "f" ))("꿀"))
((("R" "n" "f" "g" ))("꿇"))
((("R" "n" "j" ))("꿔"))
((("R" "n" "j" "T" ))("꿨"))
((("R" "n" "j" "d" ))("꿩"))
((("R" "n" "j" "f" ))("꿜"))
((("R" "n" "l" ))("뀌"))
((("R" "n" "l" "a" ))("뀜"))
((("R" "n" "l" "f" ))("뀔"))
((("R" "n" "l" "q" ))("뀝"))
((("R" "n" "l" "s" ))("뀐"))
((("R" "n" "p" ))("꿰"))
((("R" "n" "p" "T" ))("뀄"))
((("R" "n" "p" "a" ))("뀀"))
((("R" "n" "p" "f" ))("꿸"))
((("R" "n" "p" "q" ))("뀁"))
((("R" "n" "p" "r" ))("꿱"))
((("R" "n" "p" "s" ))("꿴"))
((("R" "n" "q" ))("꿉"))
((("R" "n" "r" ))("꾹"))
((("R" "n" "s" ))("꾼"))
((("R" "n" "t" ))("꿋"))
((("R" "n" "w" ))("꿎"))
((("R" "o" ))("깨"))
((("R" "o" "T" ))("깼"))
((("R" "o" "a" ))("깸"))
((("R" "o" "d" ))("깽"))
((("R" "o" "f" ))("깰"))
((("R" "o" "q" ))("깹"))
((("R" "o" "r" ))("깩"))
((("R" "o" "s" ))("깬"))
((("R" "o" "t" ))("깻"))
((("R" "p" ))("께"))
((("R" "p" "a" ))("껨"))
((("R" "p" "d" ))("껭"))
((("R" "p" "r" ))("껙"))
((("R" "p" "s" ))("껜"))
((("R" "p" "t" ))("껫"))
((("R" "u" ))("껴"))
((("R" "u" "T" ))("꼈"))
((("R" "u" "f" ))("껼"))
((("R" "u" "s" ))("껸"))
((("R" "u" "t" ))("꼇"))
((("R" "u" "x" ))("꼍"))
((("R" "y" ))("꾜"))
((("S" "%" ))("‰"))
((("S" "A" ))("Å"))
((("S" "C" ))("℃"))
((("S" "C" "/" ))("¢"))
((("S" "C" "o" ))("㏇"))
((("S" "F" ))("℉"))
((("S" "N" "o" ))("№"))
((("S" "P" ))("£"))
((("S" "T" "M" ))("™"))
((("S" "T" "e" "l" ))("℡"))
((("S" "W" ))("₩"))
((("S" "Y" ))("¥"))
((("S" "a" "m" ))("㏂"))
((("S" "k" "s" ))("㉿"))
((("S" "p" "m" ))("㏘"))
((("S" "w" "n" ))("㈜"))
((("T" ))("ㅆ"))
((("T" "P" "s" ))("쏀"))
((("T" "b" "d" ))("쓩"))
((("T" "h" ))("쏘"))
((("T" "h" "a" ))("쏨"))
((("T" "h" "d" ))("쏭"))
((("T" "h" "e" ))("쏟"))
((("T" "h" "f" ))("쏠"))
((("T" "h" "f" "a" ))("쏢"))
((("T" "h" "k" ))("쏴"))
((("T" "h" "k" "T" ))("쐈"))
((("T" "h" "k" "r" ))("쏵"))
((("T" "h" "k" "s" ))("쏸"))
((("T" "h" "l" ))("쐬"))
((("T" "h" "l" "a" ))("쐼"))
((("T" "h" "l" "f" ))("쐴"))
((("T" "h" "l" "q" ))("쐽"))
((("T" "h" "l" "s" ))("쐰"))
((("T" "h" "o" ))("쐐"))
((("T" "h" "o" "T" ))("쐤"))
((("T" "h" "q" ))("쏩"))
((("T" "h" "r" ))("쏙"))
((("T" "h" "s" ))("쏜"))
((("T" "i" "d" ))("썅"))
((("T" "j" ))("써"))
((("T" "j" "T" ))("썼"))
((("T" "j" "a" ))("썸"))
((("T" "j" "d" ))("썽"))
((("T" "j" "f" ))("썰"))
((("T" "j" "f" "a" ))("썲"))
((("T" "j" "q" ))("썹"))
((("T" "j" "r" ))("썩"))
((("T" "j" "s" ))("썬"))
((("T" "k" ))("싸"))
((("T" "k" "T" ))("쌌"))
((("T" "k" "a" ))("쌈"))
((("T" "k" "d" ))("쌍"))
((("T" "k" "f" ))("쌀"))
((("T" "k" "g" ))("쌓"))
((("T" "k" "q" ))("쌉"))
((("T" "k" "r" ))("싹"))
((("T" "k" "r" "t" ))("싻"))
((("T" "k" "s" ))("싼"))
((("T" "l" ))("씨"))
((("T" "l" "a" ))("씸"))
((("T" "l" "d" ))("씽"))
((("T" "l" "f" ))("씰"))
((("T" "l" "q" ))("씹"))
((("T" "l" "r" ))("씩"))
((("T" "l" "s" ))("씬"))
((("T" "l" "t" ))("씻"))
((("T" "m" ))("쓰"))
((("T" "m" "a" ))("씀"))
((("T" "m" "f" ))("쓸"))
((("T" "m" "f" "a" ))("쓺"))
((("T" "m" "f" "g" ))("쓿"))
((("T" "m" "l" ))("씌"))
((("T" "m" "l" "a" ))("씜"))
((("T" "m" "l" "f" ))("씔"))
((("T" "m" "l" "s" ))("씐"))
((("T" "m" "q" ))("씁"))
((("T" "m" "r" ))("쓱"))
((("T" "m" "s" ))("쓴"))
((("T" "n" ))("쑤"))
((("T" "n" "a" ))("쑴"))
((("T" "n" "d" ))("쑹"))
((("T" "n" "f" ))("쑬"))
((("T" "n" "j" ))("쒀"))
((("T" "n" "j" "T" ))("쒔"))
((("T" "n" "l" ))("쒸"))
((("T" "n" "l" "s" ))("쒼"))
((("T" "n" "p" ))("쒜"))
((("T" "n" "q" ))("쑵"))
((("T" "n" "r" ))("쑥"))
((("T" "n" "s" ))("쑨"))
((("T" "o" ))("쌔"))
((("T" "o" "T" ))("쌨"))
((("T" "o" "a" ))("쌤"))
((("T" "o" "d" ))("쌩"))
((("T" "o" "f" ))("쌜"))
((("T" "o" "q" ))("쌥"))
((("T" "o" "r" ))("쌕"))
((("T" "o" "s" ))("쌘"))
((("T" "p" ))("쎄"))
((("T" "p" "f" ))("쎌"))
((("T" "p" "s" ))("쎈"))
((("T" "y" ))("쑈"))
((("W" ))("ㅉ"))
((("W" "b" ))("쮸"))
((("W" "h" ))("쪼"))
((("W" "h" "a" ))("쫌"))
((("W" "h" "c" ))("쫓"))
((("W" "h" "d" ))("쫑"))
((("W" "h" "f" ))("쫄"))
((("W" "h" "k" ))("쫘"))
((("W" "h" "k" "T" ))("쫬"))
((("W" "h" "k" "f" ))("쫠"))
((("W" "h" "k" "r" ))("쫙"))
((("W" "h" "l" ))("쬐"))
((("W" "h" "l" "a" ))("쬠"))
((("W" "h" "l" "f" ))("쬘"))
((("W" "h" "l" "q" ))("쬡"))
((("W" "h" "l" "s" ))("쬔"))
((("W" "h" "o" ))("쫴"))
((("W" "h" "o" "T" ))("쬈"))
((("W" "h" "q" ))("쫍"))
((("W" "h" "r" ))("쪽"))
((("W" "h" "s" ))("쫀"))
((("W" "h" "t" ))("쫏"))
((("W" "i" ))("쨔"))
((("W" "i" "d" ))("쨩"))
((("W" "i" "s" ))("쨘"))
((("W" "j" ))("쩌"))
((("W" "j" "T" ))("쩠"))
((("W" "j" "a" ))("쩜"))
((("W" "j" "d" ))("쩡"))
((("W" "j" "f" ))("쩔"))
((("W" "j" "q" ))("쩝"))
((("W" "j" "r" ))("쩍"))
((("W" "j" "s" ))("쩐"))
((("W" "j" "t" ))("쩟"))
((("W" "k" ))("짜"))
((("W" "k" "T" ))("짰"))
((("W" "k" "a" ))("짬"))
((("W" "k" "d" ))("짱"))
((("W" "k" "f" ))("짤"))
((("W" "k" "f" "q" ))("짧"))
((("W" "k" "q" ))("짭"))
((("W" "k" "r" ))("짝"))
((("W" "k" "s" ))("짠"))
((("W" "k" "s" "g" ))("짢"))
((("W" "k" "t" ))("짯"))
((("W" "l" ))("찌"))
((("W" "l" "a" ))("찜"))
((("W" "l" "d" ))("찡"))
((("W" "l" "f" ))("찔"))
((("W" "l" "g" ))("찧"))
((("W" "l" "q" ))("찝"))
((("W" "l" "r" ))("찍"))
((("W" "l" "s" ))("찐"))
((("W" "l" "w" ))("찢"))
((("W" "m" ))("쯔"))
((("W" "m" "a" ))("쯤"))
((("W" "m" "d" ))("쯩"))
((("W" "m" "t" ))("쯧"))
((("W" "n" ))("쭈"))
((("W" "n" "a" ))("쭘"))
((("W" "n" "d" ))("쭝"))
((("W" "n" "f" ))("쭐"))
((("W" "n" "j" ))("쭤"))
((("W" "n" "j" "T" ))("쭸"))
((("W" "n" "j" "d" ))("쭹"))
((("W" "n" "l" ))("쮜"))
((("W" "n" "q" ))("쭙"))
((("W" "n" "r" ))("쭉"))
((("W" "n" "s" ))("쭌"))
((("W" "o" ))("째"))
((("W" "o" "T" ))("쨌"))
((("W" "o" "a" ))("쨈"))
((("W" "o" "d" ))("쨍"))
((("W" "o" "f" ))("쨀"))
((("W" "o" "q" ))("쨉"))
((("W" "o" "r" ))("짹"))
((("W" "o" "s" ))("짼"))
((("W" "o" "t" ))("쨋"))
((("W" "p" ))("쩨"))
((("W" "p" "d" ))("쩽"))
((("W" "u" ))("쪄"))
((("W" "u" "T" ))("쪘"))
((("W" "y" "d" ))("쭁"))
((("Z" ))(")"))
((("Z" "!" ))("!"))
((("Z" "#" ))("#"))
((("Z" "$" ))("$"))
((("Z" "%" ))("%"))
((("Z" "&" ))("&"))
((("Z" "'" ))("'"))
((("Z" "(" ))("("))
((("Z" "*" ))("*"))
((("Z" "+" ))("+"))
((("Z" "," ))(","))
((("Z" "-" ))("-"))
((("Z" "." ))("."))
((("Z" "/" ))("/"))
((("Z" "0" ))("0"))
((("Z" "1" ))("1"))
((("Z" "2" ))("2"))
((("Z" "3" ))("3"))
((("Z" "4" ))("4"))
((("Z" "5" ))("5"))
((("Z" "6" ))("6"))
((("Z" "7" ))("7"))
((("Z" "8" ))("8"))
((("Z" "9" ))("9"))
((("Z" ":" ))(":"))
((("Z" ";" ))(";"))
((("Z" "<" ))("<"))
((("Z" "=" ))("="))
((("Z" ">" ))(">"))
((("Z" "?" ))("?"))
((("Z" "@" ))("@"))
((("Z" "A" ))("A"))
((("Z" "B" ))("B"))
((("Z" "C" ))("C"))
((("Z" "D" ))("D"))
((("Z" "E" ))("E"))
((("Z" "F" ))("F"))
((("Z" "G" ))("G"))
((("Z" "H" ))("H"))
((("Z" "I" ))("I"))
((("Z" "J" ))("J"))
((("Z" "K" ))("K"))
((("Z" "L" ))("L"))
((("Z" "M" ))("M"))
((("Z" "N" ))("N"))
((("Z" "O" ))("O"))
((("Z" "P" ))("P"))
((("Z" "Q" ))("Q"))
((("Z" "R" ))("R"))
((("Z" "S" ))("S"))
((("Z" "T" ))("T"))
((("Z" "U" ))("U"))
((("Z" "V" ))("V"))
((("Z" "W" ))("W"))
((("Z" "X" ))("X"))
((("Z" "Y" ))("Y"))
((("Z" "Z" ))("Z"))
((("Z" "[" ))("["))
((("Z" "\\" ))("?"))
((("Z" "]" ))("]"))
((("Z" "^" ))("^"))
((("Z" "^" "-" ))(" ̄"))
((("Z" "_" ))("_"))
((("Z" "`" ))("`"))
((("Z" "a" ))("a"))
((("Z" "b" ))("b"))
((("Z" "c" ))("c"))
((("Z" "d" ))("d"))
((("Z" "e" ))("e"))
((("Z" "f" ))("f"))
((("Z" "g" ))("g"))
((("Z" "h" ))("h"))
((("Z" "i" ))("i"))
((("Z" "j" ))("j"))
((("Z" "k" ))("k"))
((("Z" "l" ))("l"))
((("Z" "m" ))("m"))
((("Z" "n" ))("n"))
((("Z" "o" ))("o"))
((("Z" "p" ))("p"))
((("Z" "q" ))("q"))
((("Z" "r" ))("r"))
((("Z" "s" ))("s"))
((("Z" "t" ))("t"))
((("Z" "u" ))("u"))
((("Z" "v" ))("v"))
((("Z" "w" ))("w"))
((("Z" "x" ))("x"))
((("Z" "y" ))("y"))
((("Z" "z" ))("z"))
((("Z" "{" ))("{"))
((("Z" "|" ))("|"))
((("Z" "}" ))("}"))
((("a" ))("ㅁ"))
((("a" "P" ))("몌"))
((("a" "b" ))("뮤"))
((("a" "b" "a" ))("뮴"))
((("a" "b" "f" ))("뮬"))
((("a" "b" "s" ))("뮨"))
((("a" "b" "t" ))("뮷"))
((("a" "h" ))("모"))
((("a" "h" "a" ))("몸"))
((("a" "h" "d" ))("몽"))
((("a" "h" "f" ))("몰"))
((("a" "h" "f" "a" ))("몲"))
((("a" "h" "k" ))("뫄"))
((("a" "h" "k" "T" ))("뫘"))
((("a" "h" "k" "d" ))("뫙"))
((("a" "h" "k" "s" ))("뫈"))
((("a" "h" "l" ))("뫼"))
((("a" "h" "l" "d" ))("묑"))
((("a" "h" "l" "f" ))("묄"))
((("a" "h" "l" "q" ))("묍"))
((("a" "h" "l" "s" ))("묀"))
((("a" "h" "l" "t" ))("묏"))
((("a" "h" "q" ))("몹"))
((("a" "h" "r" ))("목"))
((("a" "h" "r" "t" ))("몫"))
((("a" "h" "s" ))("몬"))
((("a" "h" "t" ))("못"))
((("a" "i" ))("먀"))
((("a" "i" "d" ))("먕"))
((("a" "i" "f" ))("먈"))
((("a" "i" "r" ))("먁"))
((("a" "j" ))("머"))
((("a" "j" "a" ))("멈"))
((("a" "j" "d" ))("멍"))
((("a" "j" "f" ))("멀"))
((("a" "j" "f" "a" ))("멂"))
((("a" "j" "g" ))("멓"))
((("a" "j" "q" ))("멉"))
((("a" "j" "r" ))("먹"))
((("a" "j" "s" ))("먼"))
((("a" "j" "t" ))("멋"))
((("a" "j" "w" ))("멎"))
((("a" "k" ))("마"))
((("a" "k" "a" ))("맘"))
((("a" "k" "d" ))("망"))
((("a" "k" "e" ))("맏"))
((("a" "k" "f" ))("말"))
((("a" "k" "f" "a" ))("맒"))
((("a" "k" "f" "r" ))("맑"))
((("a" "k" "g" ))("맣"))
((("a" "k" "q" ))("맙"))
((("a" "k" "r" ))("막"))
((("a" "k" "s" ))("만"))
((("a" "k" "s" "g" ))("많"))
((("a" "k" "t" ))("맛"))
((("a" "k" "w" ))("맞"))
((("a" "k" "x" ))("맡"))
((("a" "l" ))("미"))
((("a" "l" "T" ))("밌"))
((("a" "l" "a" ))("밈"))
((("a" "l" "c" ))("및"))
((("a" "l" "d" ))("밍"))
((("a" "l" "e" ))("믿"))
((("a" "l" "f" ))("밀"))
((("a" "l" "f" "a" ))("밂"))
((("a" "l" "q" ))("밉"))
((("a" "l" "r" ))("믹"))
((("a" "l" "s" ))("민"))
((("a" "l" "t" ))("밋"))
((("a" "l" "x" ))("밑"))
((("a" "m" ))("므"))
((("a" "m" "a" ))("믐"))
((("a" "m" "f" ))("믈"))
((("a" "m" "s" ))("믄"))
((("a" "m" "t" ))("믓"))
((("a" "n" ))("무"))
((("a" "n" "R" ))("묶"))
((("a" "n" "a" ))("뭄"))
((("a" "n" "d" ))("뭉"))
((("a" "n" "e" ))("묻"))
((("a" "n" "f" ))("물"))
((("a" "n" "f" "a" ))("묾"))
((("a" "n" "f" "r" ))("묽"))
((("a" "n" "g" ))("뭏"))
((("a" "n" "j" ))("뭐"))
((("a" "n" "j" "f" ))("뭘"))
((("a" "n" "j" "q" ))("뭡"))
((("a" "n" "j" "s" ))("뭔"))
((("a" "n" "j" "t" ))("뭣"))
((("a" "n" "l" ))("뮈"))
((("a" "n" "l" "f" ))("뮐"))
((("a" "n" "l" "s" ))("뮌"))
((("a" "n" "p" ))("뭬"))
((("a" "n" "q" ))("뭅"))
((("a" "n" "r" ))("묵"))
((("a" "n" "s" ))("문"))
((("a" "n" "t" ))("뭇"))
((("a" "n" "x" ))("뭍"))
((("a" "o" ))("매"))
((("a" "o" "T" ))("맸"))
((("a" "o" "a" ))("맴"))
((("a" "o" "d" ))("맹"))
((("a" "o" "f" ))("맬"))
((("a" "o" "q" ))("맵"))
((("a" "o" "r" ))("맥"))
((("a" "o" "s" ))("맨"))
((("a" "o" "t" ))("맷"))
((("a" "o" "w" ))("맺"))
((("a" "p" ))("메"))
((("a" "p" "T" ))("멨"))
((("a" "p" "a" ))("멤"))
((("a" "p" "d" ))("멩"))
((("a" "p" "f" ))("멜"))
((("a" "p" "q" ))("멥"))
((("a" "p" "r" ))("멕"))
((("a" "p" "s" ))("멘"))
((("a" "p" "t" ))("멧"))
((("a" "u" ))("며"))
((("a" "u" "T" ))("몄"))
((("a" "u" "c" ))("몇"))
((("a" "u" "d" ))("명"))
((("a" "u" "f" ))("멸"))
((("a" "u" "r" ))("멱"))
((("a" "u" "s" ))("면"))
((("a" "u" "t" ))("몃"))
((("a" "y" ))("묘"))
((("a" "y" "f" ))("묠"))
((("a" "y" "q" ))("묩"))
((("a" "y" "s" ))("묜"))
((("a" "y" "t" ))("묫"))
((("b" ))("ㅠ"))
((("c" ))("ㅊ"))
((("c" "P" ))("쳬"))
((("c" "P" "d" ))("촁"))
((("c" "P" "s" ))("쳰"))
((("c" "b" ))("츄"))
((("c" "b" "a" ))("츔"))
((("c" "b" "d" ))("츙"))
((("c" "b" "f" ))("츌"))
((("c" "b" "s" ))("츈"))
((("c" "h" ))("초"))
((("c" "h" "a" ))("촘"))
((("c" "h" "d" ))("총"))
((("c" "h" "f" ))("촐"))
((("c" "h" "k" ))("촤"))
((("c" "h" "k" "d" ))("촹"))
((("c" "h" "k" "f" ))("촬"))
((("c" "h" "k" "s" ))("촨"))
((("c" "h" "l" ))("최"))
((("c" "h" "l" "a" ))("쵬"))
((("c" "h" "l" "d" ))("쵱"))
((("c" "h" "l" "f" ))("쵤"))
((("c" "h" "l" "q" ))("쵭"))
((("c" "h" "l" "s" ))("쵠"))
((("c" "h" "l" "t" ))("쵯"))
((("c" "h" "q" ))("촙"))
((("c" "h" "r" ))("촉"))
((("c" "h" "s" ))("촌"))
((("c" "h" "t" ))("촛"))
((("c" "i" ))("챠"))
((("c" "i" "a" ))("챰"))
((("c" "i" "d" ))("챵"))
((("c" "i" "f" ))("챨"))
((("c" "i" "s" ))("챤"))
((("c" "i" "s" "g" ))("챦"))
((("c" "j" ))("처"))
((("c" "j" "T" ))("첬"))
((("c" "j" "a" ))("첨"))
((("c" "j" "d" ))("청"))
((("c" "j" "f" ))("철"))
((("c" "j" "q" ))("첩"))
((("c" "j" "r" ))("척"))
((("c" "j" "s" ))("천"))
((("c" "j" "t" ))("첫"))
((("c" "k" ))("차"))
((("c" "k" "T" ))("찼"))
((("c" "k" "a" ))("참"))
((("c" "k" "d" ))("창"))
((("c" "k" "f" ))("찰"))
((("c" "k" "q" ))("찹"))
((("c" "k" "r" ))("착"))
((("c" "k" "s" ))("찬"))
((("c" "k" "s" "g" ))("찮"))
((("c" "k" "t" ))("찻"))
((("c" "k" "w" ))("찾"))
((("c" "l" ))("치"))
((("c" "l" "a" ))("침"))
((("c" "l" "d" ))("칭"))
((("c" "l" "e" ))("칟"))
((("c" "l" "f" ))("칠"))
((("c" "l" "f" "r" ))("칡"))
((("c" "l" "q" ))("칩"))
((("c" "l" "r" ))("칙"))
((("c" "l" "s" ))("친"))
((("c" "l" "t" ))("칫"))
((("c" "m" ))("츠"))
((("c" "m" "a" ))("츰"))
((("c" "m" "d" ))("층"))
((("c" "m" "f" ))("츨"))
((("c" "m" "q" ))("츱"))
((("c" "m" "r" ))("측"))
((("c" "m" "s" ))("츤"))
((("c" "m" "t" ))("츳"))
((("c" "n" ))("추"))
((("c" "n" "a" ))("춤"))
((("c" "n" "d" ))("충"))
((("c" "n" "f" ))("출"))
((("c" "n" "j" ))("춰"))
((("c" "n" "j" "T" ))("췄"))
((("c" "n" "l" ))("취"))
((("c" "n" "l" "a" ))("췸"))
((("c" "n" "l" "d" ))("췽"))
((("c" "n" "l" "f" ))("췰"))
((("c" "n" "l" "q" ))("췹"))
((("c" "n" "l" "s" ))("췬"))
((("c" "n" "l" "t" ))("췻"))
((("c" "n" "p" ))("췌"))
((("c" "n" "p" "s" ))("췐"))
((("c" "n" "q" ))("춥"))
((("c" "n" "r" ))("축"))
((("c" "n" "s" ))("춘"))
((("c" "n" "t" ))("춧"))
((("c" "o" ))("채"))
((("c" "o" "T" ))("챘"))
((("c" "o" "a" ))("챔"))
((("c" "o" "d" ))("챙"))
((("c" "o" "f" ))("챌"))
((("c" "o" "q" ))("챕"))
((("c" "o" "r" ))("책"))
((("c" "o" "s" ))("챈"))
((("c" "o" "t" ))("챗"))
((("c" "p" ))("체"))
((("c" "p" "a" ))("쳄"))
((("c" "p" "d" ))("쳉"))
((("c" "p" "f" ))("첼"))
((("c" "p" "q" ))("쳅"))
((("c" "p" "r" ))("첵"))
((("c" "p" "s" ))("첸"))
((("c" "p" "t" ))("쳇"))
((("c" "u" ))("쳐"))
((("c" "u" "T" ))("쳤"))
((("c" "u" "s" ))("쳔"))
((("c" "y" ))("쵸"))
((("c" "y" "a" ))("춈"))
((("d" ))("ㅇ"))
((("d" "O" ))("얘"))
((("d" "O" "f" ))("얠"))
((("d" "O" "q" ))("얩"))
((("d" "O" "s" ))("얜"))
((("d" "P" ))("예"))
((("d" "P" "T" ))("옜"))
((("d" "P" "a" ))("옘"))
((("d" "P" "f" ))("옐"))
((("d" "P" "q" ))("옙"))
((("d" "P" "s" ))("옌"))
((("d" "P" "t" ))("옛"))
((("d" "b" ))("유"))
((("d" "b" "a" ))("윰"))
((("d" "b" "c" ))("윷"))
((("d" "b" "d" ))("융"))
((("d" "b" "f" ))("율"))
((("d" "b" "q" ))("윱"))
((("d" "b" "r" ))("육"))
((("d" "b" "s" ))("윤"))
((("d" "b" "t" ))("윳"))
((("d" "h" ))("오"))
((("d" "h" "a" ))("옴"))
((("d" "h" "c" ))("옻"))
((("d" "h" "d" ))("옹"))
((("d" "h" "f" ))("올"))
((("d" "h" "f" "a" ))("옮"))
((("d" "h" "f" "g" ))("옳"))
((("d" "h" "f" "r" ))("옭"))
((("d" "h" "f" "t" ))("옰"))
((("d" "h" "k" ))("와"))
((("d" "h" "k" "T" ))("왔"))
((("d" "h" "k" "a" ))("왐"))
((("d" "h" "k" "d" ))("왕"))
((("d" "h" "k" "f" ))("왈"))
((("d" "h" "k" "q" ))("왑"))
((("d" "h" "k" "r" ))("왁"))
((("d" "h" "k" "s" ))("완"))
((("d" "h" "k" "t" ))("왓"))
((("d" "h" "l" ))("외"))
((("d" "h" "l" "a" ))("욈"))
((("d" "h" "l" "d" ))("욍"))
((("d" "h" "l" "f" ))("욀"))
((("d" "h" "l" "q" ))("욉"))
((("d" "h" "l" "r" ))("왹"))
((("d" "h" "l" "s" ))("왼"))
((("d" "h" "l" "t" ))("욋"))
((("d" "h" "o" ))("왜"))
((("d" "h" "o" "a" ))("왬"))
((("d" "h" "o" "d" ))("왱"))
((("d" "h" "o" "r" ))("왝"))
((("d" "h" "o" "s" ))("왠"))
((("d" "h" "o" "t" ))("왯"))
((("d" "h" "q" ))("옵"))
((("d" "h" "r" ))("옥"))
((("d" "h" "s" ))("온"))
((("d" "h" "t" ))("옷"))
((("d" "i" ))("야"))
((("d" "i" "a" ))("얌"))
((("d" "i" "d" ))("양"))
((("d" "i" "f" ))("얄"))
((("d" "i" "f" "q" ))("얇"))
((("d" "i" "g" ))("얗"))
((("d" "i" "q" ))("얍"))
((("d" "i" "r" ))("약"))
((("d" "i" "s" ))("얀"))
((("d" "i" "t" ))("얏"))
((("d" "i" "x" ))("얕"))
((("d" "j" ))("어"))
((("d" "j" "T" ))("었"))
((("d" "j" "a" ))("엄"))
((("d" "j" "d" ))("엉"))
((("d" "j" "e" ))("얻"))
((("d" "j" "f" ))("얼"))
((("d" "j" "f" "a" ))("얾"))
((("d" "j" "f" "r" ))("얽"))
((("d" "j" "q" ))("업"))
((("d" "j" "q" "t" ))("없"))
((("d" "j" "r" ))("억"))
((("d" "j" "s" ))("언"))
((("d" "j" "s" "w" ))("얹"))
((("d" "j" "t" ))("엇"))
((("d" "j" "v" ))("엎"))
((("d" "j" "w" ))("엊"))
((("d" "j" "z" ))("엌"))
((("d" "k" ))("아"))
((("d" "k" "T" ))("았"))
((("d" "k" "a" ))("암"))
((("d" "k" "d" ))("앙"))
((("d" "k" "f" ))("알"))
((("d" "k" "f" "a" ))("앎"))
((("d" "k" "f" "g" ))("앓"))
((("d" "k" "f" "r" ))("앍"))
((("d" "k" "q" ))("압"))
((("d" "k" "r" ))("악"))
((("d" "k" "s" ))("안"))
((("d" "k" "s" "g" ))("않"))
((("d" "k" "s" "w" ))("앉"))
((("d" "k" "t" ))("앗"))
((("d" "k" "v" ))("앞"))
((("d" "k" "x" ))("앝"))
((("d" "l" ))("이"))
((("d" "l" "T" ))("있"))
((("d" "l" "a" ))("임"))
((("d" "l" "d" ))("잉"))
((("d" "l" "f" ))("일"))
((("d" "l" "f" "a" ))("읾"))
((("d" "l" "f" "g" ))("잃"))
((("d" "l" "f" "r" ))("읽"))
((("d" "l" "q" ))("입"))
((("d" "l" "r" ))("익"))
((("d" "l" "s" ))("인"))
((("d" "l" "t" ))("잇"))
((("d" "l" "v" ))("잎"))
((("d" "l" "w" ))("잊"))
((("d" "m" ))("으"))
((("d" "m" "a" ))("음"))
((("d" "m" "c" ))("읓"))
((("d" "m" "d" ))("응"))
((("d" "m" "f" ))("을"))
((("d" "m" "f" "v" ))("읊"))
((("d" "m" "g" ))("읗"))
((("d" "m" "l" ))("의"))
((("d" "m" "l" "a" ))("읨"))
((("d" "m" "l" "f" ))("읠"))
((("d" "m" "l" "s" ))("읜"))
((("d" "m" "l" "t" ))("읫"))
((("d" "m" "q" ))("읍"))
((("d" "m" "r" ))("윽"))
((("d" "m" "s" ))("은"))
((("d" "m" "t" ))("읏"))
((("d" "m" "v" ))("읖"))
((("d" "m" "w" ))("읒"))
((("d" "m" "x" ))("읕"))
((("d" "m" "z" ))("읔"))
((("d" "n" ))("우"))
((("d" "n" "a" ))("움"))
((("d" "n" "d" ))("웅"))
((("d" "n" "f" ))("울"))
((("d" "n" "f" "a" ))("욺"))
((("d" "n" "f" "r" ))("욹"))
((("d" "n" "j" ))("워"))
((("d" "n" "j" "T" ))("웠"))
((("d" "n" "j" "a" ))("웜"))
((("d" "n" "j" "d" ))("웡"))
((("d" "n" "j" "f" ))("월"))
((("d" "n" "j" "q" ))("웝"))
((("d" "n" "j" "r" ))("웍"))
((("d" "n" "j" "s" ))("원"))
((("d" "n" "l" ))("위"))
((("d" "n" "l" "a" ))("윔"))
((("d" "n" "l" "d" ))("윙"))
((("d" "n" "l" "f" ))("윌"))
((("d" "n" "l" "q" ))("윕"))
((("d" "n" "l" "r" ))("윅"))
((("d" "n" "l" "s" ))("윈"))
((("d" "n" "l" "t" ))("윗"))
((("d" "n" "p" ))("웨"))
((("d" "n" "p" "a" ))("웸"))
((("d" "n" "p" "d" ))("웽"))
((("d" "n" "p" "f" ))("웰"))
((("d" "n" "p" "q" ))("웹"))
((("d" "n" "p" "r" ))("웩"))
((("d" "n" "p" "s" ))("웬"))
((("d" "n" "q" ))("웁"))
((("d" "n" "r" ))("욱"))
((("d" "n" "s" ))("운"))
((("d" "n" "t" ))("웃"))
((("d" "o" ))("애"))
((("d" "o" "T" ))("앴"))
((("d" "o" "a" ))("앰"))
((("d" "o" "d" ))("앵"))
((("d" "o" "f" ))("앨"))
((("d" "o" "q" ))("앱"))
((("d" "o" "r" ))("액"))
((("d" "o" "s" ))("앤"))
((("d" "o" "t" ))("앳"))
((("d" "p" ))("에"))
((("d" "p" "a" ))("엠"))
((("d" "p" "d" ))("엥"))
((("d" "p" "f" ))("엘"))
((("d" "p" "q" ))("엡"))
((("d" "p" "r" ))("엑"))
((("d" "p" "s" ))("엔"))
((("d" "p" "t" ))("엣"))
((("d" "u" ))("여"))
((("d" "u" "R" ))("엮"))
((("d" "u" "T" ))("였"))
((("d" "u" "a" ))("염"))
((("d" "u" "d" ))("영"))
((("d" "u" "f" ))("열"))
((("d" "u" "f" "a" ))("엶"))
((("d" "u" "f" "q" ))("엷"))
((("d" "u" "g" ))("옇"))
((("d" "u" "q" ))("엽"))
((("d" "u" "q" "t" ))("엾"))
((("d" "u" "r" ))("역"))
((("d" "u" "s" ))("연"))
((("d" "u" "t" ))("엿"))
((("d" "u" "v" ))("옆"))
((("d" "u" "x" ))("옅"))
((("d" "y" ))("요"))
((("d" "y" "a" ))("욤"))
((("d" "y" "d" ))("용"))
((("d" "y" "f" ))("욜"))
((("d" "y" "q" ))("욥"))
((("d" "y" "r" ))("욕"))
((("d" "y" "s" ))("욘"))
((("d" "y" "t" ))("욧"))
((("e" ))("ㄷ"))
((("e" "P" ))("뎨"))
((("e" "P" "s" ))("뎬"))
((("e" "b" ))("듀"))
((("e" "b" "a" ))("듐"))
((("e" "b" "d" ))("듕"))
((("e" "b" "f" ))("듈"))
((("e" "b" "s" ))("듄"))
((("e" "h" ))("도"))
((("e" "h" "a" ))("돔"))
((("e" "h" "c" ))("돛"))
((("e" "h" "d" ))("동"))
((("e" "h" "e" ))("돋"))
((("e" "h" "f" ))("돌"))
((("e" "h" "f" "a" ))("돎"))
((("e" "h" "f" "t" ))("돐"))
((("e" "h" "k" ))("돠"))
((("e" "h" "k" "f" ))("돨"))
((("e" "h" "k" "s" ))("돤"))
((("e" "h" "l" ))("되"))
((("e" "h" "l" "a" ))("됨"))
((("e" "h" "l" "f" ))("될"))
((("e" "h" "l" "q" ))("됩"))
((("e" "h" "l" "s" ))("된"))
((("e" "h" "l" "t" ))("됫"))
((("e" "h" "o" ))("돼"))
((("e" "h" "o" "T" ))("됐"))
((("e" "h" "q" ))("돕"))
((("e" "h" "r" ))("독"))
((("e" "h" "s" ))("돈"))
((("e" "h" "t" ))("돗"))
((("e" "h" "x" ))("돝"))
((("e" "i" ))("댜"))
((("e" "j" ))("더"))
((("e" "j" "R" ))("덖"))
((("e" "j" "a" ))("덤"))
((("e" "j" "c" ))("덫"))
((("e" "j" "d" ))("덩"))
((("e" "j" "e" ))("덛"))
((("e" "j" "f" ))("덜"))
((("e" "j" "f" "a" ))("덞"))
((("e" "j" "f" "q" ))("덟"))
((("e" "j" "q" ))("덥"))
((("e" "j" "r" ))("덕"))
((("e" "j" "s" ))("던"))
((("e" "j" "t" ))("덧"))
((("e" "j" "v" ))("덮"))
((("e" "k" ))("다"))
((("e" "k" "R" ))("닦"))
((("e" "k" "T" ))("닸"))
((("e" "k" "a" ))("담"))
((("e" "k" "c" ))("닻"))
((("e" "k" "d" ))("당"))
((("e" "k" "e" ))("닫"))
((("e" "k" "f" ))("달"))
((("e" "k" "f" "a" ))("닮"))
((("e" "k" "f" "g" ))("닳"))
((("e" "k" "f" "q" ))("닯"))
((("e" "k" "f" "r" ))("닭"))
((("e" "k" "g" ))("닿"))
((("e" "k" "q" ))("답"))
((("e" "k" "r" ))("닥"))
((("e" "k" "s" ))("단"))
((("e" "k" "t" ))("닷"))
((("e" "k" "w" ))("닺"))
((("e" "l" ))("디"))
((("e" "l" "T" ))("딨"))
((("e" "l" "a" ))("딤"))
((("e" "l" "d" ))("딩"))
((("e" "l" "e" ))("딛"))
((("e" "l" "f" ))("딜"))
((("e" "l" "q" ))("딥"))
((("e" "l" "r" ))("딕"))
((("e" "l" "s" ))("딘"))
((("e" "l" "t" ))("딧"))
((("e" "l" "w" ))("딪"))
((("e" "m" ))("드"))
((("e" "m" "a" ))("듬"))
((("e" "m" "d" ))("등"))
((("e" "m" "e" ))("듣"))
((("e" "m" "f" ))("들"))
((("e" "m" "f" "a" ))("듦"))
((("e" "m" "l" ))("듸"))
((("e" "m" "q" ))("듭"))
((("e" "m" "r" ))("득"))
((("e" "m" "s" ))("든"))
((("e" "m" "t" ))("듯"))
((("e" "n" ))("두"))
((("e" "n" "a" ))("둠"))
((("e" "n" "d" ))("둥"))
((("e" "n" "f" ))("둘"))
((("e" "n" "j" ))("둬"))
((("e" "n" "j" "T" ))("뒀"))
((("e" "n" "l" ))("뒤"))
((("e" "n" "l" "d" ))("뒹"))
((("e" "n" "l" "f" ))("뒬"))
((("e" "n" "l" "q" ))("뒵"))
((("e" "n" "l" "s" ))("뒨"))
((("e" "n" "l" "t" ))("뒷"))
((("e" "n" "p" ))("뒈"))
((("e" "n" "p" "d" ))("뒝"))
((("e" "n" "q" ))("둡"))
((("e" "n" "r" ))("둑"))
((("e" "n" "s" ))("둔"))
((("e" "n" "t" ))("둣"))
((("e" "o" ))("대"))
((("e" "o" "T" ))("댔"))
((("e" "o" "a" ))("댐"))
((("e" "o" "d" ))("댕"))
((("e" "o" "f" ))("댈"))
((("e" "o" "q" ))("댑"))
((("e" "o" "r" ))("댁"))
((("e" "o" "s" ))("댄"))
((("e" "o" "t" ))("댓"))
((("e" "p" ))("데"))
((("e" "p" "T" ))("뎄"))
((("e" "p" "a" ))("뎀"))
((("e" "p" "d" ))("뎅"))
((("e" "p" "f" ))("델"))
((("e" "p" "q" ))("뎁"))
((("e" "p" "r" ))("덱"))
((("e" "p" "s" ))("덴"))
((("e" "p" "t" ))("뎃"))
((("e" "u" ))("뎌"))
((("e" "u" "T" ))("뎠"))
((("e" "u" "d" ))("뎡"))
((("e" "u" "f" ))("뎔"))
((("e" "u" "s" ))("뎐"))
((("e" "y" ))("됴"))
((("f" ))("ㄹ"))
((("f" "P" ))("례"))
((("f" "P" "q" ))("롑"))
((("f" "P" "s" ))("롄"))
((("f" "P" "t" ))("롓"))
((("f" "b" ))("류"))
((("f" "b" "a" ))("륨"))
((("f" "b" "d" ))("륭"))
((("f" "b" "f" ))("률"))
((("f" "b" "q" ))("륩"))
((("f" "b" "r" ))("륙"))
((("f" "b" "s" ))("륜"))
((("f" "b" "t" ))("륫"))
((("f" "h" ))("로"))
((("f" "h" "a" ))("롬"))
((("f" "h" "d" ))("롱"))
((("f" "h" "f" ))("롤"))
((("f" "h" "k" ))("롸"))
((("f" "h" "k" "d" ))("뢍"))
((("f" "h" "k" "s" ))("롼"))
((("f" "h" "l" ))("뢰"))
((("f" "h" "l" "a" ))("룀"))
((("f" "h" "l" "d" ))("룅"))
((("f" "h" "l" "f" ))("뢸"))
((("f" "h" "l" "q" ))("룁"))
((("f" "h" "l" "s" ))("뢴"))
((("f" "h" "l" "t" ))("룃"))
((("f" "h" "o" "T" ))("뢨"))
((("f" "h" "q" ))("롭"))
((("f" "h" "r" ))("록"))
((("f" "h" "s" ))("론"))
((("f" "h" "t" ))("롯"))
((("f" "i" ))("랴"))
((("f" "i" "d" ))("량"))
((("f" "i" "r" ))("략"))
((("f" "i" "s" ))("랸"))
((("f" "i" "t" ))("럇"))
((("f" "j" ))("러"))
((("f" "j" "T" ))("렀"))
((("f" "j" "a" ))("럼"))
((("f" "j" "d" ))("렁"))
((("f" "j" "f" ))("럴"))
((("f" "j" "g" ))("렇"))
((("f" "j" "q" ))("럽"))
((("f" "j" "r" ))("럭"))
((("f" "j" "s" ))("런"))
((("f" "j" "t" ))("럿"))
((("f" "k" ))("라"))
((("f" "k" "T" ))("랐"))
((("f" "k" "a" ))("람"))
((("f" "k" "d" ))("랑"))
((("f" "k" "f" ))("랄"))
((("f" "k" "g" ))("랗"))
((("f" "k" "q" ))("랍"))
((("f" "k" "r" ))("락"))
((("f" "k" "s" ))("란"))
((("f" "k" "t" ))("랏"))
((("f" "k" "v" ))("랖"))
((("f" "k" "w" ))("랒"))
((("f" "l" ))("리"))
((("f" "l" "a" ))("림"))
((("f" "l" "d" ))("링"))
((("f" "l" "f" ))("릴"))
((("f" "l" "q" ))("립"))
((("f" "l" "r" ))("릭"))
((("f" "l" "s" ))("린"))
((("f" "l" "t" ))("릿"))
((("f" "m" ))("르"))
((("f" "m" "a" ))("름"))
((("f" "m" "d" ))("릉"))
((("f" "m" "f" ))("를"))
((("f" "m" "q" ))("릅"))
((("f" "m" "r" ))("륵"))
((("f" "m" "s" ))("른"))
((("f" "m" "t" ))("릇"))
((("f" "m" "v" ))("릎"))
((("f" "m" "w" ))("릊"))
((("f" "m" "x" ))("릍"))
((("f" "n" ))("루"))
((("f" "n" "a" ))("룸"))
((("f" "n" "d" ))("룽"))
((("f" "n" "f" ))("룰"))
((("f" "n" "j" ))("뤄"))
((("f" "n" "j" "T" ))("뤘"))
((("f" "n" "l" ))("뤼"))
((("f" "n" "l" "a" ))("륌"))
((("f" "n" "l" "d" ))("륑"))
((("f" "n" "l" "f" ))("륄"))
((("f" "n" "l" "r" ))("뤽"))
((("f" "n" "l" "s" ))("륀"))
((("f" "n" "l" "t" ))("륏"))
((("f" "n" "p" ))("뤠"))
((("f" "n" "q" ))("룹"))
((("f" "n" "r" ))("룩"))
((("f" "n" "s" ))("룬"))
((("f" "n" "t" ))("룻"))
((("f" "o" ))("래"))
((("f" "o" "T" ))("랬"))
((("f" "o" "a" ))("램"))
((("f" "o" "d" ))("랭"))
((("f" "o" "f" ))("랠"))
((("f" "o" "q" ))("랩"))
((("f" "o" "r" ))("랙"))
((("f" "o" "s" ))("랜"))
((("f" "o" "t" ))("랫"))
((("f" "p" ))("레"))
((("f" "p" "a" ))("렘"))
((("f" "p" "d" ))("렝"))
((("f" "p" "f" ))("렐"))
((("f" "p" "q" ))("렙"))
((("f" "p" "r" ))("렉"))
((("f" "p" "s" ))("렌"))
((("f" "p" "t" ))("렛"))
((("f" "u" ))("려"))
((("f" "u" "T" ))("렸"))
((("f" "u" "a" ))("렴"))
((("f" "u" "d" ))("령"))
((("f" "u" "f" ))("렬"))
((("f" "u" "q" ))("렵"))
((("f" "u" "r" ))("력"))
((("f" "u" "s" ))("련"))
((("f" "u" "t" ))("렷"))
((("f" "y" ))("료"))
((("f" "y" "d" ))("룡"))
((("f" "y" "f" ))("룔"))
((("f" "y" "q" ))("룝"))
((("f" "y" "s" ))("룐"))
((("f" "y" "t" ))("룟"))
((("g" ))("ㅎ"))
((("g" "P" ))("혜"))
((("g" "P" "f" ))("혤"))
((("g" "P" "q" ))("혭"))
((("g" "P" "s" ))("혠"))
((("g" "b" ))("휴"))
((("g" "b" "a" ))("흄"))
((("g" "b" "d" ))("흉"))
((("g" "b" "f" ))("휼"))
((("g" "b" "r" ))("휵"))
((("g" "b" "s" ))("휸"))
((("g" "b" "t" ))("흇"))
((("g" "h" ))("호"))
((("g" "h" "a" ))("홈"))
((("g" "h" "d" ))("홍"))
((("g" "h" "f" ))("홀"))
((("g" "h" "f" "x" ))("홅"))
((("g" "h" "k" ))("화"))
((("g" "h" "k" "d" ))("황"))
((("g" "h" "k" "f" ))("활"))
((("g" "h" "k" "r" ))("확"))
((("g" "h" "k" "s" ))("환"))
((("g" "h" "k" "t" ))("홧"))
((("g" "h" "l" ))("회"))
((("g" "h" "l" "d" ))("횡"))
((("g" "h" "l" "f" ))("횔"))
((("g" "h" "l" "q" ))("횝"))
((("g" "h" "l" "r" ))("획"))
((("g" "h" "l" "s" ))("횐"))
((("g" "h" "l" "t" ))("횟"))
((("g" "h" "o" ))("홰"))
((("g" "h" "o" "d" ))("횅"))
((("g" "h" "o" "r" ))("홱"))
((("g" "h" "o" "s" ))("홴"))
((("g" "h" "o" "t" ))("횃"))
((("g" "h" "q" ))("홉"))
((("g" "h" "r" ))("혹"))
((("g" "h" "s" ))("혼"))
((("g" "h" "t" ))("홋"))
((("g" "h" "x" ))("홑"))
((("g" "i" ))("햐"))
((("g" "i" "d" ))("향"))
((("g" "j" ))("허"))
((("g" "j" "a" ))("험"))
((("g" "j" "d" ))("헝"))
((("g" "j" "f" ))("헐"))
((("g" "j" "f" "a" ))("헒"))
((("g" "j" "q" ))("헙"))
((("g" "j" "r" ))("헉"))
((("g" "j" "s" ))("헌"))
((("g" "j" "t" ))("헛"))
((("g" "k" ))("하"))
((("g" "k" "a" ))("함"))
((("g" "k" "d" ))("항"))
((("g" "k" "f" ))("할"))
((("g" "k" "f" "x" ))("핥"))
((("g" "k" "q" ))("합"))
((("g" "k" "r" ))("학"))
((("g" "k" "s" ))("한"))
((("g" "k" "t" ))("핫"))
((("g" "l" ))("히"))
((("g" "l" "a" ))("힘"))
((("g" "l" "d" ))("힝"))
((("g" "l" "f" ))("힐"))
((("g" "l" "q" ))("힙"))
((("g" "l" "r" ))("힉"))
((("g" "l" "s" ))("힌"))
((("g" "l" "t" ))("힛"))
((("g" "m" ))("흐"))
((("g" "m" "a" ))("흠"))
((("g" "m" "d" ))("흥"))
((("g" "m" "e" ))("흗"))
((("g" "m" "f" ))("흘"))
((("g" "m" "f" "r" ))("흙"))
((("g" "m" "l" ))("희"))
((("g" "m" "l" "a" ))("흼"))
((("g" "m" "l" "d" ))("힁"))
((("g" "m" "l" "f" ))("흴"))
((("g" "m" "l" "q" ))("흽"))
((("g" "m" "l" "s" ))("흰"))
((("g" "m" "q" ))("흡"))
((("g" "m" "r" ))("흑"))
((("g" "m" "s" ))("흔"))
((("g" "m" "s" "g" ))("흖"))
((("g" "m" "t" ))("흣"))
((("g" "m" "x" ))("흩"))
((("g" "n" ))("후"))
((("g" "n" "a" ))("훔"))
((("g" "n" "d" ))("훙"))
((("g" "n" "f" ))("훌"))
((("g" "n" "f" "x" ))("훑"))
((("g" "n" "j" ))("훠"))
((("g" "n" "j" "a" ))("훰"))
((("g" "n" "j" "d" ))("훵"))
((("g" "n" "j" "f" ))("훨"))
((("g" "n" "j" "s" ))("훤"))
((("g" "n" "l" ))("휘"))
((("g" "n" "l" "a" ))("휨"))
((("g" "n" "l" "d" ))("휭"))
((("g" "n" "l" "f" ))("휠"))
((("g" "n" "l" "q" ))("휩"))
((("g" "n" "l" "r" ))("휙"))
((("g" "n" "l" "s" ))("휜"))
((("g" "n" "l" "t" ))("휫"))
((("g" "n" "p" ))("훼"))
((("g" "n" "p" "d" ))("휑"))
((("g" "n" "p" "f" ))("휄"))
((("g" "n" "p" "r" ))("훽"))
((("g" "n" "p" "s" ))("휀"))
((("g" "n" "r" ))("훅"))
((("g" "n" "s" ))("훈"))
((("g" "n" "t" ))("훗"))
((("g" "o" ))("해"))
((("g" "o" "T" ))("했"))
((("g" "o" "a" ))("햄"))
((("g" "o" "d" ))("행"))
((("g" "o" "f" ))("핼"))
((("g" "o" "q" ))("햅"))
((("g" "o" "r" ))("핵"))
((("g" "o" "s" ))("핸"))
((("g" "o" "t" ))("햇"))
((("g" "p" ))("헤"))
((("g" "p" "a" ))("헴"))
((("g" "p" "d" ))("헹"))
((("g" "p" "f" ))("헬"))
((("g" "p" "q" ))("헵"))
((("g" "p" "r" ))("헥"))
((("g" "p" "s" ))("헨"))
((("g" "p" "t" ))("헷"))
((("g" "u" ))("혀"))
((("g" "u" "T" ))("혔"))
((("g" "u" "a" ))("혐"))
((("g" "u" "d" ))("형"))
((("g" "u" "f" ))("혈"))
((("g" "u" "q" ))("협"))
((("g" "u" "r" ))("혁"))
((("g" "u" "s" ))("현"))
((("g" "u" "t" ))("혓"))
((("g" "y" ))("효"))
((("g" "y" "f" ))("횰"))
((("g" "y" "q" ))("횹"))
((("g" "y" "s" ))("횬"))
((("g" "y" "t" ))("횻"))
((("h" ))("ㅗ"))
((("i" ))("ㅑ"))
((("j" ))("ㅓ"))
((("k" ))("ㅏ"))
((("l" ))("ㅣ"))
((("m" ))("ㅡ"))
((("n" ))("ㅜ"))
((("o" ))("ㅐ"))
((("p" ))("ㅔ"))
((("q" ))("ㅂ"))
((("q" "P" ))("볘"))
((("q" "P" "s" ))("볜"))
((("q" "b" ))("뷰"))
((("q" "b" "a" ))("븀"))
((("q" "b" "d" ))("븅"))
((("q" "b" "f" ))("뷸"))
((("q" "b" "s" ))("뷴"))
((("q" "b" "t" ))("븃"))
((("q" "h" ))("보"))
((("q" "h" "R" ))("볶"))
((("q" "h" "a" ))("봄"))
((("q" "h" "d" ))("봉"))
((("q" "h" "f" ))("볼"))
((("q" "h" "k" ))("봐"))
((("q" "h" "k" "T" ))("봤"))
((("q" "h" "k" "s" ))("봔"))
((("q" "h" "l" ))("뵈"))
((("q" "h" "l" "a" ))("뵘"))
((("q" "h" "l" "f" ))("뵐"))
((("q" "h" "l" "q" ))("뵙"))
((("q" "h" "l" "r" ))("뵉"))
((("q" "h" "l" "s" ))("뵌"))
((("q" "h" "o" ))("봬"))
((("q" "h" "o" "T" ))("뵀"))
((("q" "h" "q" ))("봅"))
((("q" "h" "r" ))("복"))
((("q" "h" "s" ))("본"))
((("q" "h" "t" ))("봇"))
((("q" "i" ))("뱌"))
((("q" "i" "q" ))("뱝"))
((("q" "i" "r" ))("뱍"))
((("q" "i" "s" ))("뱐"))
((("q" "j" ))("버"))
((("q" "j" "a" ))("범"))
((("q" "j" "d" ))("벙"))
((("q" "j" "e" ))("벋"))
((("q" "j" "f" ))("벌"))
((("q" "j" "f" "a" ))("벎"))
((("q" "j" "q" ))("법"))
((("q" "j" "r" ))("벅"))
((("q" "j" "s" ))("번"))
((("q" "j" "t" ))("벗"))
((("q" "j" "w" ))("벚"))
((("q" "k" ))("바"))
((("q" "k" "R" ))("밖"))
((("q" "k" "a" ))("밤"))
((("q" "k" "d" ))("방"))
((("q" "k" "e" ))("받"))
((("q" "k" "f" ))("발"))
((("q" "k" "f" "a" ))("밞"))
((("q" "k" "f" "q" ))("밟"))
((("q" "k" "f" "r" ))("밝"))
((("q" "k" "q" ))("밥"))
((("q" "k" "r" ))("박"))
((("q" "k" "r" "t" ))("밗"))
((("q" "k" "s" ))("반"))
((("q" "k" "t" ))("밧"))
((("q" "k" "x" ))("밭"))
((("q" "l" ))("비"))
((("q" "l" "a" ))("빔"))
((("q" "l" "c" ))("빛"))
((("q" "l" "d" ))("빙"))
((("q" "l" "f" ))("빌"))
((("q" "l" "f" "a" ))("빎"))
((("q" "l" "q" ))("빕"))
((("q" "l" "r" ))("빅"))
((("q" "l" "s" ))("빈"))
((("q" "l" "t" ))("빗"))
((("q" "l" "w" ))("빚"))
((("q" "m" ))("브"))
((("q" "m" "a" ))("븜"))
((("q" "m" "f" ))("블"))
((("q" "m" "q" ))("븝"))
((("q" "m" "r" ))("븍"))
((("q" "m" "s" ))("븐"))
((("q" "m" "t" ))("븟"))
((("q" "n" ))("부"))
((("q" "n" "a" ))("붐"))
((("q" "n" "d" ))("붕"))
((("q" "n" "e" ))("붇"))
((("q" "n" "f" ))("불"))
((("q" "n" "f" "a" ))("붊"))
((("q" "n" "f" "r" ))("붉"))
((("q" "n" "j" ))("붜"))
((("q" "n" "j" "T" ))("붰"))
((("q" "n" "j" "f" ))("붤"))
((("q" "n" "l" ))("뷔"))
((("q" "n" "l" "d" ))("뷩"))
((("q" "n" "l" "f" ))("뷜"))
((("q" "n" "l" "r" ))("뷕"))
((("q" "n" "l" "s" ))("뷘"))
((("q" "n" "p" ))("붸"))
((("q" "n" "q" ))("붑"))
((("q" "n" "r" ))("북"))
((("q" "n" "s" ))("분"))
((("q" "n" "t" ))("붓"))
((("q" "n" "v" ))("붚"))
((("q" "n" "x" ))("붙"))
((("q" "o" ))("배"))
((("q" "o" "T" ))("뱄"))
((("q" "o" "a" ))("뱀"))
((("q" "o" "d" ))("뱅"))
((("q" "o" "f" ))("밸"))
((("q" "o" "q" ))("뱁"))
((("q" "o" "r" ))("백"))
((("q" "o" "s" ))("밴"))
((("q" "o" "t" ))("뱃"))
((("q" "o" "x" ))("뱉"))
((("q" "p" ))("베"))
((("q" "p" "T" ))("벴"))
((("q" "p" "a" ))("벰"))
((("q" "p" "d" ))("벵"))
((("q" "p" "e" ))("벧"))
((("q" "p" "f" ))("벨"))
((("q" "p" "q" ))("벱"))
((("q" "p" "r" ))("벡"))
((("q" "p" "s" ))("벤"))
((("q" "p" "t" ))("벳"))
((("q" "u" ))("벼"))
((("q" "u" "T" ))("볐"))
((("q" "u" "d" ))("병"))
((("q" "u" "f" ))("별"))
((("q" "u" "q" ))("볍"))
((("q" "u" "r" ))("벽"))
((("q" "u" "s" ))("변"))
((("q" "u" "t" ))("볏"))
((("q" "u" "x" ))("볕"))
((("q" "y" ))("뵤"))
((("q" "y" "s" ))("뵨"))
((("r" ))("ㄱ"))
((("r" "O" ))("걔"))
((("r" "O" "f" ))("걜"))
((("r" "O" "s" ))("걘"))
((("r" "P" ))("계"))
((("r" "P" "f" ))("곌"))
((("r" "P" "q" ))("곕"))
((("r" "P" "s" ))("곈"))
((("r" "P" "t" ))("곗"))
((("r" "b" ))("규"))
((("r" "b" "f" ))("귤"))
((("r" "b" "s" ))("균"))
((("r" "h" ))("고"))
((("r" "h" "a" ))("곰"))
((("r" "h" "d" ))("공"))
((("r" "h" "e" ))("곧"))
((("r" "h" "f" ))("골"))
((("r" "h" "f" "a" ))("곪"))
((("r" "h" "f" "g" ))("곯"))
((("r" "h" "f" "t" ))("곬"))
((("r" "h" "k" ))("과"))
((("r" "h" "k" "a" ))("괌"))
((("r" "h" "k" "d" ))("광"))
((("r" "h" "k" "f" ))("괄"))
((("r" "h" "k" "f" "a" ))("괆"))
((("r" "h" "k" "q" ))("괍"))
((("r" "h" "k" "r" ))("곽"))
((("r" "h" "k" "s" ))("관"))
((("r" "h" "k" "t" ))("괏"))
((("r" "h" "l" ))("괴"))
((("r" "h" "l" "a" ))("굄"))
((("r" "h" "l" "d" ))("굉"))
((("r" "h" "l" "f" ))("괼"))
((("r" "h" "l" "q" ))("굅"))
((("r" "h" "l" "r" ))("괵"))
((("r" "h" "l" "s" ))("괸"))
((("r" "h" "l" "t" ))("굇"))
((("r" "h" "o" ))("괘"))
((("r" "h" "o" "T" ))("괬"))
((("r" "h" "o" "d" ))("괭"))
((("r" "h" "o" "f" ))("괠"))
((("r" "h" "o" "q" ))("괩"))
((("r" "h" "o" "s" ))("괜"))
((("r" "h" "q" ))("곱"))
((("r" "h" "r" ))("곡"))
((("r" "h" "s" ))("곤"))
((("r" "h" "t" ))("곳"))
((("r" "h" "w" ))("곶"))
((("r" "i" ))("갸"))
((("r" "i" "d" ))("걍"))
((("r" "i" "f" ))("걀"))
((("r" "i" "r" ))("갹"))
((("r" "i" "s" ))("갼"))
((("r" "i" "t" ))("걋"))
((("r" "j" ))("거"))
((("r" "j" "T" ))("겄"))
((("r" "j" "a" ))("검"))
((("r" "j" "d" ))("겅"))
((("r" "j" "e" ))("걷"))
((("r" "j" "f" ))("걸"))
((("r" "j" "f" "a" ))("걺"))
((("r" "j" "g" ))("겋"))
((("r" "j" "q" ))("겁"))
((("r" "j" "r" ))("걱"))
((("r" "j" "s" ))("건"))
((("r" "j" "t" ))("것"))
((("r" "j" "v" ))("겊"))
((("r" "j" "w" ))("겆"))
((("r" "j" "x" ))("겉"))
((("r" "k" ))("가"))
((("r" "k" "T" ))("갔"))
((("r" "k" "a" ))("감"))
((("r" "k" "c" ))("갗"))
((("r" "k" "d" ))("강"))
((("r" "k" "e" ))("갇"))
((("r" "k" "f" ))("갈"))
((("r" "k" "f" "a" ))("갊"))
((("r" "k" "f" "r" ))("갉"))
((("r" "k" "g" ))("갛"))
((("r" "k" "q" ))("갑"))
((("r" "k" "q" "t" ))("값"))
((("r" "k" "r" ))("각"))
((("r" "k" "s" ))("간"))
((("r" "k" "t" ))("갓"))
((("r" "k" "v" ))("갚"))
((("r" "k" "w" ))("갖"))
((("r" "k" "x" ))("같"))
((("r" "l" ))("기"))
((("r" "l" "a" ))("김"))
((("r" "l" "d" ))("깅"))
((("r" "l" "e" ))("긷"))
((("r" "l" "f" ))("길"))
((("r" "l" "f" "a" ))("긺"))
((("r" "l" "q" ))("깁"))
((("r" "l" "r" ))("긱"))
((("r" "l" "s" ))("긴"))
((("r" "l" "t" ))("깃"))
((("r" "l" "v" ))("깊"))
((("r" "l" "w" ))("깆"))
((("r" "m" ))("그"))
((("r" "m" "a" ))("금"))
((("r" "m" "d" ))("긍"))
((("r" "m" "e" ))("귿"))
((("r" "m" "f" ))("글"))
((("r" "m" "f" "r" ))("긁"))
((("r" "m" "l" ))("긔"))
((("r" "m" "q" ))("급"))
((("r" "m" "r" ))("극"))
((("r" "m" "s" ))("근"))
((("r" "m" "t" ))("긋"))
((("r" "n" ))("구"))
((("r" "n" "a" ))("굼"))
((("r" "n" "d" ))("궁"))
((("r" "n" "e" ))("굳"))
((("r" "n" "f" ))("굴"))
((("r" "n" "f" "a" ))("굶"))
((("r" "n" "f" "g" ))("굻"))
((("r" "n" "f" "r" ))("굵"))
((("r" "n" "j" ))("궈"))
((("r" "n" "j" "T" ))("궜"))
((("r" "n" "j" "d" ))("궝"))
((("r" "n" "j" "f" ))("궐"))
((("r" "n" "j" "r" ))("궉"))
((("r" "n" "j" "s" ))("권"))
((("r" "n" "l" ))("귀"))
((("r" "n" "l" "a" ))("귐"))
((("r" "n" "l" "f" ))("귈"))
((("r" "n" "l" "q" ))("귑"))
((("r" "n" "l" "r" ))("귁"))
((("r" "n" "l" "s" ))("귄"))
((("r" "n" "l" "t" ))("귓"))
((("r" "n" "p" ))("궤"))
((("r" "n" "p" "t" ))("궷"))
((("r" "n" "q" ))("굽"))
((("r" "n" "r" ))("국"))
((("r" "n" "s" ))("군"))
((("r" "n" "t" ))("굿"))
((("r" "n" "w" ))("궂"))
((("r" "o" ))("개"))
((("r" "o" "T" ))("갰"))
((("r" "o" "a" ))("갬"))
((("r" "o" "d" ))("갱"))
((("r" "o" "f" ))("갤"))
((("r" "o" "q" ))("갭"))
((("r" "o" "r" ))("객"))
((("r" "o" "s" ))("갠"))
((("r" "o" "t" ))("갯"))
((("r" "p" ))("게"))
((("r" "p" "T" ))("겠"))
((("r" "p" "a" ))("겜"))
((("r" "p" "d" ))("겡"))
((("r" "p" "f" ))("겔"))
((("r" "p" "q" ))("겝"))
((("r" "p" "s" ))("겐"))
((("r" "p" "t" ))("겟"))
((("r" "u" ))("겨"))
((("r" "u" "R" ))("겪"))
((("r" "u" "T" ))("겼"))
((("r" "u" "a" ))("겸"))
((("r" "u" "d" ))("경"))
((("r" "u" "e" ))("겯"))
((("r" "u" "f" ))("결"))
((("r" "u" "q" ))("겹"))
((("r" "u" "r" ))("격"))
((("r" "u" "s" ))("견"))
((("r" "u" "t" ))("겻"))
((("r" "u" "x" ))("곁"))
((("r" "y" ))("교"))
((("r" "y" "f" ))("굘"))
((("r" "y" "q" ))("굡"))
((("r" "y" "s" ))("굔"))
((("r" "y" "t" ))("굣"))
((("s" ))("ㄴ"))
((("s" "P" ))("녜"))
((("s" "P" "s" ))("녠"))
((("s" "b" ))("뉴"))
((("s" "b" "a" ))("늄"))
((("s" "b" "d" ))("늉"))
((("s" "b" "f" ))("뉼"))
((("s" "b" "q" ))("늅"))
((("s" "b" "r" ))("뉵"))
((("s" "h" ))("노"))
((("s" "h" "a" ))("놈"))
((("s" "h" "d" ))("농"))
((("s" "h" "f" ))("놀"))
((("s" "h" "f" "a" ))("놂"))
((("s" "h" "g" ))("놓"))
((("s" "h" "k" ))("놔"))
((("s" "h" "k" "T" ))("놨"))
((("s" "h" "k" "f" ))("놜"))
((("s" "h" "k" "s" ))("놘"))
((("s" "h" "l" ))("뇌"))
((("s" "h" "l" "a" ))("뇜"))
((("s" "h" "l" "f" ))("뇔"))
((("s" "h" "l" "q" ))("뇝"))
((("s" "h" "l" "s" ))("뇐"))
((("s" "h" "l" "t" ))("뇟"))
((("s" "h" "q" ))("놉"))
((("s" "h" "r" ))("녹"))
((("s" "h" "s" ))("논"))
((("s" "h" "t" ))("놋"))
((("s" "h" "v" ))("높"))
((("s" "i" ))("냐"))
((("s" "i" "a" ))("냠"))
((("s" "i" "d" ))("냥"))
((("s" "i" "f" ))("냘"))
((("s" "i" "r" ))("냑"))
((("s" "i" "s" ))("냔"))
((("s" "j" ))("너"))
((("s" "j" "T" ))("넜"))
((("s" "j" "a" ))("넘"))
((("s" "j" "d" ))("넝"))
((("s" "j" "f" ))("널"))
((("s" "j" "f" "a" ))("넒"))
((("s" "j" "f" "q" ))("넓"))
((("s" "j" "g" ))("넣"))
((("s" "j" "q" ))("넙"))
((("s" "j" "r" ))("넉"))
((("s" "j" "r" "t" ))("넋"))
((("s" "j" "s" ))("넌"))
((("s" "j" "t" ))("넛"))
((("s" "k" ))("나"))
((("s" "k" "R" ))("낚"))
((("s" "k" "T" ))("났"))
((("s" "k" "a" ))("남"))
((("s" "k" "c" ))("낯"))
((("s" "k" "d" ))("낭"))
((("s" "k" "e" ))("낟"))
((("s" "k" "f" ))("날"))
((("s" "k" "f" "a" ))("낢"))
((("s" "k" "f" "r" ))("낡"))
((("s" "k" "g" ))("낳"))
((("s" "k" "q" ))("납"))
((("s" "k" "r" ))("낙"))
((("s" "k" "s" ))("난"))
((("s" "k" "t" ))("낫"))
((("s" "k" "w" ))("낮"))
((("s" "k" "x" ))("낱"))
((("s" "l" ))("니"))
((("s" "l" "a" ))("님"))
((("s" "l" "d" ))("닝"))
((("s" "l" "f" ))("닐"))
((("s" "l" "f" "a" ))("닒"))
((("s" "l" "q" ))("닙"))
((("s" "l" "r" ))("닉"))
((("s" "l" "s" ))("닌"))
((("s" "l" "t" ))("닛"))
((("s" "l" "v" ))("닢"))
((("s" "m" ))("느"))
((("s" "m" "a" ))("늠"))
((("s" "m" "d" ))("능"))
((("s" "m" "f" ))("늘"))
((("s" "m" "f" "a" ))("늚"))
((("s" "m" "f" "r" ))("늙"))
((("s" "m" "l" ))("늬"))
((("s" "m" "l" "f" ))("늴"))
((("s" "m" "l" "s" ))("늰"))
((("s" "m" "q" ))("늡"))
((("s" "m" "r" ))("늑"))
((("s" "m" "s" ))("는"))
((("s" "m" "t" ))("늣"))
((("s" "m" "v" ))("늪"))
((("s" "m" "w" ))("늦"))
((("s" "n" ))("누"))
((("s" "n" "a" ))("눔"))
((("s" "n" "d" ))("눙"))
((("s" "n" "e" ))("눋"))
((("s" "n" "f" ))("눌"))
((("s" "n" "j" ))("눠"))
((("s" "n" "j" "T" ))("눴"))
((("s" "n" "l" ))("뉘"))
((("s" "n" "l" "a" ))("뉨"))
((("s" "n" "l" "f" ))("뉠"))
((("s" "n" "l" "q" ))("뉩"))
((("s" "n" "l" "s" ))("뉜"))
((("s" "n" "p" ))("눼"))
((("s" "n" "q" ))("눕"))
((("s" "n" "r" ))("눅"))
((("s" "n" "s" ))("눈"))
((("s" "n" "t" ))("눗"))
((("s" "o" ))("내"))
((("s" "o" "T" ))("냈"))
((("s" "o" "a" ))("냄"))
((("s" "o" "d" ))("냉"))
((("s" "o" "f" ))("낼"))
((("s" "o" "q" ))("냅"))
((("s" "o" "r" ))("낵"))
((("s" "o" "s" ))("낸"))
((("s" "o" "t" ))("냇"))
((("s" "p" ))("네"))
((("s" "p" "T" ))("넸"))
((("s" "p" "a" ))("넴"))
((("s" "p" "d" ))("넹"))
((("s" "p" "f" ))("넬"))
((("s" "p" "q" ))("넵"))
((("s" "p" "r" ))("넥"))
((("s" "p" "s" ))("넨"))
((("s" "p" "t" ))("넷"))
((("s" "u" ))("녀"))
((("s" "u" "T" ))("녔"))
((("s" "u" "a" ))("념"))
((("s" "u" "d" ))("녕"))
((("s" "u" "f" ))("녈"))
((("s" "u" "q" ))("녑"))
((("s" "u" "r" ))("녁"))
((("s" "u" "s" ))("년"))
((("s" "u" "z" ))("녘"))
((("s" "y" ))("뇨"))
((("s" "y" "d" ))("뇽"))
((("s" "y" "f" ))("뇰"))
((("s" "y" "q" ))("뇹"))
((("s" "y" "r" ))("뇩"))
((("s" "y" "s" ))("뇬"))
((("s" "y" "t" ))("뇻"))
((("t" ))("ㅅ"))
((("t" "O" ))("섀"))
((("t" "O" "a" ))("섐"))
((("t" "O" "d" ))("섕"))
((("t" "O" "f" ))("섈"))
((("t" "O" "s" ))("섄"))
((("t" "P" ))("셰"))
((("t" "P" "d" ))("솅"))
((("t" "P" "f" ))("셸"))
((("t" "P" "s" ))("셴"))
((("t" "b" ))("슈"))
((("t" "b" "a" ))("슘"))
((("t" "b" "d" ))("슝"))
((("t" "b" "f" ))("슐"))
((("t" "b" "r" ))("슉"))
((("t" "b" "t" ))("슛"))
((("t" "h" ))("소"))
((("t" "h" "R" ))("솎"))
((("t" "h" "a" ))("솜"))
((("t" "h" "d" ))("송"))
((("t" "h" "f" ))("솔"))
((("t" "h" "f" "a" ))("솖"))
((("t" "h" "k" ))("솨"))
((("t" "h" "k" "d" ))("솽"))
((("t" "h" "k" "f" ))("솰"))
((("t" "h" "k" "r" ))("솩"))
((("t" "h" "k" "s" ))("솬"))
((("t" "h" "l" ))("쇠"))
((("t" "h" "l" "a" ))("쇰"))
((("t" "h" "l" "f" ))("쇨"))
((("t" "h" "l" "q" ))("쇱"))
((("t" "h" "l" "s" ))("쇤"))
((("t" "h" "l" "t" ))("쇳"))
((("t" "h" "o" ))("쇄"))
((("t" "h" "o" "T" ))("쇘"))
((("t" "h" "o" "a" ))("쇔"))
((("t" "h" "o" "f" ))("쇌"))
((("t" "h" "o" "s" ))("쇈"))
((("t" "h" "o" "t" ))("쇗"))
((("t" "h" "q" ))("솝"))
((("t" "h" "r" ))("속"))
((("t" "h" "s" ))("손"))
((("t" "h" "t" ))("솟"))
((("t" "h" "x" ))("솥"))
((("t" "i" ))("샤"))
((("t" "i" "a" ))("샴"))
((("t" "i" "d" ))("샹"))
((("t" "i" "f" ))("샬"))
((("t" "i" "q" ))("샵"))
((("t" "i" "r" ))("샥"))
((("t" "i" "s" ))("샨"))
((("t" "i" "t" ))("샷"))
((("t" "j" ))("서"))
((("t" "j" "R" ))("섞"))
((("t" "j" "T" ))("섰"))
((("t" "j" "a" ))("섬"))
((("t" "j" "d" ))("성"))
((("t" "j" "e" ))("섣"))
((("t" "j" "f" ))("설"))
((("t" "j" "f" "a" ))("섦"))
((("t" "j" "f" "q" ))("섧"))
((("t" "j" "q" ))("섭"))
((("t" "j" "r" ))("석"))
((("t" "j" "r" "t" ))("섟"))
((("t" "j" "s" ))("선"))
((("t" "j" "t" ))("섯"))
((("t" "j" "v" ))("섶"))
((("t" "k" ))("사"))
((("t" "k" "T" ))("샀"))
((("t" "k" "a" ))("삼"))
((("t" "k" "d" ))("상"))
((("t" "k" "e" ))("삳"))
((("t" "k" "f" ))("살"))
((("t" "k" "f" "a" ))("삶"))
((("t" "k" "f" "r" ))("삵"))
((("t" "k" "q" ))("삽"))
((("t" "k" "r" ))("삭"))
((("t" "k" "r" "t" ))("삯"))
((("t" "k" "s" ))("산"))
((("t" "k" "t" ))("삿"))
((("t" "k" "x" ))("샅"))
((("t" "l" ))("시"))
((("t" "l" "a" ))("심"))
((("t" "l" "d" ))("싱"))
((("t" "l" "e" ))("싣"))
((("t" "l" "f" ))("실"))
((("t" "l" "f" "g" ))("싫"))
((("t" "l" "q" ))("십"))
((("t" "l" "r" ))("식"))
((("t" "l" "s" ))("신"))
((("t" "l" "t" ))("싯"))
((("t" "l" "v" ))("싶"))
((("t" "m" ))("스"))
((("t" "m" "a" ))("슴"))
((("t" "m" "d" ))("승"))
((("t" "m" "f" ))("슬"))
((("t" "m" "f" "r" ))("슭"))
((("t" "m" "q" ))("습"))
((("t" "m" "r" ))("슥"))
((("t" "m" "s" ))("슨"))
((("t" "m" "t" ))("슷"))
((("t" "n" ))("수"))
((("t" "n" "a" ))("숨"))
((("t" "n" "c" ))("숯"))
((("t" "n" "d" ))("숭"))
((("t" "n" "e" ))("숟"))
((("t" "n" "f" ))("술"))
((("t" "n" "j" ))("숴"))
((("t" "n" "j" "T" ))("쉈"))
((("t" "n" "l" ))("쉬"))
((("t" "n" "l" "a" ))("쉼"))
((("t" "n" "l" "d" ))("슁"))
((("t" "n" "l" "f" ))("쉴"))
((("t" "n" "l" "q" ))("쉽"))
((("t" "n" "l" "r" ))("쉭"))
((("t" "n" "l" "s" ))("쉰"))
((("t" "n" "l" "t" ))("쉿"))
((("t" "n" "p" ))("쉐"))
((("t" "n" "p" "a" ))("쉠"))
((("t" "n" "p" "d" ))("쉥"))
((("t" "n" "p" "f" ))("쉘"))
((("t" "n" "p" "r" ))("쉑"))
((("t" "n" "p" "s" ))("쉔"))
((("t" "n" "q" ))("숩"))
((("t" "n" "r" ))("숙"))
((("t" "n" "s" ))("순"))
((("t" "n" "t" ))("숫"))
((("t" "n" "v" ))("숲"))
((("t" "n" "x" ))("숱"))
((("t" "o" ))("새"))
((("t" "o" "T" ))("샜"))
((("t" "o" "a" ))("샘"))
((("t" "o" "d" ))("생"))
((("t" "o" "f" ))("샐"))
((("t" "o" "q" ))("샙"))
((("t" "o" "r" ))("색"))
((("t" "o" "s" ))("샌"))
((("t" "o" "t" ))("샛"))
((("t" "p" ))("세"))
((("t" "p" "T" ))("셌"))
((("t" "p" "a" ))("셈"))
((("t" "p" "d" ))("셍"))
((("t" "p" "f" ))("셀"))
((("t" "p" "q" ))("셉"))
((("t" "p" "r" ))("섹"))
((("t" "p" "s" ))("센"))
((("t" "p" "t" ))("셋"))
((("t" "u" ))("셔"))
((("t" "u" "T" ))("셨"))
((("t" "u" "a" ))("셤"))
((("t" "u" "d" ))("셩"))
((("t" "u" "f" ))("셜"))
((("t" "u" "q" ))("셥"))
((("t" "u" "r" ))("셕"))
((("t" "u" "s" ))("션"))
((("t" "u" "t" ))("셧"))
((("t" "y" ))("쇼"))
((("t" "y" "a" ))("숌"))
((("t" "y" "d" ))("숑"))
((("t" "y" "f" ))("숄"))
((("t" "y" "q" ))("숍"))
((("t" "y" "r" ))("쇽"))
((("t" "y" "s" ))("숀"))
((("t" "y" "t" ))("숏"))
((("u" ))("ㅕ"))
((("v" ))("ㅍ"))
((("v" "P" ))("폐"))
((("v" "P" "f" ))("폘"))
((("v" "P" "q" ))("폡"))
((("v" "P" "t" ))("폣"))
((("v" "b" ))("퓨"))
((("v" "b" "a" ))("퓸"))
((("v" "b" "d" ))("퓽"))
((("v" "b" "f" ))("퓰"))
((("v" "b" "s" ))("퓬"))
((("v" "b" "t" ))("퓻"))
((("v" "h" ))("포"))
((("v" "h" "a" ))("폼"))
((("v" "h" "d" ))("퐁"))
((("v" "h" "f" ))("폴"))
((("v" "h" "k" ))("퐈"))
((("v" "h" "k" "d" ))("퐝"))
((("v" "h" "l" ))("푀"))
((("v" "h" "l" "s" ))("푄"))
((("v" "h" "q" ))("폽"))
((("v" "h" "r" ))("폭"))
((("v" "h" "s" ))("폰"))
((("v" "h" "t" ))("폿"))
((("v" "i" ))("퍄"))
((("v" "i" "r" ))("퍅"))
((("v" "j" ))("퍼"))
((("v" "j" "T" ))("펐"))
((("v" "j" "a" ))("펌"))
((("v" "j" "d" ))("펑"))
((("v" "j" "f" ))("펄"))
((("v" "j" "q" ))("펍"))
((("v" "j" "r" ))("퍽"))
((("v" "j" "s" ))("펀"))
((("v" "j" "t" ))("펏"))
((("v" "k" ))("파"))
((("v" "k" "R" ))("팎"))
((("v" "k" "T" ))("팠"))
((("v" "k" "a" ))("팜"))
((("v" "k" "d" ))("팡"))
((("v" "k" "f" ))("팔"))
((("v" "k" "f" "a" ))("팖"))
((("v" "k" "q" ))("팝"))
((("v" "k" "r" ))("팍"))
((("v" "k" "s" ))("판"))
((("v" "k" "t" ))("팟"))
((("v" "k" "x" ))("팥"))
((("v" "l" ))("피"))
((("v" "l" "a" ))("핌"))
((("v" "l" "d" ))("핑"))
((("v" "l" "f" ))("필"))
((("v" "l" "q" ))("핍"))
((("v" "l" "r" ))("픽"))
((("v" "l" "s" ))("핀"))
((("v" "l" "t" ))("핏"))
((("v" "m" ))("프"))
((("v" "m" "a" ))("픔"))
((("v" "m" "f" ))("플"))
((("v" "m" "q" ))("픕"))
((("v" "m" "s" ))("픈"))
((("v" "m" "t" ))("픗"))
((("v" "n" ))("푸"))
((("v" "n" "a" ))("품"))
((("v" "n" "d" ))("풍"))
((("v" "n" "e" ))("푿"))
((("v" "n" "f" ))("풀"))
((("v" "n" "f" "a" ))("풂"))
((("v" "n" "j" ))("풔"))
((("v" "n" "j" "d" ))("풩"))
((("v" "n" "l" ))("퓌"))
((("v" "n" "l" "a" ))("퓜"))
((("v" "n" "l" "f" ))("퓔"))
((("v" "n" "l" "s" ))("퓐"))
((("v" "n" "l" "t" ))("퓟"))
((("v" "n" "q" ))("풉"))
((("v" "n" "r" ))("푹"))
((("v" "n" "s" ))("푼"))
((("v" "n" "t" ))("풋"))
((("v" "o" ))("패"))
((("v" "o" "T" ))("팼"))
((("v" "o" "a" ))("팸"))
((("v" "o" "d" ))("팽"))
((("v" "o" "f" ))("팰"))
((("v" "o" "q" ))("팹"))
((("v" "o" "r" ))("팩"))
((("v" "o" "s" ))("팬"))
((("v" "o" "t" ))("팻"))
((("v" "p" ))("페"))
((("v" "p" "a" ))("펨"))
((("v" "p" "d" ))("펭"))
((("v" "p" "f" ))("펠"))
((("v" "p" "q" ))("펩"))
((("v" "p" "r" ))("펙"))
((("v" "p" "s" ))("펜"))
((("v" "p" "t" ))("펫"))
((("v" "u" ))("펴"))
((("v" "u" "T" ))("폈"))
((("v" "u" "a" ))("폄"))
((("v" "u" "d" ))("평"))
((("v" "u" "f" ))("펼"))
((("v" "u" "q" ))("폅"))
((("v" "u" "s" ))("편"))
((("v" "y" ))("표"))
((("v" "y" "f" ))("푤"))
((("v" "y" "q" ))("푭"))
((("v" "y" "s" ))("푠"))
((("v" "y" "t" ))("푯"))
((("w" ))("ㅈ"))
((("w" "O" ))("쟤"))
((("w" "O" "f" ))("쟬"))
((("w" "O" "s" ))("쟨"))
((("w" "P" ))("졔"))
((("w" "b" ))("쥬"))
((("w" "b" "a" ))("쥼"))
((("w" "b" "f" ))("쥴"))
((("w" "b" "s" ))("쥰"))
((("w" "h" ))("조"))
((("w" "h" "a" ))("좀"))
((("w" "h" "c" ))("좇"))
((("w" "h" "d" ))("종"))
((("w" "h" "f" ))("졸"))
((("w" "h" "f" "a" ))("졺"))
((("w" "h" "g" ))("좋"))
((("w" "h" "k" ))("좌"))
((("w" "h" "k" "d" ))("좡"))
((("w" "h" "k" "f" ))("좔"))
((("w" "h" "k" "q" ))("좝"))
((("w" "h" "k" "r" ))("좍"))
((("w" "h" "k" "t" ))("좟"))
((("w" "h" "l" ))("죄"))
((("w" "h" "l" "a" ))("죔"))
((("w" "h" "l" "d" ))("죙"))
((("w" "h" "l" "f" ))("죌"))
((("w" "h" "l" "q" ))("죕"))
((("w" "h" "l" "s" ))("죈"))
((("w" "h" "l" "t" ))("죗"))
((("w" "h" "o" ))("좨"))
((("w" "h" "o" "T" ))("좼"))
((("w" "h" "o" "d" ))("좽"))
((("w" "h" "q" ))("좁"))
((("w" "h" "r" ))("족"))
((("w" "h" "s" ))("존"))
((("w" "h" "t" ))("좃"))
((("w" "h" "w" ))("좆"))
((("w" "i" ))("쟈"))
((("w" "i" "a" ))("쟘"))
((("w" "i" "d" ))("쟝"))
((("w" "i" "f" ))("쟐"))
((("w" "i" "r" ))("쟉"))
((("w" "i" "s" ))("쟌"))
((("w" "i" "s" "g" ))("쟎"))
((("w" "j" ))("저"))
((("w" "j" "a" ))("점"))
((("w" "j" "d" ))("정"))
((("w" "j" "f" ))("절"))
((("w" "j" "f" "a" ))("젊"))
((("w" "j" "q" ))("접"))
((("w" "j" "r" ))("적"))
((("w" "j" "s" ))("전"))
((("w" "j" "t" ))("젓"))
((("w" "j" "w" ))("젖"))
((("w" "k" ))("자"))
((("w" "k" "T" ))("잤"))
((("w" "k" "a" ))("잠"))
((("w" "k" "d" ))("장"))
((("w" "k" "e" ))("잗"))
((("w" "k" "f" ))("잘"))
((("w" "k" "f" "a" ))("잚"))
((("w" "k" "q" ))("잡"))
((("w" "k" "r" ))("작"))
((("w" "k" "s" ))("잔"))
((("w" "k" "s" "g" ))("잖"))
((("w" "k" "t" ))("잣"))
((("w" "k" "w" ))("잦"))
((("w" "l" ))("지"))
((("w" "l" "a" ))("짐"))
((("w" "l" "d" ))("징"))
((("w" "l" "e" ))("짇"))
((("w" "l" "f" ))("질"))
((("w" "l" "f" "a" ))("짊"))
((("w" "l" "q" ))("집"))
((("w" "l" "r" ))("직"))
((("w" "l" "s" ))("진"))
((("w" "l" "t" ))("짓"))
((("w" "l" "v" ))("짚"))
((("w" "l" "w" ))("짖"))
((("w" "l" "x" ))("짙"))
((("w" "m" ))("즈"))
((("w" "m" "a" ))("즘"))
((("w" "m" "d" ))("증"))
((("w" "m" "f" ))("즐"))
((("w" "m" "q" ))("즙"))
((("w" "m" "r" ))("즉"))
((("w" "m" "s" ))("즌"))
((("w" "m" "t" ))("즛"))
((("w" "n" ))("주"))
((("w" "n" "a" ))("줌"))
((("w" "n" "d" ))("중"))
((("w" "n" "f" ))("줄"))
((("w" "n" "f" "a" ))("줆"))
((("w" "n" "f" "r" ))("줅"))
((("w" "n" "j" ))("줘"))
((("w" "n" "j" "T" ))("줬"))
((("w" "n" "l" ))("쥐"))
((("w" "n" "l" "a" ))("쥠"))
((("w" "n" "l" "f" ))("쥘"))
((("w" "n" "l" "q" ))("쥡"))
((("w" "n" "l" "r" ))("쥑"))
((("w" "n" "l" "s" ))("쥔"))
((("w" "n" "l" "t" ))("쥣"))
((("w" "n" "p" ))("줴"))
((("w" "n" "q" ))("줍"))
((("w" "n" "r" ))("죽"))
((("w" "n" "s" ))("준"))
((("w" "n" "t" ))("줏"))
((("w" "o" ))("재"))
((("w" "o" "T" ))("쟀"))
((("w" "o" "a" ))("잼"))
((("w" "o" "d" ))("쟁"))
((("w" "o" "f" ))("잴"))
((("w" "o" "q" ))("잽"))
((("w" "o" "r" ))("잭"))
((("w" "o" "s" ))("잰"))
((("w" "o" "t" ))("잿"))
((("w" "p" ))("제"))
((("w" "p" "a" ))("젬"))
((("w" "p" "d" ))("젱"))
((("w" "p" "f" ))("젤"))
((("w" "p" "q" ))("젭"))
((("w" "p" "r" ))("젝"))
((("w" "p" "s" ))("젠"))
((("w" "p" "t" ))("젯"))
((("w" "u" ))("져"))
((("w" "u" "T" ))("졌"))
((("w" "u" "a" ))("졈"))
((("w" "u" "d" ))("졍"))
((("w" "u" "f" ))("졀"))
((("w" "u" "q" ))("졉"))
((("w" "u" "s" ))("젼"))
((("w" "y" ))("죠"))
((("w" "y" "d" ))("죵"))
((("w" "y" "r" ))("죡"))
((("w" "y" "s" ))("죤"))
((("x" ))("ㅌ"))
((("x" "P" ))("톄"))
((("x" "P" "s" ))("톈"))
((("x" "b" ))("튜"))
((("x" "b" "a" ))("튬"))
((("x" "b" "d" ))("튱"))
((("x" "b" "f" ))("튤"))
((("x" "b" "s" ))("튠"))
((("x" "h" ))("토"))
((("x" "h" "a" ))("톰"))
((("x" "h" "d" ))("통"))
((("x" "h" "f" ))("톨"))
((("x" "h" "k" ))("톼"))
((("x" "h" "k" "s" ))("퇀"))
((("x" "h" "l" ))("퇴"))
((("x" "h" "l" "d" ))("툉"))
((("x" "h" "l" "s" ))("퇸"))
((("x" "h" "l" "t" ))("툇"))
((("x" "h" "o" ))("퇘"))
((("x" "h" "q" ))("톱"))
((("x" "h" "r" ))("톡"))
((("x" "h" "s" ))("톤"))
((("x" "h" "t" ))("톳"))
((("x" "h" "v" ))("톺"))
((("x" "i" ))("탸"))
((("x" "i" "d" ))("턍"))
((("x" "j" ))("터"))
((("x" "j" "T" ))("텄"))
((("x" "j" "a" ))("텀"))
((("x" "j" "d" ))("텅"))
((("x" "j" "f" ))("털"))
((("x" "j" "f" "a" ))("턺"))
((("x" "j" "q" ))("텁"))
((("x" "j" "r" ))("턱"))
((("x" "j" "s" ))("턴"))
((("x" "j" "t" ))("텃"))
((("x" "k" ))("타"))
((("x" "k" "T" ))("탔"))
((("x" "k" "a" ))("탐"))
((("x" "k" "d" ))("탕"))
((("x" "k" "f" ))("탈"))
((("x" "k" "f" "r" ))("탉"))
((("x" "k" "q" ))("탑"))
((("x" "k" "r" ))("탁"))
((("x" "k" "s" ))("탄"))
((("x" "k" "t" ))("탓"))
((("x" "l" ))("티"))
((("x" "l" "a" ))("팀"))
((("x" "l" "d" ))("팅"))
((("x" "l" "f" ))("틸"))
((("x" "l" "q" ))("팁"))
((("x" "l" "r" ))("틱"))
((("x" "l" "s" ))("틴"))
((("x" "l" "t" ))("팃"))
((("x" "m" ))("트"))
((("x" "m" "a" ))("틈"))
((("x" "m" "e" ))("튿"))
((("x" "m" "f" ))("틀"))
((("x" "m" "f" "a" ))("틂"))
((("x" "m" "l" ))("틔"))
((("x" "m" "l" "a" ))("틤"))
((("x" "m" "l" "f" ))("틜"))
((("x" "m" "l" "q" ))("틥"))
((("x" "m" "l" "s" ))("틘"))
((("x" "m" "q" ))("틉"))
((("x" "m" "r" ))("특"))
((("x" "m" "s" ))("튼"))
((("x" "m" "t" ))("틋"))
((("x" "n" ))("투"))
((("x" "n" "a" ))("툼"))
((("x" "n" "d" ))("퉁"))
((("x" "n" "f" ))("툴"))
((("x" "n" "j" ))("퉈"))
((("x" "n" "j" "T" ))("퉜"))
((("x" "n" "l" ))("튀"))
((("x" "n" "l" "a" ))("튐"))
((("x" "n" "l" "d" ))("튕"))
((("x" "n" "l" "f" ))("튈"))
((("x" "n" "l" "q" ))("튑"))
((("x" "n" "l" "r" ))("튁"))
((("x" "n" "l" "s" ))("튄"))
((("x" "n" "p" ))("퉤"))
((("x" "n" "q" ))("툽"))
((("x" "n" "r" ))("툭"))
((("x" "n" "s" ))("툰"))
((("x" "n" "t" ))("툿"))
((("x" "o" ))("태"))
((("x" "o" "T" ))("탰"))
((("x" "o" "a" ))("탬"))
((("x" "o" "d" ))("탱"))
((("x" "o" "f" ))("탤"))
((("x" "o" "q" ))("탭"))
((("x" "o" "r" ))("택"))
((("x" "o" "s" ))("탠"))
((("x" "o" "t" ))("탯"))
((("x" "p" ))("테"))
((("x" "p" "a" ))("템"))
((("x" "p" "d" ))("텡"))
((("x" "p" "f" ))("텔"))
((("x" "p" "q" ))("텝"))
((("x" "p" "r" ))("텍"))
((("x" "p" "s" ))("텐"))
((("x" "p" "t" ))("텟"))
((("x" "u" ))("텨"))
((("x" "u" "T" ))("텼"))
((("x" "u" "s" ))("텬"))
((("x" "y" ))("툐"))
((("y" ))("ㅛ"))
((("z" ))("ㅋ"))
((("z" "P" ))("켸"))
((("z" "b" ))("큐"))
((("z" "b" "a" ))("큠"))
((("z" "b" "f" ))("큘"))
((("z" "b" "s" ))("큔"))
((("z" "h" ))("코"))
((("z" "h" "a" ))("콤"))
((("z" "h" "d" ))("콩"))
((("z" "h" "f" ))("콜"))
((("z" "h" "k" ))("콰"))
((("z" "h" "k" "a" ))("쾀"))
((("z" "h" "k" "d" ))("쾅"))
((("z" "h" "k" "f" ))("콸"))
((("z" "h" "k" "r" ))("콱"))
((("z" "h" "k" "s" ))("콴"))
((("z" "h" "l" ))("쾨"))
((("z" "h" "l" "f" ))("쾰"))
((("z" "h" "o" ))("쾌"))
((("z" "h" "o" "d" ))("쾡"))
((("z" "h" "q" ))("콥"))
((("z" "h" "r" ))("콕"))
((("z" "h" "s" ))("콘"))
((("z" "h" "t" ))("콧"))
((("z" "i" ))("캬"))
((("z" "i" "d" ))("컁"))
((("z" "i" "r" ))("캭"))
((("z" "j" ))("커"))
((("z" "j" "T" ))("컸"))
((("z" "j" "a" ))("컴"))
((("z" "j" "d" ))("컹"))
((("z" "j" "e" ))("컫"))
((("z" "j" "f" ))("컬"))
((("z" "j" "q" ))("컵"))
((("z" "j" "r" ))("컥"))
((("z" "j" "s" ))("컨"))
((("z" "j" "t" ))("컷"))
((("z" "k" ))("카"))
((("z" "k" "a" ))("캄"))
((("z" "k" "d" ))("캉"))
((("z" "k" "f" ))("칼"))
((("z" "k" "q" ))("캅"))
((("z" "k" "r" ))("칵"))
((("z" "k" "s" ))("칸"))
((("z" "k" "t" ))("캇"))
((("z" "l" ))("키"))
((("z" "l" "a" ))("킴"))
((("z" "l" "d" ))("킹"))
((("z" "l" "f" ))("킬"))
((("z" "l" "q" ))("킵"))
((("z" "l" "r" ))("킥"))
((("z" "l" "s" ))("킨"))
((("z" "l" "t" ))("킷"))
((("z" "m" ))("크"))
((("z" "m" "a" ))("큼"))
((("z" "m" "d" ))("킁"))
((("z" "m" "f" ))("클"))
((("z" "m" "q" ))("큽"))
((("z" "m" "r" ))("큭"))
((("z" "m" "s" ))("큰"))
((("z" "n" ))("쿠"))
((("z" "n" "a" ))("쿰"))
((("z" "n" "d" ))("쿵"))
((("z" "n" "f" ))("쿨"))
((("z" "n" "j" ))("쿼"))
((("z" "n" "j" "d" ))("퀑"))
((("z" "n" "j" "f" ))("퀄"))
((("z" "n" "j" "s" ))("퀀"))
((("z" "n" "l" ))("퀴"))
((("z" "n" "l" "a" ))("큄"))
((("z" "n" "l" "d" ))("큉"))
((("z" "n" "l" "f" ))("퀼"))
((("z" "n" "l" "q" ))("큅"))
((("z" "n" "l" "r" ))("퀵"))
((("z" "n" "l" "s" ))("퀸"))
((("z" "n" "l" "t" ))("큇"))
((("z" "n" "p" ))("퀘"))
((("z" "n" "p" "d" ))("퀭"))
((("z" "n" "q" ))("쿱"))
((("z" "n" "r" ))("쿡"))
((("z" "n" "s" ))("쿤"))
((("z" "n" "t" ))("쿳"))
((("z" "o" ))("캐"))
((("z" "o" "T" ))("캤"))
((("z" "o" "a" ))("캠"))
((("z" "o" "d" ))("캥"))
((("z" "o" "f" ))("캘"))
((("z" "o" "q" ))("캡"))
((("z" "o" "r" ))("캑"))
((("z" "o" "s" ))("캔"))
((("z" "o" "t" ))("캣"))
((("z" "p" ))("케"))
((("z" "p" "a" ))("켐"))
((("z" "p" "d" ))("켕"))
((("z" "p" "f" ))("켈"))
((("z" "p" "q" ))("켑"))
((("z" "p" "r" ))("켁"))
((("z" "p" "s" ))("켄"))
((("z" "p" "t" ))("켓"))
((("z" "u" ))("켜"))
((("z" "u" "T" ))("켰"))
((("z" "u" "a" ))("켬"))
((("z" "u" "d" ))("켱"))
((("z" "u" "f" ))("켤"))
((("z" "u" "q" ))("켭"))
((("z" "u" "s" ))("켠"))
((("z" "u" "t" ))("켯"))
((("z" "y" ))("쿄"))
))
| null | https://raw.githubusercontent.com/uim/uim/d1ac9d9315ff8c57c713b502544fef9b3a83b3e5/scm/hangul2.scm | scheme |
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
may be used to endorse or promote products derived from this software
without specific prior written permission.
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
SUCH DAMAGE.
| Copyright ( c ) 2003 - 2013 uim Project
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
3 . Neither the name of authors nor the names of its contributors
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ` ` AS IS '' AND
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR LIABLE
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT
(define hangul2-rule
'(
((("E" ))("ㄸ"))
((("E" "h" ))("또"))
((("E" "h" "d" ))("똥"))
((("E" "h" "f" ))("똘"))
((("E" "h" "k" ))("똬"))
((("E" "h" "k" "f" ))("똴"))
((("E" "h" "l" ))("뙤"))
((("E" "h" "l" "s" ))("뙨"))
((("E" "h" "o" ))("뙈"))
((("E" "h" "r" ))("똑"))
((("E" "h" "s" ))("똔"))
((("E" "j" ))("떠"))
((("E" "j" "T" ))("떴"))
((("E" "j" "a" ))("떰"))
((("E" "j" "d" ))("떵"))
((("E" "j" "f" ))("떨"))
((("E" "j" "f" "a" ))("떪"))
((("E" "j" "f" "q" ))("떫"))
((("E" "j" "g" ))("떻"))
((("E" "j" "q" ))("떱"))
((("E" "j" "r" ))("떡"))
((("E" "j" "s" ))("떤"))
((("E" "j" "t" ))("떳"))
((("E" "k" ))("따"))
((("E" "k" "T" ))("땄"))
((("E" "k" "a" ))("땀"))
((("E" "k" "d" ))("땅"))
((("E" "k" "f" ))("딸"))
((("E" "k" "g" ))("땋"))
((("E" "k" "q" ))("땁"))
((("E" "k" "r" ))("딱"))
((("E" "k" "s" ))("딴"))
((("E" "k" "t" ))("땃"))
((("E" "l" ))("띠"))
((("E" "l" "a" ))("띰"))
((("E" "l" "d" ))("띵"))
((("E" "l" "f" ))("띨"))
((("E" "l" "q" ))("띱"))
((("E" "l" "s" ))("띤"))
((("E" "l" "t" ))("띳"))
((("E" "m" ))("뜨"))
((("E" "m" "a" ))("뜸"))
((("E" "m" "e" ))("뜯"))
((("E" "m" "f" ))("뜰"))
((("E" "m" "l" ))("띄"))
((("E" "m" "l" "a" ))("띔"))
((("E" "m" "l" "f" ))("띌"))
((("E" "m" "l" "q" ))("띕"))
((("E" "m" "l" "s" ))("띈"))
((("E" "m" "q" ))("뜹"))
((("E" "m" "r" ))("뜩"))
((("E" "m" "s" ))("뜬"))
((("E" "m" "t" ))("뜻"))
((("E" "n" ))("뚜"))
((("E" "n" "a" ))("뚬"))
((("E" "n" "d" ))("뚱"))
((("E" "n" "f" ))("뚤"))
((("E" "n" "f" "g" ))("뚫"))
((("E" "n" "l" ))("뛰"))
((("E" "n" "l" "a" ))("뜀"))
((("E" "n" "l" "d" ))("뜅"))
((("E" "n" "l" "f" ))("뛸"))
((("E" "n" "l" "q" ))("뜁"))
((("E" "n" "l" "s" ))("뛴"))
((("E" "n" "p" ))("뛔"))
((("E" "n" "r" ))("뚝"))
((("E" "n" "s" ))("뚠"))
((("E" "o" ))("때"))
((("E" "o" "T" ))("땠"))
((("E" "o" "a" ))("땜"))
((("E" "o" "d" ))("땡"))
((("E" "o" "f" ))("땔"))
((("E" "o" "q" ))("땝"))
((("E" "o" "r" ))("땍"))
((("E" "o" "s" ))("땐"))
((("E" "o" "t" ))("땟"))
((("E" "p" ))("떼"))
((("E" "p" "T" ))("뗐"))
((("E" "p" "a" ))("뗌"))
((("E" "p" "d" ))("뗑"))
((("E" "p" "f" ))("뗄"))
((("E" "p" "q" ))("뗍"))
((("E" "p" "r" ))("떽"))
((("E" "p" "s" ))("뗀"))
((("E" "p" "t" ))("뗏"))
((("E" "u" ))("뗘"))
((("E" "u" "T" ))("뗬"))
((("H" "." ))("ㆍ"))
((("H" "." "l" ))("ㆎ"))
((("H" "D" ))("ㆀ"))
((("H" "G" ))("ㆅ"))
((("H" "Q" "d" ))("ㅹ"))
((("H" "S" ))("ㅥ"))
((("H" "T" ))("ㅿ"))
((("H" "a" "T" ))("ㅰ"))
((("H" "a" "d" ))("ㅱ"))
((("H" "a" "q" ))("ㅮ"))
((("H" "a" "t" ))("ㅯ"))
((("H" "b" "P" ))("ㆋ"))
((("H" "b" "l" ))("ㆌ"))
((("H" "b" "u" ))("ㆊ"))
((("H" "d" ))("ㆁ"))
((("H" "d" "T" ))("ㆃ"))
((("H" "d" "w" ))("ㆂ"))
((("H" "f" "G" ))("ㅭ"))
((("H" "f" "T" ))("ㅬ"))
((("H" "f" "e" ))("ㅪ"))
((("H" "f" "q" "t" ))("ㅫ"))
((("H" "f" "r" "t" ))("ㅩ"))
((("H" "g" ))("ㆆ"))
((("H" "q" "d" ))("ㅸ"))
((("H" "q" "e" ))("ㅳ"))
((("H" "q" "r" ))("ㅲ"))
((("H" "q" "t" "e" ))("ㅵ"))
((("H" "q" "t" "r" ))("ㅴ"))
((("H" "q" "w" ))("ㅶ"))
((("H" "q" "x" ))("ㅷ"))
((("H" "s" "T" ))("ㅨ"))
((("H" "s" "e" ))("ㅦ"))
((("H" "s" "t" ))("ㅧ"))
((("H" "t" "e" ))("ㅼ"))
((("H" "t" "q" ))("ㅽ"))
((("H" "t" "r" ))("ㅺ"))
((("H" "t" "s" ))("ㅻ"))
((("H" "t" "w" ))("ㅾ"))
((("H" "v" "d" ))("ㆄ"))
((("H" "y" "O" ))("ㆈ"))
((("H" "y" "i" ))("ㆇ"))
((("H" "y" "l" ))("ㆉ"))
((("O" ))("ㅒ"))
((("O" "T" ))("쟀"))
((("O" "a" ))("잼"))
((("O" "d" ))("쟁"))
((("O" "f" ))("잴"))
((("O" "q" ))("잽"))
((("O" "r" ))("잭"))
((("O" "s" ))("잰"))
((("O" "t" ))("잿"))
((("P" ))("ㅖ"))
((("Q" ))("ㅃ"))
((("Q" "b" ))("쀼"))
((("Q" "b" "d" ))("쁑"))
((("Q" "h" ))("뽀"))
((("Q" "h" "a" ))("뽐"))
((("Q" "h" "d" ))("뽕"))
((("Q" "h" "f" ))("뽈"))
((("Q" "h" "l" ))("뾔"))
((("Q" "h" "q" ))("뽑"))
((("Q" "h" "r" ))("뽁"))
((("Q" "h" "s" ))("뽄"))
((("Q" "i" ))("뺘"))
((("Q" "i" "a" ))("뺨"))
((("Q" "i" "r" ))("뺙"))
((("Q" "j" ))("뻐"))
((("Q" "j" "T" ))("뻤"))
((("Q" "j" "a" ))("뻠"))
((("Q" "j" "d" ))("뻥"))
((("Q" "j" "e" ))("뻗"))
((("Q" "j" "f" ))("뻘"))
((("Q" "j" "r" ))("뻑"))
((("Q" "j" "s" ))("뻔"))
((("Q" "j" "t" ))("뻣"))
((("Q" "k" ))("빠"))
((("Q" "k" "T" ))("빴"))
((("Q" "k" "a" ))("빰"))
((("Q" "k" "d" ))("빵"))
((("Q" "k" "f" ))("빨"))
((("Q" "k" "f" "a" ))("빪"))
((("Q" "k" "g" ))("빻"))
((("Q" "k" "q" ))("빱"))
((("Q" "k" "r" ))("빡"))
((("Q" "k" "s" ))("빤"))
((("Q" "k" "t" ))("빳"))
((("Q" "l" ))("삐"))
((("Q" "l" "a" ))("삠"))
((("Q" "l" "d" ))("삥"))
((("Q" "l" "f" ))("삘"))
((("Q" "l" "q" ))("삡"))
((("Q" "l" "r" ))("삑"))
((("Q" "l" "s" ))("삔"))
((("Q" "l" "t" ))("삣"))
((("Q" "m" ))("쁘"))
((("Q" "m" "a" ))("쁨"))
((("Q" "m" "f" ))("쁠"))
((("Q" "m" "q" ))("쁩"))
((("Q" "m" "s" ))("쁜"))
((("Q" "n" ))("뿌"))
((("Q" "n" "a" ))("뿜"))
((("Q" "n" "d" ))("뿡"))
((("Q" "n" "f" ))("뿔"))
((("Q" "n" "r" ))("뿍"))
((("Q" "n" "s" ))("뿐"))
((("Q" "n" "t" ))("뿟"))
((("Q" "o" ))("빼"))
((("Q" "o" "T" ))("뺐"))
((("Q" "o" "a" ))("뺌"))
((("Q" "o" "d" ))("뺑"))
((("Q" "o" "f" ))("뺄"))
((("Q" "o" "q" ))("뺍"))
((("Q" "o" "r" ))("빽"))
((("Q" "o" "s" ))("뺀"))
((("Q" "o" "t" ))("뺏"))
((("Q" "p" ))("뻬"))
((("Q" "p" "d" ))("뼁"))
((("Q" "u" ))("뼈"))
((("Q" "u" "T" ))("뼜"))
((("Q" "u" "a" ))("뼘"))
((("Q" "u" "d" ))("뼝"))
((("Q" "u" "q" ))("뼙"))
((("Q" "u" "r" ))("뼉"))
((("Q" "u" "t" ))("뼛"))
((("Q" "y" ))("뾰"))
((("Q" "y" "d" ))("뿅"))
((("R" ))("ㄲ"))
((("R" "P" ))("꼐"))
((("R" "b" ))("뀨"))
((("R" "h" ))("꼬"))
((("R" "h" "a" ))("꼼"))
((("R" "h" "c" ))("꽃"))
((("R" "h" "d" ))("꽁"))
((("R" "h" "f" ))("꼴"))
((("R" "h" "k" ))("꽈"))
((("R" "h" "k" "T" ))("꽜"))
((("R" "h" "k" "d" ))("꽝"))
((("R" "h" "k" "f" ))("꽐"))
((("R" "h" "k" "r" ))("꽉"))
((("R" "h" "l" ))("꾀"))
((("R" "h" "l" "a" ))("꾐"))
((("R" "h" "l" "d" ))("꾕"))
((("R" "h" "l" "f" ))("꾈"))
((("R" "h" "l" "q" ))("꾑"))
((("R" "h" "l" "s" ))("꾄"))
((("R" "h" "o" ))("꽤"))
((("R" "h" "o" "d" ))("꽹"))
((("R" "h" "o" "r" ))("꽥"))
((("R" "h" "q" ))("꼽"))
((("R" "h" "r" ))("꼭"))
((("R" "h" "s" ))("꼰"))
((("R" "h" "s" "g" ))("꼲"))
((("R" "h" "t" ))("꼿"))
((("R" "h" "w" ))("꽂"))
((("R" "i" ))("꺄"))
((("R" "i" "f" ))("꺌"))
((("R" "i" "r" ))("꺅"))
((("R" "j" ))("꺼"))
((("R" "j" "R" ))("꺾"))
((("R" "j" "T" ))("껐"))
((("R" "j" "a" ))("껌"))
((("R" "j" "d" ))("껑"))
((("R" "j" "f" ))("껄"))
((("R" "j" "q" ))("껍"))
((("R" "j" "r" ))("꺽"))
((("R" "j" "s" ))("껀"))
((("R" "j" "t" ))("껏"))
((("R" "k" ))("까"))
((("R" "k" "R" ))("깎"))
((("R" "k" "T" ))("깠"))
((("R" "k" "a" ))("깜"))
((("R" "k" "d" ))("깡"))
((("R" "k" "f" ))("깔"))
((("R" "k" "f" "a" ))("깖"))
((("R" "k" "q" ))("깝"))
((("R" "k" "r" ))("깍"))
((("R" "k" "s" ))("깐"))
((("R" "k" "t" ))("깟"))
((("R" "k" "x" ))("깥"))
((("R" "l" ))("끼"))
((("R" "l" "a" ))("낌"))
((("R" "l" "d" ))("낑"))
((("R" "l" "f" ))("낄"))
((("R" "l" "q" ))("낍"))
((("R" "l" "r" ))("끽"))
((("R" "l" "s" ))("낀"))
((("R" "l" "t" ))("낏"))
((("R" "m" ))("끄"))
((("R" "m" "a" ))("끔"))
((("R" "m" "d" ))("끙"))
((("R" "m" "f" ))("끌"))
((("R" "m" "f" "a" ))("끎"))
((("R" "m" "f" "g" ))("끓"))
((("R" "m" "q" ))("끕"))
((("R" "m" "r" ))("끅"))
((("R" "m" "s" ))("끈"))
((("R" "m" "s" "g" ))("끊"))
((("R" "m" "t" ))("끗"))
((("R" "m" "x" ))("끝"))
((("R" "n" ))("꾸"))
((("R" "n" "a" ))("꿈"))
((("R" "n" "d" ))("꿍"))
((("R" "n" "f" ))("꿀"))
((("R" "n" "f" "g" ))("꿇"))
((("R" "n" "j" ))("꿔"))
((("R" "n" "j" "T" ))("꿨"))
((("R" "n" "j" "d" ))("꿩"))
((("R" "n" "j" "f" ))("꿜"))
((("R" "n" "l" ))("뀌"))
((("R" "n" "l" "a" ))("뀜"))
((("R" "n" "l" "f" ))("뀔"))
((("R" "n" "l" "q" ))("뀝"))
((("R" "n" "l" "s" ))("뀐"))
((("R" "n" "p" ))("꿰"))
((("R" "n" "p" "T" ))("뀄"))
((("R" "n" "p" "a" ))("뀀"))
((("R" "n" "p" "f" ))("꿸"))
((("R" "n" "p" "q" ))("뀁"))
((("R" "n" "p" "r" ))("꿱"))
((("R" "n" "p" "s" ))("꿴"))
((("R" "n" "q" ))("꿉"))
((("R" "n" "r" ))("꾹"))
((("R" "n" "s" ))("꾼"))
((("R" "n" "t" ))("꿋"))
((("R" "n" "w" ))("꿎"))
((("R" "o" ))("깨"))
((("R" "o" "T" ))("깼"))
((("R" "o" "a" ))("깸"))
((("R" "o" "d" ))("깽"))
((("R" "o" "f" ))("깰"))
((("R" "o" "q" ))("깹"))
((("R" "o" "r" ))("깩"))
((("R" "o" "s" ))("깬"))
((("R" "o" "t" ))("깻"))
((("R" "p" ))("께"))
((("R" "p" "a" ))("껨"))
((("R" "p" "d" ))("껭"))
((("R" "p" "r" ))("껙"))
((("R" "p" "s" ))("껜"))
((("R" "p" "t" ))("껫"))
((("R" "u" ))("껴"))
((("R" "u" "T" ))("꼈"))
((("R" "u" "f" ))("껼"))
((("R" "u" "s" ))("껸"))
((("R" "u" "t" ))("꼇"))
((("R" "u" "x" ))("꼍"))
((("R" "y" ))("꾜"))
((("S" "%" ))("‰"))
((("S" "A" ))("Å"))
((("S" "C" ))("℃"))
((("S" "C" "/" ))("¢"))
((("S" "C" "o" ))("㏇"))
((("S" "F" ))("℉"))
((("S" "N" "o" ))("№"))
((("S" "P" ))("£"))
((("S" "T" "M" ))("™"))
((("S" "T" "e" "l" ))("℡"))
((("S" "W" ))("₩"))
((("S" "Y" ))("¥"))
((("S" "a" "m" ))("㏂"))
((("S" "k" "s" ))("㉿"))
((("S" "p" "m" ))("㏘"))
((("S" "w" "n" ))("㈜"))
((("T" ))("ㅆ"))
((("T" "P" "s" ))("쏀"))
((("T" "b" "d" ))("쓩"))
((("T" "h" ))("쏘"))
((("T" "h" "a" ))("쏨"))
((("T" "h" "d" ))("쏭"))
((("T" "h" "e" ))("쏟"))
((("T" "h" "f" ))("쏠"))
((("T" "h" "f" "a" ))("쏢"))
((("T" "h" "k" ))("쏴"))
((("T" "h" "k" "T" ))("쐈"))
((("T" "h" "k" "r" ))("쏵"))
((("T" "h" "k" "s" ))("쏸"))
((("T" "h" "l" ))("쐬"))
((("T" "h" "l" "a" ))("쐼"))
((("T" "h" "l" "f" ))("쐴"))
((("T" "h" "l" "q" ))("쐽"))
((("T" "h" "l" "s" ))("쐰"))
((("T" "h" "o" ))("쐐"))
((("T" "h" "o" "T" ))("쐤"))
((("T" "h" "q" ))("쏩"))
((("T" "h" "r" ))("쏙"))
((("T" "h" "s" ))("쏜"))
((("T" "i" "d" ))("썅"))
((("T" "j" ))("써"))
((("T" "j" "T" ))("썼"))
((("T" "j" "a" ))("썸"))
((("T" "j" "d" ))("썽"))
((("T" "j" "f" ))("썰"))
((("T" "j" "f" "a" ))("썲"))
((("T" "j" "q" ))("썹"))
((("T" "j" "r" ))("썩"))
((("T" "j" "s" ))("썬"))
((("T" "k" ))("싸"))
((("T" "k" "T" ))("쌌"))
((("T" "k" "a" ))("쌈"))
((("T" "k" "d" ))("쌍"))
((("T" "k" "f" ))("쌀"))
((("T" "k" "g" ))("쌓"))
((("T" "k" "q" ))("쌉"))
((("T" "k" "r" ))("싹"))
((("T" "k" "r" "t" ))("싻"))
((("T" "k" "s" ))("싼"))
((("T" "l" ))("씨"))
((("T" "l" "a" ))("씸"))
((("T" "l" "d" ))("씽"))
((("T" "l" "f" ))("씰"))
((("T" "l" "q" ))("씹"))
((("T" "l" "r" ))("씩"))
((("T" "l" "s" ))("씬"))
((("T" "l" "t" ))("씻"))
((("T" "m" ))("쓰"))
((("T" "m" "a" ))("씀"))
((("T" "m" "f" ))("쓸"))
((("T" "m" "f" "a" ))("쓺"))
((("T" "m" "f" "g" ))("쓿"))
((("T" "m" "l" ))("씌"))
((("T" "m" "l" "a" ))("씜"))
((("T" "m" "l" "f" ))("씔"))
((("T" "m" "l" "s" ))("씐"))
((("T" "m" "q" ))("씁"))
((("T" "m" "r" ))("쓱"))
((("T" "m" "s" ))("쓴"))
((("T" "n" ))("쑤"))
((("T" "n" "a" ))("쑴"))
((("T" "n" "d" ))("쑹"))
((("T" "n" "f" ))("쑬"))
((("T" "n" "j" ))("쒀"))
((("T" "n" "j" "T" ))("쒔"))
((("T" "n" "l" ))("쒸"))
((("T" "n" "l" "s" ))("쒼"))
((("T" "n" "p" ))("쒜"))
((("T" "n" "q" ))("쑵"))
((("T" "n" "r" ))("쑥"))
((("T" "n" "s" ))("쑨"))
((("T" "o" ))("쌔"))
((("T" "o" "T" ))("쌨"))
((("T" "o" "a" ))("쌤"))
((("T" "o" "d" ))("쌩"))
((("T" "o" "f" ))("쌜"))
((("T" "o" "q" ))("쌥"))
((("T" "o" "r" ))("쌕"))
((("T" "o" "s" ))("쌘"))
((("T" "p" ))("쎄"))
((("T" "p" "f" ))("쎌"))
((("T" "p" "s" ))("쎈"))
((("T" "y" ))("쑈"))
((("W" ))("ㅉ"))
((("W" "b" ))("쮸"))
((("W" "h" ))("쪼"))
((("W" "h" "a" ))("쫌"))
((("W" "h" "c" ))("쫓"))
((("W" "h" "d" ))("쫑"))
((("W" "h" "f" ))("쫄"))
((("W" "h" "k" ))("쫘"))
((("W" "h" "k" "T" ))("쫬"))
((("W" "h" "k" "f" ))("쫠"))
((("W" "h" "k" "r" ))("쫙"))
((("W" "h" "l" ))("쬐"))
((("W" "h" "l" "a" ))("쬠"))
((("W" "h" "l" "f" ))("쬘"))
((("W" "h" "l" "q" ))("쬡"))
((("W" "h" "l" "s" ))("쬔"))
((("W" "h" "o" ))("쫴"))
((("W" "h" "o" "T" ))("쬈"))
((("W" "h" "q" ))("쫍"))
((("W" "h" "r" ))("쪽"))
((("W" "h" "s" ))("쫀"))
((("W" "h" "t" ))("쫏"))
((("W" "i" ))("쨔"))
((("W" "i" "d" ))("쨩"))
((("W" "i" "s" ))("쨘"))
((("W" "j" ))("쩌"))
((("W" "j" "T" ))("쩠"))
((("W" "j" "a" ))("쩜"))
((("W" "j" "d" ))("쩡"))
((("W" "j" "f" ))("쩔"))
((("W" "j" "q" ))("쩝"))
((("W" "j" "r" ))("쩍"))
((("W" "j" "s" ))("쩐"))
((("W" "j" "t" ))("쩟"))
((("W" "k" ))("짜"))
((("W" "k" "T" ))("짰"))
((("W" "k" "a" ))("짬"))
((("W" "k" "d" ))("짱"))
((("W" "k" "f" ))("짤"))
((("W" "k" "f" "q" ))("짧"))
((("W" "k" "q" ))("짭"))
((("W" "k" "r" ))("짝"))
((("W" "k" "s" ))("짠"))
((("W" "k" "s" "g" ))("짢"))
((("W" "k" "t" ))("짯"))
((("W" "l" ))("찌"))
((("W" "l" "a" ))("찜"))
((("W" "l" "d" ))("찡"))
((("W" "l" "f" ))("찔"))
((("W" "l" "g" ))("찧"))
((("W" "l" "q" ))("찝"))
((("W" "l" "r" ))("찍"))
((("W" "l" "s" ))("찐"))
((("W" "l" "w" ))("찢"))
((("W" "m" ))("쯔"))
((("W" "m" "a" ))("쯤"))
((("W" "m" "d" ))("쯩"))
((("W" "m" "t" ))("쯧"))
((("W" "n" ))("쭈"))
((("W" "n" "a" ))("쭘"))
((("W" "n" "d" ))("쭝"))
((("W" "n" "f" ))("쭐"))
((("W" "n" "j" ))("쭤"))
((("W" "n" "j" "T" ))("쭸"))
((("W" "n" "j" "d" ))("쭹"))
((("W" "n" "l" ))("쮜"))
((("W" "n" "q" ))("쭙"))
((("W" "n" "r" ))("쭉"))
((("W" "n" "s" ))("쭌"))
((("W" "o" ))("째"))
((("W" "o" "T" ))("쨌"))
((("W" "o" "a" ))("쨈"))
((("W" "o" "d" ))("쨍"))
((("W" "o" "f" ))("쨀"))
((("W" "o" "q" ))("쨉"))
((("W" "o" "r" ))("짹"))
((("W" "o" "s" ))("짼"))
((("W" "o" "t" ))("쨋"))
((("W" "p" ))("쩨"))
((("W" "p" "d" ))("쩽"))
((("W" "u" ))("쪄"))
((("W" "u" "T" ))("쪘"))
((("W" "y" "d" ))("쭁"))
((("Z" ))(")"))
((("Z" "!" ))("!"))
((("Z" "#" ))("#"))
((("Z" "$" ))("$"))
((("Z" "%" ))("%"))
((("Z" "&" ))("&"))
((("Z" "'" ))("'"))
((("Z" "(" ))("("))
((("Z" "*" ))("*"))
((("Z" "+" ))("+"))
((("Z" "," ))(","))
((("Z" "-" ))("-"))
((("Z" "." ))("."))
((("Z" "/" ))("/"))
((("Z" "0" ))("0"))
((("Z" "1" ))("1"))
((("Z" "2" ))("2"))
((("Z" "3" ))("3"))
((("Z" "4" ))("4"))
((("Z" "5" ))("5"))
((("Z" "6" ))("6"))
((("Z" "7" ))("7"))
((("Z" "8" ))("8"))
((("Z" "9" ))("9"))
((("Z" ":" ))(":"))
((("Z" ";" ))(";"))
((("Z" "<" ))("<"))
((("Z" "=" ))("="))
((("Z" ">" ))(">"))
((("Z" "?" ))("?"))
((("Z" "@" ))("@"))
((("Z" "A" ))("A"))
((("Z" "B" ))("B"))
((("Z" "C" ))("C"))
((("Z" "D" ))("D"))
((("Z" "E" ))("E"))
((("Z" "F" ))("F"))
((("Z" "G" ))("G"))
((("Z" "H" ))("H"))
((("Z" "I" ))("I"))
((("Z" "J" ))("J"))
((("Z" "K" ))("K"))
((("Z" "L" ))("L"))
((("Z" "M" ))("M"))
((("Z" "N" ))("N"))
((("Z" "O" ))("O"))
((("Z" "P" ))("P"))
((("Z" "Q" ))("Q"))
((("Z" "R" ))("R"))
((("Z" "S" ))("S"))
((("Z" "T" ))("T"))
((("Z" "U" ))("U"))
((("Z" "V" ))("V"))
((("Z" "W" ))("W"))
((("Z" "X" ))("X"))
((("Z" "Y" ))("Y"))
((("Z" "Z" ))("Z"))
((("Z" "[" ))("["))
((("Z" "\\" ))("?"))
((("Z" "]" ))("]"))
((("Z" "^" ))("^"))
((("Z" "^" "-" ))(" ̄"))
((("Z" "_" ))("_"))
((("Z" "`" ))("`"))
((("Z" "a" ))("a"))
((("Z" "b" ))("b"))
((("Z" "c" ))("c"))
((("Z" "d" ))("d"))
((("Z" "e" ))("e"))
((("Z" "f" ))("f"))
((("Z" "g" ))("g"))
((("Z" "h" ))("h"))
((("Z" "i" ))("i"))
((("Z" "j" ))("j"))
((("Z" "k" ))("k"))
((("Z" "l" ))("l"))
((("Z" "m" ))("m"))
((("Z" "n" ))("n"))
((("Z" "o" ))("o"))
((("Z" "p" ))("p"))
((("Z" "q" ))("q"))
((("Z" "r" ))("r"))
((("Z" "s" ))("s"))
((("Z" "t" ))("t"))
((("Z" "u" ))("u"))
((("Z" "v" ))("v"))
((("Z" "w" ))("w"))
((("Z" "x" ))("x"))
((("Z" "y" ))("y"))
((("Z" "z" ))("z"))
((("Z" "{" ))("{"))
((("Z" "|" ))("|"))
((("Z" "}" ))("}"))
((("a" ))("ㅁ"))
((("a" "P" ))("몌"))
((("a" "b" ))("뮤"))
((("a" "b" "a" ))("뮴"))
((("a" "b" "f" ))("뮬"))
((("a" "b" "s" ))("뮨"))
((("a" "b" "t" ))("뮷"))
((("a" "h" ))("모"))
((("a" "h" "a" ))("몸"))
((("a" "h" "d" ))("몽"))
((("a" "h" "f" ))("몰"))
((("a" "h" "f" "a" ))("몲"))
((("a" "h" "k" ))("뫄"))
((("a" "h" "k" "T" ))("뫘"))
((("a" "h" "k" "d" ))("뫙"))
((("a" "h" "k" "s" ))("뫈"))
((("a" "h" "l" ))("뫼"))
((("a" "h" "l" "d" ))("묑"))
((("a" "h" "l" "f" ))("묄"))
((("a" "h" "l" "q" ))("묍"))
((("a" "h" "l" "s" ))("묀"))
((("a" "h" "l" "t" ))("묏"))
((("a" "h" "q" ))("몹"))
((("a" "h" "r" ))("목"))
((("a" "h" "r" "t" ))("몫"))
((("a" "h" "s" ))("몬"))
((("a" "h" "t" ))("못"))
((("a" "i" ))("먀"))
((("a" "i" "d" ))("먕"))
((("a" "i" "f" ))("먈"))
((("a" "i" "r" ))("먁"))
((("a" "j" ))("머"))
((("a" "j" "a" ))("멈"))
((("a" "j" "d" ))("멍"))
((("a" "j" "f" ))("멀"))
((("a" "j" "f" "a" ))("멂"))
((("a" "j" "g" ))("멓"))
((("a" "j" "q" ))("멉"))
((("a" "j" "r" ))("먹"))
((("a" "j" "s" ))("먼"))
((("a" "j" "t" ))("멋"))
((("a" "j" "w" ))("멎"))
((("a" "k" ))("마"))
((("a" "k" "a" ))("맘"))
((("a" "k" "d" ))("망"))
((("a" "k" "e" ))("맏"))
((("a" "k" "f" ))("말"))
((("a" "k" "f" "a" ))("맒"))
((("a" "k" "f" "r" ))("맑"))
((("a" "k" "g" ))("맣"))
((("a" "k" "q" ))("맙"))
((("a" "k" "r" ))("막"))
((("a" "k" "s" ))("만"))
((("a" "k" "s" "g" ))("많"))
((("a" "k" "t" ))("맛"))
((("a" "k" "w" ))("맞"))
((("a" "k" "x" ))("맡"))
((("a" "l" ))("미"))
((("a" "l" "T" ))("밌"))
((("a" "l" "a" ))("밈"))
((("a" "l" "c" ))("및"))
((("a" "l" "d" ))("밍"))
((("a" "l" "e" ))("믿"))
((("a" "l" "f" ))("밀"))
((("a" "l" "f" "a" ))("밂"))
((("a" "l" "q" ))("밉"))
((("a" "l" "r" ))("믹"))
((("a" "l" "s" ))("민"))
((("a" "l" "t" ))("밋"))
((("a" "l" "x" ))("밑"))
((("a" "m" ))("므"))
((("a" "m" "a" ))("믐"))
((("a" "m" "f" ))("믈"))
((("a" "m" "s" ))("믄"))
((("a" "m" "t" ))("믓"))
((("a" "n" ))("무"))
((("a" "n" "R" ))("묶"))
((("a" "n" "a" ))("뭄"))
((("a" "n" "d" ))("뭉"))
((("a" "n" "e" ))("묻"))
((("a" "n" "f" ))("물"))
((("a" "n" "f" "a" ))("묾"))
((("a" "n" "f" "r" ))("묽"))
((("a" "n" "g" ))("뭏"))
((("a" "n" "j" ))("뭐"))
((("a" "n" "j" "f" ))("뭘"))
((("a" "n" "j" "q" ))("뭡"))
((("a" "n" "j" "s" ))("뭔"))
((("a" "n" "j" "t" ))("뭣"))
((("a" "n" "l" ))("뮈"))
((("a" "n" "l" "f" ))("뮐"))
((("a" "n" "l" "s" ))("뮌"))
((("a" "n" "p" ))("뭬"))
((("a" "n" "q" ))("뭅"))
((("a" "n" "r" ))("묵"))
((("a" "n" "s" ))("문"))
((("a" "n" "t" ))("뭇"))
((("a" "n" "x" ))("뭍"))
((("a" "o" ))("매"))
((("a" "o" "T" ))("맸"))
((("a" "o" "a" ))("맴"))
((("a" "o" "d" ))("맹"))
((("a" "o" "f" ))("맬"))
((("a" "o" "q" ))("맵"))
((("a" "o" "r" ))("맥"))
((("a" "o" "s" ))("맨"))
((("a" "o" "t" ))("맷"))
((("a" "o" "w" ))("맺"))
((("a" "p" ))("메"))
((("a" "p" "T" ))("멨"))
((("a" "p" "a" ))("멤"))
((("a" "p" "d" ))("멩"))
((("a" "p" "f" ))("멜"))
((("a" "p" "q" ))("멥"))
((("a" "p" "r" ))("멕"))
((("a" "p" "s" ))("멘"))
((("a" "p" "t" ))("멧"))
((("a" "u" ))("며"))
((("a" "u" "T" ))("몄"))
((("a" "u" "c" ))("몇"))
((("a" "u" "d" ))("명"))
((("a" "u" "f" ))("멸"))
((("a" "u" "r" ))("멱"))
((("a" "u" "s" ))("면"))
((("a" "u" "t" ))("몃"))
((("a" "y" ))("묘"))
((("a" "y" "f" ))("묠"))
((("a" "y" "q" ))("묩"))
((("a" "y" "s" ))("묜"))
((("a" "y" "t" ))("묫"))
((("b" ))("ㅠ"))
((("c" ))("ㅊ"))
((("c" "P" ))("쳬"))
((("c" "P" "d" ))("촁"))
((("c" "P" "s" ))("쳰"))
((("c" "b" ))("츄"))
((("c" "b" "a" ))("츔"))
((("c" "b" "d" ))("츙"))
((("c" "b" "f" ))("츌"))
((("c" "b" "s" ))("츈"))
((("c" "h" ))("초"))
((("c" "h" "a" ))("촘"))
((("c" "h" "d" ))("총"))
((("c" "h" "f" ))("촐"))
((("c" "h" "k" ))("촤"))
((("c" "h" "k" "d" ))("촹"))
((("c" "h" "k" "f" ))("촬"))
((("c" "h" "k" "s" ))("촨"))
((("c" "h" "l" ))("최"))
((("c" "h" "l" "a" ))("쵬"))
((("c" "h" "l" "d" ))("쵱"))
((("c" "h" "l" "f" ))("쵤"))
((("c" "h" "l" "q" ))("쵭"))
((("c" "h" "l" "s" ))("쵠"))
((("c" "h" "l" "t" ))("쵯"))
((("c" "h" "q" ))("촙"))
((("c" "h" "r" ))("촉"))
((("c" "h" "s" ))("촌"))
((("c" "h" "t" ))("촛"))
((("c" "i" ))("챠"))
((("c" "i" "a" ))("챰"))
((("c" "i" "d" ))("챵"))
((("c" "i" "f" ))("챨"))
((("c" "i" "s" ))("챤"))
((("c" "i" "s" "g" ))("챦"))
((("c" "j" ))("처"))
((("c" "j" "T" ))("첬"))
((("c" "j" "a" ))("첨"))
((("c" "j" "d" ))("청"))
((("c" "j" "f" ))("철"))
((("c" "j" "q" ))("첩"))
((("c" "j" "r" ))("척"))
((("c" "j" "s" ))("천"))
((("c" "j" "t" ))("첫"))
((("c" "k" ))("차"))
((("c" "k" "T" ))("찼"))
((("c" "k" "a" ))("참"))
((("c" "k" "d" ))("창"))
((("c" "k" "f" ))("찰"))
((("c" "k" "q" ))("찹"))
((("c" "k" "r" ))("착"))
((("c" "k" "s" ))("찬"))
((("c" "k" "s" "g" ))("찮"))
((("c" "k" "t" ))("찻"))
((("c" "k" "w" ))("찾"))
((("c" "l" ))("치"))
((("c" "l" "a" ))("침"))
((("c" "l" "d" ))("칭"))
((("c" "l" "e" ))("칟"))
((("c" "l" "f" ))("칠"))
((("c" "l" "f" "r" ))("칡"))
((("c" "l" "q" ))("칩"))
((("c" "l" "r" ))("칙"))
((("c" "l" "s" ))("친"))
((("c" "l" "t" ))("칫"))
((("c" "m" ))("츠"))
((("c" "m" "a" ))("츰"))
((("c" "m" "d" ))("층"))
((("c" "m" "f" ))("츨"))
((("c" "m" "q" ))("츱"))
((("c" "m" "r" ))("측"))
((("c" "m" "s" ))("츤"))
((("c" "m" "t" ))("츳"))
((("c" "n" ))("추"))
((("c" "n" "a" ))("춤"))
((("c" "n" "d" ))("충"))
((("c" "n" "f" ))("출"))
((("c" "n" "j" ))("춰"))
((("c" "n" "j" "T" ))("췄"))
((("c" "n" "l" ))("취"))
((("c" "n" "l" "a" ))("췸"))
((("c" "n" "l" "d" ))("췽"))
((("c" "n" "l" "f" ))("췰"))
((("c" "n" "l" "q" ))("췹"))
((("c" "n" "l" "s" ))("췬"))
((("c" "n" "l" "t" ))("췻"))
((("c" "n" "p" ))("췌"))
((("c" "n" "p" "s" ))("췐"))
((("c" "n" "q" ))("춥"))
((("c" "n" "r" ))("축"))
((("c" "n" "s" ))("춘"))
((("c" "n" "t" ))("춧"))
((("c" "o" ))("채"))
((("c" "o" "T" ))("챘"))
((("c" "o" "a" ))("챔"))
((("c" "o" "d" ))("챙"))
((("c" "o" "f" ))("챌"))
((("c" "o" "q" ))("챕"))
((("c" "o" "r" ))("책"))
((("c" "o" "s" ))("챈"))
((("c" "o" "t" ))("챗"))
((("c" "p" ))("체"))
((("c" "p" "a" ))("쳄"))
((("c" "p" "d" ))("쳉"))
((("c" "p" "f" ))("첼"))
((("c" "p" "q" ))("쳅"))
((("c" "p" "r" ))("첵"))
((("c" "p" "s" ))("첸"))
((("c" "p" "t" ))("쳇"))
((("c" "u" ))("쳐"))
((("c" "u" "T" ))("쳤"))
((("c" "u" "s" ))("쳔"))
((("c" "y" ))("쵸"))
((("c" "y" "a" ))("춈"))
((("d" ))("ㅇ"))
((("d" "O" ))("얘"))
((("d" "O" "f" ))("얠"))
((("d" "O" "q" ))("얩"))
((("d" "O" "s" ))("얜"))
((("d" "P" ))("예"))
((("d" "P" "T" ))("옜"))
((("d" "P" "a" ))("옘"))
((("d" "P" "f" ))("옐"))
((("d" "P" "q" ))("옙"))
((("d" "P" "s" ))("옌"))
((("d" "P" "t" ))("옛"))
((("d" "b" ))("유"))
((("d" "b" "a" ))("윰"))
((("d" "b" "c" ))("윷"))
((("d" "b" "d" ))("융"))
((("d" "b" "f" ))("율"))
((("d" "b" "q" ))("윱"))
((("d" "b" "r" ))("육"))
((("d" "b" "s" ))("윤"))
((("d" "b" "t" ))("윳"))
((("d" "h" ))("오"))
((("d" "h" "a" ))("옴"))
((("d" "h" "c" ))("옻"))
((("d" "h" "d" ))("옹"))
((("d" "h" "f" ))("올"))
((("d" "h" "f" "a" ))("옮"))
((("d" "h" "f" "g" ))("옳"))
((("d" "h" "f" "r" ))("옭"))
((("d" "h" "f" "t" ))("옰"))
((("d" "h" "k" ))("와"))
((("d" "h" "k" "T" ))("왔"))
((("d" "h" "k" "a" ))("왐"))
((("d" "h" "k" "d" ))("왕"))
((("d" "h" "k" "f" ))("왈"))
((("d" "h" "k" "q" ))("왑"))
((("d" "h" "k" "r" ))("왁"))
((("d" "h" "k" "s" ))("완"))
((("d" "h" "k" "t" ))("왓"))
((("d" "h" "l" ))("외"))
((("d" "h" "l" "a" ))("욈"))
((("d" "h" "l" "d" ))("욍"))
((("d" "h" "l" "f" ))("욀"))
((("d" "h" "l" "q" ))("욉"))
((("d" "h" "l" "r" ))("왹"))
((("d" "h" "l" "s" ))("왼"))
((("d" "h" "l" "t" ))("욋"))
((("d" "h" "o" ))("왜"))
((("d" "h" "o" "a" ))("왬"))
((("d" "h" "o" "d" ))("왱"))
((("d" "h" "o" "r" ))("왝"))
((("d" "h" "o" "s" ))("왠"))
((("d" "h" "o" "t" ))("왯"))
((("d" "h" "q" ))("옵"))
((("d" "h" "r" ))("옥"))
((("d" "h" "s" ))("온"))
((("d" "h" "t" ))("옷"))
((("d" "i" ))("야"))
((("d" "i" "a" ))("얌"))
((("d" "i" "d" ))("양"))
((("d" "i" "f" ))("얄"))
((("d" "i" "f" "q" ))("얇"))
((("d" "i" "g" ))("얗"))
((("d" "i" "q" ))("얍"))
((("d" "i" "r" ))("약"))
((("d" "i" "s" ))("얀"))
((("d" "i" "t" ))("얏"))
((("d" "i" "x" ))("얕"))
((("d" "j" ))("어"))
((("d" "j" "T" ))("었"))
((("d" "j" "a" ))("엄"))
((("d" "j" "d" ))("엉"))
((("d" "j" "e" ))("얻"))
((("d" "j" "f" ))("얼"))
((("d" "j" "f" "a" ))("얾"))
((("d" "j" "f" "r" ))("얽"))
((("d" "j" "q" ))("업"))
((("d" "j" "q" "t" ))("없"))
((("d" "j" "r" ))("억"))
((("d" "j" "s" ))("언"))
((("d" "j" "s" "w" ))("얹"))
((("d" "j" "t" ))("엇"))
((("d" "j" "v" ))("엎"))
((("d" "j" "w" ))("엊"))
((("d" "j" "z" ))("엌"))
((("d" "k" ))("아"))
((("d" "k" "T" ))("았"))
((("d" "k" "a" ))("암"))
((("d" "k" "d" ))("앙"))
((("d" "k" "f" ))("알"))
((("d" "k" "f" "a" ))("앎"))
((("d" "k" "f" "g" ))("앓"))
((("d" "k" "f" "r" ))("앍"))
((("d" "k" "q" ))("압"))
((("d" "k" "r" ))("악"))
((("d" "k" "s" ))("안"))
((("d" "k" "s" "g" ))("않"))
((("d" "k" "s" "w" ))("앉"))
((("d" "k" "t" ))("앗"))
((("d" "k" "v" ))("앞"))
((("d" "k" "x" ))("앝"))
((("d" "l" ))("이"))
((("d" "l" "T" ))("있"))
((("d" "l" "a" ))("임"))
((("d" "l" "d" ))("잉"))
((("d" "l" "f" ))("일"))
((("d" "l" "f" "a" ))("읾"))
((("d" "l" "f" "g" ))("잃"))
((("d" "l" "f" "r" ))("읽"))
((("d" "l" "q" ))("입"))
((("d" "l" "r" ))("익"))
((("d" "l" "s" ))("인"))
((("d" "l" "t" ))("잇"))
((("d" "l" "v" ))("잎"))
((("d" "l" "w" ))("잊"))
((("d" "m" ))("으"))
((("d" "m" "a" ))("음"))
((("d" "m" "c" ))("읓"))
((("d" "m" "d" ))("응"))
((("d" "m" "f" ))("을"))
((("d" "m" "f" "v" ))("읊"))
((("d" "m" "g" ))("읗"))
((("d" "m" "l" ))("의"))
((("d" "m" "l" "a" ))("읨"))
((("d" "m" "l" "f" ))("읠"))
((("d" "m" "l" "s" ))("읜"))
((("d" "m" "l" "t" ))("읫"))
((("d" "m" "q" ))("읍"))
((("d" "m" "r" ))("윽"))
((("d" "m" "s" ))("은"))
((("d" "m" "t" ))("읏"))
((("d" "m" "v" ))("읖"))
((("d" "m" "w" ))("읒"))
((("d" "m" "x" ))("읕"))
((("d" "m" "z" ))("읔"))
((("d" "n" ))("우"))
((("d" "n" "a" ))("움"))
((("d" "n" "d" ))("웅"))
((("d" "n" "f" ))("울"))
((("d" "n" "f" "a" ))("욺"))
((("d" "n" "f" "r" ))("욹"))
((("d" "n" "j" ))("워"))
((("d" "n" "j" "T" ))("웠"))
((("d" "n" "j" "a" ))("웜"))
((("d" "n" "j" "d" ))("웡"))
((("d" "n" "j" "f" ))("월"))
((("d" "n" "j" "q" ))("웝"))
((("d" "n" "j" "r" ))("웍"))
((("d" "n" "j" "s" ))("원"))
((("d" "n" "l" ))("위"))
((("d" "n" "l" "a" ))("윔"))
((("d" "n" "l" "d" ))("윙"))
((("d" "n" "l" "f" ))("윌"))
((("d" "n" "l" "q" ))("윕"))
((("d" "n" "l" "r" ))("윅"))
((("d" "n" "l" "s" ))("윈"))
((("d" "n" "l" "t" ))("윗"))
((("d" "n" "p" ))("웨"))
((("d" "n" "p" "a" ))("웸"))
((("d" "n" "p" "d" ))("웽"))
((("d" "n" "p" "f" ))("웰"))
((("d" "n" "p" "q" ))("웹"))
((("d" "n" "p" "r" ))("웩"))
((("d" "n" "p" "s" ))("웬"))
((("d" "n" "q" ))("웁"))
((("d" "n" "r" ))("욱"))
((("d" "n" "s" ))("운"))
((("d" "n" "t" ))("웃"))
((("d" "o" ))("애"))
((("d" "o" "T" ))("앴"))
((("d" "o" "a" ))("앰"))
((("d" "o" "d" ))("앵"))
((("d" "o" "f" ))("앨"))
((("d" "o" "q" ))("앱"))
((("d" "o" "r" ))("액"))
((("d" "o" "s" ))("앤"))
((("d" "o" "t" ))("앳"))
((("d" "p" ))("에"))
((("d" "p" "a" ))("엠"))
((("d" "p" "d" ))("엥"))
((("d" "p" "f" ))("엘"))
((("d" "p" "q" ))("엡"))
((("d" "p" "r" ))("엑"))
((("d" "p" "s" ))("엔"))
((("d" "p" "t" ))("엣"))
((("d" "u" ))("여"))
((("d" "u" "R" ))("엮"))
((("d" "u" "T" ))("였"))
((("d" "u" "a" ))("염"))
((("d" "u" "d" ))("영"))
((("d" "u" "f" ))("열"))
((("d" "u" "f" "a" ))("엶"))
((("d" "u" "f" "q" ))("엷"))
((("d" "u" "g" ))("옇"))
((("d" "u" "q" ))("엽"))
((("d" "u" "q" "t" ))("엾"))
((("d" "u" "r" ))("역"))
((("d" "u" "s" ))("연"))
((("d" "u" "t" ))("엿"))
((("d" "u" "v" ))("옆"))
((("d" "u" "x" ))("옅"))
((("d" "y" ))("요"))
((("d" "y" "a" ))("욤"))
((("d" "y" "d" ))("용"))
((("d" "y" "f" ))("욜"))
((("d" "y" "q" ))("욥"))
((("d" "y" "r" ))("욕"))
((("d" "y" "s" ))("욘"))
((("d" "y" "t" ))("욧"))
((("e" ))("ㄷ"))
((("e" "P" ))("뎨"))
((("e" "P" "s" ))("뎬"))
((("e" "b" ))("듀"))
((("e" "b" "a" ))("듐"))
((("e" "b" "d" ))("듕"))
((("e" "b" "f" ))("듈"))
((("e" "b" "s" ))("듄"))
((("e" "h" ))("도"))
((("e" "h" "a" ))("돔"))
((("e" "h" "c" ))("돛"))
((("e" "h" "d" ))("동"))
((("e" "h" "e" ))("돋"))
((("e" "h" "f" ))("돌"))
((("e" "h" "f" "a" ))("돎"))
((("e" "h" "f" "t" ))("돐"))
((("e" "h" "k" ))("돠"))
((("e" "h" "k" "f" ))("돨"))
((("e" "h" "k" "s" ))("돤"))
((("e" "h" "l" ))("되"))
((("e" "h" "l" "a" ))("됨"))
((("e" "h" "l" "f" ))("될"))
((("e" "h" "l" "q" ))("됩"))
((("e" "h" "l" "s" ))("된"))
((("e" "h" "l" "t" ))("됫"))
((("e" "h" "o" ))("돼"))
((("e" "h" "o" "T" ))("됐"))
((("e" "h" "q" ))("돕"))
((("e" "h" "r" ))("독"))
((("e" "h" "s" ))("돈"))
((("e" "h" "t" ))("돗"))
((("e" "h" "x" ))("돝"))
((("e" "i" ))("댜"))
((("e" "j" ))("더"))
((("e" "j" "R" ))("덖"))
((("e" "j" "a" ))("덤"))
((("e" "j" "c" ))("덫"))
((("e" "j" "d" ))("덩"))
((("e" "j" "e" ))("덛"))
((("e" "j" "f" ))("덜"))
((("e" "j" "f" "a" ))("덞"))
((("e" "j" "f" "q" ))("덟"))
((("e" "j" "q" ))("덥"))
((("e" "j" "r" ))("덕"))
((("e" "j" "s" ))("던"))
((("e" "j" "t" ))("덧"))
((("e" "j" "v" ))("덮"))
((("e" "k" ))("다"))
((("e" "k" "R" ))("닦"))
((("e" "k" "T" ))("닸"))
((("e" "k" "a" ))("담"))
((("e" "k" "c" ))("닻"))
((("e" "k" "d" ))("당"))
((("e" "k" "e" ))("닫"))
((("e" "k" "f" ))("달"))
((("e" "k" "f" "a" ))("닮"))
((("e" "k" "f" "g" ))("닳"))
((("e" "k" "f" "q" ))("닯"))
((("e" "k" "f" "r" ))("닭"))
((("e" "k" "g" ))("닿"))
((("e" "k" "q" ))("답"))
((("e" "k" "r" ))("닥"))
((("e" "k" "s" ))("단"))
((("e" "k" "t" ))("닷"))
((("e" "k" "w" ))("닺"))
((("e" "l" ))("디"))
((("e" "l" "T" ))("딨"))
((("e" "l" "a" ))("딤"))
((("e" "l" "d" ))("딩"))
((("e" "l" "e" ))("딛"))
((("e" "l" "f" ))("딜"))
((("e" "l" "q" ))("딥"))
((("e" "l" "r" ))("딕"))
((("e" "l" "s" ))("딘"))
((("e" "l" "t" ))("딧"))
((("e" "l" "w" ))("딪"))
((("e" "m" ))("드"))
((("e" "m" "a" ))("듬"))
((("e" "m" "d" ))("등"))
((("e" "m" "e" ))("듣"))
((("e" "m" "f" ))("들"))
((("e" "m" "f" "a" ))("듦"))
((("e" "m" "l" ))("듸"))
((("e" "m" "q" ))("듭"))
((("e" "m" "r" ))("득"))
((("e" "m" "s" ))("든"))
((("e" "m" "t" ))("듯"))
((("e" "n" ))("두"))
((("e" "n" "a" ))("둠"))
((("e" "n" "d" ))("둥"))
((("e" "n" "f" ))("둘"))
((("e" "n" "j" ))("둬"))
((("e" "n" "j" "T" ))("뒀"))
((("e" "n" "l" ))("뒤"))
((("e" "n" "l" "d" ))("뒹"))
((("e" "n" "l" "f" ))("뒬"))
((("e" "n" "l" "q" ))("뒵"))
((("e" "n" "l" "s" ))("뒨"))
((("e" "n" "l" "t" ))("뒷"))
((("e" "n" "p" ))("뒈"))
((("e" "n" "p" "d" ))("뒝"))
((("e" "n" "q" ))("둡"))
((("e" "n" "r" ))("둑"))
((("e" "n" "s" ))("둔"))
((("e" "n" "t" ))("둣"))
((("e" "o" ))("대"))
((("e" "o" "T" ))("댔"))
((("e" "o" "a" ))("댐"))
((("e" "o" "d" ))("댕"))
((("e" "o" "f" ))("댈"))
((("e" "o" "q" ))("댑"))
((("e" "o" "r" ))("댁"))
((("e" "o" "s" ))("댄"))
((("e" "o" "t" ))("댓"))
((("e" "p" ))("데"))
((("e" "p" "T" ))("뎄"))
((("e" "p" "a" ))("뎀"))
((("e" "p" "d" ))("뎅"))
((("e" "p" "f" ))("델"))
((("e" "p" "q" ))("뎁"))
((("e" "p" "r" ))("덱"))
((("e" "p" "s" ))("덴"))
((("e" "p" "t" ))("뎃"))
((("e" "u" ))("뎌"))
((("e" "u" "T" ))("뎠"))
((("e" "u" "d" ))("뎡"))
((("e" "u" "f" ))("뎔"))
((("e" "u" "s" ))("뎐"))
((("e" "y" ))("됴"))
((("f" ))("ㄹ"))
((("f" "P" ))("례"))
((("f" "P" "q" ))("롑"))
((("f" "P" "s" ))("롄"))
((("f" "P" "t" ))("롓"))
((("f" "b" ))("류"))
((("f" "b" "a" ))("륨"))
((("f" "b" "d" ))("륭"))
((("f" "b" "f" ))("률"))
((("f" "b" "q" ))("륩"))
((("f" "b" "r" ))("륙"))
((("f" "b" "s" ))("륜"))
((("f" "b" "t" ))("륫"))
((("f" "h" ))("로"))
((("f" "h" "a" ))("롬"))
((("f" "h" "d" ))("롱"))
((("f" "h" "f" ))("롤"))
((("f" "h" "k" ))("롸"))
((("f" "h" "k" "d" ))("뢍"))
((("f" "h" "k" "s" ))("롼"))
((("f" "h" "l" ))("뢰"))
((("f" "h" "l" "a" ))("룀"))
((("f" "h" "l" "d" ))("룅"))
((("f" "h" "l" "f" ))("뢸"))
((("f" "h" "l" "q" ))("룁"))
((("f" "h" "l" "s" ))("뢴"))
((("f" "h" "l" "t" ))("룃"))
((("f" "h" "o" "T" ))("뢨"))
((("f" "h" "q" ))("롭"))
((("f" "h" "r" ))("록"))
((("f" "h" "s" ))("론"))
((("f" "h" "t" ))("롯"))
((("f" "i" ))("랴"))
((("f" "i" "d" ))("량"))
((("f" "i" "r" ))("략"))
((("f" "i" "s" ))("랸"))
((("f" "i" "t" ))("럇"))
((("f" "j" ))("러"))
((("f" "j" "T" ))("렀"))
((("f" "j" "a" ))("럼"))
((("f" "j" "d" ))("렁"))
((("f" "j" "f" ))("럴"))
((("f" "j" "g" ))("렇"))
((("f" "j" "q" ))("럽"))
((("f" "j" "r" ))("럭"))
((("f" "j" "s" ))("런"))
((("f" "j" "t" ))("럿"))
((("f" "k" ))("라"))
((("f" "k" "T" ))("랐"))
((("f" "k" "a" ))("람"))
((("f" "k" "d" ))("랑"))
((("f" "k" "f" ))("랄"))
((("f" "k" "g" ))("랗"))
((("f" "k" "q" ))("랍"))
((("f" "k" "r" ))("락"))
((("f" "k" "s" ))("란"))
((("f" "k" "t" ))("랏"))
((("f" "k" "v" ))("랖"))
((("f" "k" "w" ))("랒"))
((("f" "l" ))("리"))
((("f" "l" "a" ))("림"))
((("f" "l" "d" ))("링"))
((("f" "l" "f" ))("릴"))
((("f" "l" "q" ))("립"))
((("f" "l" "r" ))("릭"))
((("f" "l" "s" ))("린"))
((("f" "l" "t" ))("릿"))
((("f" "m" ))("르"))
((("f" "m" "a" ))("름"))
((("f" "m" "d" ))("릉"))
((("f" "m" "f" ))("를"))
((("f" "m" "q" ))("릅"))
((("f" "m" "r" ))("륵"))
((("f" "m" "s" ))("른"))
((("f" "m" "t" ))("릇"))
((("f" "m" "v" ))("릎"))
((("f" "m" "w" ))("릊"))
((("f" "m" "x" ))("릍"))
((("f" "n" ))("루"))
((("f" "n" "a" ))("룸"))
((("f" "n" "d" ))("룽"))
((("f" "n" "f" ))("룰"))
((("f" "n" "j" ))("뤄"))
((("f" "n" "j" "T" ))("뤘"))
((("f" "n" "l" ))("뤼"))
((("f" "n" "l" "a" ))("륌"))
((("f" "n" "l" "d" ))("륑"))
((("f" "n" "l" "f" ))("륄"))
((("f" "n" "l" "r" ))("뤽"))
((("f" "n" "l" "s" ))("륀"))
((("f" "n" "l" "t" ))("륏"))
((("f" "n" "p" ))("뤠"))
((("f" "n" "q" ))("룹"))
((("f" "n" "r" ))("룩"))
((("f" "n" "s" ))("룬"))
((("f" "n" "t" ))("룻"))
((("f" "o" ))("래"))
((("f" "o" "T" ))("랬"))
((("f" "o" "a" ))("램"))
((("f" "o" "d" ))("랭"))
((("f" "o" "f" ))("랠"))
((("f" "o" "q" ))("랩"))
((("f" "o" "r" ))("랙"))
((("f" "o" "s" ))("랜"))
((("f" "o" "t" ))("랫"))
((("f" "p" ))("레"))
((("f" "p" "a" ))("렘"))
((("f" "p" "d" ))("렝"))
((("f" "p" "f" ))("렐"))
((("f" "p" "q" ))("렙"))
((("f" "p" "r" ))("렉"))
((("f" "p" "s" ))("렌"))
((("f" "p" "t" ))("렛"))
((("f" "u" ))("려"))
((("f" "u" "T" ))("렸"))
((("f" "u" "a" ))("렴"))
((("f" "u" "d" ))("령"))
((("f" "u" "f" ))("렬"))
((("f" "u" "q" ))("렵"))
((("f" "u" "r" ))("력"))
((("f" "u" "s" ))("련"))
((("f" "u" "t" ))("렷"))
((("f" "y" ))("료"))
((("f" "y" "d" ))("룡"))
((("f" "y" "f" ))("룔"))
((("f" "y" "q" ))("룝"))
((("f" "y" "s" ))("룐"))
((("f" "y" "t" ))("룟"))
((("g" ))("ㅎ"))
((("g" "P" ))("혜"))
((("g" "P" "f" ))("혤"))
((("g" "P" "q" ))("혭"))
((("g" "P" "s" ))("혠"))
((("g" "b" ))("휴"))
((("g" "b" "a" ))("흄"))
((("g" "b" "d" ))("흉"))
((("g" "b" "f" ))("휼"))
((("g" "b" "r" ))("휵"))
((("g" "b" "s" ))("휸"))
((("g" "b" "t" ))("흇"))
((("g" "h" ))("호"))
((("g" "h" "a" ))("홈"))
((("g" "h" "d" ))("홍"))
((("g" "h" "f" ))("홀"))
((("g" "h" "f" "x" ))("홅"))
((("g" "h" "k" ))("화"))
((("g" "h" "k" "d" ))("황"))
((("g" "h" "k" "f" ))("활"))
((("g" "h" "k" "r" ))("확"))
((("g" "h" "k" "s" ))("환"))
((("g" "h" "k" "t" ))("홧"))
((("g" "h" "l" ))("회"))
((("g" "h" "l" "d" ))("횡"))
((("g" "h" "l" "f" ))("횔"))
((("g" "h" "l" "q" ))("횝"))
((("g" "h" "l" "r" ))("획"))
((("g" "h" "l" "s" ))("횐"))
((("g" "h" "l" "t" ))("횟"))
((("g" "h" "o" ))("홰"))
((("g" "h" "o" "d" ))("횅"))
((("g" "h" "o" "r" ))("홱"))
((("g" "h" "o" "s" ))("홴"))
((("g" "h" "o" "t" ))("횃"))
((("g" "h" "q" ))("홉"))
((("g" "h" "r" ))("혹"))
((("g" "h" "s" ))("혼"))
((("g" "h" "t" ))("홋"))
((("g" "h" "x" ))("홑"))
((("g" "i" ))("햐"))
((("g" "i" "d" ))("향"))
((("g" "j" ))("허"))
((("g" "j" "a" ))("험"))
((("g" "j" "d" ))("헝"))
((("g" "j" "f" ))("헐"))
((("g" "j" "f" "a" ))("헒"))
((("g" "j" "q" ))("헙"))
((("g" "j" "r" ))("헉"))
((("g" "j" "s" ))("헌"))
((("g" "j" "t" ))("헛"))
((("g" "k" ))("하"))
((("g" "k" "a" ))("함"))
((("g" "k" "d" ))("항"))
((("g" "k" "f" ))("할"))
((("g" "k" "f" "x" ))("핥"))
((("g" "k" "q" ))("합"))
((("g" "k" "r" ))("학"))
((("g" "k" "s" ))("한"))
((("g" "k" "t" ))("핫"))
((("g" "l" ))("히"))
((("g" "l" "a" ))("힘"))
((("g" "l" "d" ))("힝"))
((("g" "l" "f" ))("힐"))
((("g" "l" "q" ))("힙"))
((("g" "l" "r" ))("힉"))
((("g" "l" "s" ))("힌"))
((("g" "l" "t" ))("힛"))
((("g" "m" ))("흐"))
((("g" "m" "a" ))("흠"))
((("g" "m" "d" ))("흥"))
((("g" "m" "e" ))("흗"))
((("g" "m" "f" ))("흘"))
((("g" "m" "f" "r" ))("흙"))
((("g" "m" "l" ))("희"))
((("g" "m" "l" "a" ))("흼"))
((("g" "m" "l" "d" ))("힁"))
((("g" "m" "l" "f" ))("흴"))
((("g" "m" "l" "q" ))("흽"))
((("g" "m" "l" "s" ))("흰"))
((("g" "m" "q" ))("흡"))
((("g" "m" "r" ))("흑"))
((("g" "m" "s" ))("흔"))
((("g" "m" "s" "g" ))("흖"))
((("g" "m" "t" ))("흣"))
((("g" "m" "x" ))("흩"))
((("g" "n" ))("후"))
((("g" "n" "a" ))("훔"))
((("g" "n" "d" ))("훙"))
((("g" "n" "f" ))("훌"))
((("g" "n" "f" "x" ))("훑"))
((("g" "n" "j" ))("훠"))
((("g" "n" "j" "a" ))("훰"))
((("g" "n" "j" "d" ))("훵"))
((("g" "n" "j" "f" ))("훨"))
((("g" "n" "j" "s" ))("훤"))
((("g" "n" "l" ))("휘"))
((("g" "n" "l" "a" ))("휨"))
((("g" "n" "l" "d" ))("휭"))
((("g" "n" "l" "f" ))("휠"))
((("g" "n" "l" "q" ))("휩"))
((("g" "n" "l" "r" ))("휙"))
((("g" "n" "l" "s" ))("휜"))
((("g" "n" "l" "t" ))("휫"))
((("g" "n" "p" ))("훼"))
((("g" "n" "p" "d" ))("휑"))
((("g" "n" "p" "f" ))("휄"))
((("g" "n" "p" "r" ))("훽"))
((("g" "n" "p" "s" ))("휀"))
((("g" "n" "r" ))("훅"))
((("g" "n" "s" ))("훈"))
((("g" "n" "t" ))("훗"))
((("g" "o" ))("해"))
((("g" "o" "T" ))("했"))
((("g" "o" "a" ))("햄"))
((("g" "o" "d" ))("행"))
((("g" "o" "f" ))("핼"))
((("g" "o" "q" ))("햅"))
((("g" "o" "r" ))("핵"))
((("g" "o" "s" ))("핸"))
((("g" "o" "t" ))("햇"))
((("g" "p" ))("헤"))
((("g" "p" "a" ))("헴"))
((("g" "p" "d" ))("헹"))
((("g" "p" "f" ))("헬"))
((("g" "p" "q" ))("헵"))
((("g" "p" "r" ))("헥"))
((("g" "p" "s" ))("헨"))
((("g" "p" "t" ))("헷"))
((("g" "u" ))("혀"))
((("g" "u" "T" ))("혔"))
((("g" "u" "a" ))("혐"))
((("g" "u" "d" ))("형"))
((("g" "u" "f" ))("혈"))
((("g" "u" "q" ))("협"))
((("g" "u" "r" ))("혁"))
((("g" "u" "s" ))("현"))
((("g" "u" "t" ))("혓"))
((("g" "y" ))("효"))
((("g" "y" "f" ))("횰"))
((("g" "y" "q" ))("횹"))
((("g" "y" "s" ))("횬"))
((("g" "y" "t" ))("횻"))
((("h" ))("ㅗ"))
((("i" ))("ㅑ"))
((("j" ))("ㅓ"))
((("k" ))("ㅏ"))
((("l" ))("ㅣ"))
((("m" ))("ㅡ"))
((("n" ))("ㅜ"))
((("o" ))("ㅐ"))
((("p" ))("ㅔ"))
((("q" ))("ㅂ"))
((("q" "P" ))("볘"))
((("q" "P" "s" ))("볜"))
((("q" "b" ))("뷰"))
((("q" "b" "a" ))("븀"))
((("q" "b" "d" ))("븅"))
((("q" "b" "f" ))("뷸"))
((("q" "b" "s" ))("뷴"))
((("q" "b" "t" ))("븃"))
((("q" "h" ))("보"))
((("q" "h" "R" ))("볶"))
((("q" "h" "a" ))("봄"))
((("q" "h" "d" ))("봉"))
((("q" "h" "f" ))("볼"))
((("q" "h" "k" ))("봐"))
((("q" "h" "k" "T" ))("봤"))
((("q" "h" "k" "s" ))("봔"))
((("q" "h" "l" ))("뵈"))
((("q" "h" "l" "a" ))("뵘"))
((("q" "h" "l" "f" ))("뵐"))
((("q" "h" "l" "q" ))("뵙"))
((("q" "h" "l" "r" ))("뵉"))
((("q" "h" "l" "s" ))("뵌"))
((("q" "h" "o" ))("봬"))
((("q" "h" "o" "T" ))("뵀"))
((("q" "h" "q" ))("봅"))
((("q" "h" "r" ))("복"))
((("q" "h" "s" ))("본"))
((("q" "h" "t" ))("봇"))
((("q" "i" ))("뱌"))
((("q" "i" "q" ))("뱝"))
((("q" "i" "r" ))("뱍"))
((("q" "i" "s" ))("뱐"))
((("q" "j" ))("버"))
((("q" "j" "a" ))("범"))
((("q" "j" "d" ))("벙"))
((("q" "j" "e" ))("벋"))
((("q" "j" "f" ))("벌"))
((("q" "j" "f" "a" ))("벎"))
((("q" "j" "q" ))("법"))
((("q" "j" "r" ))("벅"))
((("q" "j" "s" ))("번"))
((("q" "j" "t" ))("벗"))
((("q" "j" "w" ))("벚"))
((("q" "k" ))("바"))
((("q" "k" "R" ))("밖"))
((("q" "k" "a" ))("밤"))
((("q" "k" "d" ))("방"))
((("q" "k" "e" ))("받"))
((("q" "k" "f" ))("발"))
((("q" "k" "f" "a" ))("밞"))
((("q" "k" "f" "q" ))("밟"))
((("q" "k" "f" "r" ))("밝"))
((("q" "k" "q" ))("밥"))
((("q" "k" "r" ))("박"))
((("q" "k" "r" "t" ))("밗"))
((("q" "k" "s" ))("반"))
((("q" "k" "t" ))("밧"))
((("q" "k" "x" ))("밭"))
((("q" "l" ))("비"))
((("q" "l" "a" ))("빔"))
((("q" "l" "c" ))("빛"))
((("q" "l" "d" ))("빙"))
((("q" "l" "f" ))("빌"))
((("q" "l" "f" "a" ))("빎"))
((("q" "l" "q" ))("빕"))
((("q" "l" "r" ))("빅"))
((("q" "l" "s" ))("빈"))
((("q" "l" "t" ))("빗"))
((("q" "l" "w" ))("빚"))
((("q" "m" ))("브"))
((("q" "m" "a" ))("븜"))
((("q" "m" "f" ))("블"))
((("q" "m" "q" ))("븝"))
((("q" "m" "r" ))("븍"))
((("q" "m" "s" ))("븐"))
((("q" "m" "t" ))("븟"))
((("q" "n" ))("부"))
((("q" "n" "a" ))("붐"))
((("q" "n" "d" ))("붕"))
((("q" "n" "e" ))("붇"))
((("q" "n" "f" ))("불"))
((("q" "n" "f" "a" ))("붊"))
((("q" "n" "f" "r" ))("붉"))
((("q" "n" "j" ))("붜"))
((("q" "n" "j" "T" ))("붰"))
((("q" "n" "j" "f" ))("붤"))
((("q" "n" "l" ))("뷔"))
((("q" "n" "l" "d" ))("뷩"))
((("q" "n" "l" "f" ))("뷜"))
((("q" "n" "l" "r" ))("뷕"))
((("q" "n" "l" "s" ))("뷘"))
((("q" "n" "p" ))("붸"))
((("q" "n" "q" ))("붑"))
((("q" "n" "r" ))("북"))
((("q" "n" "s" ))("분"))
((("q" "n" "t" ))("붓"))
((("q" "n" "v" ))("붚"))
((("q" "n" "x" ))("붙"))
((("q" "o" ))("배"))
((("q" "o" "T" ))("뱄"))
((("q" "o" "a" ))("뱀"))
((("q" "o" "d" ))("뱅"))
((("q" "o" "f" ))("밸"))
((("q" "o" "q" ))("뱁"))
((("q" "o" "r" ))("백"))
((("q" "o" "s" ))("밴"))
((("q" "o" "t" ))("뱃"))
((("q" "o" "x" ))("뱉"))
((("q" "p" ))("베"))
((("q" "p" "T" ))("벴"))
((("q" "p" "a" ))("벰"))
((("q" "p" "d" ))("벵"))
((("q" "p" "e" ))("벧"))
((("q" "p" "f" ))("벨"))
((("q" "p" "q" ))("벱"))
((("q" "p" "r" ))("벡"))
((("q" "p" "s" ))("벤"))
((("q" "p" "t" ))("벳"))
((("q" "u" ))("벼"))
((("q" "u" "T" ))("볐"))
((("q" "u" "d" ))("병"))
((("q" "u" "f" ))("별"))
((("q" "u" "q" ))("볍"))
((("q" "u" "r" ))("벽"))
((("q" "u" "s" ))("변"))
((("q" "u" "t" ))("볏"))
((("q" "u" "x" ))("볕"))
((("q" "y" ))("뵤"))
((("q" "y" "s" ))("뵨"))
((("r" ))("ㄱ"))
((("r" "O" ))("걔"))
((("r" "O" "f" ))("걜"))
((("r" "O" "s" ))("걘"))
((("r" "P" ))("계"))
((("r" "P" "f" ))("곌"))
((("r" "P" "q" ))("곕"))
((("r" "P" "s" ))("곈"))
((("r" "P" "t" ))("곗"))
((("r" "b" ))("규"))
((("r" "b" "f" ))("귤"))
((("r" "b" "s" ))("균"))
((("r" "h" ))("고"))
((("r" "h" "a" ))("곰"))
((("r" "h" "d" ))("공"))
((("r" "h" "e" ))("곧"))
((("r" "h" "f" ))("골"))
((("r" "h" "f" "a" ))("곪"))
((("r" "h" "f" "g" ))("곯"))
((("r" "h" "f" "t" ))("곬"))
((("r" "h" "k" ))("과"))
((("r" "h" "k" "a" ))("괌"))
((("r" "h" "k" "d" ))("광"))
((("r" "h" "k" "f" ))("괄"))
((("r" "h" "k" "f" "a" ))("괆"))
((("r" "h" "k" "q" ))("괍"))
((("r" "h" "k" "r" ))("곽"))
((("r" "h" "k" "s" ))("관"))
((("r" "h" "k" "t" ))("괏"))
((("r" "h" "l" ))("괴"))
((("r" "h" "l" "a" ))("굄"))
((("r" "h" "l" "d" ))("굉"))
((("r" "h" "l" "f" ))("괼"))
((("r" "h" "l" "q" ))("굅"))
((("r" "h" "l" "r" ))("괵"))
((("r" "h" "l" "s" ))("괸"))
((("r" "h" "l" "t" ))("굇"))
((("r" "h" "o" ))("괘"))
((("r" "h" "o" "T" ))("괬"))
((("r" "h" "o" "d" ))("괭"))
((("r" "h" "o" "f" ))("괠"))
((("r" "h" "o" "q" ))("괩"))
((("r" "h" "o" "s" ))("괜"))
((("r" "h" "q" ))("곱"))
((("r" "h" "r" ))("곡"))
((("r" "h" "s" ))("곤"))
((("r" "h" "t" ))("곳"))
((("r" "h" "w" ))("곶"))
((("r" "i" ))("갸"))
((("r" "i" "d" ))("걍"))
((("r" "i" "f" ))("걀"))
((("r" "i" "r" ))("갹"))
((("r" "i" "s" ))("갼"))
((("r" "i" "t" ))("걋"))
((("r" "j" ))("거"))
((("r" "j" "T" ))("겄"))
((("r" "j" "a" ))("검"))
((("r" "j" "d" ))("겅"))
((("r" "j" "e" ))("걷"))
((("r" "j" "f" ))("걸"))
((("r" "j" "f" "a" ))("걺"))
((("r" "j" "g" ))("겋"))
((("r" "j" "q" ))("겁"))
((("r" "j" "r" ))("걱"))
((("r" "j" "s" ))("건"))
((("r" "j" "t" ))("것"))
((("r" "j" "v" ))("겊"))
((("r" "j" "w" ))("겆"))
((("r" "j" "x" ))("겉"))
((("r" "k" ))("가"))
((("r" "k" "T" ))("갔"))
((("r" "k" "a" ))("감"))
((("r" "k" "c" ))("갗"))
((("r" "k" "d" ))("강"))
((("r" "k" "e" ))("갇"))
((("r" "k" "f" ))("갈"))
((("r" "k" "f" "a" ))("갊"))
((("r" "k" "f" "r" ))("갉"))
((("r" "k" "g" ))("갛"))
((("r" "k" "q" ))("갑"))
((("r" "k" "q" "t" ))("값"))
((("r" "k" "r" ))("각"))
((("r" "k" "s" ))("간"))
((("r" "k" "t" ))("갓"))
((("r" "k" "v" ))("갚"))
((("r" "k" "w" ))("갖"))
((("r" "k" "x" ))("같"))
((("r" "l" ))("기"))
((("r" "l" "a" ))("김"))
((("r" "l" "d" ))("깅"))
((("r" "l" "e" ))("긷"))
((("r" "l" "f" ))("길"))
((("r" "l" "f" "a" ))("긺"))
((("r" "l" "q" ))("깁"))
((("r" "l" "r" ))("긱"))
((("r" "l" "s" ))("긴"))
((("r" "l" "t" ))("깃"))
((("r" "l" "v" ))("깊"))
((("r" "l" "w" ))("깆"))
((("r" "m" ))("그"))
((("r" "m" "a" ))("금"))
((("r" "m" "d" ))("긍"))
((("r" "m" "e" ))("귿"))
((("r" "m" "f" ))("글"))
((("r" "m" "f" "r" ))("긁"))
((("r" "m" "l" ))("긔"))
((("r" "m" "q" ))("급"))
((("r" "m" "r" ))("극"))
((("r" "m" "s" ))("근"))
((("r" "m" "t" ))("긋"))
((("r" "n" ))("구"))
((("r" "n" "a" ))("굼"))
((("r" "n" "d" ))("궁"))
((("r" "n" "e" ))("굳"))
((("r" "n" "f" ))("굴"))
((("r" "n" "f" "a" ))("굶"))
((("r" "n" "f" "g" ))("굻"))
((("r" "n" "f" "r" ))("굵"))
((("r" "n" "j" ))("궈"))
((("r" "n" "j" "T" ))("궜"))
((("r" "n" "j" "d" ))("궝"))
((("r" "n" "j" "f" ))("궐"))
((("r" "n" "j" "r" ))("궉"))
((("r" "n" "j" "s" ))("권"))
((("r" "n" "l" ))("귀"))
((("r" "n" "l" "a" ))("귐"))
((("r" "n" "l" "f" ))("귈"))
((("r" "n" "l" "q" ))("귑"))
((("r" "n" "l" "r" ))("귁"))
((("r" "n" "l" "s" ))("귄"))
((("r" "n" "l" "t" ))("귓"))
((("r" "n" "p" ))("궤"))
((("r" "n" "p" "t" ))("궷"))
((("r" "n" "q" ))("굽"))
((("r" "n" "r" ))("국"))
((("r" "n" "s" ))("군"))
((("r" "n" "t" ))("굿"))
((("r" "n" "w" ))("궂"))
((("r" "o" ))("개"))
((("r" "o" "T" ))("갰"))
((("r" "o" "a" ))("갬"))
((("r" "o" "d" ))("갱"))
((("r" "o" "f" ))("갤"))
((("r" "o" "q" ))("갭"))
((("r" "o" "r" ))("객"))
((("r" "o" "s" ))("갠"))
((("r" "o" "t" ))("갯"))
((("r" "p" ))("게"))
((("r" "p" "T" ))("겠"))
((("r" "p" "a" ))("겜"))
((("r" "p" "d" ))("겡"))
((("r" "p" "f" ))("겔"))
((("r" "p" "q" ))("겝"))
((("r" "p" "s" ))("겐"))
((("r" "p" "t" ))("겟"))
((("r" "u" ))("겨"))
((("r" "u" "R" ))("겪"))
((("r" "u" "T" ))("겼"))
((("r" "u" "a" ))("겸"))
((("r" "u" "d" ))("경"))
((("r" "u" "e" ))("겯"))
((("r" "u" "f" ))("결"))
((("r" "u" "q" ))("겹"))
((("r" "u" "r" ))("격"))
((("r" "u" "s" ))("견"))
((("r" "u" "t" ))("겻"))
((("r" "u" "x" ))("곁"))
((("r" "y" ))("교"))
((("r" "y" "f" ))("굘"))
((("r" "y" "q" ))("굡"))
((("r" "y" "s" ))("굔"))
((("r" "y" "t" ))("굣"))
((("s" ))("ㄴ"))
((("s" "P" ))("녜"))
((("s" "P" "s" ))("녠"))
((("s" "b" ))("뉴"))
((("s" "b" "a" ))("늄"))
((("s" "b" "d" ))("늉"))
((("s" "b" "f" ))("뉼"))
((("s" "b" "q" ))("늅"))
((("s" "b" "r" ))("뉵"))
((("s" "h" ))("노"))
((("s" "h" "a" ))("놈"))
((("s" "h" "d" ))("농"))
((("s" "h" "f" ))("놀"))
((("s" "h" "f" "a" ))("놂"))
((("s" "h" "g" ))("놓"))
((("s" "h" "k" ))("놔"))
((("s" "h" "k" "T" ))("놨"))
((("s" "h" "k" "f" ))("놜"))
((("s" "h" "k" "s" ))("놘"))
((("s" "h" "l" ))("뇌"))
((("s" "h" "l" "a" ))("뇜"))
((("s" "h" "l" "f" ))("뇔"))
((("s" "h" "l" "q" ))("뇝"))
((("s" "h" "l" "s" ))("뇐"))
((("s" "h" "l" "t" ))("뇟"))
((("s" "h" "q" ))("놉"))
((("s" "h" "r" ))("녹"))
((("s" "h" "s" ))("논"))
((("s" "h" "t" ))("놋"))
((("s" "h" "v" ))("높"))
((("s" "i" ))("냐"))
((("s" "i" "a" ))("냠"))
((("s" "i" "d" ))("냥"))
((("s" "i" "f" ))("냘"))
((("s" "i" "r" ))("냑"))
((("s" "i" "s" ))("냔"))
((("s" "j" ))("너"))
((("s" "j" "T" ))("넜"))
((("s" "j" "a" ))("넘"))
((("s" "j" "d" ))("넝"))
((("s" "j" "f" ))("널"))
((("s" "j" "f" "a" ))("넒"))
((("s" "j" "f" "q" ))("넓"))
((("s" "j" "g" ))("넣"))
((("s" "j" "q" ))("넙"))
((("s" "j" "r" ))("넉"))
((("s" "j" "r" "t" ))("넋"))
((("s" "j" "s" ))("넌"))
((("s" "j" "t" ))("넛"))
((("s" "k" ))("나"))
((("s" "k" "R" ))("낚"))
((("s" "k" "T" ))("났"))
((("s" "k" "a" ))("남"))
((("s" "k" "c" ))("낯"))
((("s" "k" "d" ))("낭"))
((("s" "k" "e" ))("낟"))
((("s" "k" "f" ))("날"))
((("s" "k" "f" "a" ))("낢"))
((("s" "k" "f" "r" ))("낡"))
((("s" "k" "g" ))("낳"))
((("s" "k" "q" ))("납"))
((("s" "k" "r" ))("낙"))
((("s" "k" "s" ))("난"))
((("s" "k" "t" ))("낫"))
((("s" "k" "w" ))("낮"))
((("s" "k" "x" ))("낱"))
((("s" "l" ))("니"))
((("s" "l" "a" ))("님"))
((("s" "l" "d" ))("닝"))
((("s" "l" "f" ))("닐"))
((("s" "l" "f" "a" ))("닒"))
((("s" "l" "q" ))("닙"))
((("s" "l" "r" ))("닉"))
((("s" "l" "s" ))("닌"))
((("s" "l" "t" ))("닛"))
((("s" "l" "v" ))("닢"))
((("s" "m" ))("느"))
((("s" "m" "a" ))("늠"))
((("s" "m" "d" ))("능"))
((("s" "m" "f" ))("늘"))
((("s" "m" "f" "a" ))("늚"))
((("s" "m" "f" "r" ))("늙"))
((("s" "m" "l" ))("늬"))
((("s" "m" "l" "f" ))("늴"))
((("s" "m" "l" "s" ))("늰"))
((("s" "m" "q" ))("늡"))
((("s" "m" "r" ))("늑"))
((("s" "m" "s" ))("는"))
((("s" "m" "t" ))("늣"))
((("s" "m" "v" ))("늪"))
((("s" "m" "w" ))("늦"))
((("s" "n" ))("누"))
((("s" "n" "a" ))("눔"))
((("s" "n" "d" ))("눙"))
((("s" "n" "e" ))("눋"))
((("s" "n" "f" ))("눌"))
((("s" "n" "j" ))("눠"))
((("s" "n" "j" "T" ))("눴"))
((("s" "n" "l" ))("뉘"))
((("s" "n" "l" "a" ))("뉨"))
((("s" "n" "l" "f" ))("뉠"))
((("s" "n" "l" "q" ))("뉩"))
((("s" "n" "l" "s" ))("뉜"))
((("s" "n" "p" ))("눼"))
((("s" "n" "q" ))("눕"))
((("s" "n" "r" ))("눅"))
((("s" "n" "s" ))("눈"))
((("s" "n" "t" ))("눗"))
((("s" "o" ))("내"))
((("s" "o" "T" ))("냈"))
((("s" "o" "a" ))("냄"))
((("s" "o" "d" ))("냉"))
((("s" "o" "f" ))("낼"))
((("s" "o" "q" ))("냅"))
((("s" "o" "r" ))("낵"))
((("s" "o" "s" ))("낸"))
((("s" "o" "t" ))("냇"))
((("s" "p" ))("네"))
((("s" "p" "T" ))("넸"))
((("s" "p" "a" ))("넴"))
((("s" "p" "d" ))("넹"))
((("s" "p" "f" ))("넬"))
((("s" "p" "q" ))("넵"))
((("s" "p" "r" ))("넥"))
((("s" "p" "s" ))("넨"))
((("s" "p" "t" ))("넷"))
((("s" "u" ))("녀"))
((("s" "u" "T" ))("녔"))
((("s" "u" "a" ))("념"))
((("s" "u" "d" ))("녕"))
((("s" "u" "f" ))("녈"))
((("s" "u" "q" ))("녑"))
((("s" "u" "r" ))("녁"))
((("s" "u" "s" ))("년"))
((("s" "u" "z" ))("녘"))
((("s" "y" ))("뇨"))
((("s" "y" "d" ))("뇽"))
((("s" "y" "f" ))("뇰"))
((("s" "y" "q" ))("뇹"))
((("s" "y" "r" ))("뇩"))
((("s" "y" "s" ))("뇬"))
((("s" "y" "t" ))("뇻"))
((("t" ))("ㅅ"))
((("t" "O" ))("섀"))
((("t" "O" "a" ))("섐"))
((("t" "O" "d" ))("섕"))
((("t" "O" "f" ))("섈"))
((("t" "O" "s" ))("섄"))
((("t" "P" ))("셰"))
((("t" "P" "d" ))("솅"))
((("t" "P" "f" ))("셸"))
((("t" "P" "s" ))("셴"))
((("t" "b" ))("슈"))
((("t" "b" "a" ))("슘"))
((("t" "b" "d" ))("슝"))
((("t" "b" "f" ))("슐"))
((("t" "b" "r" ))("슉"))
((("t" "b" "t" ))("슛"))
((("t" "h" ))("소"))
((("t" "h" "R" ))("솎"))
((("t" "h" "a" ))("솜"))
((("t" "h" "d" ))("송"))
((("t" "h" "f" ))("솔"))
((("t" "h" "f" "a" ))("솖"))
((("t" "h" "k" ))("솨"))
((("t" "h" "k" "d" ))("솽"))
((("t" "h" "k" "f" ))("솰"))
((("t" "h" "k" "r" ))("솩"))
((("t" "h" "k" "s" ))("솬"))
((("t" "h" "l" ))("쇠"))
((("t" "h" "l" "a" ))("쇰"))
((("t" "h" "l" "f" ))("쇨"))
((("t" "h" "l" "q" ))("쇱"))
((("t" "h" "l" "s" ))("쇤"))
((("t" "h" "l" "t" ))("쇳"))
((("t" "h" "o" ))("쇄"))
((("t" "h" "o" "T" ))("쇘"))
((("t" "h" "o" "a" ))("쇔"))
((("t" "h" "o" "f" ))("쇌"))
((("t" "h" "o" "s" ))("쇈"))
((("t" "h" "o" "t" ))("쇗"))
((("t" "h" "q" ))("솝"))
((("t" "h" "r" ))("속"))
((("t" "h" "s" ))("손"))
((("t" "h" "t" ))("솟"))
((("t" "h" "x" ))("솥"))
((("t" "i" ))("샤"))
((("t" "i" "a" ))("샴"))
((("t" "i" "d" ))("샹"))
((("t" "i" "f" ))("샬"))
((("t" "i" "q" ))("샵"))
((("t" "i" "r" ))("샥"))
((("t" "i" "s" ))("샨"))
((("t" "i" "t" ))("샷"))
((("t" "j" ))("서"))
((("t" "j" "R" ))("섞"))
((("t" "j" "T" ))("섰"))
((("t" "j" "a" ))("섬"))
((("t" "j" "d" ))("성"))
((("t" "j" "e" ))("섣"))
((("t" "j" "f" ))("설"))
((("t" "j" "f" "a" ))("섦"))
((("t" "j" "f" "q" ))("섧"))
((("t" "j" "q" ))("섭"))
((("t" "j" "r" ))("석"))
((("t" "j" "r" "t" ))("섟"))
((("t" "j" "s" ))("선"))
((("t" "j" "t" ))("섯"))
((("t" "j" "v" ))("섶"))
((("t" "k" ))("사"))
((("t" "k" "T" ))("샀"))
((("t" "k" "a" ))("삼"))
((("t" "k" "d" ))("상"))
((("t" "k" "e" ))("삳"))
((("t" "k" "f" ))("살"))
((("t" "k" "f" "a" ))("삶"))
((("t" "k" "f" "r" ))("삵"))
((("t" "k" "q" ))("삽"))
((("t" "k" "r" ))("삭"))
((("t" "k" "r" "t" ))("삯"))
((("t" "k" "s" ))("산"))
((("t" "k" "t" ))("삿"))
((("t" "k" "x" ))("샅"))
((("t" "l" ))("시"))
((("t" "l" "a" ))("심"))
((("t" "l" "d" ))("싱"))
((("t" "l" "e" ))("싣"))
((("t" "l" "f" ))("실"))
((("t" "l" "f" "g" ))("싫"))
((("t" "l" "q" ))("십"))
((("t" "l" "r" ))("식"))
((("t" "l" "s" ))("신"))
((("t" "l" "t" ))("싯"))
((("t" "l" "v" ))("싶"))
((("t" "m" ))("스"))
((("t" "m" "a" ))("슴"))
((("t" "m" "d" ))("승"))
((("t" "m" "f" ))("슬"))
((("t" "m" "f" "r" ))("슭"))
((("t" "m" "q" ))("습"))
((("t" "m" "r" ))("슥"))
((("t" "m" "s" ))("슨"))
((("t" "m" "t" ))("슷"))
((("t" "n" ))("수"))
((("t" "n" "a" ))("숨"))
((("t" "n" "c" ))("숯"))
((("t" "n" "d" ))("숭"))
((("t" "n" "e" ))("숟"))
((("t" "n" "f" ))("술"))
((("t" "n" "j" ))("숴"))
((("t" "n" "j" "T" ))("쉈"))
((("t" "n" "l" ))("쉬"))
((("t" "n" "l" "a" ))("쉼"))
((("t" "n" "l" "d" ))("슁"))
((("t" "n" "l" "f" ))("쉴"))
((("t" "n" "l" "q" ))("쉽"))
((("t" "n" "l" "r" ))("쉭"))
((("t" "n" "l" "s" ))("쉰"))
((("t" "n" "l" "t" ))("쉿"))
((("t" "n" "p" ))("쉐"))
((("t" "n" "p" "a" ))("쉠"))
((("t" "n" "p" "d" ))("쉥"))
((("t" "n" "p" "f" ))("쉘"))
((("t" "n" "p" "r" ))("쉑"))
((("t" "n" "p" "s" ))("쉔"))
((("t" "n" "q" ))("숩"))
((("t" "n" "r" ))("숙"))
((("t" "n" "s" ))("순"))
((("t" "n" "t" ))("숫"))
((("t" "n" "v" ))("숲"))
((("t" "n" "x" ))("숱"))
((("t" "o" ))("새"))
((("t" "o" "T" ))("샜"))
((("t" "o" "a" ))("샘"))
((("t" "o" "d" ))("생"))
((("t" "o" "f" ))("샐"))
((("t" "o" "q" ))("샙"))
((("t" "o" "r" ))("색"))
((("t" "o" "s" ))("샌"))
((("t" "o" "t" ))("샛"))
((("t" "p" ))("세"))
((("t" "p" "T" ))("셌"))
((("t" "p" "a" ))("셈"))
((("t" "p" "d" ))("셍"))
((("t" "p" "f" ))("셀"))
((("t" "p" "q" ))("셉"))
((("t" "p" "r" ))("섹"))
((("t" "p" "s" ))("센"))
((("t" "p" "t" ))("셋"))
((("t" "u" ))("셔"))
((("t" "u" "T" ))("셨"))
((("t" "u" "a" ))("셤"))
((("t" "u" "d" ))("셩"))
((("t" "u" "f" ))("셜"))
((("t" "u" "q" ))("셥"))
((("t" "u" "r" ))("셕"))
((("t" "u" "s" ))("션"))
((("t" "u" "t" ))("셧"))
((("t" "y" ))("쇼"))
((("t" "y" "a" ))("숌"))
((("t" "y" "d" ))("숑"))
((("t" "y" "f" ))("숄"))
((("t" "y" "q" ))("숍"))
((("t" "y" "r" ))("쇽"))
((("t" "y" "s" ))("숀"))
((("t" "y" "t" ))("숏"))
((("u" ))("ㅕ"))
((("v" ))("ㅍ"))
((("v" "P" ))("폐"))
((("v" "P" "f" ))("폘"))
((("v" "P" "q" ))("폡"))
((("v" "P" "t" ))("폣"))
((("v" "b" ))("퓨"))
((("v" "b" "a" ))("퓸"))
((("v" "b" "d" ))("퓽"))
((("v" "b" "f" ))("퓰"))
((("v" "b" "s" ))("퓬"))
((("v" "b" "t" ))("퓻"))
((("v" "h" ))("포"))
((("v" "h" "a" ))("폼"))
((("v" "h" "d" ))("퐁"))
((("v" "h" "f" ))("폴"))
((("v" "h" "k" ))("퐈"))
((("v" "h" "k" "d" ))("퐝"))
((("v" "h" "l" ))("푀"))
((("v" "h" "l" "s" ))("푄"))
((("v" "h" "q" ))("폽"))
((("v" "h" "r" ))("폭"))
((("v" "h" "s" ))("폰"))
((("v" "h" "t" ))("폿"))
((("v" "i" ))("퍄"))
((("v" "i" "r" ))("퍅"))
((("v" "j" ))("퍼"))
((("v" "j" "T" ))("펐"))
((("v" "j" "a" ))("펌"))
((("v" "j" "d" ))("펑"))
((("v" "j" "f" ))("펄"))
((("v" "j" "q" ))("펍"))
((("v" "j" "r" ))("퍽"))
((("v" "j" "s" ))("펀"))
((("v" "j" "t" ))("펏"))
((("v" "k" ))("파"))
((("v" "k" "R" ))("팎"))
((("v" "k" "T" ))("팠"))
((("v" "k" "a" ))("팜"))
((("v" "k" "d" ))("팡"))
((("v" "k" "f" ))("팔"))
((("v" "k" "f" "a" ))("팖"))
((("v" "k" "q" ))("팝"))
((("v" "k" "r" ))("팍"))
((("v" "k" "s" ))("판"))
((("v" "k" "t" ))("팟"))
((("v" "k" "x" ))("팥"))
((("v" "l" ))("피"))
((("v" "l" "a" ))("핌"))
((("v" "l" "d" ))("핑"))
((("v" "l" "f" ))("필"))
((("v" "l" "q" ))("핍"))
((("v" "l" "r" ))("픽"))
((("v" "l" "s" ))("핀"))
((("v" "l" "t" ))("핏"))
((("v" "m" ))("프"))
((("v" "m" "a" ))("픔"))
((("v" "m" "f" ))("플"))
((("v" "m" "q" ))("픕"))
((("v" "m" "s" ))("픈"))
((("v" "m" "t" ))("픗"))
((("v" "n" ))("푸"))
((("v" "n" "a" ))("품"))
((("v" "n" "d" ))("풍"))
((("v" "n" "e" ))("푿"))
((("v" "n" "f" ))("풀"))
((("v" "n" "f" "a" ))("풂"))
((("v" "n" "j" ))("풔"))
((("v" "n" "j" "d" ))("풩"))
((("v" "n" "l" ))("퓌"))
((("v" "n" "l" "a" ))("퓜"))
((("v" "n" "l" "f" ))("퓔"))
((("v" "n" "l" "s" ))("퓐"))
((("v" "n" "l" "t" ))("퓟"))
((("v" "n" "q" ))("풉"))
((("v" "n" "r" ))("푹"))
((("v" "n" "s" ))("푼"))
((("v" "n" "t" ))("풋"))
((("v" "o" ))("패"))
((("v" "o" "T" ))("팼"))
((("v" "o" "a" ))("팸"))
((("v" "o" "d" ))("팽"))
((("v" "o" "f" ))("팰"))
((("v" "o" "q" ))("팹"))
((("v" "o" "r" ))("팩"))
((("v" "o" "s" ))("팬"))
((("v" "o" "t" ))("팻"))
((("v" "p" ))("페"))
((("v" "p" "a" ))("펨"))
((("v" "p" "d" ))("펭"))
((("v" "p" "f" ))("펠"))
((("v" "p" "q" ))("펩"))
((("v" "p" "r" ))("펙"))
((("v" "p" "s" ))("펜"))
((("v" "p" "t" ))("펫"))
((("v" "u" ))("펴"))
((("v" "u" "T" ))("폈"))
((("v" "u" "a" ))("폄"))
((("v" "u" "d" ))("평"))
((("v" "u" "f" ))("펼"))
((("v" "u" "q" ))("폅"))
((("v" "u" "s" ))("편"))
((("v" "y" ))("표"))
((("v" "y" "f" ))("푤"))
((("v" "y" "q" ))("푭"))
((("v" "y" "s" ))("푠"))
((("v" "y" "t" ))("푯"))
((("w" ))("ㅈ"))
((("w" "O" ))("쟤"))
((("w" "O" "f" ))("쟬"))
((("w" "O" "s" ))("쟨"))
((("w" "P" ))("졔"))
((("w" "b" ))("쥬"))
((("w" "b" "a" ))("쥼"))
((("w" "b" "f" ))("쥴"))
((("w" "b" "s" ))("쥰"))
((("w" "h" ))("조"))
((("w" "h" "a" ))("좀"))
((("w" "h" "c" ))("좇"))
((("w" "h" "d" ))("종"))
((("w" "h" "f" ))("졸"))
((("w" "h" "f" "a" ))("졺"))
((("w" "h" "g" ))("좋"))
((("w" "h" "k" ))("좌"))
((("w" "h" "k" "d" ))("좡"))
((("w" "h" "k" "f" ))("좔"))
((("w" "h" "k" "q" ))("좝"))
((("w" "h" "k" "r" ))("좍"))
((("w" "h" "k" "t" ))("좟"))
((("w" "h" "l" ))("죄"))
((("w" "h" "l" "a" ))("죔"))
((("w" "h" "l" "d" ))("죙"))
((("w" "h" "l" "f" ))("죌"))
((("w" "h" "l" "q" ))("죕"))
((("w" "h" "l" "s" ))("죈"))
((("w" "h" "l" "t" ))("죗"))
((("w" "h" "o" ))("좨"))
((("w" "h" "o" "T" ))("좼"))
((("w" "h" "o" "d" ))("좽"))
((("w" "h" "q" ))("좁"))
((("w" "h" "r" ))("족"))
((("w" "h" "s" ))("존"))
((("w" "h" "t" ))("좃"))
((("w" "h" "w" ))("좆"))
((("w" "i" ))("쟈"))
((("w" "i" "a" ))("쟘"))
((("w" "i" "d" ))("쟝"))
((("w" "i" "f" ))("쟐"))
((("w" "i" "r" ))("쟉"))
((("w" "i" "s" ))("쟌"))
((("w" "i" "s" "g" ))("쟎"))
((("w" "j" ))("저"))
((("w" "j" "a" ))("점"))
((("w" "j" "d" ))("정"))
((("w" "j" "f" ))("절"))
((("w" "j" "f" "a" ))("젊"))
((("w" "j" "q" ))("접"))
((("w" "j" "r" ))("적"))
((("w" "j" "s" ))("전"))
((("w" "j" "t" ))("젓"))
((("w" "j" "w" ))("젖"))
((("w" "k" ))("자"))
((("w" "k" "T" ))("잤"))
((("w" "k" "a" ))("잠"))
((("w" "k" "d" ))("장"))
((("w" "k" "e" ))("잗"))
((("w" "k" "f" ))("잘"))
((("w" "k" "f" "a" ))("잚"))
((("w" "k" "q" ))("잡"))
((("w" "k" "r" ))("작"))
((("w" "k" "s" ))("잔"))
((("w" "k" "s" "g" ))("잖"))
((("w" "k" "t" ))("잣"))
((("w" "k" "w" ))("잦"))
((("w" "l" ))("지"))
((("w" "l" "a" ))("짐"))
((("w" "l" "d" ))("징"))
((("w" "l" "e" ))("짇"))
((("w" "l" "f" ))("질"))
((("w" "l" "f" "a" ))("짊"))
((("w" "l" "q" ))("집"))
((("w" "l" "r" ))("직"))
((("w" "l" "s" ))("진"))
((("w" "l" "t" ))("짓"))
((("w" "l" "v" ))("짚"))
((("w" "l" "w" ))("짖"))
((("w" "l" "x" ))("짙"))
((("w" "m" ))("즈"))
((("w" "m" "a" ))("즘"))
((("w" "m" "d" ))("증"))
((("w" "m" "f" ))("즐"))
((("w" "m" "q" ))("즙"))
((("w" "m" "r" ))("즉"))
((("w" "m" "s" ))("즌"))
((("w" "m" "t" ))("즛"))
((("w" "n" ))("주"))
((("w" "n" "a" ))("줌"))
((("w" "n" "d" ))("중"))
((("w" "n" "f" ))("줄"))
((("w" "n" "f" "a" ))("줆"))
((("w" "n" "f" "r" ))("줅"))
((("w" "n" "j" ))("줘"))
((("w" "n" "j" "T" ))("줬"))
((("w" "n" "l" ))("쥐"))
((("w" "n" "l" "a" ))("쥠"))
((("w" "n" "l" "f" ))("쥘"))
((("w" "n" "l" "q" ))("쥡"))
((("w" "n" "l" "r" ))("쥑"))
((("w" "n" "l" "s" ))("쥔"))
((("w" "n" "l" "t" ))("쥣"))
((("w" "n" "p" ))("줴"))
((("w" "n" "q" ))("줍"))
((("w" "n" "r" ))("죽"))
((("w" "n" "s" ))("준"))
((("w" "n" "t" ))("줏"))
((("w" "o" ))("재"))
((("w" "o" "T" ))("쟀"))
((("w" "o" "a" ))("잼"))
((("w" "o" "d" ))("쟁"))
((("w" "o" "f" ))("잴"))
((("w" "o" "q" ))("잽"))
((("w" "o" "r" ))("잭"))
((("w" "o" "s" ))("잰"))
((("w" "o" "t" ))("잿"))
((("w" "p" ))("제"))
((("w" "p" "a" ))("젬"))
((("w" "p" "d" ))("젱"))
((("w" "p" "f" ))("젤"))
((("w" "p" "q" ))("젭"))
((("w" "p" "r" ))("젝"))
((("w" "p" "s" ))("젠"))
((("w" "p" "t" ))("젯"))
((("w" "u" ))("져"))
((("w" "u" "T" ))("졌"))
((("w" "u" "a" ))("졈"))
((("w" "u" "d" ))("졍"))
((("w" "u" "f" ))("졀"))
((("w" "u" "q" ))("졉"))
((("w" "u" "s" ))("젼"))
((("w" "y" ))("죠"))
((("w" "y" "d" ))("죵"))
((("w" "y" "r" ))("죡"))
((("w" "y" "s" ))("죤"))
((("x" ))("ㅌ"))
((("x" "P" ))("톄"))
((("x" "P" "s" ))("톈"))
((("x" "b" ))("튜"))
((("x" "b" "a" ))("튬"))
((("x" "b" "d" ))("튱"))
((("x" "b" "f" ))("튤"))
((("x" "b" "s" ))("튠"))
((("x" "h" ))("토"))
((("x" "h" "a" ))("톰"))
((("x" "h" "d" ))("통"))
((("x" "h" "f" ))("톨"))
((("x" "h" "k" ))("톼"))
((("x" "h" "k" "s" ))("퇀"))
((("x" "h" "l" ))("퇴"))
((("x" "h" "l" "d" ))("툉"))
((("x" "h" "l" "s" ))("퇸"))
((("x" "h" "l" "t" ))("툇"))
((("x" "h" "o" ))("퇘"))
((("x" "h" "q" ))("톱"))
((("x" "h" "r" ))("톡"))
((("x" "h" "s" ))("톤"))
((("x" "h" "t" ))("톳"))
((("x" "h" "v" ))("톺"))
((("x" "i" ))("탸"))
((("x" "i" "d" ))("턍"))
((("x" "j" ))("터"))
((("x" "j" "T" ))("텄"))
((("x" "j" "a" ))("텀"))
((("x" "j" "d" ))("텅"))
((("x" "j" "f" ))("털"))
((("x" "j" "f" "a" ))("턺"))
((("x" "j" "q" ))("텁"))
((("x" "j" "r" ))("턱"))
((("x" "j" "s" ))("턴"))
((("x" "j" "t" ))("텃"))
((("x" "k" ))("타"))
((("x" "k" "T" ))("탔"))
((("x" "k" "a" ))("탐"))
((("x" "k" "d" ))("탕"))
((("x" "k" "f" ))("탈"))
((("x" "k" "f" "r" ))("탉"))
((("x" "k" "q" ))("탑"))
((("x" "k" "r" ))("탁"))
((("x" "k" "s" ))("탄"))
((("x" "k" "t" ))("탓"))
((("x" "l" ))("티"))
((("x" "l" "a" ))("팀"))
((("x" "l" "d" ))("팅"))
((("x" "l" "f" ))("틸"))
((("x" "l" "q" ))("팁"))
((("x" "l" "r" ))("틱"))
((("x" "l" "s" ))("틴"))
((("x" "l" "t" ))("팃"))
((("x" "m" ))("트"))
((("x" "m" "a" ))("틈"))
((("x" "m" "e" ))("튿"))
((("x" "m" "f" ))("틀"))
((("x" "m" "f" "a" ))("틂"))
((("x" "m" "l" ))("틔"))
((("x" "m" "l" "a" ))("틤"))
((("x" "m" "l" "f" ))("틜"))
((("x" "m" "l" "q" ))("틥"))
((("x" "m" "l" "s" ))("틘"))
((("x" "m" "q" ))("틉"))
((("x" "m" "r" ))("특"))
((("x" "m" "s" ))("튼"))
((("x" "m" "t" ))("틋"))
((("x" "n" ))("투"))
((("x" "n" "a" ))("툼"))
((("x" "n" "d" ))("퉁"))
((("x" "n" "f" ))("툴"))
((("x" "n" "j" ))("퉈"))
((("x" "n" "j" "T" ))("퉜"))
((("x" "n" "l" ))("튀"))
((("x" "n" "l" "a" ))("튐"))
((("x" "n" "l" "d" ))("튕"))
((("x" "n" "l" "f" ))("튈"))
((("x" "n" "l" "q" ))("튑"))
((("x" "n" "l" "r" ))("튁"))
((("x" "n" "l" "s" ))("튄"))
((("x" "n" "p" ))("퉤"))
((("x" "n" "q" ))("툽"))
((("x" "n" "r" ))("툭"))
((("x" "n" "s" ))("툰"))
((("x" "n" "t" ))("툿"))
((("x" "o" ))("태"))
((("x" "o" "T" ))("탰"))
((("x" "o" "a" ))("탬"))
((("x" "o" "d" ))("탱"))
((("x" "o" "f" ))("탤"))
((("x" "o" "q" ))("탭"))
((("x" "o" "r" ))("택"))
((("x" "o" "s" ))("탠"))
((("x" "o" "t" ))("탯"))
((("x" "p" ))("테"))
((("x" "p" "a" ))("템"))
((("x" "p" "d" ))("텡"))
((("x" "p" "f" ))("텔"))
((("x" "p" "q" ))("텝"))
((("x" "p" "r" ))("텍"))
((("x" "p" "s" ))("텐"))
((("x" "p" "t" ))("텟"))
((("x" "u" ))("텨"))
((("x" "u" "T" ))("텼"))
((("x" "u" "s" ))("텬"))
((("x" "y" ))("툐"))
((("y" ))("ㅛ"))
((("z" ))("ㅋ"))
((("z" "P" ))("켸"))
((("z" "b" ))("큐"))
((("z" "b" "a" ))("큠"))
((("z" "b" "f" ))("큘"))
((("z" "b" "s" ))("큔"))
((("z" "h" ))("코"))
((("z" "h" "a" ))("콤"))
((("z" "h" "d" ))("콩"))
((("z" "h" "f" ))("콜"))
((("z" "h" "k" ))("콰"))
((("z" "h" "k" "a" ))("쾀"))
((("z" "h" "k" "d" ))("쾅"))
((("z" "h" "k" "f" ))("콸"))
((("z" "h" "k" "r" ))("콱"))
((("z" "h" "k" "s" ))("콴"))
((("z" "h" "l" ))("쾨"))
((("z" "h" "l" "f" ))("쾰"))
((("z" "h" "o" ))("쾌"))
((("z" "h" "o" "d" ))("쾡"))
((("z" "h" "q" ))("콥"))
((("z" "h" "r" ))("콕"))
((("z" "h" "s" ))("콘"))
((("z" "h" "t" ))("콧"))
((("z" "i" ))("캬"))
((("z" "i" "d" ))("컁"))
((("z" "i" "r" ))("캭"))
((("z" "j" ))("커"))
((("z" "j" "T" ))("컸"))
((("z" "j" "a" ))("컴"))
((("z" "j" "d" ))("컹"))
((("z" "j" "e" ))("컫"))
((("z" "j" "f" ))("컬"))
((("z" "j" "q" ))("컵"))
((("z" "j" "r" ))("컥"))
((("z" "j" "s" ))("컨"))
((("z" "j" "t" ))("컷"))
((("z" "k" ))("카"))
((("z" "k" "a" ))("캄"))
((("z" "k" "d" ))("캉"))
((("z" "k" "f" ))("칼"))
((("z" "k" "q" ))("캅"))
((("z" "k" "r" ))("칵"))
((("z" "k" "s" ))("칸"))
((("z" "k" "t" ))("캇"))
((("z" "l" ))("키"))
((("z" "l" "a" ))("킴"))
((("z" "l" "d" ))("킹"))
((("z" "l" "f" ))("킬"))
((("z" "l" "q" ))("킵"))
((("z" "l" "r" ))("킥"))
((("z" "l" "s" ))("킨"))
((("z" "l" "t" ))("킷"))
((("z" "m" ))("크"))
((("z" "m" "a" ))("큼"))
((("z" "m" "d" ))("킁"))
((("z" "m" "f" ))("클"))
((("z" "m" "q" ))("큽"))
((("z" "m" "r" ))("큭"))
((("z" "m" "s" ))("큰"))
((("z" "n" ))("쿠"))
((("z" "n" "a" ))("쿰"))
((("z" "n" "d" ))("쿵"))
((("z" "n" "f" ))("쿨"))
((("z" "n" "j" ))("쿼"))
((("z" "n" "j" "d" ))("퀑"))
((("z" "n" "j" "f" ))("퀄"))
((("z" "n" "j" "s" ))("퀀"))
((("z" "n" "l" ))("퀴"))
((("z" "n" "l" "a" ))("큄"))
((("z" "n" "l" "d" ))("큉"))
((("z" "n" "l" "f" ))("퀼"))
((("z" "n" "l" "q" ))("큅"))
((("z" "n" "l" "r" ))("퀵"))
((("z" "n" "l" "s" ))("퀸"))
((("z" "n" "l" "t" ))("큇"))
((("z" "n" "p" ))("퀘"))
((("z" "n" "p" "d" ))("퀭"))
((("z" "n" "q" ))("쿱"))
((("z" "n" "r" ))("쿡"))
((("z" "n" "s" ))("쿤"))
((("z" "n" "t" ))("쿳"))
((("z" "o" ))("캐"))
((("z" "o" "T" ))("캤"))
((("z" "o" "a" ))("캠"))
((("z" "o" "d" ))("캥"))
((("z" "o" "f" ))("캘"))
((("z" "o" "q" ))("캡"))
((("z" "o" "r" ))("캑"))
((("z" "o" "s" ))("캔"))
((("z" "o" "t" ))("캣"))
((("z" "p" ))("케"))
((("z" "p" "a" ))("켐"))
((("z" "p" "d" ))("켕"))
((("z" "p" "f" ))("켈"))
((("z" "p" "q" ))("켑"))
((("z" "p" "r" ))("켁"))
((("z" "p" "s" ))("켄"))
((("z" "p" "t" ))("켓"))
((("z" "u" ))("켜"))
((("z" "u" "T" ))("켰"))
((("z" "u" "a" ))("켬"))
((("z" "u" "d" ))("켱"))
((("z" "u" "f" ))("켤"))
((("z" "u" "q" ))("켭"))
((("z" "u" "s" ))("켠"))
((("z" "u" "t" ))("켯"))
((("z" "y" ))("쿄"))
))
|
65672f4d6f8ed351c0e8857a35d2d3c01c076b60bf779ab826216d4340830d7a | google/lisp-koans | vectors.lisp | Copyright 2013 Google 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.
Vectors are one - dimensional arrays . This means that general array operations
will work on vectors normally . However , also defines some functions for
;;; operating on sequences - which means, either vectors or lists.
(define-test vector-basics
;; #(...) is syntax sugar for defining literal vectors.
(let ((vector #(1 11 111)))
(true-or-false? ____ (typep vector 'vector))
(assert-equal ____ (aref vector 1))))
(define-test length
;; The function LENGTH works both for vectors and for lists.
(assert-equal ____ (length '(1 2 3)))
(assert-equal ____ (length #(1 2 3))))
(define-test bit-vector
# * 0011 defines a bit vector literal with four elements : 0 , 0 , 1 and 1 .
(assert-equal #*0011 (make-array 4 :element-type 'bit :initial-contents ____))
(true-or-false? ____ (typep #*1001 'bit-vector))
(assert-equal ____ (aref #*1001 1)))
(define-test bitwise-operations
;; Lisp defines a few bitwise operations that work on bit vectors.
(assert-equal ____ (bit-and #*1100 #*1010))
(assert-equal ____ (bit-ior #*1100 #*1010))
(assert-equal ____ (bit-xor #*1100 #*1010)))
(defun list-to-bit-vector (list)
;; Implement a function that turns a list into a bit vector.
____)
(define-test list-to-bit-vector
;; You need to fill in the blank in LIST-TO-BIT-VECTOR.
(assert-true (typep (list-to-bit-vector '(0 0 1 1 0)) 'bit-vector))
(assert-equal (aref (list-to-bit-vector '(0)) 0) 0)
(assert-equal (aref (list-to-bit-vector '(0 1)) 1) 1)
(assert-equal (length (list-to-bit-vector '(0 0 1 1 0 0 1 1))) 8))
| null | https://raw.githubusercontent.com/google/lisp-koans/df5e58dc88429ef0ff202d0b45c21ce572144ba8/koans/vectors.lisp | lisp |
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.
operating on sequences - which means, either vectors or lists.
#(...) is syntax sugar for defining literal vectors.
The function LENGTH works both for vectors and for lists.
Lisp defines a few bitwise operations that work on bit vectors.
Implement a function that turns a list into a bit vector.
You need to fill in the blank in LIST-TO-BIT-VECTOR. | Copyright 2013 Google Inc.
distributed under the License is distributed on an " AS IS " BASIS ,
Vectors are one - dimensional arrays . This means that general array operations
will work on vectors normally . However , also defines some functions for
(define-test vector-basics
(let ((vector #(1 11 111)))
(true-or-false? ____ (typep vector 'vector))
(assert-equal ____ (aref vector 1))))
(define-test length
(assert-equal ____ (length '(1 2 3)))
(assert-equal ____ (length #(1 2 3))))
(define-test bit-vector
# * 0011 defines a bit vector literal with four elements : 0 , 0 , 1 and 1 .
(assert-equal #*0011 (make-array 4 :element-type 'bit :initial-contents ____))
(true-or-false? ____ (typep #*1001 'bit-vector))
(assert-equal ____ (aref #*1001 1)))
(define-test bitwise-operations
(assert-equal ____ (bit-and #*1100 #*1010))
(assert-equal ____ (bit-ior #*1100 #*1010))
(assert-equal ____ (bit-xor #*1100 #*1010)))
(defun list-to-bit-vector (list)
____)
(define-test list-to-bit-vector
(assert-true (typep (list-to-bit-vector '(0 0 1 1 0)) 'bit-vector))
(assert-equal (aref (list-to-bit-vector '(0)) 0) 0)
(assert-equal (aref (list-to-bit-vector '(0 1)) 1) 1)
(assert-equal (length (list-to-bit-vector '(0 0 1 1 0 0 1 1))) 8))
|
28ea792121922de8ce92acc1bcbf44425e17b7638c974e05f09490201ade66b2 | divipp/emulator-stunts | Dos.hs | {-# LANGUAGE OverloadedStrings #-}
module Dos where
import Data.Word
import Data.Int
import Data.Bits hiding (bit)
import Data.Char
import Data.List
import Data.Monoid
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.Map as M
import qualified Data.IntMap.Strict as IM
import qualified Data.Vector.Storable as V
import Control.Applicative
import Control.Monad.State
import Control.Lens as Lens
import Control.Concurrent
import System.Directory
import System.FilePath (takeFileName)
import System.FilePath.Glob
import Sound.ALUT (play, stop, sourceGain, pitch, ($=))
import Prelude
import Helper
import MachineState
exePath = "restunts/stunts"
---------------------------------------------- memory allocation
allocateMem :: Word16 -> MemPiece -> (Word16, MemPiece)
allocateMem req' (alloc, end) = (r + 1, (alloc ++ [(r, r + 1 + req')], end))
where
r = snd $ last alloc
modifyAllocated :: Word16 -> Word16 -> MemPiece -> Either Word16 MemPiece
modifyAllocated addr req (alloc, endf) = head $ concatMap f $ getOut $ zip alloc $ tail $ map fst alloc ++ [endf]
where
getOut xs = zip (inits xs) (tails xs)
f (ys, ((beg,end),max): xs) | beg == addr - 1
= [ if req > max - beg - 1
then Left $ max - beg - 1
else Right (map fst ys ++ (beg, beg + req + 1): map fst xs, endf)
]
f _ = []
--------------------------------------
everyNth n [] = []
everyNth n xs = take n xs: everyNth n (drop n xs)
(@:) :: BS.ByteString -> a -> a
b @: x = x
infix 5 @:
combine :: Iso' (Word8, Word8) Word16
combine = iso (\(hi,lo) -> fromIntegral hi `shiftL` 8 .|. fromIntegral lo) (\d -> (fromIntegral $ d `shiftR` 8, fromIntegral d))
paragraph :: Word16 -> Int
paragraph = (`shiftL` 4) . fromIntegral
hiret :: Machine ()
hiret = do
pop >>= (ip ..=)
pop >>= (cs ..=)
pop >>= (flags ..=)
iret :: Machine ()
iret = do
pop >>= (ip ..=)
pop >>= (cs ..=)
flags' <- pop
interruptF ..= testBit flags' 9
haltWith = error
halt = error "CleanHalt"
getSender = do
v <- use'' interruptRequest
return $ \r -> modifyMVar_ v $ return . (++ [r])
setCounter = timerOn ...= True
timerThread = do
v <- use'' instPerSec
threadDelay $ round $ 1000000 / v
o <- use'' timerOn
when o $ do
counter ..%= (+1)
c <- use'' counter
send <- getSender
send $ AskTimerInterrupt c
timerThread
--------------------------------------------------------------------------------
input :: Word16 -> Machine (Word16)
input = \case
0x21 -> do
x <- use'' intMask
trace_ $ "Get interrupt mask " ++ showHex' 2 x
return $ "???" @: fromIntegral x
0x60 -> do
k <- use'' keyDown
trace_ $ "Keyboard scan code " ++ showHex' 4 k
return $ "???" @: k
0x61 -> do
x <- use'' speaker
when ((x .&. 0xfc) /= 0x30) $ trace_ $ "speaker -> " ++ showHex' 2 x
return $ "???" @: fromIntegral x
0x03da -> do
TODO
r <- head <$> use'' retrace
retrace ..%= tail
trace_ $ "VGA hardware " ++ showHex' 4 r
return $ "Vretrace | DD" @: r
v -> haltWith $ "input #" ++ showHex' 4 v
output' :: Word16 -> Word16 -> Machine ()
output' v x = case v of
0x20 -> do
trace _ $ " int resume " + + showHex ' 2 x -- ?
case x of
0x20 -> setCounter
-- v -> trace_ "int resume " ++ show
0x21 -> do
trace_ $ "Set interrupt mask " ++ showHex' 2 x -- ?
intMask ...= fromIntegral x
when (not $ testBit x 0) setCounter
0x40 -> do
show ( 1193182 / fromIntegral x ) + + " HZ "
0x41 -> do
trace_ $ "ch #41 " ++ showHex' 2 x -- ?
0x42 -> do
trace _ $ " ch # 42 " + + showHex ' 2 x
frequency ..%= (.|. (x `shiftL` 8)) . (`shiftR` 8)
f <- use'' frequency
source <- use'' soundSource
when (fromIntegral f >= 256) $ pitch source $= 2711 / fromIntegral f
0x43 -> do -- Set timer control
case x of
0x36 -> trace_ "Set timer frequency, square wave"
0xb6 -> trace_ "Set speaker frequency, square wave"
0x61 -> do
x' <- use'' speaker
speaker ...= fromIntegral x
when (x .&. 0xfc /= 0x30) $ trace_ $ "speaker <- " ++ showHex' 2 x
source <- use'' soundSource
when (testBit x 0 /= testBit x' 0) $ sourceGain source $= if testBit x 0 then 0.1 else 0
when (testBit x 1 /= testBit x' 1) $ (if testBit x 1 then play else stop) [source]
_ -> haltWith $ "output #" ++ showHex' 4 v ++ " 0x" ++ showHex' 4 x
--------------------------------------------------------
imMax m | IM.null m = 0
| otherwise = succ . fst . IM.findMax $ m
origInterrupt :: M.Map (Word16, Word16) (Word8, Machine ())
origInterrupt = M.fromList
[ hitem 0x00 (0xf000, 0x1060) $ do
trace_ "Divison by zero interrupt"
haltWith $ "int 00"
, hitem 0x08 (0xf000, 0xfea5) $ do
-- trace_ "orig timer"
output' 0x20 0x20
, hitem 0x09 (0xf000, 0xe987) $ do
trace_ "Orig keyboard interrupt"
haltWith $ "int 09"
, item 0x10 (0xf000, 0x1320) $ do -- Video Services
v <- use' ah
case v of
0x00 -> do
video_mode_number <- use' al
trace_ $ "Set Video Mode #" ++ showHex' 2 video_mode_number
case video_mode_number of
0x00 -> do
trace_' "text mode"
0x03 -> do
trace_' "mode 3"
0x13 -> do
4 -- ? ? ?
_ -> haltWith $ "#" ++ showHex' 2 video_mode_number
0x0b -> do
trace_ "Select Graphics Palette or Text Border Color"
0x0e -> do
a <- use' al
chr . fromIntegral $ a
trace_ $ "Write Character as TTY: " ++ show (chr $ fromIntegral a)
0x0f -> do
trace_ "Get Current Video Mode"
al ..= "text mode" @: 3
ah ..= "width of screen, in character columns" @: 80
b8
0x10 -> do -- Set/Get Palette Registers (EGA/VGA)
f <- use' al
case f of
0x12 -> do
trace_ "Set block of DAC color registers"
first_DAC_register <- use' bx -- (0-00ffH)
number_of_registers <- use' cx -- (0-00ffH)
Es : DX addr of a table of R , G , B values ( it will be CX*3 bytes long )
addr <- dxAddr'
colors <- getBytesAt addr $ 3 * fromIntegral number_of_registers
palette ..%= \cs -> cs V.//
zip [fromIntegral first_DAC_register .. fromIntegral (first_DAC_register + number_of_registers - 1)]
shift 2 more positions because there are 64 intesity levels
[ fromIntegral r `shiftL` 26 .|. fromIntegral g `shiftL` 18 .|. fromIntegral b `shiftL` 10
| [r, g, b] <- everyNth 3 $ colors]
v -> haltWith $ "interrupt #10,#10,#" ++ showHex' 2 f
v -> haltWith $ "interrupt #10,#" ++ showHex' 2 v
, item 0x15 (0xf000, 0x11e0) $ do -- Misc System Services
v <- use' ah
case v of
0xc2 -> do -- Pointing device BIOS interface
w <- use' al
case w of
0x01 -> do
trace_ "Reset Pointing device"
ah ..= 0 -- ?
bl ..= 0xaa -- ?
returnOK
v -> haltWith $ "interrupt #15,#" ++ showHex' 2 v
Keyboard Services
v <- use' ah
case v of
0x00 -> do
trace_ "Read (Wait for) Next Keystroke"
ah ..= "Esc scan code" @: 0x39
al ..= "Esc ASCII code" @: 0x1b
0x01 -> do
trace_ "Query Keyboard Status / Preview Key"
zeroF ..= False -- no keys in buffer
v -> haltWith $ "interrupt #16,#" ++ showHex' 2 v
, item 0x20 (0x0000, 0x0000) $ do
trace_ "interrupt halt"
halt
DOS rutine
v <- use' ah
case v of
0x00 -> do
trace_ "dos Program terminate"
halt
0x1a -> do
trace_ "Set DTA" -- Disk Transfer Address
addr <- dxAddr
dta ...= addr
0x25 -> do
v <- fromIntegral <$> use' al -- interrupt vector number
trace_ $ "Set Interrupt Vector " ++ showHex' 2 v
use' dx >>= setWordAt System (4*v) -- DS:DX = pointer to interrupt handler
use' ds >>= setWordAt System (4*v + 2)
0x30 -> do
trace_ "Get DOS version"
( 2 - 5 )
( in hundredths decimal )
bh ..= "MS-DOS" @: 0xff
24 bit OEM serial number
bl ..= "OEM serial number (high bits)" @: 0
cx ..= "OEM serial number (low bits)" @: 0
0x35 -> do
v <- fromIntegral <$> use' al
trace_ $ "Get Interrupt Vector " ++ showHex' 2 v
getWordAt System (4*v) >>= (bx ..=)
getWordAt System (4*v + 2) >>= (es ..=) -- Es:BX = pointer to interrupt handler
0x3c -> do
trace_ "Create"
(f, fn) <- getFileName
attributes <- use' cx
b <- doesFileExist fn
if b then dosFail 0x05 -- access denied
else do
writeFile fn ""
newHandle fn
0x3d -> do
trace_ "Open"
open_access_mode <- use' al
case open_access_mode of
0 -> do -- read mode
(f,fn) <- getFileName
checkExists fn $ newHandle fn
0x3e -> do
handle <- fromIntegral <$> use' bx
trace_ $ "Close " ++ showHandle handle
x <- IM.lookup handle <$> use'' files
case x of
Just (fn, _) -> do
files ..%= IM.delete handle
returnOK
0x3f -> do
handle <- fromIntegral <$> use' bx
(fn, seek) <- (IM.! handle) <$> use'' files
num <- fromIntegral <$> use' cx
loc <- dxAddr
s <- BS.take num . BS.drop seek <$> BS.readFile fn
let len = BS.length s
trace_ $ "Read " ++ showHandle handle ++ " " ++ showBytes len
files ..%= flip IM.adjust handle (\(fn, p) -> (fn, p+len))
setBytesAt loc $ BS.unpack s
ax ..= "length" @: fromIntegral len
returnOK
0x40 -> do
handle <- fromIntegral <$> use' bx
num <- fromIntegral <$> use' cx
trace_ $ "Write " ++ showHandle handle ++ " " ++ showBytes num
loc <- dxAddr
this <- getBytesAt loc num
case handle of
1 -> trace_' . ("STDOUT: " ++) . map (chr . fromIntegral) $ this
2 -> trace_' . ("STDERR: " ++) . map (chr . fromIntegral) $ this
_ -> return ()
returnOK
0x41 -> do
trace_ "Delete"
(f,fn) <- getFileName
checkExists fn $ do
removeFile fn
returnOK
0x42 -> do
handle <- fromIntegral <$> use' bx
fn <- (^. _1) . (IM.! handle) <$> use'' files
mode <- use' al
pos <- fromIntegral . (fromIntegral :: Word32 -> Int32) <$> use' cxdx
let showMode = \case
0 -> ""
1 -> "+"
2 -> "-"
trace_ $ "Seek " ++ showHandle handle ++ " " ++ showMode mode ++ show pos
s <- BS.readFile fn
files ..%= (flip IM.adjust handle $ \(fn, p) -> case mode of
0 -> (fn, pos)
1 -> (fn, p + pos)
2 -> (fn, BS.length s + pos)
)
pos' <- (^. _2) . (IM.! handle) <$> use'' files
dxax ..= fromIntegral pos'
returnOK
I / O Control for Devices ( IOCTL )
0x44 <- use' ah
function_value <- use' al
case function_value of
0x00 -> do
handle <- use' bx
trace_ $ "Get Device Information of " ++ showHandle handle
let v = case handle of
0010 1000 00 000100 no D : drive
0010 1000 00 000011 no C : drive
0010 1000 00 000011 B : drive
0010 1000 00 000011 A : drive
0010 1000 00 000011 default drive
dx ..= v
ax ..= v
returnOK
0x48 -> do
memory_paragraphs_requested <- use' bx
trace_ $ "Allocate Memory " ++ showBlocks memory_paragraphs_requested
h <- use'' heap
let (x, h') = allocateMem memory_paragraphs_requested h
heap ...= h'
( MCB + 1para )
returnOK
0x4a -> do
new_requested_block_size_in_paragraphs <- use' bx
trace_ $ "Modify allocated memory to " ++ showBlocks new_requested_block_size_in_paragraphs
( MCB + 1para )
h <- use'' heap
case modifyAllocated segment_of_the_block new_requested_block_size_in_paragraphs h of
Left x -> do
bx ..= "maximum block size possible" @: x
trace_' $ "max possible: " ++ showBlocks x
dosFail 0x08 -- insufficient memory
Right h -> do
ds <- use' ds
ax ..= ds -- why???
heap ...= h
returnOK
0x4c -> do
code <- use' al
trace_ $ "Terminate Process With Return Code #" ++ showHex' 2 code
halt
0x4e -> do
trace_ $ "Find file"
(f_,_) <- getFileName
attribute_used_during_search <- use' cx
ad <- use'' dta
s <- do
b <- globDir1 (compile $ map toUpper f_) exePath
case b of
(f:_) -> Just . (,) f <$> BS.readFile f
_ -> return Nothing
case s of
Just (f, s) -> do
let f' = strip $ takeFileName f
trace_' $ "found " ++ f'
setByteAt System (ad + 0x00) 1
setBytesAt (ad + 0x02) $ map (fromIntegral . ord) (take 12 $ strip f_) ++ [0]
setByteAt System (ad + 0x15) $ "attribute of matching file" @: fromIntegral attribute_used_during_search
TODO
TODO
snd (dwordAt__ System $ ad + 0x1a) $ fromIntegral (BS.length s)
setBytesAt (ad + 0x1e) $ map (fromIntegral . ord) (take 12 f') ++ [0]
ax ..= 0 -- ?
returnOK
Nothing -> dosFail 0x02 -- File not found
0x4f -> do
ad <- use'' dta
fname <- getBytesAt (ad + 0x02) 13
let f_ = map (chr . fromIntegral) $ takeWhile (/=0) fname
trace_ $ "Find next matching file " ++ show f_
n <- getByteAt System $ ad + 0x00
s <- do
b <- globDir1 (compile $ map toUpper f_) exePath
case drop (fromIntegral n) b of
filenames@(f:_) -> Just . (,) f <$> (BS.readFile f)
_ -> return Nothing
case s of
Just (f, s) -> do
trace_' $ "found: " ++ show f
TODO
TODO
snd (dwordAt__ System $ ad + 0x1a) $ fromIntegral (BS.length s)
setBytesAt (ad + 0x1e) $ map (fromIntegral . ord) (take 12 $ strip $ takeFileName f) ++ [0]
setByteAt System (ad + 0x00) $ n+1
ax ..= 0 -- ?
returnOK
Nothing -> dosFail 0x02
0x62 -> do
trace_ "Get PSP address"
bx ..= "segment address of current process" @: 0x1fe -- hack!!! !!!
returnOK
_ -> haltWith $ "dos function #" ++ showHex' 2 v
, hitem 0x24 (0x0118,0x0110) $ do
trace_ "critical error handler interrupt"
haltWith "int 24"
, item 0x33 (0xc7ff, 0x0010) $ do -- Mouse Services
v <- use' ax
case v of
0x00 -> do
trace_ "Mouse Reset/Get Mouse Installed Flag"
" mouse ? " @ : 0xffff
3
0x03 -> do
-- trace_ "Get Mouse position and button status"
cx ..= "mouse X" @: 0
dx ..= "mouse Y" @: 0
bx ..= "button status" @: 0
0x07 -> do
trace_ "Set Mouse Horizontal Min/Max Position"
minimum_horizontal_position <- use' cx
maximum_horizontal_position <- use' dx
return ()
0x08 -> do
trace_ "Set Mouse Vertical Min/Max Position"
minimum_vertical_position <- use' cx
maximum_vertical_position <- use' dx
return ()
0x0f -> do
trace_ "Set Mouse Mickey Pixel Ratio"
_ -> haltWith $ "Int 33h, #" ++ showHex' 2 v
]
where
item : : Word8 - > ( Word16 , ( ) - > ( ( Word16 , ) , ( Word8 , Machine ( ) ) )
item a k m = (k, (a, m >> iret))
hitem a k m = (k, (a, m >> hiret))
newHandle fn = do
handle <- max 5 . imMax <$> use'' files
files ..%= IM.insert handle (fn, 0)
trace_' $ showHandle handle
ax ..= "file handle" @: fromIntegral handle
returnOK
getFileName = do
addr <- dxAddr
fname <- getBytesAt addr 40
let f = map (toUpper . chr . fromIntegral) $ takeWhile (/=0) fname
trace_' f
return (f, exePath ++ "/" ++ f)
showHandle h = "#" ++ show h
showBytes i = show i ++ " bytes"
showBlocks i = "0x" ++ showHex' 4 i ++ " blocks"
dxAddr = liftM2 segAddr (use' ds) (use' dx)
dxAddr' = liftM2 segAddr (use' es) (use' dx)
checkExists fn cont = do
b <- doesFileExist fn
if b then cont else dosFail 0x02
returnOK = carryF ..= False
dosFail errcode = do
trace_' $ "! " ++ showerr errcode
ax ..= errcode
carryF ..= True
where
showerr = \case
0x01 -> "Invalid function number"
0x02 -> "File not found"
0x03 -> "Path not found"
0x04 -> "Too many open files (no handles left)"
0x05 -> "Access denied"
0x06 -> "Invalid handle"
0x07 -> "Memory control blocks destroyed"
0x08 -> "Insufficient memory"
0x09 -> "Invalid memory block address"
0x0A -> "Invalid environment"
0x0B -> "Invalid format"
0x0C -> "Invalid access mode (open mode is invalid)"
strip = reverse . dropWhile (==' ') . reverse . dropWhile (==' ')
----------------------------------------------
programSegmentPrefix' :: Word16 -> Word16 -> Word16 -> BS.ByteString -> Machine ()
programSegmentPrefix' baseseg envseg endseg args = do
wordAt_ 0x00 $ "CP/M exit, always contain code 'int 20h'" @: 0x20CD
wordAt_ 0x02 $ "Segment of the first byte beyond the memory allocated to the program" @: endseg
bytesAt 0x05 5 .= [ 0xea , 0xff , 0xff , 0xad , ] -- FAR call to MSDOS function dispatcher ( int 21h ) ?
dwordAt 0x0a .= 0xf00020c8 -- Terminate address of previous program ( old INT 22h )
dwordAt 0x0e .= 0x01180000 -- Break address of previous program ( old INT 23h )
dwordAt 0x12 .= 0x01180110 -- Critical error address of previous program ( old INT 24h )
wordAt 0x16 .= 0x0118 -- Caller 's PSP segment ( usually COMMAND.COM - internal )
Job File Table ( JFT ) ( internal )
-- bytesAt 0x18 20 .= [0x01, 0x01, 0x01, 0x00, 0x02, 0x03] ++ repeat 0xff
wordAt_ 0x2c $ "Environment segment" @: envseg
dwordAt 0x2e .= 0x0192ffe6 -- SS : SP on entry to last INT 21h call ( internal )
wordAt 0x32 .= 0x0014 -- JFT size ( internal )
dwordAt 0x34 .= 0x01920018 - - Pointer to JFT ( internal )
dwordAt 0x38 .= 0xffffffff -- Pointer to previous PSP ( only used by SHARE in DOS 3.3 and later )
3Ch-3Fh 4 bytes Reserved
wordAt 0x40 .= 0x0005 -- DOS version to return ( DOS 4 and later , alterable via SETVER in DOS 5 and later )
42h-4Fh 14 bytes Reserved
bytesAt_ 0x50 [0xcd, 0x21, 0xcb] -- (code) Far call to DOS (always contain INT 21h + RETF)
53h-54h 2 bytes Reserved
55h-5Bh 7 bytes Reserved ( can be used to make first FCB into an extended FCB )
5Ch-6Bh 16 bytes Unopened Standard FCB 1
6Ch-7Fh 20 bytes Unopened Standard FCB 2 ( overwritten if FCB 1 is opened )
bytesAt 0x5c ( 16 + 20 ) .= repeat 0
byteAt_ 0x80 $ "args length" @: fromIntegral (min maxlength $ BS.length args)
bytesAt_ 0x81 $ take maxlength (BS.unpack args) ++ [0x0D] -- Command line string
-- byteAt 0xff .= 0x36 -- dosbox specific?
where
base = baseseg & paragraph
wordAt_ i = setWordAt System (i+base)
byteAt_ i = setByteAt System (i+base)
bytesAt_ i = setBytesAt (i+base)
maxlength = 125
getBytesAt i j = mapM (getByteAt System) $ take j [i..]
setBytesAt i = zipWithM_ (setByteAt System) [i..]
pspSegSize = 16
envvarsSegment = 0x1f4
envvars :: [Word8]
envvars = map (fromIntegral . ord) "PATH=Z:\\\NULCOMSPEC=Z:\\COMMAND.COM\NULBLASTER=A220 I7 D1 H5 T6\0\0\1\0C:\\GAME.EXE" ++
replicate 20 0
loadExe :: Word16 -> BS.ByteString -> Machine (Int -> BSC.ByteString)
loadExe loadSegment gameExe = do
flags ..= wordToFlags 0xf202
heap ...= ( [(pspSegment - 1, endseg)], 0xa000 - 1)
setBytesAt (envvarsSegment & paragraph) envvars
setBytesAt exeStart $ BS.unpack relocatedExe
ss ..= (ssInit + loadSegment)
sp ..= spInit
cs ..= (csInit + loadSegment)
ip ..= ipInit
ds ..= pspSegment
es ..= pspSegment
cx ..= 0x00ff -- why?
dx ..= pspSegment -- why?
bp ..= 0x091c -- why?
si ..= 0x0012 -- why?
di ..= envvarsSegment `shiftL` 4
labels ...= mempty
setWordAt System 0x410 $ "equipment word" @: 0xd426 --- 0x4463 --- ???
setByteAt System 0x417 $ "keyboard shift flag 1" @: 0x20
forM_ [(fromIntegral a, b, m) | (b, (a, m)) <- M.toList origInterrupt] $ \(i, (hi, lo), m) -> do
setWordAt System (4*i) $ "interrupt lo" @: lo
setWordAt System (4*i + 2) $ "interrupt hi" @: hi
cache .%= IM.insert (segAddr hi lo) (BuiltIn m)
programSegmentPrefix' pspSegment envvarsSegment endseg ""
gameexe ...= (exeStart, relocatedExe)
hack for stunts : skip the first few instructions to ensure constant ss value during run
ip ..= 0x004f
si ..= 0x0d20
di ..= 0x2d85
sp ..= 0xcc5e
ss ..= 0x2d85
return getInst
where
getInst i
| j >= 0 && j < BS.length relocatedExe = BS.drop j relocatedExe
where
j = i - exeStart
exeStart = loadSegment & paragraph
relocatedExe = relocate relocationTable loadSegment $ BS.drop headerSize gameExe
pspSegment = loadSegment - pspSegSize
endseg = loadSegment + executableSegSize + additionalMemoryAllocated
additionalMemoryAllocated = additionalMemoryNeeded
-- could be anything between additionalMemoryNeeded and maxAdditionalMemoryNeeded
(0x5a4d: bytesInLastPage: pagesInExecutable: relocationEntries:
paragraphsInHeader: additionalMemoryNeeded: _maxAdditionalMemoryNeeded: ssInit:
spInit: _checksum: ipInit: csInit:
firstRelocationItemOffset: _overlayNumber: headerLeft)
= map (\[low, high] -> (high, low) ^. combine) $ everyNth 2 $ BS.unpack $ gameExe
headerSize = paragraphsInHeader & paragraph
executableSegSize = pagesInExecutable `shiftL` 5
+ (if (bytesInLastPage > 0) then (bytesInLastPage + 0xf) `shiftL` 4 - 0x20 else 0)
- 0x22f -- ???
relocationTable = sort $ take (fromIntegral relocationEntries)
$ map (\[a,b]-> segAddr b a) $ everyNth 2 $ drop (fromIntegral firstRelocationItemOffset `div` 2 - 14) headerLeft
unique xs = length xs == length (nub xs)
relocate :: [Int] -> Word16 -> BS.ByteString -> BS.ByteString
relocate table loc exe = BS.concat $ fst: map add (bss ++ [last])
where
(last, fst: bss) = mapAccumL (flip go) exe $ zipWith (-) table $ 0: table
go r (BS.splitAt r -> (xs, ys)) = (ys, xs)
add (BS.uncons -> Just (x, BS.uncons -> Just (y, xs))) = BS.cons x' $ BS.cons y' xs
where (y',x') = combine %~ (+ loc) $ (y,x)
| null | https://raw.githubusercontent.com/divipp/emulator-stunts/5f7077ff04f44af24c6a95504a52818b73a7f3b1/emulate8086/Dos.hs | haskell | # LANGUAGE OverloadedStrings #
-------------------------------------------- memory allocation
------------------------------------
------------------------------------------------------------------------------
?
v -> trace_ "int resume " ++ show
?
?
Set timer control
------------------------------------------------------
trace_ "orig timer"
Video Services
? ? ?
Set/Get Palette Registers (EGA/VGA)
(0-00ffH)
(0-00ffH)
Misc System Services
Pointing device BIOS interface
?
?
no keys in buffer
Disk Transfer Address
interrupt vector number
DS:DX = pointer to interrupt handler
Es:BX = pointer to interrupt handler
access denied
read mode
insufficient memory
why???
?
File not found
?
hack!!! !!!
Mouse Services
trace_ "Get Mouse position and button status"
--------------------------------------------
FAR call to MSDOS function dispatcher ( int 21h ) ?
Terminate address of previous program ( old INT 22h )
Break address of previous program ( old INT 23h )
Critical error address of previous program ( old INT 24h )
Caller 's PSP segment ( usually COMMAND.COM - internal )
bytesAt 0x18 20 .= [0x01, 0x01, 0x01, 0x00, 0x02, 0x03] ++ repeat 0xff
SS : SP on entry to last INT 21h call ( internal )
JFT size ( internal )
Pointer to previous PSP ( only used by SHARE in DOS 3.3 and later )
DOS version to return ( DOS 4 and later , alterable via SETVER in DOS 5 and later )
(code) Far call to DOS (always contain INT 21h + RETF)
Command line string
byteAt 0xff .= 0x36 -- dosbox specific?
why?
why?
why?
why?
- 0x4463 --- ???
could be anything between additionalMemoryNeeded and maxAdditionalMemoryNeeded
??? | module Dos where
import Data.Word
import Data.Int
import Data.Bits hiding (bit)
import Data.Char
import Data.List
import Data.Monoid
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as BSC
import qualified Data.Map as M
import qualified Data.IntMap.Strict as IM
import qualified Data.Vector.Storable as V
import Control.Applicative
import Control.Monad.State
import Control.Lens as Lens
import Control.Concurrent
import System.Directory
import System.FilePath (takeFileName)
import System.FilePath.Glob
import Sound.ALUT (play, stop, sourceGain, pitch, ($=))
import Prelude
import Helper
import MachineState
exePath = "restunts/stunts"
allocateMem :: Word16 -> MemPiece -> (Word16, MemPiece)
allocateMem req' (alloc, end) = (r + 1, (alloc ++ [(r, r + 1 + req')], end))
where
r = snd $ last alloc
modifyAllocated :: Word16 -> Word16 -> MemPiece -> Either Word16 MemPiece
modifyAllocated addr req (alloc, endf) = head $ concatMap f $ getOut $ zip alloc $ tail $ map fst alloc ++ [endf]
where
getOut xs = zip (inits xs) (tails xs)
f (ys, ((beg,end),max): xs) | beg == addr - 1
= [ if req > max - beg - 1
then Left $ max - beg - 1
else Right (map fst ys ++ (beg, beg + req + 1): map fst xs, endf)
]
f _ = []
everyNth n [] = []
everyNth n xs = take n xs: everyNth n (drop n xs)
(@:) :: BS.ByteString -> a -> a
b @: x = x
infix 5 @:
combine :: Iso' (Word8, Word8) Word16
combine = iso (\(hi,lo) -> fromIntegral hi `shiftL` 8 .|. fromIntegral lo) (\d -> (fromIntegral $ d `shiftR` 8, fromIntegral d))
paragraph :: Word16 -> Int
paragraph = (`shiftL` 4) . fromIntegral
hiret :: Machine ()
hiret = do
pop >>= (ip ..=)
pop >>= (cs ..=)
pop >>= (flags ..=)
iret :: Machine ()
iret = do
pop >>= (ip ..=)
pop >>= (cs ..=)
flags' <- pop
interruptF ..= testBit flags' 9
haltWith = error
halt = error "CleanHalt"
getSender = do
v <- use'' interruptRequest
return $ \r -> modifyMVar_ v $ return . (++ [r])
setCounter = timerOn ...= True
timerThread = do
v <- use'' instPerSec
threadDelay $ round $ 1000000 / v
o <- use'' timerOn
when o $ do
counter ..%= (+1)
c <- use'' counter
send <- getSender
send $ AskTimerInterrupt c
timerThread
input :: Word16 -> Machine (Word16)
input = \case
0x21 -> do
x <- use'' intMask
trace_ $ "Get interrupt mask " ++ showHex' 2 x
return $ "???" @: fromIntegral x
0x60 -> do
k <- use'' keyDown
trace_ $ "Keyboard scan code " ++ showHex' 4 k
return $ "???" @: k
0x61 -> do
x <- use'' speaker
when ((x .&. 0xfc) /= 0x30) $ trace_ $ "speaker -> " ++ showHex' 2 x
return $ "???" @: fromIntegral x
0x03da -> do
TODO
r <- head <$> use'' retrace
retrace ..%= tail
trace_ $ "VGA hardware " ++ showHex' 4 r
return $ "Vretrace | DD" @: r
v -> haltWith $ "input #" ++ showHex' 4 v
output' :: Word16 -> Word16 -> Machine ()
output' v x = case v of
0x20 -> do
case x of
0x20 -> setCounter
0x21 -> do
intMask ...= fromIntegral x
when (not $ testBit x 0) setCounter
0x40 -> do
show ( 1193182 / fromIntegral x ) + + " HZ "
0x41 -> do
0x42 -> do
trace _ $ " ch # 42 " + + showHex ' 2 x
frequency ..%= (.|. (x `shiftL` 8)) . (`shiftR` 8)
f <- use'' frequency
source <- use'' soundSource
when (fromIntegral f >= 256) $ pitch source $= 2711 / fromIntegral f
case x of
0x36 -> trace_ "Set timer frequency, square wave"
0xb6 -> trace_ "Set speaker frequency, square wave"
0x61 -> do
x' <- use'' speaker
speaker ...= fromIntegral x
when (x .&. 0xfc /= 0x30) $ trace_ $ "speaker <- " ++ showHex' 2 x
source <- use'' soundSource
when (testBit x 0 /= testBit x' 0) $ sourceGain source $= if testBit x 0 then 0.1 else 0
when (testBit x 1 /= testBit x' 1) $ (if testBit x 1 then play else stop) [source]
_ -> haltWith $ "output #" ++ showHex' 4 v ++ " 0x" ++ showHex' 4 x
imMax m | IM.null m = 0
| otherwise = succ . fst . IM.findMax $ m
origInterrupt :: M.Map (Word16, Word16) (Word8, Machine ())
origInterrupt = M.fromList
[ hitem 0x00 (0xf000, 0x1060) $ do
trace_ "Divison by zero interrupt"
haltWith $ "int 00"
, hitem 0x08 (0xf000, 0xfea5) $ do
output' 0x20 0x20
, hitem 0x09 (0xf000, 0xe987) $ do
trace_ "Orig keyboard interrupt"
haltWith $ "int 09"
v <- use' ah
case v of
0x00 -> do
video_mode_number <- use' al
trace_ $ "Set Video Mode #" ++ showHex' 2 video_mode_number
case video_mode_number of
0x00 -> do
trace_' "text mode"
0x03 -> do
trace_' "mode 3"
0x13 -> do
_ -> haltWith $ "#" ++ showHex' 2 video_mode_number
0x0b -> do
trace_ "Select Graphics Palette or Text Border Color"
0x0e -> do
a <- use' al
chr . fromIntegral $ a
trace_ $ "Write Character as TTY: " ++ show (chr $ fromIntegral a)
0x0f -> do
trace_ "Get Current Video Mode"
al ..= "text mode" @: 3
ah ..= "width of screen, in character columns" @: 80
b8
f <- use' al
case f of
0x12 -> do
trace_ "Set block of DAC color registers"
Es : DX addr of a table of R , G , B values ( it will be CX*3 bytes long )
addr <- dxAddr'
colors <- getBytesAt addr $ 3 * fromIntegral number_of_registers
palette ..%= \cs -> cs V.//
zip [fromIntegral first_DAC_register .. fromIntegral (first_DAC_register + number_of_registers - 1)]
shift 2 more positions because there are 64 intesity levels
[ fromIntegral r `shiftL` 26 .|. fromIntegral g `shiftL` 18 .|. fromIntegral b `shiftL` 10
| [r, g, b] <- everyNth 3 $ colors]
v -> haltWith $ "interrupt #10,#10,#" ++ showHex' 2 f
v -> haltWith $ "interrupt #10,#" ++ showHex' 2 v
v <- use' ah
case v of
w <- use' al
case w of
0x01 -> do
trace_ "Reset Pointing device"
returnOK
v -> haltWith $ "interrupt #15,#" ++ showHex' 2 v
Keyboard Services
v <- use' ah
case v of
0x00 -> do
trace_ "Read (Wait for) Next Keystroke"
ah ..= "Esc scan code" @: 0x39
al ..= "Esc ASCII code" @: 0x1b
0x01 -> do
trace_ "Query Keyboard Status / Preview Key"
v -> haltWith $ "interrupt #16,#" ++ showHex' 2 v
, item 0x20 (0x0000, 0x0000) $ do
trace_ "interrupt halt"
halt
DOS rutine
v <- use' ah
case v of
0x00 -> do
trace_ "dos Program terminate"
halt
0x1a -> do
addr <- dxAddr
dta ...= addr
0x25 -> do
trace_ $ "Set Interrupt Vector " ++ showHex' 2 v
use' ds >>= setWordAt System (4*v + 2)
0x30 -> do
trace_ "Get DOS version"
( 2 - 5 )
( in hundredths decimal )
bh ..= "MS-DOS" @: 0xff
24 bit OEM serial number
bl ..= "OEM serial number (high bits)" @: 0
cx ..= "OEM serial number (low bits)" @: 0
0x35 -> do
v <- fromIntegral <$> use' al
trace_ $ "Get Interrupt Vector " ++ showHex' 2 v
getWordAt System (4*v) >>= (bx ..=)
0x3c -> do
trace_ "Create"
(f, fn) <- getFileName
attributes <- use' cx
b <- doesFileExist fn
else do
writeFile fn ""
newHandle fn
0x3d -> do
trace_ "Open"
open_access_mode <- use' al
case open_access_mode of
(f,fn) <- getFileName
checkExists fn $ newHandle fn
0x3e -> do
handle <- fromIntegral <$> use' bx
trace_ $ "Close " ++ showHandle handle
x <- IM.lookup handle <$> use'' files
case x of
Just (fn, _) -> do
files ..%= IM.delete handle
returnOK
0x3f -> do
handle <- fromIntegral <$> use' bx
(fn, seek) <- (IM.! handle) <$> use'' files
num <- fromIntegral <$> use' cx
loc <- dxAddr
s <- BS.take num . BS.drop seek <$> BS.readFile fn
let len = BS.length s
trace_ $ "Read " ++ showHandle handle ++ " " ++ showBytes len
files ..%= flip IM.adjust handle (\(fn, p) -> (fn, p+len))
setBytesAt loc $ BS.unpack s
ax ..= "length" @: fromIntegral len
returnOK
0x40 -> do
handle <- fromIntegral <$> use' bx
num <- fromIntegral <$> use' cx
trace_ $ "Write " ++ showHandle handle ++ " " ++ showBytes num
loc <- dxAddr
this <- getBytesAt loc num
case handle of
1 -> trace_' . ("STDOUT: " ++) . map (chr . fromIntegral) $ this
2 -> trace_' . ("STDERR: " ++) . map (chr . fromIntegral) $ this
_ -> return ()
returnOK
0x41 -> do
trace_ "Delete"
(f,fn) <- getFileName
checkExists fn $ do
removeFile fn
returnOK
0x42 -> do
handle <- fromIntegral <$> use' bx
fn <- (^. _1) . (IM.! handle) <$> use'' files
mode <- use' al
pos <- fromIntegral . (fromIntegral :: Word32 -> Int32) <$> use' cxdx
let showMode = \case
0 -> ""
1 -> "+"
2 -> "-"
trace_ $ "Seek " ++ showHandle handle ++ " " ++ showMode mode ++ show pos
s <- BS.readFile fn
files ..%= (flip IM.adjust handle $ \(fn, p) -> case mode of
0 -> (fn, pos)
1 -> (fn, p + pos)
2 -> (fn, BS.length s + pos)
)
pos' <- (^. _2) . (IM.! handle) <$> use'' files
dxax ..= fromIntegral pos'
returnOK
I / O Control for Devices ( IOCTL )
0x44 <- use' ah
function_value <- use' al
case function_value of
0x00 -> do
handle <- use' bx
trace_ $ "Get Device Information of " ++ showHandle handle
let v = case handle of
0010 1000 00 000100 no D : drive
0010 1000 00 000011 no C : drive
0010 1000 00 000011 B : drive
0010 1000 00 000011 A : drive
0010 1000 00 000011 default drive
dx ..= v
ax ..= v
returnOK
0x48 -> do
memory_paragraphs_requested <- use' bx
trace_ $ "Allocate Memory " ++ showBlocks memory_paragraphs_requested
h <- use'' heap
let (x, h') = allocateMem memory_paragraphs_requested h
heap ...= h'
( MCB + 1para )
returnOK
0x4a -> do
new_requested_block_size_in_paragraphs <- use' bx
trace_ $ "Modify allocated memory to " ++ showBlocks new_requested_block_size_in_paragraphs
( MCB + 1para )
h <- use'' heap
case modifyAllocated segment_of_the_block new_requested_block_size_in_paragraphs h of
Left x -> do
bx ..= "maximum block size possible" @: x
trace_' $ "max possible: " ++ showBlocks x
Right h -> do
ds <- use' ds
heap ...= h
returnOK
0x4c -> do
code <- use' al
trace_ $ "Terminate Process With Return Code #" ++ showHex' 2 code
halt
0x4e -> do
trace_ $ "Find file"
(f_,_) <- getFileName
attribute_used_during_search <- use' cx
ad <- use'' dta
s <- do
b <- globDir1 (compile $ map toUpper f_) exePath
case b of
(f:_) -> Just . (,) f <$> BS.readFile f
_ -> return Nothing
case s of
Just (f, s) -> do
let f' = strip $ takeFileName f
trace_' $ "found " ++ f'
setByteAt System (ad + 0x00) 1
setBytesAt (ad + 0x02) $ map (fromIntegral . ord) (take 12 $ strip f_) ++ [0]
setByteAt System (ad + 0x15) $ "attribute of matching file" @: fromIntegral attribute_used_during_search
TODO
TODO
snd (dwordAt__ System $ ad + 0x1a) $ fromIntegral (BS.length s)
setBytesAt (ad + 0x1e) $ map (fromIntegral . ord) (take 12 f') ++ [0]
returnOK
0x4f -> do
ad <- use'' dta
fname <- getBytesAt (ad + 0x02) 13
let f_ = map (chr . fromIntegral) $ takeWhile (/=0) fname
trace_ $ "Find next matching file " ++ show f_
n <- getByteAt System $ ad + 0x00
s <- do
b <- globDir1 (compile $ map toUpper f_) exePath
case drop (fromIntegral n) b of
filenames@(f:_) -> Just . (,) f <$> (BS.readFile f)
_ -> return Nothing
case s of
Just (f, s) -> do
trace_' $ "found: " ++ show f
TODO
TODO
snd (dwordAt__ System $ ad + 0x1a) $ fromIntegral (BS.length s)
setBytesAt (ad + 0x1e) $ map (fromIntegral . ord) (take 12 $ strip $ takeFileName f) ++ [0]
setByteAt System (ad + 0x00) $ n+1
returnOK
Nothing -> dosFail 0x02
0x62 -> do
trace_ "Get PSP address"
returnOK
_ -> haltWith $ "dos function #" ++ showHex' 2 v
, hitem 0x24 (0x0118,0x0110) $ do
trace_ "critical error handler interrupt"
haltWith "int 24"
v <- use' ax
case v of
0x00 -> do
trace_ "Mouse Reset/Get Mouse Installed Flag"
" mouse ? " @ : 0xffff
3
0x03 -> do
cx ..= "mouse X" @: 0
dx ..= "mouse Y" @: 0
bx ..= "button status" @: 0
0x07 -> do
trace_ "Set Mouse Horizontal Min/Max Position"
minimum_horizontal_position <- use' cx
maximum_horizontal_position <- use' dx
return ()
0x08 -> do
trace_ "Set Mouse Vertical Min/Max Position"
minimum_vertical_position <- use' cx
maximum_vertical_position <- use' dx
return ()
0x0f -> do
trace_ "Set Mouse Mickey Pixel Ratio"
_ -> haltWith $ "Int 33h, #" ++ showHex' 2 v
]
where
item : : Word8 - > ( Word16 , ( ) - > ( ( Word16 , ) , ( Word8 , Machine ( ) ) )
item a k m = (k, (a, m >> iret))
hitem a k m = (k, (a, m >> hiret))
newHandle fn = do
handle <- max 5 . imMax <$> use'' files
files ..%= IM.insert handle (fn, 0)
trace_' $ showHandle handle
ax ..= "file handle" @: fromIntegral handle
returnOK
getFileName = do
addr <- dxAddr
fname <- getBytesAt addr 40
let f = map (toUpper . chr . fromIntegral) $ takeWhile (/=0) fname
trace_' f
return (f, exePath ++ "/" ++ f)
showHandle h = "#" ++ show h
showBytes i = show i ++ " bytes"
showBlocks i = "0x" ++ showHex' 4 i ++ " blocks"
dxAddr = liftM2 segAddr (use' ds) (use' dx)
dxAddr' = liftM2 segAddr (use' es) (use' dx)
checkExists fn cont = do
b <- doesFileExist fn
if b then cont else dosFail 0x02
returnOK = carryF ..= False
dosFail errcode = do
trace_' $ "! " ++ showerr errcode
ax ..= errcode
carryF ..= True
where
showerr = \case
0x01 -> "Invalid function number"
0x02 -> "File not found"
0x03 -> "Path not found"
0x04 -> "Too many open files (no handles left)"
0x05 -> "Access denied"
0x06 -> "Invalid handle"
0x07 -> "Memory control blocks destroyed"
0x08 -> "Insufficient memory"
0x09 -> "Invalid memory block address"
0x0A -> "Invalid environment"
0x0B -> "Invalid format"
0x0C -> "Invalid access mode (open mode is invalid)"
strip = reverse . dropWhile (==' ') . reverse . dropWhile (==' ')
programSegmentPrefix' :: Word16 -> Word16 -> Word16 -> BS.ByteString -> Machine ()
programSegmentPrefix' baseseg envseg endseg args = do
wordAt_ 0x00 $ "CP/M exit, always contain code 'int 20h'" @: 0x20CD
wordAt_ 0x02 $ "Segment of the first byte beyond the memory allocated to the program" @: endseg
Job File Table ( JFT ) ( internal )
wordAt_ 0x2c $ "Environment segment" @: envseg
dwordAt 0x34 .= 0x01920018 - - Pointer to JFT ( internal )
3Ch-3Fh 4 bytes Reserved
42h-4Fh 14 bytes Reserved
53h-54h 2 bytes Reserved
55h-5Bh 7 bytes Reserved ( can be used to make first FCB into an extended FCB )
5Ch-6Bh 16 bytes Unopened Standard FCB 1
6Ch-7Fh 20 bytes Unopened Standard FCB 2 ( overwritten if FCB 1 is opened )
bytesAt 0x5c ( 16 + 20 ) .= repeat 0
byteAt_ 0x80 $ "args length" @: fromIntegral (min maxlength $ BS.length args)
where
base = baseseg & paragraph
wordAt_ i = setWordAt System (i+base)
byteAt_ i = setByteAt System (i+base)
bytesAt_ i = setBytesAt (i+base)
maxlength = 125
getBytesAt i j = mapM (getByteAt System) $ take j [i..]
setBytesAt i = zipWithM_ (setByteAt System) [i..]
pspSegSize = 16
envvarsSegment = 0x1f4
envvars :: [Word8]
envvars = map (fromIntegral . ord) "PATH=Z:\\\NULCOMSPEC=Z:\\COMMAND.COM\NULBLASTER=A220 I7 D1 H5 T6\0\0\1\0C:\\GAME.EXE" ++
replicate 20 0
loadExe :: Word16 -> BS.ByteString -> Machine (Int -> BSC.ByteString)
loadExe loadSegment gameExe = do
flags ..= wordToFlags 0xf202
heap ...= ( [(pspSegment - 1, endseg)], 0xa000 - 1)
setBytesAt (envvarsSegment & paragraph) envvars
setBytesAt exeStart $ BS.unpack relocatedExe
ss ..= (ssInit + loadSegment)
sp ..= spInit
cs ..= (csInit + loadSegment)
ip ..= ipInit
ds ..= pspSegment
es ..= pspSegment
di ..= envvarsSegment `shiftL` 4
labels ...= mempty
setByteAt System 0x417 $ "keyboard shift flag 1" @: 0x20
forM_ [(fromIntegral a, b, m) | (b, (a, m)) <- M.toList origInterrupt] $ \(i, (hi, lo), m) -> do
setWordAt System (4*i) $ "interrupt lo" @: lo
setWordAt System (4*i + 2) $ "interrupt hi" @: hi
cache .%= IM.insert (segAddr hi lo) (BuiltIn m)
programSegmentPrefix' pspSegment envvarsSegment endseg ""
gameexe ...= (exeStart, relocatedExe)
hack for stunts : skip the first few instructions to ensure constant ss value during run
ip ..= 0x004f
si ..= 0x0d20
di ..= 0x2d85
sp ..= 0xcc5e
ss ..= 0x2d85
return getInst
where
getInst i
| j >= 0 && j < BS.length relocatedExe = BS.drop j relocatedExe
where
j = i - exeStart
exeStart = loadSegment & paragraph
relocatedExe = relocate relocationTable loadSegment $ BS.drop headerSize gameExe
pspSegment = loadSegment - pspSegSize
endseg = loadSegment + executableSegSize + additionalMemoryAllocated
additionalMemoryAllocated = additionalMemoryNeeded
(0x5a4d: bytesInLastPage: pagesInExecutable: relocationEntries:
paragraphsInHeader: additionalMemoryNeeded: _maxAdditionalMemoryNeeded: ssInit:
spInit: _checksum: ipInit: csInit:
firstRelocationItemOffset: _overlayNumber: headerLeft)
= map (\[low, high] -> (high, low) ^. combine) $ everyNth 2 $ BS.unpack $ gameExe
headerSize = paragraphsInHeader & paragraph
executableSegSize = pagesInExecutable `shiftL` 5
+ (if (bytesInLastPage > 0) then (bytesInLastPage + 0xf) `shiftL` 4 - 0x20 else 0)
relocationTable = sort $ take (fromIntegral relocationEntries)
$ map (\[a,b]-> segAddr b a) $ everyNth 2 $ drop (fromIntegral firstRelocationItemOffset `div` 2 - 14) headerLeft
unique xs = length xs == length (nub xs)
relocate :: [Int] -> Word16 -> BS.ByteString -> BS.ByteString
relocate table loc exe = BS.concat $ fst: map add (bss ++ [last])
where
(last, fst: bss) = mapAccumL (flip go) exe $ zipWith (-) table $ 0: table
go r (BS.splitAt r -> (xs, ys)) = (ys, xs)
add (BS.uncons -> Just (x, BS.uncons -> Just (y, xs))) = BS.cons x' $ BS.cons y' xs
where (y',x') = combine %~ (+ loc) $ (y,x)
|
d31254304cf7bf4a0867668f5c4695622d7030f78f8cb5a28da15ecfa8144df5 | acieroid/scala-am | count7.scm | (letrec ((i 100)
(thread (lambda (n)
(if (<= i 0)
#t
(begin (set! i (- i 1)) (thread n)))))
(t1 (fork (thread 1)))
(t2 (fork (thread 2)))
(t3 (fork (thread 3)))
(t4 (fork (thread 4)))
(t5 (fork (thread 5)))
(t6 (fork (thread 6)))
(t7 (fork (thread 7))))
(join t1)
(join t2)
(join t3)
(join t4)
(join t5)
(join t6)
(join t7)) | null | https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/concurrentScheme/threads/variations/count7.scm | scheme | (letrec ((i 100)
(thread (lambda (n)
(if (<= i 0)
#t
(begin (set! i (- i 1)) (thread n)))))
(t1 (fork (thread 1)))
(t2 (fork (thread 2)))
(t3 (fork (thread 3)))
(t4 (fork (thread 4)))
(t5 (fork (thread 5)))
(t6 (fork (thread 6)))
(t7 (fork (thread 7))))
(join t1)
(join t2)
(join t3)
(join t4)
(join t5)
(join t6)
(join t7)) | |
9a912d865c156a89206310afdb50a0451d3dd5950c17c318b358a22381153e76 | shamazmazum/easy-audio | frame.lisp | (in-package :easy-audio.ape)
(defconstant +mono-silence+ 1)
(defconstant +stereo-silence+ 3)
(defconstant +pseudo-stereo+ 4)
(deftype octet-reader ()
'(function (&optional) (ub 8)))
(defparameter *stereo-entropy-versions*
'#.(reverse '(0 3860 3900 3930 3990)))
(defparameter *mono-entropy-versions*
'#.(reverse '(0 3860 3900 3990)))
(defparameter *counts-3980*
(make-array 22
:element-type '(ub 16)
:initial-contents '(0 19578 36160 48417 56323 60899 63265 64435
64971 65232 65351 65416 65447 65466 65476 65482
65485 65488 65490 65491 65492 65493)))
;; TODO: calculate this from *counts*
(defparameter *counts-diff-3980*
(make-array 21
:element-type '(ub 16)
:initial-contents (map 'list #'-
(subseq *counts-3980* 1)
*counts-3980*)))
(defun make-swapped-reader (reader)
"This function generates a closure that read octets in strange
reversed order observed in ffmpeg (as if they are part of
little-endian values)."
(declare (optimize (speed 3)))
(let (octets)
(declare (type list octets))
(lambda ()
(when (null octets)
(setq octets
(reverse (loop repeat 4 collect (read-octet reader)))))
(destructuring-bind (car . cdr)
octets
(setq octets cdr)
car))))
(defun read-32 (reader)
(logior
(ash (funcall reader) 24)
(ash (funcall reader) 16)
(ash (funcall reader) 8)
(ash (funcall reader) 0)))
(defun read-crc-and-flags (reader frame)
;; What's the difference between bytestream_get_[b|l]e32() and
;; get_bits_long()?
(let ((version (frame-version frame)))
(with-accessors ((crc frame-crc)
(flags frame-flags))
frame
(setf crc (read-32 reader))
(when (and (> version 3820)
(not (zerop (ldb (byte 1 31) crc))))
(setf crc (logand crc #.(1- #x80000000))
flags (read-32 reader))))))
(defun entropy-promote-version (version &key channels)
(declare (type (member :mono :stereo) channels))
(find version
(ecase channels
(:mono *mono-entropy-versions*)
(:stereo *stereo-entropy-versions*))
:test #'>=))
(defun read-stereo-frame (reader frame)
(let ((version (frame-version frame))
(flags (frame-flags frame)))
(when (not (zerop (logand flags +stereo-silence+)))
(return-from read-stereo-frame frame))
(entropy-decode
reader frame
(entropy-promote-version
version
:channels :stereo))))
(defun read-mono-frame (reader frame)
(declare (ignore reader))
frame)
(defun read-frame% (reader metadata &key last-frame)
(let* ((version (metadata-version metadata))
;; Copy version and calculate compression level
(frame (make-frame :version version
:bps (metadata-bps metadata)
:fset (1- (floor
(metadata-compression-type metadata)
1000)))))
Read CRC and frame flags
(read-crc-and-flags reader frame)
(when (>= version 3900)
Drop first 8 bits
(funcall reader)
(setf (frame-buffer frame)
(funcall reader)))
Initialize output buffer
(let ((samples (if last-frame
(metadata-final-frame-blocks metadata)
(metadata-blocks-per-frame metadata))))
(setf (frame-samples frame) samples
(frame-output frame)
(loop repeat (metadata-channels metadata)
collect
(make-array samples
:element-type '(signed-byte 32)
:initial-element 0))))
;; Read entropy
(if (and (> (metadata-channels metadata) 1)
(zerop (logand +pseudo-stereo+
(frame-flags frame))))
(read-stereo-frame reader frame)
(read-mono-frame reader frame))))
(defun read-frame (reader metadata n)
"Read the @c(n)-th audio frame from @c(reader). @c(metadata) is the
metadata structure for this audio file."
(multiple-value-bind (start skip)
(frame-start metadata n)
;; Seek to the start of a frame
(reader-position reader start)
;; Make that peculiar swapped-bytes reader needed to read a frame
(let ((swapped-reader (make-swapped-reader reader)))
;; Skip some bytes from the beginning
(loop repeat skip do (funcall swapped-reader))
;; Read a frame
(read-frame%
swapped-reader metadata
:last-frame (= n (1- (metadata-total-frames metadata)))))))
(defun range-dec-normalize (reader range-coder)
(declare (optimize (speed 3))
(type octet-reader reader))
(with-accessors ((buffer range-coder-buffer)
(low range-coder-low)
(range range-coder-range))
range-coder
;; Overflows can happen here, so values must be bringed back to
( ub 32 ) type .
(loop while (<= range +bottom-value+) do
(setf buffer (+ (logand (ash buffer 8)
#xffffffff)
(funcall reader))
low (logior (logand (ash low 8)
#xffffffff)
(logand (ash buffer -1) #xff))
range (logand (ash range 8)
#xffffffff)))))
(defun range-decode-culshift (reader range-coder shift)
(declare (optimize (speed 3))
(type (integer 0 32) shift))
(range-dec-normalize reader range-coder)
(with-accessors ((help range-coder-help)
(low range-coder-low)
(range range-coder-range))
range-coder
(setf help (ash range (- shift)))
(floor low help)))
(defun range-decode-culfreq (reader range-coder tot-f)
(declare (optimize (speed 3))
(type (ub 16) tot-f))
(range-dec-normalize reader range-coder)
(with-accessors ((help range-coder-help)
(low range-coder-low)
(range range-coder-range))
range-coder
(setf help (floor range tot-f))
(floor low help)))
(defun range-decode-update (range-coder sy-f lt-f)
(declare (optimize (speed 3))
(type (ub 16) sy-f lt-f))
(let ((help (range-coder-help range-coder)))
(decf (range-coder-low range-coder)
(* help lt-f))
(setf (range-coder-range range-coder)
(* help sy-f))))
(defun range-get-symbol (reader range-coder counts counts-diff)
(declare (optimize (speed 3))
(type (sa-ub 16) counts counts-diff))
(let ((cf (range-decode-culshift reader range-coder 16)))
(declare (type (ub 16) cf))
(cond
((> cf 65492)
(range-decode-update range-coder 1 cf)
(- cf #.(- 65535 63)))
(t
Position never returns NIL here because cf is less than 65493
(let ((symbol (max 0 (1- (position cf counts :test #'<)))))
(declare (type (integer 0 20) symbol))
(range-decode-update
range-coder
(aref counts-diff symbol)
(aref counts symbol))
symbol)))))
(defun range-decode-bits (reader range-coder n)
(declare (optimize (speed 3))
(type (integer 0 16) n))
(let ((sym (range-decode-culshift reader range-coder n)))
(range-decode-update range-coder 1 sym)
sym))
(defun update-rice (rice-state x)
(with-accessors ((k rice-state-k)
(ksum rice-state-ksum))
rice-state
(declare (optimize (speed 3))
(type (ub 32) x))
(let ((lim (if (zerop k) 0 (ash 1 (+ 4 k)))))
(incf ksum (- (ash (1+ x) -1)
(ash (+ ksum 16) -5)))
(cond
((< ksum lim)
(decf k))
((and (< k 24)
(>= ksum (ash 1 (+ k 5))))
(incf k))))))
(defmethod entropy-decode (reader frame (version (eql 3990)))
(declare (ignore version)
(optimize (speed 3)))
(let ((outputs (frame-output frame))
(samples (frame-samples frame))
(range-coder (make-range-coder
:buffer (frame-buffer frame)
:low (ash (frame-buffer frame)
(- +extra-bits+ 8)))))
(flet ((read-value (rice-state)
(let* ((overflow% (range-get-symbol
reader range-coder
*counts-3980* *counts-diff-3980*))
(overflow (if (= overflow% 63)
(let ((high (range-decode-bits reader range-coder 16))
(low (range-decode-bits reader range-coder 16)))
(logior (ash high 16) low))
overflow%))
(pivot (max 1 (ash (rice-state-ksum rice-state) -5)))
(base (cond
((< pivot #x10000)
(let ((base (range-decode-culfreq reader range-coder pivot)))
(range-decode-update range-coder 1 base)
base))
(t
(let* ((bbits (max 0 (- (integer-length pivot) 16)))
(base-hi
(let ((tmp (range-decode-culfreq
reader range-coder
(1+ (ash pivot (- bbits))))))
(range-decode-update range-coder 1 tmp)
tmp))
(base-low
(let ((tmp (range-decode-culfreq
reader range-coder
(ash 1 bbits))))
(range-decode-update range-coder 1 tmp)
tmp)))
(+ base-low (ash base-hi bbits))))))
(x (+ base (* overflow pivot))))
(declare (type (ub 32) overflow))
(update-rice rice-state x)
(1+ (logxor (ash x -1)
(1- (logand x 1)))))))
(let ((rice-states (loop repeat (length outputs)
collect (make-rice-state))))
(dotimes (i samples)
(mapc
(lambda (output rice-state)
(declare (type (sa-sb 32) output))
(setf (aref output i)
(read-value rice-state)))
outputs rice-states)))))
frame)
| null | https://raw.githubusercontent.com/shamazmazum/easy-audio/64700a5c84aa27176f2dd9936e1051966611a481/ape/frame.lisp | lisp | TODO: calculate this from *counts*
What's the difference between bytestream_get_[b|l]e32() and
get_bits_long()?
Copy version and calculate compression level
Read entropy
Seek to the start of a frame
Make that peculiar swapped-bytes reader needed to read a frame
Skip some bytes from the beginning
Read a frame
Overflows can happen here, so values must be bringed back to | (in-package :easy-audio.ape)
(defconstant +mono-silence+ 1)
(defconstant +stereo-silence+ 3)
(defconstant +pseudo-stereo+ 4)
(deftype octet-reader ()
'(function (&optional) (ub 8)))
(defparameter *stereo-entropy-versions*
'#.(reverse '(0 3860 3900 3930 3990)))
(defparameter *mono-entropy-versions*
'#.(reverse '(0 3860 3900 3990)))
(defparameter *counts-3980*
(make-array 22
:element-type '(ub 16)
:initial-contents '(0 19578 36160 48417 56323 60899 63265 64435
64971 65232 65351 65416 65447 65466 65476 65482
65485 65488 65490 65491 65492 65493)))
(defparameter *counts-diff-3980*
(make-array 21
:element-type '(ub 16)
:initial-contents (map 'list #'-
(subseq *counts-3980* 1)
*counts-3980*)))
(defun make-swapped-reader (reader)
"This function generates a closure that read octets in strange
reversed order observed in ffmpeg (as if they are part of
little-endian values)."
(declare (optimize (speed 3)))
(let (octets)
(declare (type list octets))
(lambda ()
(when (null octets)
(setq octets
(reverse (loop repeat 4 collect (read-octet reader)))))
(destructuring-bind (car . cdr)
octets
(setq octets cdr)
car))))
(defun read-32 (reader)
(logior
(ash (funcall reader) 24)
(ash (funcall reader) 16)
(ash (funcall reader) 8)
(ash (funcall reader) 0)))
(defun read-crc-and-flags (reader frame)
(let ((version (frame-version frame)))
(with-accessors ((crc frame-crc)
(flags frame-flags))
frame
(setf crc (read-32 reader))
(when (and (> version 3820)
(not (zerop (ldb (byte 1 31) crc))))
(setf crc (logand crc #.(1- #x80000000))
flags (read-32 reader))))))
(defun entropy-promote-version (version &key channels)
(declare (type (member :mono :stereo) channels))
(find version
(ecase channels
(:mono *mono-entropy-versions*)
(:stereo *stereo-entropy-versions*))
:test #'>=))
(defun read-stereo-frame (reader frame)
(let ((version (frame-version frame))
(flags (frame-flags frame)))
(when (not (zerop (logand flags +stereo-silence+)))
(return-from read-stereo-frame frame))
(entropy-decode
reader frame
(entropy-promote-version
version
:channels :stereo))))
(defun read-mono-frame (reader frame)
(declare (ignore reader))
frame)
(defun read-frame% (reader metadata &key last-frame)
(let* ((version (metadata-version metadata))
(frame (make-frame :version version
:bps (metadata-bps metadata)
:fset (1- (floor
(metadata-compression-type metadata)
1000)))))
Read CRC and frame flags
(read-crc-and-flags reader frame)
(when (>= version 3900)
Drop first 8 bits
(funcall reader)
(setf (frame-buffer frame)
(funcall reader)))
Initialize output buffer
(let ((samples (if last-frame
(metadata-final-frame-blocks metadata)
(metadata-blocks-per-frame metadata))))
(setf (frame-samples frame) samples
(frame-output frame)
(loop repeat (metadata-channels metadata)
collect
(make-array samples
:element-type '(signed-byte 32)
:initial-element 0))))
(if (and (> (metadata-channels metadata) 1)
(zerop (logand +pseudo-stereo+
(frame-flags frame))))
(read-stereo-frame reader frame)
(read-mono-frame reader frame))))
(defun read-frame (reader metadata n)
"Read the @c(n)-th audio frame from @c(reader). @c(metadata) is the
metadata structure for this audio file."
(multiple-value-bind (start skip)
(frame-start metadata n)
(reader-position reader start)
(let ((swapped-reader (make-swapped-reader reader)))
(loop repeat skip do (funcall swapped-reader))
(read-frame%
swapped-reader metadata
:last-frame (= n (1- (metadata-total-frames metadata)))))))
(defun range-dec-normalize (reader range-coder)
(declare (optimize (speed 3))
(type octet-reader reader))
(with-accessors ((buffer range-coder-buffer)
(low range-coder-low)
(range range-coder-range))
range-coder
( ub 32 ) type .
(loop while (<= range +bottom-value+) do
(setf buffer (+ (logand (ash buffer 8)
#xffffffff)
(funcall reader))
low (logior (logand (ash low 8)
#xffffffff)
(logand (ash buffer -1) #xff))
range (logand (ash range 8)
#xffffffff)))))
(defun range-decode-culshift (reader range-coder shift)
(declare (optimize (speed 3))
(type (integer 0 32) shift))
(range-dec-normalize reader range-coder)
(with-accessors ((help range-coder-help)
(low range-coder-low)
(range range-coder-range))
range-coder
(setf help (ash range (- shift)))
(floor low help)))
(defun range-decode-culfreq (reader range-coder tot-f)
(declare (optimize (speed 3))
(type (ub 16) tot-f))
(range-dec-normalize reader range-coder)
(with-accessors ((help range-coder-help)
(low range-coder-low)
(range range-coder-range))
range-coder
(setf help (floor range tot-f))
(floor low help)))
(defun range-decode-update (range-coder sy-f lt-f)
(declare (optimize (speed 3))
(type (ub 16) sy-f lt-f))
(let ((help (range-coder-help range-coder)))
(decf (range-coder-low range-coder)
(* help lt-f))
(setf (range-coder-range range-coder)
(* help sy-f))))
(defun range-get-symbol (reader range-coder counts counts-diff)
(declare (optimize (speed 3))
(type (sa-ub 16) counts counts-diff))
(let ((cf (range-decode-culshift reader range-coder 16)))
(declare (type (ub 16) cf))
(cond
((> cf 65492)
(range-decode-update range-coder 1 cf)
(- cf #.(- 65535 63)))
(t
Position never returns NIL here because cf is less than 65493
(let ((symbol (max 0 (1- (position cf counts :test #'<)))))
(declare (type (integer 0 20) symbol))
(range-decode-update
range-coder
(aref counts-diff symbol)
(aref counts symbol))
symbol)))))
(defun range-decode-bits (reader range-coder n)
(declare (optimize (speed 3))
(type (integer 0 16) n))
(let ((sym (range-decode-culshift reader range-coder n)))
(range-decode-update range-coder 1 sym)
sym))
(defun update-rice (rice-state x)
(with-accessors ((k rice-state-k)
(ksum rice-state-ksum))
rice-state
(declare (optimize (speed 3))
(type (ub 32) x))
(let ((lim (if (zerop k) 0 (ash 1 (+ 4 k)))))
(incf ksum (- (ash (1+ x) -1)
(ash (+ ksum 16) -5)))
(cond
((< ksum lim)
(decf k))
((and (< k 24)
(>= ksum (ash 1 (+ k 5))))
(incf k))))))
(defmethod entropy-decode (reader frame (version (eql 3990)))
(declare (ignore version)
(optimize (speed 3)))
(let ((outputs (frame-output frame))
(samples (frame-samples frame))
(range-coder (make-range-coder
:buffer (frame-buffer frame)
:low (ash (frame-buffer frame)
(- +extra-bits+ 8)))))
(flet ((read-value (rice-state)
(let* ((overflow% (range-get-symbol
reader range-coder
*counts-3980* *counts-diff-3980*))
(overflow (if (= overflow% 63)
(let ((high (range-decode-bits reader range-coder 16))
(low (range-decode-bits reader range-coder 16)))
(logior (ash high 16) low))
overflow%))
(pivot (max 1 (ash (rice-state-ksum rice-state) -5)))
(base (cond
((< pivot #x10000)
(let ((base (range-decode-culfreq reader range-coder pivot)))
(range-decode-update range-coder 1 base)
base))
(t
(let* ((bbits (max 0 (- (integer-length pivot) 16)))
(base-hi
(let ((tmp (range-decode-culfreq
reader range-coder
(1+ (ash pivot (- bbits))))))
(range-decode-update range-coder 1 tmp)
tmp))
(base-low
(let ((tmp (range-decode-culfreq
reader range-coder
(ash 1 bbits))))
(range-decode-update range-coder 1 tmp)
tmp)))
(+ base-low (ash base-hi bbits))))))
(x (+ base (* overflow pivot))))
(declare (type (ub 32) overflow))
(update-rice rice-state x)
(1+ (logxor (ash x -1)
(1- (logand x 1)))))))
(let ((rice-states (loop repeat (length outputs)
collect (make-rice-state))))
(dotimes (i samples)
(mapc
(lambda (output rice-state)
(declare (type (sa-sb 32) output))
(setf (aref output i)
(read-value rice-state)))
outputs rice-states)))))
frame)
|
3efcae6a0ce869970003a2f30f7d5fd8676092814ad37019d6c44813794dcfbd | racket/racket7 | jitify.rkt | #lang racket/base
(require "match.rkt"
"wrap.rkt")
;; Convert `lambda`s to make them fully closed, which is compatible
;; with JIT compilation of the `lambda` or separate ahead-of-time
;; compilation (as opposed to compiling a whole linklet).
;; If `convert-size-threashold` is #f, then every `lambda` is
;; converted. If it's a number, then only `lambda`s smaller than the
;; threshold are converted, and and no `lambda` within a converted
;; `lambda` is converted. So, supplying a numerical threshold is
;; useful for drawing a boundary between compiled and non-compiled
;; code, as opposed to a true JIT setup.
;; An environment maps a variables that needs to be passed into the
;; closed code:
;;
;; * id -> '#:direct --- ready by the time it's needed and immutable
;;
;; * id -> expression --- rewrite access to expression
;;
;; * id -> `(self ,m) --- a reference to the enclosing function; can
;; use directly in rator position, otherwise
;; use m
(provide jitify-schemified-linklet)
(define (jitify-schemified-linklet v
need-extract?
convert-size-threshold ; #f or a number; see above
extractable-annotation
reannotate)
a closed ` lambda ` form as wrapped with
;; `extractable-annotaton` and generates an application of
;; `extract[-closed]-id` to the wrapped form.
(define (make-jit-on-call free-vars argss v name env)
(define ids (for/list ([id (in-hash-keys free-vars)])
id))
(define (extract-id m id)
(match m
[`(variable-ref ,var) var]
[`(unbox ,var) var]
[`(unbox/check-undefined ,var ,_) var]
[`(self ,m ,orig-id) orig-id]
[`(self ,m) (extract-id m id)]
[`,_ id]))
(define captures (hash-keys
;; `extract-id` for different `id`s can produce the
;; same `id`, so hash and then convert to a list
(for/hash ([id (in-list ids)])
(values (extract-id (hash-ref env id) id) #t))))
(define jitted-proc
(or (match (and name
(hash-ref free-vars (unwrap name) #f)
(hash-ref env (unwrap name) #f))
[`(self ,m ,orig-name)
(cond
[(eq? orig-name name)
(define self-id (extract-id m name))
`(let ([,self-id ,orig-name])
(letrec ([,name ,v])
,name))]
[else #f])]
[`,_ #f])
(match (and name
(hash-ref env (unwrap name) #f))
[`(self . ,_)
;; Might have a direct self-call, so use `letrec`:
`(letrec ([,name ,v])
,name)]
[`,_ #f])
(cond
[name
;; No direct self-reference, but encourage the compiler
;; to name the procedure:
`(let ([,name ,v])
,name)]
[else v])))
(define arity-mask (argss->arity-mask argss))
(cond
[(null? captures)
(let ([e (extractable-annotation jitted-proc arity-mask name)])
(if need-extract?
`(jitified-extract-closed ',e)
`',e))]
[else
(let ([e (extractable-annotation `(lambda ,captures
,jitted-proc)
arity-mask
name)])
(if need-extract?
`((jitified-extract ',e) . ,captures)
`(',e . ,captures)))]))
;; ----------------------------------------
(define (top)
Match outer shape of a linklet produced by `
;; and lift in the linklet body:
(let loop ([v v] [env #hasheq()])
(match v
[`(lambda ,args . ,body)
(define new-body (jitify-schemified-body body (plain-add-args env args)))
(if (for/and ([old (in-list body)]
[new (in-list new-body)])
(eq? old new))
v
(reannotate v `(lambda ,args . ,new-body)))]
[`(let* ,bindings ,body)
(define new-body (loop body (add-bindings env bindings)))
(if (eq? body new-body)
v
(reannotate v `(let* ,bindings ,new-body)))])))
(define (jitify-schemified-body body env)
(define top-env
(for/fold ([env env]) ([v (in-list body)])
(let loop ([v v] [env env])
(match v
[`(variable-set! ,var-id ,id . ,_)
(hash-set env (unwrap id) `(variable-ref ,(unwrap var-id)))]
[`(define ,_ (begin (variable-set! ,var-id ,id . ,_) (void)))
(hash-set env (unwrap id) `(variable-ref ,(unwrap var-id)))]
[`(define ,id ,rhs) (plain-add-args env id)]
[`(define-values ,ids ,rhs) (plain-add-args env ids)]
[`(begin . ,vs)
(for/fold ([env env]) ([v (in-wrap-list vs)])
(loop v env))]
[`,_ env]))))
(let loop ([body body])
(for/list ([v (in-list body)])
(match v
[`(variable-set! ,var-id ,id . ,_) v]
[`(define ,_ (begin (variable-set! ,var-id ,id . ,_) (void))) v]
[`(define ,id ,rhs)
If there 's a direct reference to ` i d ` in ` rhs ` , then
;; `id` must not be mutable
(define self-env (add-self top-env #hasheq() id))
(reannotate v `(define ,id ,(jitify-top-expr rhs self-env id)))]
[`(define-values ,ids ,rhs)
(reannotate v `(define-values ,ids ,(jitify-top-expr rhs top-env #f)))]
[`(begin . ,vs)
(reannotate v `(begin . ,(loop vs)))]
[`,_ (jitify-top-expr v top-env #f)]))))
(define (jitify-top-expr v env name)
;; The `mutables` table doesn't track shadowing on the assumption
;; that local variable names are sufficiently distinguished to prevent
;; one mutable variable from polluting another in a different scope
(define mutables (find-mutable #hasheq() v #hasheq()))
(define convert-mode (init-convert-mode v))
(define-values (new-v free) (jitify-expr v env mutables #hasheq() convert-mode name #f))
new-v)
;; The `name` argument is a name to be given to the expresison `v`
;; if it's a function. It also corresponds to a name that can be
;; called directly, as long as it's mapped in `env` to a '(self ...)
;; value.
;; The `in-name` argument is the current self `name` that is in effect
;; for the current expression. It might be mapped to '(self ...)
;; and need to be unmapped for a more nested function.
(define (jitify-expr v env mutables free convert-mode name in-name)
(match v
[`(lambda ,args . ,body)
(define convert? (convert-mode-convert-lambda? convert-mode v))
(define body-convert-mode (convert-mode-lambda-body-mode convert-mode convert?))
(define self-env (if convert?
(activate-self (deactivate-self env in-name) name)
env))
(define body-env (add-args self-env args mutables body-convert-mode))
(define body-in-name (if convert? (or name '#:anonymous) in-name))
(define-values (new-body lam-body-free)
(jitify-body body body-env mutables #hasheq() body-convert-mode #f body-in-name))
(define lam-free (remove-args lam-body-free args))
(define new-v (reannotate v `(lambda ,args . ,(mutable-box-bindings args mutables body-convert-mode
new-body))))
(values (if (not convert?)
new-v
(make-jit-on-call lam-free (list args) new-v name self-env))
(union-free free lam-free))]
[`(case-lambda [,argss . ,bodys] ...)
(define convert? (convert-mode-convert-lambda? convert-mode v))
(define body-convert-mode (convert-mode-lambda-body-mode convert-mode convert?))
(define self-env (if convert?
(activate-self (deactivate-self env in-name) name)
env))
(define body-in-name (if convert? (or name '#:anonymous) in-name))
(define-values (rev-new-bodys lam-free)
(for/fold ([rev-new-bodys '()] [lam-free #hasheq()]) ([args (in-list argss)]
[body (in-list bodys)])
(define body-env (add-args self-env args mutables body-convert-mode))
(define-values (new-body lam-body-free)
(jitify-body body body-env mutables #hasheq() body-convert-mode #f body-in-name))
(values (cons new-body rev-new-bodys)
(union-free (remove-args lam-body-free args)
lam-free))))
(define new-v (reannotate v
`(case-lambda
,@(for/list ([args (in-list argss)]
[body (in-list (reverse rev-new-bodys))])
`[,args . ,(mutable-box-bindings args mutables body-convert-mode
body)]))))
(values (if (not convert?)
new-v
(make-jit-on-call lam-free argss new-v name self-env))
(union-free free lam-free))]
[`(let . ,_) (jitify-let v env mutables free convert-mode name in-name)]
[`(letrec . ,_) (jitify-let v env mutables free convert-mode name in-name)]
[`(letrec* . ,_) (jitify-let v env mutables free convert-mode name in-name)]
[`(begin . ,vs)
(define-values (new-body new-free) (jitify-body vs env mutables free convert-mode name in-name))
(values (reannotate v `(begin . ,new-body))
new-free)]
[`(begin0 ,v0 . ,vs)
(define-values (new-v0 v0-free)
(jitify-expr v0 env mutables free (convert-mode-non-tail convert-mode) name in-name))
(define-values (new-body new-free)
(jitify-body vs env mutables v0-free (convert-mode-non-tail convert-mode) #f in-name))
(values (reannotate v `(begin0 ,new-v0 . ,new-body))
new-free)]
[`(pariah ,e)
(define-values (new-e new-free) (jitify-expr e env mutables free convert-mode name in-name))
(values (reannotate v `(pariah ,new-e))
new-free)]
[`(if ,tst ,thn ,els)
(define sub-convert-mode (convert-mode-non-tail convert-mode))
(define-values (new-tst new-free/tst) (jitify-expr tst env mutables free sub-convert-mode #f in-name))
(define-values (new-thn new-free/thn) (jitify-expr thn env mutables new-free/tst convert-mode name in-name))
(define-values (new-els new-free/els) (jitify-expr els env mutables new-free/thn convert-mode name in-name))
(values (reannotate v `(if ,new-tst ,new-thn ,new-els))
new-free/els)]
[`(with-continuation-mark ,key ,val ,body)
(define sub-convert-mode (convert-mode-non-tail convert-mode))
(define-values (new-key new-free/key) (jitify-expr key env mutables free sub-convert-mode #f in-name))
(define-values (new-val new-free/val) (jitify-expr val env mutables new-free/key sub-convert-mode #f in-name))
(define-values (new-body new-free/body) (jitify-expr body env mutables new-free/val convert-mode name in-name))
(values (reannotate v `(with-continuation-mark ,new-key ,new-val ,new-body))
new-free/body)]
[`(quote ,_) (values v free)]
[`(set! ,var ,rhs)
(define-values (new-rhs new-free) (jitify-expr rhs env mutables free (convert-mode-non-tail convert-mode) var in-name))
(define id (unwrap var))
(define dest (hash-ref env id #f))
(cond
[(and (not in-name)
(match dest
[`(variable-ref ,_) #t]
[`,_ #f]))
;; Not under lambda: don't rewrite references to definitions
(values `(set! ,var ,new-rhs)
new-free)]
[else
(define newer-free (if dest
(hash-set new-free id dest)
new-free))
(define new-v
(match (hash-ref env id '#:direct)
[`#:direct (reannotate v `(set! ,var ,new-rhs))]
[`(self ,m . ,_) (error 'set! "[internal error] self-referenceable ~s" id)]
[`(variable-ref ,var-id) (reannotate v `(variable-set! ,var-id ,new-rhs '#f))]
[`(unbox ,box-id) (reannotate v `(set-box! ,box-id ,new-rhs))]
[`(unbox/check-undefined ,box-id ,_) (reannotate v `(set-box!/check-undefined ,box-id ,new-rhs ',var))]))
(values new-v newer-free)])]
[`(call-with-values ,proc1 ,proc2)
(define proc-convert-mode (convert-mode-called convert-mode))
(define-values (new-proc1 new-free1) (jitify-expr proc1 env mutables free proc-convert-mode #f in-name))
(define-values (new-proc2 new-free2) (jitify-expr proc2 env mutables new-free1 proc-convert-mode #f in-name))
(define call-with-values-id (if (and (lambda? new-proc1) (lambda? new-proc2))
'call-with-values
'#%call-with-values))
(values (reannotate v `(,call-with-values-id ,new-proc1 ,new-proc2))
new-free2)]
[`(#%app ,_ ...)
(define-values (new-vs new-free)
(jitify-body (wrap-cdr v) env mutables free (convert-mode-non-tail convert-mode) #f in-name))
(values (reannotate v `(#%app . ,new-vs))
new-free)]
[`(,rator ,_ ...)
(define u (unwrap rator))
(match (and (symbol? u) (hash-ref env u #f))
[`(self ,_ ,orig-id)
;; Keep self call as direct
(define-values (new-vs new-free)
(jitify-body (wrap-cdr v) env mutables free (convert-mode-non-tail convert-mode) #f in-name))
(values (reannotate v `(,rator . ,new-vs))
new-free)]
[`,x
(define-values (new-vs new-free)
(jitify-body v env mutables free (convert-mode-non-tail convert-mode) #f in-name))
(values (reannotate v new-vs)
new-free)])]
[`,var
(define id (unwrap var))
(define dest (hash-ref env id #f))
(cond
[(and (not in-name)
(match dest
[`(variable-ref ,_) #t]
[`,_ #f]))
;; Not under lambda: don't rewrite references to definitions
(values var free)]
[else
(define new-var
(match dest
[`#f var]
[`#:direct var]
[`(self ,u . ,_) (reannotate v u)]
[`,u (reannotate v u)]))
(define new-free
(if dest
(hash-set free id dest)
free))
(values new-var
new-free)])]))
(define (lambda? v)
(match v
[`(lambda . ,_) #t]
[`(case-lambda . ,_) #t]
[`,_ #f]))
(define (jitify-body vs env mutables free convert-mode name in-name)
(let loop ([vs vs] [free free])
(cond
[(wrap-null? vs) (values null free)]
[(wrap-null? (wrap-cdr vs))
(define-values (new-v new-free)
(jitify-expr (wrap-car vs) env mutables free convert-mode name in-name))
(values (list new-v) new-free)]
[else
(define-values (new-v new-free)
(jitify-expr (wrap-car vs) env mutables free (convert-mode-non-tail convert-mode) #f in-name))
(define-values (new-rest newer-free)
(loop (wrap-cdr vs) new-free))
(values (cons new-v new-rest)
newer-free)])))
(define (jitify-let v env mutables free convert-mode name in-name)
(match v
[`(,let-form ([,ids ,rhss] ...) . ,body)
(define rec?
(and (case (unwrap let-form)
[(letrec letrec*) #t]
[else #f])
;; Use simpler `let` code if we're not responsible for boxing:
(convert-mode-box-mutables? convert-mode)))
(define rhs-convert-mode (convert-mode-non-tail convert-mode))
(define rhs-env (if rec?
(add-args/unbox env ids mutables
(lambda (var) #t)
(not (for/and ([rhs (in-list rhss)])
(lambda? rhs)))
convert-mode)
env))
(define-values (rev-new-rhss rhs-free)
(for/fold ([rev-new-rhss '()] [free #hasheq()]) ([id (in-list ids)]
[rhs (in-list rhss)])
(define self-env
(if rec?
(add-self rhs-env mutables id)
rhs-env))
(define-values (new-rhs rhs-free)
(jitify-expr rhs self-env mutables free rhs-convert-mode id in-name))
(values (cons new-rhs rev-new-rhss) rhs-free)))
(define local-env
(add-args/unbox env ids mutables
(lambda (var) (and rec? (hash-ref rhs-free var #f)))
#f
convert-mode))
(define-values (new-body new-free)
(jitify-body body local-env mutables (union-free free rhs-free) convert-mode name in-name))
(define new-v
(cond
[(not rec?)
;; Wrap boxes around rhs results as needed:
`(,let-form ,(for/list ([id (in-list ids)]
[new-rhs (in-list (reverse rev-new-rhss))])
`[,id ,(if (and (convert-mode-box-mutables? convert-mode)
(hash-ref mutables (unwrap id) #f))
`(box ,new-rhs)
new-rhs)])
. ,new-body)]
[else
Allocate boxes first , then fill in
`(let ,(for*/list ([id (in-list ids)]
#:when (hash-ref rhs-free (unwrap id) #f))
`[,id (box unsafe-undefined)])
;; Using nested `let`s to force left-to-right
,(for/fold ([body (body->expr new-body)]) ([id (in-list (reverse ids))]
[new-rhs (in-list rev-new-rhss)])
`(let (,(cond
[(hash-ref rhs-free (unwrap id) #f)
`[,(gensym 'ignored) (set-box! ,id ,new-rhs)]]
[(hash-ref mutables (unwrap id) #f)
`[,id (box ,new-rhs)]]
[else `[,id ,new-rhs]]))
,body)))]))
(values (reannotate v new-v)
(remove-args new-free ids))]))
(define (mutable-box-bindings args mutables convert-mode body)
(cond
[(convert-mode-box-mutables? convert-mode)
(define bindings
(let loop ([args args])
(cond
[(wrap-null? args) null]
[(wrap-pair? args)
(define id (wrap-car args))
(define var (unwrap id))
(define rest (loop (wrap-cdr args)))
(if (hash-ref mutables var #f)
(cons `[,id (box ,id)] rest)
rest)]
[else (loop (list args))])))
(if (null? bindings)
body
`((let ,bindings . ,body)))]
[else body]))
;; ----------------------------------------
;; When mutables and convert mode are not relevant:
(define (plain-add-args env args)
(define (add-one id)
(hash-set env (unwrap id) '#:direct))
(match args
[`(,id . ,args)
(plain-add-args (add-one id) args)]
[`() env]
[`,id (add-one id)]))
;; Add a binding to an environment, record whether it needs
;; to be unboxed on reference:
(define (add-args env args mutables convert-mode)
(define (add-one id)
(define u (unwrap id))
(define val (if (and (convert-mode-box-mutables? convert-mode)
(hash-ref mutables u #f))
`(unbox ,id)
'#:direct))
(hash-set env u val))
(match args
[`(,id . ,args)
(add-args (add-one id) args mutables convert-mode)]
[`() env]
[`,id (add-one id)]))
;; Further generalization of `add-args` to add undefined-checking
;; variant of unbox:
(define (add-args/unbox env args mutables var-rec? maybe-undefined? convert-mode)
(define (add-one id)
(define var (unwrap id))
(cond
[maybe-undefined? (hash-set env var `(unbox/check-undefined ,id ',id))]
[(not (or (var-rec? var) (and (convert-mode-box-mutables? convert-mode)
(hash-ref mutables var #f))))
(hash-set env var '#:direct)]
[else (hash-set env var `(unbox ,id))]))
(match args
[`(,id . ,args)
(add-args/unbox (add-one id) args mutables var-rec? maybe-undefined? convert-mode)]
[`() env]
[`,id (add-one id)]))
(define (remove-args env args)
(match args
[`(,id . ,args)
(remove-args (hash-remove env (unwrap id)) args)]
[`() env]
[`,id (hash-remove env (unwrap id))]))
(define (add-bindings env bindings)
(match bindings
[`([,ids ,_] ...)
(for/fold ([env env]) ([id (in-list ids)])
(plain-add-args env id))]))
(define (add-self env mutables name)
(define u (unwrap name))
(cond
[(hash-ref mutables u #f)
env]
[else
(hash-set env u `(self ,(hash-ref env u '#:direct)))]))
;; Adjust an environment to indicate that `name` in an application
;; position is a self-call, which helps preserves the visiblilty of
;; loops to a later compiler
(define (activate-self env name)
(cond
[name
(define (genself) (gensym 'self))
(define u (unwrap name))
(define new-m
(match (hash-ref env u #f)
[`(self #:direct)
`(self ,(genself) ,name)]
[`(self (variable-ref ,orig-id))
`(self (variable-ref ,orig-id) ,orig-id)]
[`(self (unbox ,orig-id))
`(self (unbox ,(genself)) ,orig-id)]
[`(self (unbox/check-undefined ,orig-id ,sym))
`(self (unbox/check-undefined ,(genself) ,sym) ,orig-id)]
[`,_ #f]))
(if new-m
(hash-set env u new-m)
env)]
[else env]))
;; Adjust an environment to indicate that applying `name` is no
;; longer a self call
(define (deactivate-self env name)
(cond
[name
(define u (unwrap name))
(match (hash-ref env u #f)
[`(self ,m ,_) (hash-set env u m)]
[`,_ env])]
[else env]))
;; ----------------------------------------
(define (argss->arity-mask argss)
(for/fold ([mask 0]) ([args (in-list argss)])
(bitwise-ior mask
(let loop ([args args] [count 0])
(cond
[(wrap-null? args) (arithmetic-shift 1 count)]
[(wrap-pair? args) (loop (wrap-cdr args) (add1 count))]
[else (bitwise-xor -1 (sub1 (arithmetic-shift 1 count)))])))))
(define (de-dot args)
(cond
[(wrap-pair? args) (cons (wrap-car args)
(de-dot (wrap-cdr args)))]
[else (list args)]))
(define (union-free a b)
(cond
[((hash-count b) . < . (hash-count a)) (union-free b a)]
[else
(for/fold ([b b]) ([(k v) (in-hash a)])
(hash-set b k v))]))
(define (body->expr body)
(cond
[(and (wrap-pair? body) (wrap-null? (wrap-cdr body)))
(wrap-car body)]
[else `(begin . ,body)]))
;; ----------------------------------------
(define (find-mutable env v accum)
(match v
[`(lambda ,args . ,body)
(body-find-mutable (plain-add-args env args) body accum)]
[`(case-lambda [,argss . ,bodys] ...)
(for/fold ([accum accum]) ([args (in-list argss)]
[body (in-list bodys)])
(body-find-mutable (plain-add-args env args) body accum))]
[`(let . ,_) (find-mutable-in-let env v accum)]
[`(letrec . ,_) (find-mutable-in-let env v accum)]
[`(letrec* . ,_) (find-mutable-in-let env v accum)]
[`(begin . ,vs) (body-find-mutable env vs accum)]
[`(begin0 . ,vs) (body-find-mutable env vs accum)]
[`(if ,tst ,thn ,els)
(find-mutable env tst
(find-mutable env thn
(find-mutable env els accum)))]
[`(with-continuation-mark ,key ,val ,body)
(find-mutable env key
(find-mutable env val
(find-mutable env body accum)))]
[`(quote ,_) accum]
[`(set! ,var ,rhs)
(define id (unwrap var))
(find-mutable env rhs (if (hash-ref env id #f)
(hash-set accum id #t)
accum))]
[`(,_ ...) (body-find-mutable env v accum)]
[`,_ accum]))
(define (body-find-mutable env body accum)
(for/fold ([accum accum]) ([v (in-wrap-list body)])
(find-mutable env v accum)))
(define (find-mutable-in-let env v accum)
(match v
[`(,let-form ([,ids ,rhss] ...) . ,body)
(define local-env
(for/fold ([env env]) ([id (in-list ids)])
(plain-add-args env id)))
(define rhs-env
(case (unwrap let-form)
[(letrec letrec* letrec*-values) local-env]
[else env]))
(body-find-mutable local-env
body
(for/fold ([accum accum]) ([id (in-list ids)]
[rhs (in-list rhss)])
(find-mutable rhs-env rhs accum)))]))
;; ----------------------------------------
;; Convert mode
;;
;; If there's no size threshold for conversion, then convert mode is
;; simply 'called or 'not-called.
;;
;; If there's a size threshold, then a convert mode is a
;; `convert-mode` instance.
(struct convert-mode (sizes called? no-more-conversions?))
(define (init-convert-mode v)
(cond
[convert-size-threshold
(convert-mode (record-sizes v) #f #f)]
[else 'not-called]))
(define (convert-mode-convert-lambda? cm v)
(cond
[(eq? cm 'called) #f]
[(eq? cm 'not-called) #t]
[(convert-mode-called? cm) #f]
[(convert-mode-no-more-conversions? cm) #f]
[((hash-ref (convert-mode-sizes cm) v) . >= . convert-size-threshold) #f]
[else #t]))
(define (convert-mode-lambda-body-mode cm convert?)
(cond
[(convert-mode? cm)
(if convert?
(convert-mode 'not-needed #f #t)
(convert-mode-non-tail cm))]
[else 'not-called]))
(define (convert-mode-non-tail cm)
(cond
[(convert-mode? cm)
(struct-copy convert-mode cm
[called? #f])]
[else 'not-called]))
(define (convert-mode-called cm)
(cond
[(convert-mode? cm)
(struct-copy convert-mode cm
[called? #t])]
[else 'called]))
(define (convert-mode-box-mutables? cm)
(cond
[(convert-mode? cm)
(not (convert-mode-no-more-conversions? cm))]
[else #t]))
;; ----------------------------------------
(define (record-sizes v)
(let ([sizes (make-hasheq)])
(record-sizes! v sizes)
sizes))
(define (record-size! v sizes size)
(hash-set! sizes v size)
size)
(define (record-sizes! v sizes)
(match v
[`(lambda ,args . ,body)
(record-size! v sizes (body-record-sizes! body sizes))]
[`(case-lambda [,_ . ,bodys] ...)
(define new-size
(for/sum ([body (in-list bodys)])
(body-record-sizes! body sizes)))
(record-size! v sizes new-size)]
[`(let . ,_) (record-sizes-in-let! v sizes)]
[`(letrec . ,_) (record-sizes-in-let! v sizes)]
[`(letrec* . ,_) (record-sizes-in-let! v sizes)]
[`(begin . ,vs) (add1 (body-record-sizes! vs sizes))]
[`(begin0 . ,vs) (add1 (body-record-sizes! vs sizes))]
[`(if ,tst ,thn ,els)
(+ 1
(record-sizes! tst sizes)
(record-sizes! thn sizes)
(record-sizes! els sizes))]
[`(with-continuation-mark ,key ,val ,body)
(+ 1
(record-sizes! key sizes)
(record-sizes! val sizes)
(record-sizes! body sizes))]
[`(quote ,_) 1]
[`(set! ,_ ,rhs)
(add1 (record-sizes! rhs sizes))]
[`(,_ ...) (body-record-sizes! v sizes)]
[`,_ 1]))
(define (body-record-sizes! body sizes)
(for/sum ([v (in-wrap-list body)])
(record-sizes! v sizes)))
(define (record-sizes-in-let! v sizes)
(match v
[`(,let-form ([,_ ,rhss] ...) . ,body)
(+ 1
(for/sum ([rhs (in-list rhss)])
(record-sizes! rhs sizes))
(body-record-sizes! body sizes))]))
;; ----------------------------------------
(top))
;; ============================================================
(module+ main
(require racket/pretty)
(pretty-print
(jitify-schemified-linklet (values ; datum->correlated
'(lambda (iv xv do-immediate)
(define top (letrec ([odd (lambda (x) (even x))]
[even (lambda (x) (odd x))]
[selfx (lambda (x) (selfx x))]
[selfy (lambda (x) (vector (selfy x) selfy))])
(odd 5)))
(define top-selfx (lambda (x) (top-selfx x)))
(variable-set! top-selfx-var top-selfx 'const)
(define top-selfy (lambda (x) (vector (top-selfy x) top-selfy)))
(variable-set! top-selfy-var top-selfy 'const)
(call-with-values (lambda (x) (x (lambda (w) (w))))
(lambda (z w) 10))
(call-with-values (lambda (x) (x (lambda (w) (w))))
(letrec ([selfz (lambda (z) (selfz (selfz z)))])
(lambda (z w) (selfz w))))
(call-with-values (lambda (x) (x (lambda (w) (w))))
void)
(define y (letrec ([f (lambda (x) (f (cons x x)))]
[g (lambda (q) (set! f g) (f q))])
(list (lambda (f) (list x)))))
(define x (lambda (j) j))
(define x2 (lambda () (letrec ([other (lambda () (other iv))])
other)))
(define whatever (begin (variable-set! xv x 'const) (void)))
(define end (letrec ([w (lambda (x) (let ([proc (lambda (x) x)])
(proc q)))]
[q q])
(lambda (j) (set! q j))))
(define topz (letrec ([helper (lambda (x)
(helper (topz x)))])
(lambda (y) (helper y))))
(variable-set! topz-var topz 'const)
(do-immediate topz)
(define sets-arg (lambda (x)
(values (lambda () (set! x (add1 x)))
(lambda () x))))
(letrec ([outer
(lambda (x)
(letrec ([inner
(lambda (y)
(outer y))])
(inner x)))])
(outer 5))
(lambda () (let ([x 5]) (set! x 6) x))))
#t
#f ; size threshold
vector
(lambda (v u) u)
values)))
| null | https://raw.githubusercontent.com/racket/racket7/5dbb62c6bbec198b4a790f1dc08fef0c45c2e32b/racket/src/schemify/jitify.rkt | racket | Convert `lambda`s to make them fully closed, which is compatible
with JIT compilation of the `lambda` or separate ahead-of-time
compilation (as opposed to compiling a whole linklet).
If `convert-size-threashold` is #f, then every `lambda` is
converted. If it's a number, then only `lambda`s smaller than the
threshold are converted, and and no `lambda` within a converted
`lambda` is converted. So, supplying a numerical threshold is
useful for drawing a boundary between compiled and non-compiled
code, as opposed to a true JIT setup.
An environment maps a variables that needs to be passed into the
closed code:
* id -> '#:direct --- ready by the time it's needed and immutable
* id -> expression --- rewrite access to expression
* id -> `(self ,m) --- a reference to the enclosing function; can
use directly in rator position, otherwise
use m
#f or a number; see above
`extractable-annotaton` and generates an application of
`extract[-closed]-id` to the wrapped form.
`extract-id` for different `id`s can produce the
same `id`, so hash and then convert to a list
Might have a direct self-call, so use `letrec`:
No direct self-reference, but encourage the compiler
to name the procedure:
----------------------------------------
and lift in the linklet body:
`id` must not be mutable
The `mutables` table doesn't track shadowing on the assumption
that local variable names are sufficiently distinguished to prevent
one mutable variable from polluting another in a different scope
The `name` argument is a name to be given to the expresison `v`
if it's a function. It also corresponds to a name that can be
called directly, as long as it's mapped in `env` to a '(self ...)
value.
The `in-name` argument is the current self `name` that is in effect
for the current expression. It might be mapped to '(self ...)
and need to be unmapped for a more nested function.
Not under lambda: don't rewrite references to definitions
Keep self call as direct
Not under lambda: don't rewrite references to definitions
Use simpler `let` code if we're not responsible for boxing:
Wrap boxes around rhs results as needed:
Using nested `let`s to force left-to-right
----------------------------------------
When mutables and convert mode are not relevant:
Add a binding to an environment, record whether it needs
to be unboxed on reference:
Further generalization of `add-args` to add undefined-checking
variant of unbox:
Adjust an environment to indicate that `name` in an application
position is a self-call, which helps preserves the visiblilty of
loops to a later compiler
Adjust an environment to indicate that applying `name` is no
longer a self call
----------------------------------------
----------------------------------------
----------------------------------------
Convert mode
If there's no size threshold for conversion, then convert mode is
simply 'called or 'not-called.
If there's a size threshold, then a convert mode is a
`convert-mode` instance.
----------------------------------------
----------------------------------------
============================================================
datum->correlated
size threshold | #lang racket/base
(require "match.rkt"
"wrap.rkt")
(provide jitify-schemified-linklet)
(define (jitify-schemified-linklet v
need-extract?
extractable-annotation
reannotate)
a closed ` lambda ` form as wrapped with
(define (make-jit-on-call free-vars argss v name env)
(define ids (for/list ([id (in-hash-keys free-vars)])
id))
(define (extract-id m id)
(match m
[`(variable-ref ,var) var]
[`(unbox ,var) var]
[`(unbox/check-undefined ,var ,_) var]
[`(self ,m ,orig-id) orig-id]
[`(self ,m) (extract-id m id)]
[`,_ id]))
(define captures (hash-keys
(for/hash ([id (in-list ids)])
(values (extract-id (hash-ref env id) id) #t))))
(define jitted-proc
(or (match (and name
(hash-ref free-vars (unwrap name) #f)
(hash-ref env (unwrap name) #f))
[`(self ,m ,orig-name)
(cond
[(eq? orig-name name)
(define self-id (extract-id m name))
`(let ([,self-id ,orig-name])
(letrec ([,name ,v])
,name))]
[else #f])]
[`,_ #f])
(match (and name
(hash-ref env (unwrap name) #f))
[`(self . ,_)
`(letrec ([,name ,v])
,name)]
[`,_ #f])
(cond
[name
`(let ([,name ,v])
,name)]
[else v])))
(define arity-mask (argss->arity-mask argss))
(cond
[(null? captures)
(let ([e (extractable-annotation jitted-proc arity-mask name)])
(if need-extract?
`(jitified-extract-closed ',e)
`',e))]
[else
(let ([e (extractable-annotation `(lambda ,captures
,jitted-proc)
arity-mask
name)])
(if need-extract?
`((jitified-extract ',e) . ,captures)
`(',e . ,captures)))]))
(define (top)
Match outer shape of a linklet produced by `
(let loop ([v v] [env #hasheq()])
(match v
[`(lambda ,args . ,body)
(define new-body (jitify-schemified-body body (plain-add-args env args)))
(if (for/and ([old (in-list body)]
[new (in-list new-body)])
(eq? old new))
v
(reannotate v `(lambda ,args . ,new-body)))]
[`(let* ,bindings ,body)
(define new-body (loop body (add-bindings env bindings)))
(if (eq? body new-body)
v
(reannotate v `(let* ,bindings ,new-body)))])))
(define (jitify-schemified-body body env)
(define top-env
(for/fold ([env env]) ([v (in-list body)])
(let loop ([v v] [env env])
(match v
[`(variable-set! ,var-id ,id . ,_)
(hash-set env (unwrap id) `(variable-ref ,(unwrap var-id)))]
[`(define ,_ (begin (variable-set! ,var-id ,id . ,_) (void)))
(hash-set env (unwrap id) `(variable-ref ,(unwrap var-id)))]
[`(define ,id ,rhs) (plain-add-args env id)]
[`(define-values ,ids ,rhs) (plain-add-args env ids)]
[`(begin . ,vs)
(for/fold ([env env]) ([v (in-wrap-list vs)])
(loop v env))]
[`,_ env]))))
(let loop ([body body])
(for/list ([v (in-list body)])
(match v
[`(variable-set! ,var-id ,id . ,_) v]
[`(define ,_ (begin (variable-set! ,var-id ,id . ,_) (void))) v]
[`(define ,id ,rhs)
If there 's a direct reference to ` i d ` in ` rhs ` , then
(define self-env (add-self top-env #hasheq() id))
(reannotate v `(define ,id ,(jitify-top-expr rhs self-env id)))]
[`(define-values ,ids ,rhs)
(reannotate v `(define-values ,ids ,(jitify-top-expr rhs top-env #f)))]
[`(begin . ,vs)
(reannotate v `(begin . ,(loop vs)))]
[`,_ (jitify-top-expr v top-env #f)]))))
(define (jitify-top-expr v env name)
(define mutables (find-mutable #hasheq() v #hasheq()))
(define convert-mode (init-convert-mode v))
(define-values (new-v free) (jitify-expr v env mutables #hasheq() convert-mode name #f))
new-v)
(define (jitify-expr v env mutables free convert-mode name in-name)
(match v
[`(lambda ,args . ,body)
(define convert? (convert-mode-convert-lambda? convert-mode v))
(define body-convert-mode (convert-mode-lambda-body-mode convert-mode convert?))
(define self-env (if convert?
(activate-self (deactivate-self env in-name) name)
env))
(define body-env (add-args self-env args mutables body-convert-mode))
(define body-in-name (if convert? (or name '#:anonymous) in-name))
(define-values (new-body lam-body-free)
(jitify-body body body-env mutables #hasheq() body-convert-mode #f body-in-name))
(define lam-free (remove-args lam-body-free args))
(define new-v (reannotate v `(lambda ,args . ,(mutable-box-bindings args mutables body-convert-mode
new-body))))
(values (if (not convert?)
new-v
(make-jit-on-call lam-free (list args) new-v name self-env))
(union-free free lam-free))]
[`(case-lambda [,argss . ,bodys] ...)
(define convert? (convert-mode-convert-lambda? convert-mode v))
(define body-convert-mode (convert-mode-lambda-body-mode convert-mode convert?))
(define self-env (if convert?
(activate-self (deactivate-self env in-name) name)
env))
(define body-in-name (if convert? (or name '#:anonymous) in-name))
(define-values (rev-new-bodys lam-free)
(for/fold ([rev-new-bodys '()] [lam-free #hasheq()]) ([args (in-list argss)]
[body (in-list bodys)])
(define body-env (add-args self-env args mutables body-convert-mode))
(define-values (new-body lam-body-free)
(jitify-body body body-env mutables #hasheq() body-convert-mode #f body-in-name))
(values (cons new-body rev-new-bodys)
(union-free (remove-args lam-body-free args)
lam-free))))
(define new-v (reannotate v
`(case-lambda
,@(for/list ([args (in-list argss)]
[body (in-list (reverse rev-new-bodys))])
`[,args . ,(mutable-box-bindings args mutables body-convert-mode
body)]))))
(values (if (not convert?)
new-v
(make-jit-on-call lam-free argss new-v name self-env))
(union-free free lam-free))]
[`(let . ,_) (jitify-let v env mutables free convert-mode name in-name)]
[`(letrec . ,_) (jitify-let v env mutables free convert-mode name in-name)]
[`(letrec* . ,_) (jitify-let v env mutables free convert-mode name in-name)]
[`(begin . ,vs)
(define-values (new-body new-free) (jitify-body vs env mutables free convert-mode name in-name))
(values (reannotate v `(begin . ,new-body))
new-free)]
[`(begin0 ,v0 . ,vs)
(define-values (new-v0 v0-free)
(jitify-expr v0 env mutables free (convert-mode-non-tail convert-mode) name in-name))
(define-values (new-body new-free)
(jitify-body vs env mutables v0-free (convert-mode-non-tail convert-mode) #f in-name))
(values (reannotate v `(begin0 ,new-v0 . ,new-body))
new-free)]
[`(pariah ,e)
(define-values (new-e new-free) (jitify-expr e env mutables free convert-mode name in-name))
(values (reannotate v `(pariah ,new-e))
new-free)]
[`(if ,tst ,thn ,els)
(define sub-convert-mode (convert-mode-non-tail convert-mode))
(define-values (new-tst new-free/tst) (jitify-expr tst env mutables free sub-convert-mode #f in-name))
(define-values (new-thn new-free/thn) (jitify-expr thn env mutables new-free/tst convert-mode name in-name))
(define-values (new-els new-free/els) (jitify-expr els env mutables new-free/thn convert-mode name in-name))
(values (reannotate v `(if ,new-tst ,new-thn ,new-els))
new-free/els)]
[`(with-continuation-mark ,key ,val ,body)
(define sub-convert-mode (convert-mode-non-tail convert-mode))
(define-values (new-key new-free/key) (jitify-expr key env mutables free sub-convert-mode #f in-name))
(define-values (new-val new-free/val) (jitify-expr val env mutables new-free/key sub-convert-mode #f in-name))
(define-values (new-body new-free/body) (jitify-expr body env mutables new-free/val convert-mode name in-name))
(values (reannotate v `(with-continuation-mark ,new-key ,new-val ,new-body))
new-free/body)]
[`(quote ,_) (values v free)]
[`(set! ,var ,rhs)
(define-values (new-rhs new-free) (jitify-expr rhs env mutables free (convert-mode-non-tail convert-mode) var in-name))
(define id (unwrap var))
(define dest (hash-ref env id #f))
(cond
[(and (not in-name)
(match dest
[`(variable-ref ,_) #t]
[`,_ #f]))
(values `(set! ,var ,new-rhs)
new-free)]
[else
(define newer-free (if dest
(hash-set new-free id dest)
new-free))
(define new-v
(match (hash-ref env id '#:direct)
[`#:direct (reannotate v `(set! ,var ,new-rhs))]
[`(self ,m . ,_) (error 'set! "[internal error] self-referenceable ~s" id)]
[`(variable-ref ,var-id) (reannotate v `(variable-set! ,var-id ,new-rhs '#f))]
[`(unbox ,box-id) (reannotate v `(set-box! ,box-id ,new-rhs))]
[`(unbox/check-undefined ,box-id ,_) (reannotate v `(set-box!/check-undefined ,box-id ,new-rhs ',var))]))
(values new-v newer-free)])]
[`(call-with-values ,proc1 ,proc2)
(define proc-convert-mode (convert-mode-called convert-mode))
(define-values (new-proc1 new-free1) (jitify-expr proc1 env mutables free proc-convert-mode #f in-name))
(define-values (new-proc2 new-free2) (jitify-expr proc2 env mutables new-free1 proc-convert-mode #f in-name))
(define call-with-values-id (if (and (lambda? new-proc1) (lambda? new-proc2))
'call-with-values
'#%call-with-values))
(values (reannotate v `(,call-with-values-id ,new-proc1 ,new-proc2))
new-free2)]
[`(#%app ,_ ...)
(define-values (new-vs new-free)
(jitify-body (wrap-cdr v) env mutables free (convert-mode-non-tail convert-mode) #f in-name))
(values (reannotate v `(#%app . ,new-vs))
new-free)]
[`(,rator ,_ ...)
(define u (unwrap rator))
(match (and (symbol? u) (hash-ref env u #f))
[`(self ,_ ,orig-id)
(define-values (new-vs new-free)
(jitify-body (wrap-cdr v) env mutables free (convert-mode-non-tail convert-mode) #f in-name))
(values (reannotate v `(,rator . ,new-vs))
new-free)]
[`,x
(define-values (new-vs new-free)
(jitify-body v env mutables free (convert-mode-non-tail convert-mode) #f in-name))
(values (reannotate v new-vs)
new-free)])]
[`,var
(define id (unwrap var))
(define dest (hash-ref env id #f))
(cond
[(and (not in-name)
(match dest
[`(variable-ref ,_) #t]
[`,_ #f]))
(values var free)]
[else
(define new-var
(match dest
[`#f var]
[`#:direct var]
[`(self ,u . ,_) (reannotate v u)]
[`,u (reannotate v u)]))
(define new-free
(if dest
(hash-set free id dest)
free))
(values new-var
new-free)])]))
(define (lambda? v)
(match v
[`(lambda . ,_) #t]
[`(case-lambda . ,_) #t]
[`,_ #f]))
(define (jitify-body vs env mutables free convert-mode name in-name)
(let loop ([vs vs] [free free])
(cond
[(wrap-null? vs) (values null free)]
[(wrap-null? (wrap-cdr vs))
(define-values (new-v new-free)
(jitify-expr (wrap-car vs) env mutables free convert-mode name in-name))
(values (list new-v) new-free)]
[else
(define-values (new-v new-free)
(jitify-expr (wrap-car vs) env mutables free (convert-mode-non-tail convert-mode) #f in-name))
(define-values (new-rest newer-free)
(loop (wrap-cdr vs) new-free))
(values (cons new-v new-rest)
newer-free)])))
(define (jitify-let v env mutables free convert-mode name in-name)
(match v
[`(,let-form ([,ids ,rhss] ...) . ,body)
(define rec?
(and (case (unwrap let-form)
[(letrec letrec*) #t]
[else #f])
(convert-mode-box-mutables? convert-mode)))
(define rhs-convert-mode (convert-mode-non-tail convert-mode))
(define rhs-env (if rec?
(add-args/unbox env ids mutables
(lambda (var) #t)
(not (for/and ([rhs (in-list rhss)])
(lambda? rhs)))
convert-mode)
env))
(define-values (rev-new-rhss rhs-free)
(for/fold ([rev-new-rhss '()] [free #hasheq()]) ([id (in-list ids)]
[rhs (in-list rhss)])
(define self-env
(if rec?
(add-self rhs-env mutables id)
rhs-env))
(define-values (new-rhs rhs-free)
(jitify-expr rhs self-env mutables free rhs-convert-mode id in-name))
(values (cons new-rhs rev-new-rhss) rhs-free)))
(define local-env
(add-args/unbox env ids mutables
(lambda (var) (and rec? (hash-ref rhs-free var #f)))
#f
convert-mode))
(define-values (new-body new-free)
(jitify-body body local-env mutables (union-free free rhs-free) convert-mode name in-name))
(define new-v
(cond
[(not rec?)
`(,let-form ,(for/list ([id (in-list ids)]
[new-rhs (in-list (reverse rev-new-rhss))])
`[,id ,(if (and (convert-mode-box-mutables? convert-mode)
(hash-ref mutables (unwrap id) #f))
`(box ,new-rhs)
new-rhs)])
. ,new-body)]
[else
Allocate boxes first , then fill in
`(let ,(for*/list ([id (in-list ids)]
#:when (hash-ref rhs-free (unwrap id) #f))
`[,id (box unsafe-undefined)])
,(for/fold ([body (body->expr new-body)]) ([id (in-list (reverse ids))]
[new-rhs (in-list rev-new-rhss)])
`(let (,(cond
[(hash-ref rhs-free (unwrap id) #f)
`[,(gensym 'ignored) (set-box! ,id ,new-rhs)]]
[(hash-ref mutables (unwrap id) #f)
`[,id (box ,new-rhs)]]
[else `[,id ,new-rhs]]))
,body)))]))
(values (reannotate v new-v)
(remove-args new-free ids))]))
(define (mutable-box-bindings args mutables convert-mode body)
(cond
[(convert-mode-box-mutables? convert-mode)
(define bindings
(let loop ([args args])
(cond
[(wrap-null? args) null]
[(wrap-pair? args)
(define id (wrap-car args))
(define var (unwrap id))
(define rest (loop (wrap-cdr args)))
(if (hash-ref mutables var #f)
(cons `[,id (box ,id)] rest)
rest)]
[else (loop (list args))])))
(if (null? bindings)
body
`((let ,bindings . ,body)))]
[else body]))
(define (plain-add-args env args)
(define (add-one id)
(hash-set env (unwrap id) '#:direct))
(match args
[`(,id . ,args)
(plain-add-args (add-one id) args)]
[`() env]
[`,id (add-one id)]))
(define (add-args env args mutables convert-mode)
(define (add-one id)
(define u (unwrap id))
(define val (if (and (convert-mode-box-mutables? convert-mode)
(hash-ref mutables u #f))
`(unbox ,id)
'#:direct))
(hash-set env u val))
(match args
[`(,id . ,args)
(add-args (add-one id) args mutables convert-mode)]
[`() env]
[`,id (add-one id)]))
(define (add-args/unbox env args mutables var-rec? maybe-undefined? convert-mode)
(define (add-one id)
(define var (unwrap id))
(cond
[maybe-undefined? (hash-set env var `(unbox/check-undefined ,id ',id))]
[(not (or (var-rec? var) (and (convert-mode-box-mutables? convert-mode)
(hash-ref mutables var #f))))
(hash-set env var '#:direct)]
[else (hash-set env var `(unbox ,id))]))
(match args
[`(,id . ,args)
(add-args/unbox (add-one id) args mutables var-rec? maybe-undefined? convert-mode)]
[`() env]
[`,id (add-one id)]))
(define (remove-args env args)
(match args
[`(,id . ,args)
(remove-args (hash-remove env (unwrap id)) args)]
[`() env]
[`,id (hash-remove env (unwrap id))]))
(define (add-bindings env bindings)
(match bindings
[`([,ids ,_] ...)
(for/fold ([env env]) ([id (in-list ids)])
(plain-add-args env id))]))
(define (add-self env mutables name)
(define u (unwrap name))
(cond
[(hash-ref mutables u #f)
env]
[else
(hash-set env u `(self ,(hash-ref env u '#:direct)))]))
(define (activate-self env name)
(cond
[name
(define (genself) (gensym 'self))
(define u (unwrap name))
(define new-m
(match (hash-ref env u #f)
[`(self #:direct)
`(self ,(genself) ,name)]
[`(self (variable-ref ,orig-id))
`(self (variable-ref ,orig-id) ,orig-id)]
[`(self (unbox ,orig-id))
`(self (unbox ,(genself)) ,orig-id)]
[`(self (unbox/check-undefined ,orig-id ,sym))
`(self (unbox/check-undefined ,(genself) ,sym) ,orig-id)]
[`,_ #f]))
(if new-m
(hash-set env u new-m)
env)]
[else env]))
(define (deactivate-self env name)
(cond
[name
(define u (unwrap name))
(match (hash-ref env u #f)
[`(self ,m ,_) (hash-set env u m)]
[`,_ env])]
[else env]))
(define (argss->arity-mask argss)
(for/fold ([mask 0]) ([args (in-list argss)])
(bitwise-ior mask
(let loop ([args args] [count 0])
(cond
[(wrap-null? args) (arithmetic-shift 1 count)]
[(wrap-pair? args) (loop (wrap-cdr args) (add1 count))]
[else (bitwise-xor -1 (sub1 (arithmetic-shift 1 count)))])))))
(define (de-dot args)
(cond
[(wrap-pair? args) (cons (wrap-car args)
(de-dot (wrap-cdr args)))]
[else (list args)]))
(define (union-free a b)
(cond
[((hash-count b) . < . (hash-count a)) (union-free b a)]
[else
(for/fold ([b b]) ([(k v) (in-hash a)])
(hash-set b k v))]))
(define (body->expr body)
(cond
[(and (wrap-pair? body) (wrap-null? (wrap-cdr body)))
(wrap-car body)]
[else `(begin . ,body)]))
(define (find-mutable env v accum)
(match v
[`(lambda ,args . ,body)
(body-find-mutable (plain-add-args env args) body accum)]
[`(case-lambda [,argss . ,bodys] ...)
(for/fold ([accum accum]) ([args (in-list argss)]
[body (in-list bodys)])
(body-find-mutable (plain-add-args env args) body accum))]
[`(let . ,_) (find-mutable-in-let env v accum)]
[`(letrec . ,_) (find-mutable-in-let env v accum)]
[`(letrec* . ,_) (find-mutable-in-let env v accum)]
[`(begin . ,vs) (body-find-mutable env vs accum)]
[`(begin0 . ,vs) (body-find-mutable env vs accum)]
[`(if ,tst ,thn ,els)
(find-mutable env tst
(find-mutable env thn
(find-mutable env els accum)))]
[`(with-continuation-mark ,key ,val ,body)
(find-mutable env key
(find-mutable env val
(find-mutable env body accum)))]
[`(quote ,_) accum]
[`(set! ,var ,rhs)
(define id (unwrap var))
(find-mutable env rhs (if (hash-ref env id #f)
(hash-set accum id #t)
accum))]
[`(,_ ...) (body-find-mutable env v accum)]
[`,_ accum]))
(define (body-find-mutable env body accum)
(for/fold ([accum accum]) ([v (in-wrap-list body)])
(find-mutable env v accum)))
(define (find-mutable-in-let env v accum)
(match v
[`(,let-form ([,ids ,rhss] ...) . ,body)
(define local-env
(for/fold ([env env]) ([id (in-list ids)])
(plain-add-args env id)))
(define rhs-env
(case (unwrap let-form)
[(letrec letrec* letrec*-values) local-env]
[else env]))
(body-find-mutable local-env
body
(for/fold ([accum accum]) ([id (in-list ids)]
[rhs (in-list rhss)])
(find-mutable rhs-env rhs accum)))]))
(struct convert-mode (sizes called? no-more-conversions?))
(define (init-convert-mode v)
(cond
[convert-size-threshold
(convert-mode (record-sizes v) #f #f)]
[else 'not-called]))
(define (convert-mode-convert-lambda? cm v)
(cond
[(eq? cm 'called) #f]
[(eq? cm 'not-called) #t]
[(convert-mode-called? cm) #f]
[(convert-mode-no-more-conversions? cm) #f]
[((hash-ref (convert-mode-sizes cm) v) . >= . convert-size-threshold) #f]
[else #t]))
(define (convert-mode-lambda-body-mode cm convert?)
(cond
[(convert-mode? cm)
(if convert?
(convert-mode 'not-needed #f #t)
(convert-mode-non-tail cm))]
[else 'not-called]))
(define (convert-mode-non-tail cm)
(cond
[(convert-mode? cm)
(struct-copy convert-mode cm
[called? #f])]
[else 'not-called]))
(define (convert-mode-called cm)
(cond
[(convert-mode? cm)
(struct-copy convert-mode cm
[called? #t])]
[else 'called]))
(define (convert-mode-box-mutables? cm)
(cond
[(convert-mode? cm)
(not (convert-mode-no-more-conversions? cm))]
[else #t]))
(define (record-sizes v)
(let ([sizes (make-hasheq)])
(record-sizes! v sizes)
sizes))
(define (record-size! v sizes size)
(hash-set! sizes v size)
size)
(define (record-sizes! v sizes)
(match v
[`(lambda ,args . ,body)
(record-size! v sizes (body-record-sizes! body sizes))]
[`(case-lambda [,_ . ,bodys] ...)
(define new-size
(for/sum ([body (in-list bodys)])
(body-record-sizes! body sizes)))
(record-size! v sizes new-size)]
[`(let . ,_) (record-sizes-in-let! v sizes)]
[`(letrec . ,_) (record-sizes-in-let! v sizes)]
[`(letrec* . ,_) (record-sizes-in-let! v sizes)]
[`(begin . ,vs) (add1 (body-record-sizes! vs sizes))]
[`(begin0 . ,vs) (add1 (body-record-sizes! vs sizes))]
[`(if ,tst ,thn ,els)
(+ 1
(record-sizes! tst sizes)
(record-sizes! thn sizes)
(record-sizes! els sizes))]
[`(with-continuation-mark ,key ,val ,body)
(+ 1
(record-sizes! key sizes)
(record-sizes! val sizes)
(record-sizes! body sizes))]
[`(quote ,_) 1]
[`(set! ,_ ,rhs)
(add1 (record-sizes! rhs sizes))]
[`(,_ ...) (body-record-sizes! v sizes)]
[`,_ 1]))
(define (body-record-sizes! body sizes)
(for/sum ([v (in-wrap-list body)])
(record-sizes! v sizes)))
(define (record-sizes-in-let! v sizes)
(match v
[`(,let-form ([,_ ,rhss] ...) . ,body)
(+ 1
(for/sum ([rhs (in-list rhss)])
(record-sizes! rhs sizes))
(body-record-sizes! body sizes))]))
(top))
(module+ main
(require racket/pretty)
(pretty-print
'(lambda (iv xv do-immediate)
(define top (letrec ([odd (lambda (x) (even x))]
[even (lambda (x) (odd x))]
[selfx (lambda (x) (selfx x))]
[selfy (lambda (x) (vector (selfy x) selfy))])
(odd 5)))
(define top-selfx (lambda (x) (top-selfx x)))
(variable-set! top-selfx-var top-selfx 'const)
(define top-selfy (lambda (x) (vector (top-selfy x) top-selfy)))
(variable-set! top-selfy-var top-selfy 'const)
(call-with-values (lambda (x) (x (lambda (w) (w))))
(lambda (z w) 10))
(call-with-values (lambda (x) (x (lambda (w) (w))))
(letrec ([selfz (lambda (z) (selfz (selfz z)))])
(lambda (z w) (selfz w))))
(call-with-values (lambda (x) (x (lambda (w) (w))))
void)
(define y (letrec ([f (lambda (x) (f (cons x x)))]
[g (lambda (q) (set! f g) (f q))])
(list (lambda (f) (list x)))))
(define x (lambda (j) j))
(define x2 (lambda () (letrec ([other (lambda () (other iv))])
other)))
(define whatever (begin (variable-set! xv x 'const) (void)))
(define end (letrec ([w (lambda (x) (let ([proc (lambda (x) x)])
(proc q)))]
[q q])
(lambda (j) (set! q j))))
(define topz (letrec ([helper (lambda (x)
(helper (topz x)))])
(lambda (y) (helper y))))
(variable-set! topz-var topz 'const)
(do-immediate topz)
(define sets-arg (lambda (x)
(values (lambda () (set! x (add1 x)))
(lambda () x))))
(letrec ([outer
(lambda (x)
(letrec ([inner
(lambda (y)
(outer y))])
(inner x)))])
(outer 5))
(lambda () (let ([x 5]) (set! x 6) x))))
#t
vector
(lambda (v u) u)
values)))
|
548ac3f45cc77f084621427e2597733f32bea8cda76c10ffaa6b6c7ecb58c060 | geneanet/ocaml-wikitext | wikitext_js.ml | open Js_of_ocaml
open Wikitext
let () =
let getElementById coerce id =
match Js.Opt.to_option @@ Dom_html.document##getElementById (Js.string id) with
| None -> failwith id
| Some x -> match Js.Opt.to_option @@ coerce x with
| None -> failwith id
| Some x -> x
in
let input = getElementById Dom_html.CoerceTo.textarea "input" in
let output = getElementById Dom_html.CoerceTo.div "output" in
let update () =
try
let doc = doc_from_string (Js.to_string input##.value) in
let doc = Mapper.set_toc doc in
let doc = Mapper.set_links doc in
output##.innerHTML := Js.string @@ doc_to_string doc
with
| ParsingError (line, col, lexeme) ->
output##.innerHTML :=
Js.string @@ Printf.sprintf "line %d, col %d, lexeme [%s]" line col lexeme
in
input##.oninput := Dom.handler (fun _ -> update () ; Js._false) ;
update ()
| null | https://raw.githubusercontent.com/geneanet/ocaml-wikitext/d507087a04ee72e92b430040e4a9ce31c7148a1a/test/wikitext_js.ml | ocaml | open Js_of_ocaml
open Wikitext
let () =
let getElementById coerce id =
match Js.Opt.to_option @@ Dom_html.document##getElementById (Js.string id) with
| None -> failwith id
| Some x -> match Js.Opt.to_option @@ coerce x with
| None -> failwith id
| Some x -> x
in
let input = getElementById Dom_html.CoerceTo.textarea "input" in
let output = getElementById Dom_html.CoerceTo.div "output" in
let update () =
try
let doc = doc_from_string (Js.to_string input##.value) in
let doc = Mapper.set_toc doc in
let doc = Mapper.set_links doc in
output##.innerHTML := Js.string @@ doc_to_string doc
with
| ParsingError (line, col, lexeme) ->
output##.innerHTML :=
Js.string @@ Printf.sprintf "line %d, col %d, lexeme [%s]" line col lexeme
in
input##.oninput := Dom.handler (fun _ -> update () ; Js._false) ;
update ()
| |
bff2f1b085bc78c1bdfdd2023bcb172c26d4f7ef8de2debe25288b48f3107d9e | webyrd/n-grams-for-synthesis | r7rs-shim.scm | ;;; Necessary R7RS syntax and procedures
(define-syntax when
(syntax-rules ()
((when test . body)
(if test (begin . body)))))
;;> \procedure{(string-map proc str)}
;;>
;;> Returns a new string composed of applying the procedure \var{proc}
;;> to every character in \var{string}.
(define (string-map proc str . los)
(let* ((out (open-output-string))
(void (apply string-for-each
(lambda args (write-char (apply proc args) out))
str los))
(res (get-output-string out)))
(close-output-port out)
res))
;;> \procedure{(string-for-each proc str)}
;;>
> Apply \var{proc } to every character in \var{str } in order and
;;> discard the result.
(define (string-for-each proc str . los)
(if (null? los)
(string-fold (lambda (ch a) (proc ch)) #f str)
(let ((los (cons str los)))
(let lp ((is (map string-cursor-start los)))
(cond
((any (lambda (str i)
(string-cursor>=? i (string-cursor-end str)))
los is))
(else
(apply proc (map string-cursor-ref los is))
(lp (map string-cursor-next los is))))))))
| null | https://raw.githubusercontent.com/webyrd/n-grams-for-synthesis/b53b071e53445337d3fe20db0249363aeb9f3e51/datasets/srfi/srfi-130/foof/r7rs-shim.scm | scheme | Necessary R7RS syntax and procedures
> \procedure{(string-map proc str)}
>
> Returns a new string composed of applying the procedure \var{proc}
> to every character in \var{string}.
> \procedure{(string-for-each proc str)}
>
> discard the result. |
(define-syntax when
(syntax-rules ()
((when test . body)
(if test (begin . body)))))
(define (string-map proc str . los)
(let* ((out (open-output-string))
(void (apply string-for-each
(lambda args (write-char (apply proc args) out))
str los))
(res (get-output-string out)))
(close-output-port out)
res))
> Apply \var{proc } to every character in \var{str } in order and
(define (string-for-each proc str . los)
(if (null? los)
(string-fold (lambda (ch a) (proc ch)) #f str)
(let ((los (cons str los)))
(let lp ((is (map string-cursor-start los)))
(cond
((any (lambda (str i)
(string-cursor>=? i (string-cursor-end str)))
los is))
(else
(apply proc (map string-cursor-ref los is))
(lp (map string-cursor-next los is))))))))
|
9677f5ee364220b1e2948a7ab810cad43bd0ea5ad5ead6019573913100604cf0 | yzhs/ocamlllvm | marshal.ml | (***********************************************************************)
(* *)
(* Objective Caml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1997 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
(* the special exception on linking described in file ../LICENSE. *)
(* *)
(***********************************************************************)
$ Id$
type extern_flags =
No_sharing
| Closures
external to_channel: out_channel -> 'a -> extern_flags list -> unit
= "caml_output_value"
external to_string: 'a -> extern_flags list -> string
= "caml_output_value_to_string"
external to_buffer_unsafe:
string -> int -> int -> 'a -> extern_flags list -> int
= "caml_output_value_to_buffer"
let to_buffer buff ofs len v flags =
if ofs < 0 || len < 0 || ofs > String.length buff - len
then invalid_arg "Marshal.to_buffer: substring out of bounds"
else to_buffer_unsafe buff ofs len v flags
external from_channel: in_channel -> 'a = "caml_input_value"
external from_string_unsafe: string -> int -> 'a
= "caml_input_value_from_string"
external data_size_unsafe: string -> int -> int = "caml_marshal_data_size"
let header_size = 20
let data_size buff ofs =
if ofs < 0 || ofs > String.length buff - header_size
then invalid_arg "Marshal.data_size"
else data_size_unsafe buff ofs
let total_size buff ofs = header_size + data_size buff ofs
let from_string buff ofs =
if ofs < 0 || ofs > String.length buff - header_size
then invalid_arg "Marshal.from_size"
else begin
let len = data_size_unsafe buff ofs in
if ofs > String.length buff - (header_size + len)
then invalid_arg "Marshal.from_string"
else from_string_unsafe buff ofs
end
| null | https://raw.githubusercontent.com/yzhs/ocamlllvm/45cbf449d81f2ef9d234968e49a4305aaa39ace2/src/stdlib/marshal.ml | ocaml | *********************************************************************
Objective Caml
the special exception on linking described in file ../LICENSE.
********************************************************************* | , projet Cristal , INRIA Rocquencourt
Copyright 1997 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the GNU Library General Public License , with
$ Id$
type extern_flags =
No_sharing
| Closures
external to_channel: out_channel -> 'a -> extern_flags list -> unit
= "caml_output_value"
external to_string: 'a -> extern_flags list -> string
= "caml_output_value_to_string"
external to_buffer_unsafe:
string -> int -> int -> 'a -> extern_flags list -> int
= "caml_output_value_to_buffer"
let to_buffer buff ofs len v flags =
if ofs < 0 || len < 0 || ofs > String.length buff - len
then invalid_arg "Marshal.to_buffer: substring out of bounds"
else to_buffer_unsafe buff ofs len v flags
external from_channel: in_channel -> 'a = "caml_input_value"
external from_string_unsafe: string -> int -> 'a
= "caml_input_value_from_string"
external data_size_unsafe: string -> int -> int = "caml_marshal_data_size"
let header_size = 20
let data_size buff ofs =
if ofs < 0 || ofs > String.length buff - header_size
then invalid_arg "Marshal.data_size"
else data_size_unsafe buff ofs
let total_size buff ofs = header_size + data_size buff ofs
let from_string buff ofs =
if ofs < 0 || ofs > String.length buff - header_size
then invalid_arg "Marshal.from_size"
else begin
let len = data_size_unsafe buff ofs in
if ofs > String.length buff - (header_size + len)
then invalid_arg "Marshal.from_string"
else from_string_unsafe buff ofs
end
|
74750ab9918c4b33d668e33f79cd5c0a2276ec7b2d9e8ba1978cc206a0a7bb3e | haskell/cabal | custom.test.hs | {-# LANGUAGE OverloadedStrings #-}
import Test.Cabal.Prelude
import Test.Cabal.DecodeShowBuildInfo
import Control.Monad.Trans.Reader
main = setupTest $ do
-- No cabal test because per-component is broken with it
skipUnlessGhcVersion ">= 8.1"
withPackageDb $ do
setup_build ["--enable-build-info"]
env <- ask
let buildInfoFp = testDistDir env </> "build-info.json"
buildInfo <- decodeBuildInfoFile buildInfoFp
assertCommonBuildInfo buildInfo
let [libBI, exeBI] = components buildInfo
assertComponentPure libBI defCompAssertion
{ modules = ["MyLib"]
, compType = "lib"
, sourceDirs = ["src"]
}
assertComponentPure exeBI defCompAssertion
{ sourceFiles = ["Main.hs"]
, compType = "exe"
, sourceDirs = ["app"]
}
| null | https://raw.githubusercontent.com/haskell/cabal/c21dbcd2a9d54962eb39f598dfce2d012ff7fd1c/cabal-testsuite/PackageTests/ShowBuildInfo/Custom/custom.test.hs | haskell | # LANGUAGE OverloadedStrings #
No cabal test because per-component is broken with it | import Test.Cabal.Prelude
import Test.Cabal.DecodeShowBuildInfo
import Control.Monad.Trans.Reader
main = setupTest $ do
skipUnlessGhcVersion ">= 8.1"
withPackageDb $ do
setup_build ["--enable-build-info"]
env <- ask
let buildInfoFp = testDistDir env </> "build-info.json"
buildInfo <- decodeBuildInfoFile buildInfoFp
assertCommonBuildInfo buildInfo
let [libBI, exeBI] = components buildInfo
assertComponentPure libBI defCompAssertion
{ modules = ["MyLib"]
, compType = "lib"
, sourceDirs = ["src"]
}
assertComponentPure exeBI defCompAssertion
{ sourceFiles = ["Main.hs"]
, compType = "exe"
, sourceDirs = ["app"]
}
|
1d442d6287b4cd778a4ebe594f3ae005cfa2b0cd96d2fa1b1c0a604c56d2019f | MondayMorningHaskell/haskellings | Syntax5.hs | -- I AM NOT DONE
import Test.Tasty
import Test.Tasty.HUnit
- So far our functions have been very simple . So we 've been able to write the whole
result on a single line without re - using sub - expressions . But often this is n't the case .
Suppose we want to use some part of our answer multiple times . It would make our code
more readable to be able to " save " this value :
sumEarlyDigits : : Bool - > [ Int ] - > Int
sumEarlyDigits bool ls = if then head ls + head ( tail ls )
else head ( tail ls ) + head ( tail ( tail ls ) )
- A ' where ' clause allows us to save expressions like ' tail ls ' here .
We indicate this section of our function with the ' where ' keyword
and add a series of expression definitions , which we can then use in our function .
Notice how we can use ' tail1 ' within another variable definition !
sumEarlyDigits : : Bool - > [ Int ] - > Int
sumEarlyDigits bool ls = if then head ls + second
else second + head ( tail tail1 )
where
tail1 = tail ls
second = head tail1
- A ' where ' clause can also allow you to make code more readable , even if
sub - expressions are n't re - used .
sumProducts : : Int - > Int - > Int - > Int
sumProducts x y z = prod1 + prod2 + prod3
where
prod1 = x * y
prod2 = y * z
prod3 = x * z
- The order in which ' where ' statements are defined * does not matter * . However ,
you must make sure to not create a circular dependency between your definitions !
badSum : : Int - > Int - > Int - > Int
badSum x y z = prod1 + prod2 + prod3 + prod4
where
prod2 = prod1 + ( y * z ) -- < Can use prod1 even though it 's defined " after " .
prod1 = x * y
prod3 = prod4 + x
prod4 = y * prod3 -- < This is a problem ! prod3 and prod4 depend on each other !
- So far our functions have been very simple. So we've been able to write the whole
result on a single line without re-using sub-expressions. But often this isn't the case.
Suppose we want to use some part of our answer multiple times. It would make our code
more readable to be able to "save" this value:
sumEarlyDigits :: Bool -> [Int] -> Int
sumEarlyDigits bool ls = if bool
then head ls + head (tail ls)
else head (tail ls) + head (tail (tail ls))
- A 'where' clause allows us to save expressions like 'tail ls' here.
We indicate this section of our function with the 'where' keyword
and add a series of expression definitions, which we can then use in our function.
Notice how we can use 'tail1' within another variable definition!
sumEarlyDigits :: Bool -> [Int] -> Int
sumEarlyDigits bool ls = if bool
then head ls + second
else second + head (tail tail1)
where
tail1 = tail ls
second = head tail1
- A 'where' clause can also allow you to make code more readable, even if
sub-expressions aren't re-used.
sumProducts :: Int -> Int -> Int -> Int
sumProducts x y z = prod1 + prod2 + prod3
where
prod1 = x * y
prod2 = y * z
prod3 = x * z
- The order in which 'where' statements are defined *does not matter*. However,
you must make sure to not create a circular dependency between your definitions!
badSum :: Int -> Int -> Int -> Int
badSum x y z = prod1 + prod2 + prod3 + prod4
where
prod2 = prod1 + (y * z) -- < Can use prod1 even though it's defined "after".
prod1 = x * y
prod3 = prod4 + x
prod4 = y * prod3 -- < This is a problem! prod3 and prod4 depend on each other!
-}
-- TODO: Use 'where' clauses to complete these functions!
-- Take the sum of each pairwise product of inputs.
sumPairProducts :: (Int, Int, Int, Int, Int, Int) -> Int
sumPairProducts = ???
-- Take the sum of corresponding elements of the tuples, but only include each
-- pair when the corresponding bool is true.
e.g. sumTuples ( True , False , False ) ( 1 , 2 , 3 ) ( 4 , 5 , 6 ) = 5
sumTuples ( True , False , True ) ( 1 , 2 , 3 ) ( 4 , 5 , 6 ) = 14
sumTuples :: (Bool, Bool, Bool) -> (Int, Int, Int) -> (Int, Int, Int) -> Int
sumTuples = ???
-- Testing Code
main :: IO ()
main = defaultMain $ testGroup "Syntax5" $
[ testCase "sumPairProducts 1" $ sumPairProducts (1, 2, 3, 4, 5, 6) @?= 175
, testCase "sumPairProducts 2" $ sumPairProducts (8, 2, -3, 4, -5, 7) @?= 1
, testCase "sumTuples 1" $ sumTuples (True, True, True) (1, 2, 3) (4, 5, 6) @?= 21
, testCase "sumTuples 2" $ sumTuples (True, False, True) (1, 2, 3) (4, 5, 6) @?= 14
, testCase "sumTuples 3" $ sumTuples (False, True, False) (1, 2, 3) (4, 5, 6) @?= 7
]
| null | https://raw.githubusercontent.com/MondayMorningHaskell/haskellings/fafadd5bbb722b54c1b7b114e34dc9b96bb7ca4d/exercises/syntax/Syntax5.hs | haskell | I AM NOT DONE
< Can use prod1 even though it 's defined " after " .
< This is a problem ! prod3 and prod4 depend on each other !
< Can use prod1 even though it's defined "after".
< This is a problem! prod3 and prod4 depend on each other!
TODO: Use 'where' clauses to complete these functions!
Take the sum of each pairwise product of inputs.
Take the sum of corresponding elements of the tuples, but only include each
pair when the corresponding bool is true.
Testing Code |
import Test.Tasty
import Test.Tasty.HUnit
- So far our functions have been very simple . So we 've been able to write the whole
result on a single line without re - using sub - expressions . But often this is n't the case .
Suppose we want to use some part of our answer multiple times . It would make our code
more readable to be able to " save " this value :
sumEarlyDigits : : Bool - > [ Int ] - > Int
sumEarlyDigits bool ls = if then head ls + head ( tail ls )
else head ( tail ls ) + head ( tail ( tail ls ) )
- A ' where ' clause allows us to save expressions like ' tail ls ' here .
We indicate this section of our function with the ' where ' keyword
and add a series of expression definitions , which we can then use in our function .
Notice how we can use ' tail1 ' within another variable definition !
sumEarlyDigits : : Bool - > [ Int ] - > Int
sumEarlyDigits bool ls = if then head ls + second
else second + head ( tail tail1 )
where
tail1 = tail ls
second = head tail1
- A ' where ' clause can also allow you to make code more readable , even if
sub - expressions are n't re - used .
sumProducts : : Int - > Int - > Int - > Int
sumProducts x y z = prod1 + prod2 + prod3
where
prod1 = x * y
prod2 = y * z
prod3 = x * z
- The order in which ' where ' statements are defined * does not matter * . However ,
you must make sure to not create a circular dependency between your definitions !
badSum : : Int - > Int - > Int - > Int
badSum x y z = prod1 + prod2 + prod3 + prod4
where
prod1 = x * y
prod3 = prod4 + x
- So far our functions have been very simple. So we've been able to write the whole
result on a single line without re-using sub-expressions. But often this isn't the case.
Suppose we want to use some part of our answer multiple times. It would make our code
more readable to be able to "save" this value:
sumEarlyDigits :: Bool -> [Int] -> Int
sumEarlyDigits bool ls = if bool
then head ls + head (tail ls)
else head (tail ls) + head (tail (tail ls))
- A 'where' clause allows us to save expressions like 'tail ls' here.
We indicate this section of our function with the 'where' keyword
and add a series of expression definitions, which we can then use in our function.
Notice how we can use 'tail1' within another variable definition!
sumEarlyDigits :: Bool -> [Int] -> Int
sumEarlyDigits bool ls = if bool
then head ls + second
else second + head (tail tail1)
where
tail1 = tail ls
second = head tail1
- A 'where' clause can also allow you to make code more readable, even if
sub-expressions aren't re-used.
sumProducts :: Int -> Int -> Int -> Int
sumProducts x y z = prod1 + prod2 + prod3
where
prod1 = x * y
prod2 = y * z
prod3 = x * z
- The order in which 'where' statements are defined *does not matter*. However,
you must make sure to not create a circular dependency between your definitions!
badSum :: Int -> Int -> Int -> Int
badSum x y z = prod1 + prod2 + prod3 + prod4
where
prod1 = x * y
prod3 = prod4 + x
-}
sumPairProducts :: (Int, Int, Int, Int, Int, Int) -> Int
sumPairProducts = ???
e.g. sumTuples ( True , False , False ) ( 1 , 2 , 3 ) ( 4 , 5 , 6 ) = 5
sumTuples ( True , False , True ) ( 1 , 2 , 3 ) ( 4 , 5 , 6 ) = 14
sumTuples :: (Bool, Bool, Bool) -> (Int, Int, Int) -> (Int, Int, Int) -> Int
sumTuples = ???
main :: IO ()
main = defaultMain $ testGroup "Syntax5" $
[ testCase "sumPairProducts 1" $ sumPairProducts (1, 2, 3, 4, 5, 6) @?= 175
, testCase "sumPairProducts 2" $ sumPairProducts (8, 2, -3, 4, -5, 7) @?= 1
, testCase "sumTuples 1" $ sumTuples (True, True, True) (1, 2, 3) (4, 5, 6) @?= 21
, testCase "sumTuples 2" $ sumTuples (True, False, True) (1, 2, 3) (4, 5, 6) @?= 14
, testCase "sumTuples 3" $ sumTuples (False, True, False) (1, 2, 3) (4, 5, 6) @?= 7
]
|
6e87b89a47785a1c6c59e48c6285b42526b7d6850a137f64d2c4920567d24047 | janestreet/universe | readme.ml | open Core
[ Command ] treats the first space - separated word as part of an argument .
Without the space prefix , the readme will have the following form in -help output :
[ -readme Display ] documentation for the configuration file and
Without the space prefix, the readme will have the following form in -help output:
[-readme Display] documentation for the configuration file and
*)
let doc = " Display documentation for the configuration file and other help"
let main () =
protectx
(Filename.temp_file "patdiff" ".man")
~f:(fun fn ->
let readme = Text.Readme.readme in
Out_channel.write_lines fn [ readme ];
ignore
(Unix.system (sprintf "groff -Tascii -man %s|less" fn) : Unix.Exit_or_signal.t))
~finally:(fun fn -> Exn.handle_uncaught (fun () -> Unix.unlink fn) ~exit:false)
;;
| null | https://raw.githubusercontent.com/janestreet/universe/b6cb56fdae83f5d55f9c809f1c2a2b50ea213126/patdiff/bin/readme.ml | ocaml | open Core
[ Command ] treats the first space - separated word as part of an argument .
Without the space prefix , the readme will have the following form in -help output :
[ -readme Display ] documentation for the configuration file and
Without the space prefix, the readme will have the following form in -help output:
[-readme Display] documentation for the configuration file and
*)
let doc = " Display documentation for the configuration file and other help"
let main () =
protectx
(Filename.temp_file "patdiff" ".man")
~f:(fun fn ->
let readme = Text.Readme.readme in
Out_channel.write_lines fn [ readme ];
ignore
(Unix.system (sprintf "groff -Tascii -man %s|less" fn) : Unix.Exit_or_signal.t))
~finally:(fun fn -> Exn.handle_uncaught (fun () -> Unix.unlink fn) ~exit:false)
;;
| |
9e3211ad62c1cd6730536452e43d40b65efe603abbf7456599f9d75211faa0b0 | vouch-opensource/vouch-load-tests | converter.clj | (ns io.vouch.load-tests.task.definition.converter)
(defmulti task-definition->task (fn [definition] (:task definition)))
(defmethod task-definition->task :default [definition] definition)
(defn number-definition->number
[definition]
(if (vector? definition)
(let [[low high] definition]
(+ low (rand-int (- (inc high) low))))
definition))
(defn- to-millis
[unit value]
(case unit
:hours (* value 1000 60 60)
:minutes (* value 1000 60)
:seconds (* value 1000)
:milliseconds value
(throw (ex-info "Unsupported unit" {:unit unit}))))
(defn duration-definition->number
[definition unit]
(if (vector? definition)
(let [[low high] (map (partial to-millis unit) definition)]
(+ low (rand-int (- (inc high) low))))
(to-millis unit definition)))
| null | https://raw.githubusercontent.com/vouch-opensource/vouch-load-tests/d1d3a8b7df760ad452037d69cce85b0f2ccbb3b8/src/io/vouch/load_tests/task/definition/converter.clj | clojure | (ns io.vouch.load-tests.task.definition.converter)
(defmulti task-definition->task (fn [definition] (:task definition)))
(defmethod task-definition->task :default [definition] definition)
(defn number-definition->number
[definition]
(if (vector? definition)
(let [[low high] definition]
(+ low (rand-int (- (inc high) low))))
definition))
(defn- to-millis
[unit value]
(case unit
:hours (* value 1000 60 60)
:minutes (* value 1000 60)
:seconds (* value 1000)
:milliseconds value
(throw (ex-info "Unsupported unit" {:unit unit}))))
(defn duration-definition->number
[definition unit]
(if (vector? definition)
(let [[low high] (map (partial to-millis unit) definition)]
(+ low (rand-int (- (inc high) low))))
(to-millis unit definition)))
| |
4bd50749d82d346aad91ace02f0276ca91d92ad05e18487efe362b37202117bd | SimulaVR/godot-haskell | VisualShaderNodeVectorClamp.hs | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.VisualShaderNodeVectorClamp () 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.VisualShaderNode() | null | https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/VisualShaderNodeVectorClamp.hs | haskell | # LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.VisualShaderNodeVectorClamp () 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.VisualShaderNode() | |
887206e2c81544c683c9570f3a6f944788cf3a0df54db4c844b5ae7a6943a6ce | jayrbolton/coursework | Tutorial_notes.hs | {-# LANGUAGE EmptyDataDecls
, ExistentialQuantification
, ScopedTypeVariables
, NoMonomorphismRestriction
#-}
module MAlonzo.Tutorial_notes where
import qualified Unsafe.Coerce
name1 = ("Tutorial_notes.Bool")
d1 = (())
data T1 = C2
| C3
name2 = ("Tutorial_notes.true")
name3 = ("Tutorial_notes.false")
name4 = ("Tutorial_notes.not")
d4 (C3) = ((Unsafe.Coerce.unsafeCoerce) (C2))
d4 v0
= ((Unsafe.Coerce.unsafeCoerce)
((d_1_4) ((Unsafe.Coerce.unsafeCoerce) (v0))))
where d_1_4 (C2) = ((Unsafe.Coerce.unsafeCoerce) (C3))
d_1_4 v0
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes.not"))
name5 = ("Tutorial_notes.Nat")
d5 = (())
data T5 a0 = C6
| C7 a0
name6 = ("Tutorial_notes.zero")
name7 = ("Tutorial_notes.suc")
name8 = ("Tutorial_notes._+_")
d8 (C6) v0 = ((Unsafe.Coerce.unsafeCoerce) (v0))
d8 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d_1_8) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))
where d_1_8 (C7 v0) v1
= ((Unsafe.Coerce.unsafeCoerce)
((C7)
((Unsafe.Coerce.unsafeCoerce)
(((d8) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))))
d_1_8 v0 v1
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes._+_"))
name12 = ("Tutorial_notes._*_")
d12 (C6) v0 = ((Unsafe.Coerce.unsafeCoerce) (C6))
d12 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d_1_12) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))
where d_1_12 (C7 v0) v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d8) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce)
(((d12) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))))
d_1_12 v0 v1
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes._*_"))
name16 = ("Tutorial_notes._or_")
d16 (C2) v0 = ((Unsafe.Coerce.unsafeCoerce) (v0))
d16 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d_1_16) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))
where d_1_16 (C3) v0 = ((Unsafe.Coerce.unsafeCoerce) (C3))
d_1_16 v0 v1
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes._or_"))
name19 = ("Tutorial_notes.if_then_else_")
d19 v0 (C2) v1 v2 = ((Unsafe.Coerce.unsafeCoerce) (v1))
d19 v0 v1 v2 v3
= ((Unsafe.Coerce.unsafeCoerce)
(((((d_1_19) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))
((Unsafe.Coerce.unsafeCoerce) (v2)))
((Unsafe.Coerce.unsafeCoerce) (v3))))
where d_1_19 v0 (C3) v1 v2 = ((Unsafe.Coerce.unsafeCoerce) (v2))
d_1_19 v0 v1 v2 v3
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes.if_then_else_"))
name23 = ("Tutorial_notes.List")
d23 a0 = (())
data T23 a0 a1 = C25
| C26 a0 a1
name25 = ("Tutorial_notes.[]")
name26 = ("Tutorial_notes._::_")
name28 = ("Tutorial_notes.identity")
d28 v0 v1 = ((Unsafe.Coerce.unsafeCoerce) (v1))
name32 = ("Tutorial_notes.identity'")
d32 v0 v1 = ((Unsafe.Coerce.unsafeCoerce) (v1)) | null | https://raw.githubusercontent.com/jayrbolton/coursework/f0da276527d42a6751fb8d29c76de35ce358fe65/computability_and_formal_languages/project__/agda/MAlonzo/Tutorial_notes.hs | haskell | # LANGUAGE EmptyDataDecls
, ExistentialQuantification
, ScopedTypeVariables
, NoMonomorphismRestriction
# | module MAlonzo.Tutorial_notes where
import qualified Unsafe.Coerce
name1 = ("Tutorial_notes.Bool")
d1 = (())
data T1 = C2
| C3
name2 = ("Tutorial_notes.true")
name3 = ("Tutorial_notes.false")
name4 = ("Tutorial_notes.not")
d4 (C3) = ((Unsafe.Coerce.unsafeCoerce) (C2))
d4 v0
= ((Unsafe.Coerce.unsafeCoerce)
((d_1_4) ((Unsafe.Coerce.unsafeCoerce) (v0))))
where d_1_4 (C2) = ((Unsafe.Coerce.unsafeCoerce) (C3))
d_1_4 v0
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes.not"))
name5 = ("Tutorial_notes.Nat")
d5 = (())
data T5 a0 = C6
| C7 a0
name6 = ("Tutorial_notes.zero")
name7 = ("Tutorial_notes.suc")
name8 = ("Tutorial_notes._+_")
d8 (C6) v0 = ((Unsafe.Coerce.unsafeCoerce) (v0))
d8 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d_1_8) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))
where d_1_8 (C7 v0) v1
= ((Unsafe.Coerce.unsafeCoerce)
((C7)
((Unsafe.Coerce.unsafeCoerce)
(((d8) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))))
d_1_8 v0 v1
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes._+_"))
name12 = ("Tutorial_notes._*_")
d12 (C6) v0 = ((Unsafe.Coerce.unsafeCoerce) (C6))
d12 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d_1_12) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))
where d_1_12 (C7 v0) v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d8) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce)
(((d12) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))))
d_1_12 v0 v1
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes._*_"))
name16 = ("Tutorial_notes._or_")
d16 (C2) v0 = ((Unsafe.Coerce.unsafeCoerce) (v0))
d16 v0 v1
= ((Unsafe.Coerce.unsafeCoerce)
(((d_1_16) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1))))
where d_1_16 (C3) v0 = ((Unsafe.Coerce.unsafeCoerce) (C3))
d_1_16 v0 v1
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes._or_"))
name19 = ("Tutorial_notes.if_then_else_")
d19 v0 (C2) v1 v2 = ((Unsafe.Coerce.unsafeCoerce) (v1))
d19 v0 v1 v2 v3
= ((Unsafe.Coerce.unsafeCoerce)
(((((d_1_19) ((Unsafe.Coerce.unsafeCoerce) (v0)))
((Unsafe.Coerce.unsafeCoerce) (v1)))
((Unsafe.Coerce.unsafeCoerce) (v2)))
((Unsafe.Coerce.unsafeCoerce) (v3))))
where d_1_19 v0 (C3) v1 v2 = ((Unsafe.Coerce.unsafeCoerce) (v2))
d_1_19 v0 v1 v2 v3
= ((error)
("MAlonzo Runtime Error: incomplete pattern matching: Tutorial_notes.if_then_else_"))
name23 = ("Tutorial_notes.List")
d23 a0 = (())
data T23 a0 a1 = C25
| C26 a0 a1
name25 = ("Tutorial_notes.[]")
name26 = ("Tutorial_notes._::_")
name28 = ("Tutorial_notes.identity")
d28 v0 v1 = ((Unsafe.Coerce.unsafeCoerce) (v1))
name32 = ("Tutorial_notes.identity'")
d32 v0 v1 = ((Unsafe.Coerce.unsafeCoerce) (v1)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.