_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 |
|---|---|---|---|---|---|---|---|---|
8c67351b3316fdf7f7e95d1d6ddf64589750a85864ae2dd598f9a4da8ab5160f | travelping/ergw_aaa | ergw_aaa_static.erl | Copyright 2016 - 2019 Travelping GmbH < >
%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version
2 of the License , or ( at your option ) any later version .
-module(ergw_aaa_static).
-behaviour(ergw_aaa).
AAA API
-export([validate_handler/1, validate_service/3, validate_procedure/5,
initialize_handler/1, initialize_service/2, invoke/6, handle_response/6]).
-export([get_state_atom/1]).
-import(ergw_aaa_session, [to_session/1]).
-include_lib("kernel/include/logger.hrl").
-include_lib("diameter/include/diameter.hrl").
-include_lib("diameter/include/diameter_gen_base_rfc6733.hrl").
-define(OptKeys, [answer, answers]).
%%===================================================================
%% API
%%===================================================================
initialize_handler(_Opts) ->
{ok, []}.
initialize_service(_ServiceId, _Opts) ->
{ok, []}.
validate_handler(Opts) ->
ergw_aaa_config:validate_options(fun validate_option/2, Opts, []).
validate_service(_Service, HandlerOpts, Opts) ->
ergw_aaa_config:validate_options(fun validate_option/2, Opts, HandlerOpts).
validate_procedure(_Application, _Procedure, _Service, ServiceOpts, Opts) ->
ergw_aaa_config:validate_options(fun validate_option/2, Opts, ServiceOpts).
invoke(_Service, Procedure, Session, Events, #{answers := Answers, answer := Answer}, State) ->
AVPs =
case Answers of
#{Answer := #{avps := A}} -> A;
_ -> #{}
end,
handle_response(Procedure, AVPs, Session, Events, State);
invoke(_Service, _Procedure, Session, Events, Opts, State) ->
SOpts = maps:get(defaults, Opts, #{}),
{ok, maps:merge(Session, SOpts), Events, State}.
%% handle_response/6
handle_response(_Promise, _Msg, Session, Events, _Opts, State) ->
{ok, Session, Events, State}.
%%%===================================================================
%%% Options Validation
%%%===================================================================
-define(is_opts(X), (is_list(X) orelse is_map(X))).
validate_option(handler, Value) ->
Value;
validate_option(service, Value) ->
Value;
validate_option(answers, Value) when is_map(Value) ->
ergw_aaa_config:validate_answers(Value);
validate_option(answer, Value) ->
Value;
validate_option(defaults, Opts) when ?is_opts(Opts) ->
ergw_aaa_config:validate_options(fun validate_session_default/2, Opts, []);
validate_option(Opt, Value) ->
erlang:error(badarg, [Opt, Value]).
validate_session_default(Opt, Value) when is_atom(Opt) ->
Value;
validate_session_default(Opt, Value) ->
erlang:error(badarg, [Opt, Value]).
%%===================================================================
%% internal helpers
%%===================================================================
%% to_session/3
to_session({rf, _} = Procedure, SessEvs, Avps) ->
ergw_aaa_rf:to_session(Procedure, SessEvs, Avps);
to_session({gx, _} = Procedure, SessEvs, Avps) ->
ergw_aaa_gx:to_session(Procedure, SessEvs, Avps);
to_session({gy, _} = Procedure, SessEvs, Avps) ->
ergw_aaa_ro:to_session(Procedure, SessEvs, Avps);
to_session(Procedure, SessEvs, #{handler := Handler} = Avps) ->
Handler:to_session(Procedure, SessEvs, maps:remove(handler, Avps));
to_session(_Procedure, {Session, Events}, Avps) ->
{maps:merge(Session, Avps), Events}.
handle_response(Procedure, #{'Result-Code' := Code} = Avps,
Session0, Events0, State)
when Code < 3000 ->
{Session, Events} = to_session(Procedure, {Session0, Events0}, Avps),
{ok, Session, Events, State};
handle_response({API, _}, #{'Result-Code' := Code}, Session, Events, State) ->
{{fail, Code}, Session, [{stop, {API, peer_reject}} | Events], State};
handle_response(Procedure, #{'Result-Code' := Code}, Session, Events, State) ->
{{fail, Code}, Session, [{stop, {Procedure, peer_reject}} | Events], State};
handle_response(_Procedure, Response, Session, Events, State) ->
?LOG(error, "Response: ~p", [Response]),
{Response, Session, Events, State}.
get_state_atom(_) ->
stopped.
| null | https://raw.githubusercontent.com/travelping/ergw_aaa/d52e29ac6abeff2fa6e7f3dd634a1efc3fdeb499/src/ergw_aaa_static.erl | erlang | This program is free software; you can redistribute it and/or
===================================================================
API
===================================================================
handle_response/6
===================================================================
Options Validation
===================================================================
===================================================================
internal helpers
===================================================================
to_session/3 | Copyright 2016 - 2019 Travelping GmbH < >
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation ; either version
2 of the License , or ( at your option ) any later version .
-module(ergw_aaa_static).
-behaviour(ergw_aaa).
AAA API
-export([validate_handler/1, validate_service/3, validate_procedure/5,
initialize_handler/1, initialize_service/2, invoke/6, handle_response/6]).
-export([get_state_atom/1]).
-import(ergw_aaa_session, [to_session/1]).
-include_lib("kernel/include/logger.hrl").
-include_lib("diameter/include/diameter.hrl").
-include_lib("diameter/include/diameter_gen_base_rfc6733.hrl").
-define(OptKeys, [answer, answers]).
initialize_handler(_Opts) ->
{ok, []}.
initialize_service(_ServiceId, _Opts) ->
{ok, []}.
validate_handler(Opts) ->
ergw_aaa_config:validate_options(fun validate_option/2, Opts, []).
validate_service(_Service, HandlerOpts, Opts) ->
ergw_aaa_config:validate_options(fun validate_option/2, Opts, HandlerOpts).
validate_procedure(_Application, _Procedure, _Service, ServiceOpts, Opts) ->
ergw_aaa_config:validate_options(fun validate_option/2, Opts, ServiceOpts).
invoke(_Service, Procedure, Session, Events, #{answers := Answers, answer := Answer}, State) ->
AVPs =
case Answers of
#{Answer := #{avps := A}} -> A;
_ -> #{}
end,
handle_response(Procedure, AVPs, Session, Events, State);
invoke(_Service, _Procedure, Session, Events, Opts, State) ->
SOpts = maps:get(defaults, Opts, #{}),
{ok, maps:merge(Session, SOpts), Events, State}.
handle_response(_Promise, _Msg, Session, Events, _Opts, State) ->
{ok, Session, Events, State}.
-define(is_opts(X), (is_list(X) orelse is_map(X))).
validate_option(handler, Value) ->
Value;
validate_option(service, Value) ->
Value;
validate_option(answers, Value) when is_map(Value) ->
ergw_aaa_config:validate_answers(Value);
validate_option(answer, Value) ->
Value;
validate_option(defaults, Opts) when ?is_opts(Opts) ->
ergw_aaa_config:validate_options(fun validate_session_default/2, Opts, []);
validate_option(Opt, Value) ->
erlang:error(badarg, [Opt, Value]).
validate_session_default(Opt, Value) when is_atom(Opt) ->
Value;
validate_session_default(Opt, Value) ->
erlang:error(badarg, [Opt, Value]).
to_session({rf, _} = Procedure, SessEvs, Avps) ->
ergw_aaa_rf:to_session(Procedure, SessEvs, Avps);
to_session({gx, _} = Procedure, SessEvs, Avps) ->
ergw_aaa_gx:to_session(Procedure, SessEvs, Avps);
to_session({gy, _} = Procedure, SessEvs, Avps) ->
ergw_aaa_ro:to_session(Procedure, SessEvs, Avps);
to_session(Procedure, SessEvs, #{handler := Handler} = Avps) ->
Handler:to_session(Procedure, SessEvs, maps:remove(handler, Avps));
to_session(_Procedure, {Session, Events}, Avps) ->
{maps:merge(Session, Avps), Events}.
handle_response(Procedure, #{'Result-Code' := Code} = Avps,
Session0, Events0, State)
when Code < 3000 ->
{Session, Events} = to_session(Procedure, {Session0, Events0}, Avps),
{ok, Session, Events, State};
handle_response({API, _}, #{'Result-Code' := Code}, Session, Events, State) ->
{{fail, Code}, Session, [{stop, {API, peer_reject}} | Events], State};
handle_response(Procedure, #{'Result-Code' := Code}, Session, Events, State) ->
{{fail, Code}, Session, [{stop, {Procedure, peer_reject}} | Events], State};
handle_response(_Procedure, Response, Session, Events, State) ->
?LOG(error, "Response: ~p", [Response]),
{Response, Session, Events, State}.
get_state_atom(_) ->
stopped.
|
a9dcbe7a191cf163e62b2dbc705dba2c062aa8725796035d7b42a26e95fc4cac | bsaleil/lc | nucleic.scm.scm | ;;------------------------------------------------------------------------------
Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
;;------------------------------------------------------------------------------
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(##print-perm-string "CPU time: ")
(##print-double (+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(##print-perm-string "\n")
(##print-perm-string "GC CPU time: ")
(##print-double (+ (cdr (assoc "GC user time" (cdr r)))
(cdr (assoc "GC sys time" (cdr r)))))
(##print-perm-string "\n")
(map (lambda (el)
(##print-perm-string (car el))
(##print-perm-string ": ")
(##print-double (cdr el))
(##print-perm-string "\n"))
(cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (##process-statistics))
(result (thunk))
(at-end (##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (f64vector-ref at-end idx)
(f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
;;------------------------------------------------------------------------------
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
; Gabriel benchmarks
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
; C benchmarks
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
; Other benchmarks
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
(define nbody-iters 1)
(define fftrad4-iters 4)
NUCLEIC -- 3D structure determination of a nucleic acid .
Author : ( )
;
Last modified : January 27 , 1996
;
; This program is a modified version of the program described in the paper:
;
, , , " Using Multilisp for Solving
; Constraint Satisfaction Problems: an Application to Nucleic Acid 3D
Structure Determination " published in the journal " Lisp and Symbolic
; Computation".
;
; The differences between this program and the original are described in
; the paper:
;
" ? ? ? " published in the " Journal of Functional Programming " .
; -- MATH UTILITIES -----------------------------------------------------------
(define constant-pi 3.14159265358979323846)
(define constant-minus-pi -3.14159265358979323846)
(define constant-pi/2 1.57079632679489661923)
(define constant-minus-pi/2 -1.57079632679489661923)
(define (math-atan2 y x)
(cond ((FLOAT> x 0.0)
(FLOATatan (FLOAT/ y x)))
((FLOAT< y 0.0)
(if (FLOAT= x 0.0)
constant-minus-pi/2
(FLOAT+ (FLOATatan (FLOAT/ y x)) constant-minus-pi)))
(else
(if (FLOAT= x 0.0)
constant-pi/2
(FLOAT+ (FLOATatan (FLOAT/ y x)) constant-pi)))))
; -- POINTS -------------------------------------------------------------------
(define (make-pt x y z)
(FLOATvector x y z))
(define (pt-x pt) (FLOATvector-ref pt 0))
(define (pt-x-set! pt val) (FLOATvector-set! pt 0 val))
(define (pt-y pt) (FLOATvector-ref pt 1))
(define (pt-y-set! pt val) (FLOATvector-set! pt 1 val))
(define (pt-z pt) (FLOATvector-ref pt 2))
(define (pt-z-set! pt val) (FLOATvector-set! pt 2 val))
(define (pt-sub p1 p2)
(make-pt (FLOAT- (pt-x p1) (pt-x p2))
(FLOAT- (pt-y p1) (pt-y p2))
(FLOAT- (pt-z p1) (pt-z p2))))
(define (pt-dist p1 p2)
(let ((dx (FLOAT- (pt-x p1) (pt-x p2)))
(dy (FLOAT- (pt-y p1) (pt-y p2)))
(dz (FLOAT- (pt-z p1) (pt-z p2))))
(FLOATsqrt (FLOAT+ (FLOAT* dx dx) (FLOAT* dy dy) (FLOAT* dz dz)))))
(define (pt-phi p)
(let* ((x (pt-x p))
(y (pt-y p))
(z (pt-z p))
(b (math-atan2 x z)))
(math-atan2 (FLOAT+ (FLOAT* (FLOATcos b) z) (FLOAT* (FLOATsin b) x)) y)))
(define (pt-theta p)
(math-atan2 (pt-x p) (pt-z p)))
; -- COORDINATE TRANSFORMATIONS -----------------------------------------------
The notation for the transformations follows " , R.P. ( 1981 ) Robot
Manipulators . MIT Press . " with the exception that our transformation
; matrices don't have the perspective terms and are the transpose of
's one . See also " M\"antyl\"a , M. ( 1985 ) An Introduction to
Solid Modeling , Computer Science Press " Appendix A.
;
; The components of a transformation matrix are named like this:
;
; a b c
; d e f
; tx ty tz
;
The components tx , ty , and tz are the translation vector .
(define (make-tfo a b c d e f g h i tx ty tz)
(FLOATvector a b c d e f g h i tx ty tz))
(define (tfo-a tfo) (FLOATvector-ref tfo 0))
(define (tfo-a-set! tfo val) (FLOATvector-set! tfo 0 val))
(define (tfo-b tfo) (FLOATvector-ref tfo 1))
(define (tfo-b-set! tfo val) (FLOATvector-set! tfo 1 val))
(define (tfo-c tfo) (FLOATvector-ref tfo 2))
(define (tfo-c-set! tfo val) (FLOATvector-set! tfo 2 val))
(define (tfo-d tfo) (FLOATvector-ref tfo 3))
(define (tfo-d-set! tfo val) (FLOATvector-set! tfo 3 val))
(define (tfo-e tfo) (FLOATvector-ref tfo 4))
(define (tfo-e-set! tfo val) (FLOATvector-set! tfo 4 val))
(define (tfo-f tfo) (FLOATvector-ref tfo 5))
(define (tfo-f-set! tfo val) (FLOATvector-set! tfo 5 val))
(define (tfo-g tfo) (FLOATvector-ref tfo 6))
(define (tfo-g-set! tfo val) (FLOATvector-set! tfo 6 val))
(define (tfo-h tfo) (FLOATvector-ref tfo 7))
(define (tfo-h-set! tfo val) (FLOATvector-set! tfo 7 val))
(define (tfo-i tfo) (FLOATvector-ref tfo 8))
(define (tfo-i-set! tfo val) (FLOATvector-set! tfo 8 val))
(define (tfo-tx tfo) (FLOATvector-ref tfo 9))
(define (tfo-tx-set! tfo val) (FLOATvector-set! tfo 9 val))
(define (tfo-ty tfo) (FLOATvector-ref tfo 10))
(define (tfo-ty-set! tfo val) (FLOATvector-set! tfo 10 val))
(define (tfo-tz tfo) (FLOATvector-ref tfo 11))
(define (tfo-tz-set! tfo val) (FLOATvector-set! tfo 11 val))
(define tfo-id ; the identity transformation matrix
(FLOATvector-const
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
0.0 0.0 0.0))
; The function "tfo-apply" multiplies a transformation matrix, tfo, by a
; point vector, p. The result is a new point.
(define (tfo-apply tfo p)
(let ((x (pt-x p))
(y (pt-y p))
(z (pt-z p)))
(make-pt
(FLOAT+ (FLOAT* x (tfo-a tfo))
(FLOAT* y (tfo-d tfo))
(FLOAT* z (tfo-g tfo))
(tfo-tx tfo))
(FLOAT+ (FLOAT* x (tfo-b tfo))
(FLOAT* y (tfo-e tfo))
(FLOAT* z (tfo-h tfo))
(tfo-ty tfo))
(FLOAT+ (FLOAT* x (tfo-c tfo))
(FLOAT* y (tfo-f tfo))
(FLOAT* z (tfo-i tfo))
(tfo-tz tfo)))))
The function " tfo - combine " multiplies two transformation matrices A and B.
; The result is a new matrix which cumulates the transformations described
; by A and B.
(define (tfo-combine A B)
(make-tfo
(FLOAT+ (FLOAT* (tfo-a A) (tfo-a B))
(FLOAT* (tfo-b A) (tfo-d B))
(FLOAT* (tfo-c A) (tfo-g B)))
(FLOAT+ (FLOAT* (tfo-a A) (tfo-b B))
(FLOAT* (tfo-b A) (tfo-e B))
(FLOAT* (tfo-c A) (tfo-h B)))
(FLOAT+ (FLOAT* (tfo-a A) (tfo-c B))
(FLOAT* (tfo-b A) (tfo-f B))
(FLOAT* (tfo-c A) (tfo-i B)))
(FLOAT+ (FLOAT* (tfo-d A) (tfo-a B))
(FLOAT* (tfo-e A) (tfo-d B))
(FLOAT* (tfo-f A) (tfo-g B)))
(FLOAT+ (FLOAT* (tfo-d A) (tfo-b B))
(FLOAT* (tfo-e A) (tfo-e B))
(FLOAT* (tfo-f A) (tfo-h B)))
(FLOAT+ (FLOAT* (tfo-d A) (tfo-c B))
(FLOAT* (tfo-e A) (tfo-f B))
(FLOAT* (tfo-f A) (tfo-i B)))
(FLOAT+ (FLOAT* (tfo-g A) (tfo-a B))
(FLOAT* (tfo-h A) (tfo-d B))
(FLOAT* (tfo-i A) (tfo-g B)))
(FLOAT+ (FLOAT* (tfo-g A) (tfo-b B))
(FLOAT* (tfo-h A) (tfo-e B))
(FLOAT* (tfo-i A) (tfo-h B)))
(FLOAT+ (FLOAT* (tfo-g A) (tfo-c B))
(FLOAT* (tfo-h A) (tfo-f B))
(FLOAT* (tfo-i A) (tfo-i B)))
(FLOAT+ (FLOAT* (tfo-tx A) (tfo-a B))
(FLOAT* (tfo-ty A) (tfo-d B))
(FLOAT* (tfo-tz A) (tfo-g B))
(tfo-tx B))
(FLOAT+ (FLOAT* (tfo-tx A) (tfo-b B))
(FLOAT* (tfo-ty A) (tfo-e B))
(FLOAT* (tfo-tz A) (tfo-h B))
(tfo-ty B))
(FLOAT+ (FLOAT* (tfo-tx A) (tfo-c B))
(FLOAT* (tfo-ty A) (tfo-f B))
(FLOAT* (tfo-tz A) (tfo-i B))
(tfo-tz B))))
; The function "tfo-inv-ortho" computes the inverse of a homogeneous
; transformation matrix.
(define (tfo-inv-ortho tfo)
(let* ((tx (tfo-tx tfo))
(ty (tfo-ty tfo))
(tz (tfo-tz tfo)))
(make-tfo
(tfo-a tfo) (tfo-d tfo) (tfo-g tfo)
(tfo-b tfo) (tfo-e tfo) (tfo-h tfo)
(tfo-c tfo) (tfo-f tfo) (tfo-i tfo)
(FLOAT- (FLOAT+ (FLOAT* (tfo-a tfo) tx)
(FLOAT* (tfo-b tfo) ty)
(FLOAT* (tfo-c tfo) tz)))
(FLOAT- (FLOAT+ (FLOAT* (tfo-d tfo) tx)
(FLOAT* (tfo-e tfo) ty)
(FLOAT* (tfo-f tfo) tz)))
(FLOAT- (FLOAT+ (FLOAT* (tfo-g tfo) tx)
(FLOAT* (tfo-h tfo) ty)
(FLOAT* (tfo-i tfo) tz))))))
Given three points p1 , p2 , and p3 , the function " tfo - align " computes
a transformation matrix such that point p1 gets mapped to ( 0,0,0 ) , p2 gets
; mapped to the Y axis and p3 gets mapped to the YZ plane.
(define (tfo-align p1 p2 p3)
(let* ((x1 (pt-x p1)) (y1 (pt-y p1)) (z1 (pt-z p1))
(x3 (pt-x p3)) (y3 (pt-y p3)) (z3 (pt-z p3))
(x31 (FLOAT- x3 x1)) (y31 (FLOAT- y3 y1)) (z31 (FLOAT- z3 z1))
(rotpY (pt-sub p2 p1))
(Phi (pt-phi rotpY))
(Theta (pt-theta rotpY))
(sinP (FLOATsin Phi))
(sinT (FLOATsin Theta))
(cosP (FLOATcos Phi))
(cosT (FLOATcos Theta))
(sinPsinT (FLOAT* sinP sinT))
(sinPcosT (FLOAT* sinP cosT))
(cosPsinT (FLOAT* cosP sinT))
(cosPcosT (FLOAT* cosP cosT))
(rotpZ
(make-pt
(FLOAT- (FLOAT* cosT x31)
(FLOAT* sinT z31))
(FLOAT+ (FLOAT* sinPsinT x31)
(FLOAT* cosP y31)
(FLOAT* sinPcosT z31))
(FLOAT+ (FLOAT* cosPsinT x31)
(FLOAT- (FLOAT* sinP y31))
(FLOAT* cosPcosT z31))))
(Rho (pt-theta rotpZ))
(cosR (FLOATcos Rho))
(sinR (FLOATsin Rho))
(x (FLOAT+ (FLOAT- (FLOAT* x1 cosT))
(FLOAT* z1 sinT)))
(y (FLOAT- (FLOAT- (FLOAT- (FLOAT* x1 sinPsinT))
(FLOAT* y1 cosP))
(FLOAT* z1 sinPcosT)))
(z (FLOAT- (FLOAT+ (FLOAT- (FLOAT* x1 cosPsinT))
(FLOAT* y1 sinP))
(FLOAT* z1 cosPcosT))))
(make-tfo
(FLOAT- (FLOAT* cosT cosR) (FLOAT* cosPsinT sinR))
sinPsinT
(FLOAT+ (FLOAT* cosT sinR) (FLOAT* cosPsinT cosR))
(FLOAT* sinP sinR)
cosP
(FLOAT- (FLOAT* sinP cosR))
(FLOAT- (FLOAT- (FLOAT* sinT cosR)) (FLOAT* cosPcosT sinR))
sinPcosT
(FLOAT+ (FLOAT- (FLOAT* sinT sinR)) (FLOAT* cosPcosT cosR))
(FLOAT- (FLOAT* x cosR) (FLOAT* z sinR))
y
(FLOAT+ (FLOAT* x sinR) (FLOAT* z cosR)))))
; -- NUCLEIC ACID CONFORMATIONS DATA BASE -------------------------------------
; Numbering of atoms follows the paper:
;
IUPAC - IUB Joint Commission on Biochemical Nomenclature ( JCBN )
( 1983 ) Abbreviations and Symbols for the Description of
Conformations of Polynucleotide Chains . Eur . J. Biochem 131 ,
9 - 15 .
;
; In the atom names, we have used "*" instead of "'".
Define part common to all 4 nucleotide types .
(define (nuc-dgf-base-tfo nuc) (vector-ref nuc 0))
(define (nuc-dgf-base-tfo-set! nuc val) (vector-set! nuc 0 val))
(define (nuc-P-O3*-275-tfo nuc) (vector-ref nuc 1))
(define (nuc-P-O3*-275-tfo-set! nuc val) (vector-set! nuc 1 val))
(define (nuc-P-O3*-180-tfo nuc) (vector-ref nuc 2))
(define (nuc-P-O3*-180-tfo-set! nuc val) (vector-set! nuc 2 val))
(define (nuc-P-O3*-60-tfo nuc) (vector-ref nuc 3))
(define (nuc-P-O3*-60-tfo-set! nuc val) (vector-set! nuc 3 val))
(define (nuc-P nuc) (vector-ref nuc 4))
(define (nuc-P-set! nuc val) (vector-set! nuc 4 val))
(define (nuc-O1P nuc) (vector-ref nuc 5))
(define (nuc-O1P-set! nuc val) (vector-set! nuc 5 val))
(define (nuc-O2P nuc) (vector-ref nuc 6))
(define (nuc-O2P-set! nuc val) (vector-set! nuc 6 val))
(define (nuc-O5* nuc) (vector-ref nuc 7))
(define (nuc-O5*-set! nuc val) (vector-set! nuc 7 val))
(define (nuc-C5* nuc) (vector-ref nuc 8))
(define (nuc-C5*-set! nuc val) (vector-set! nuc 8 val))
(define (nuc-H5* nuc) (vector-ref nuc 9))
(define (nuc-H5*-set! nuc val) (vector-set! nuc 9 val))
(define (nuc-H5** nuc) (vector-ref nuc 10))
(define (nuc-H5**-set! nuc val) (vector-set! nuc 10 val))
(define (nuc-C4* nuc) (vector-ref nuc 11))
(define (nuc-C4*-set! nuc val) (vector-set! nuc 11 val))
(define (nuc-H4* nuc) (vector-ref nuc 12))
(define (nuc-H4*-set! nuc val) (vector-set! nuc 12 val))
(define (nuc-O4* nuc) (vector-ref nuc 13))
(define (nuc-O4*-set! nuc val) (vector-set! nuc 13 val))
(define (nuc-C1* nuc) (vector-ref nuc 14))
(define (nuc-C1*-set! nuc val) (vector-set! nuc 14 val))
(define (nuc-H1* nuc) (vector-ref nuc 15))
(define (nuc-H1*-set! nuc val) (vector-set! nuc 15 val))
(define (nuc-C2* nuc) (vector-ref nuc 16))
(define (nuc-C2*-set! nuc val) (vector-set! nuc 16 val))
(define (nuc-H2** nuc) (vector-ref nuc 17))
(define (nuc-H2**-set! nuc val) (vector-set! nuc 17 val))
(define (nuc-O2* nuc) (vector-ref nuc 18))
(define (nuc-O2*-set! nuc val) (vector-set! nuc 18 val))
(define (nuc-H2* nuc) (vector-ref nuc 19))
(define (nuc-H2*-set! nuc val) (vector-set! nuc 19 val))
(define (nuc-C3* nuc) (vector-ref nuc 20))
(define (nuc-C3*-set! nuc val) (vector-set! nuc 20 val))
(define (nuc-H3* nuc) (vector-ref nuc 21))
(define (nuc-H3*-set! nuc val) (vector-set! nuc 21 val))
(define (nuc-O3* nuc) (vector-ref nuc 22))
(define (nuc-O3*-set! nuc val) (vector-set! nuc 22 val))
(define (nuc-N1 nuc) (vector-ref nuc 23))
(define (nuc-N1-set! nuc val) (vector-set! nuc 23 val))
(define (nuc-N3 nuc) (vector-ref nuc 24))
(define (nuc-N3-set! nuc val) (vector-set! nuc 24 val))
(define (nuc-C2 nuc) (vector-ref nuc 25))
(define (nuc-C2-set! nuc val) (vector-set! nuc 25 val))
(define (nuc-C4 nuc) (vector-ref nuc 26))
(define (nuc-C4-set! nuc val) (vector-set! nuc 26 val))
(define (nuc-C5 nuc) (vector-ref nuc 27))
(define (nuc-C5-set! nuc val) (vector-set! nuc 27 val))
(define (nuc-C6 nuc) (vector-ref nuc 28))
(define (nuc-C6-set! nuc val) (vector-set! nuc 28 val))
; Define remaining atoms for each nucleotide type.
(define (make-rA dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
N6 N7 N9 C8 H2 H61 H62 H8)
(vector dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
'rA N6 N7 N9 C8 H2 H61 H62 H8))
(define (rA? nuc) (eq? (vector-ref nuc 29) 'rA))
(define (rA-N6 nuc) (vector-ref nuc 30))
(define (rA-N6-set! nuc val) (vector-set! nuc 30 val))
(define (rA-N7 nuc) (vector-ref nuc 31))
(define (rA-N7-set! nuc val) (vector-set! nuc 31 val))
(define (rA-N9 nuc) (vector-ref nuc 32))
(define (rA-N9-set! nuc val) (vector-set! nuc 32 val))
(define (rA-C8 nuc) (vector-ref nuc 33))
(define (rA-C8-set! nuc val) (vector-set! nuc 33 val))
(define (rA-H2 nuc) (vector-ref nuc 34))
(define (rA-H2-set! nuc val) (vector-set! nuc 34 val))
(define (rA-H61 nuc) (vector-ref nuc 35))
(define (rA-H61-set! nuc val) (vector-set! nuc 35 val))
(define (rA-H62 nuc) (vector-ref nuc 36))
(define (rA-H62-set! nuc val) (vector-set! nuc 36 val))
(define (rA-H8 nuc) (vector-ref nuc 37))
(define (rA-H8-set! nuc val) (vector-set! nuc 37 val))
(define (make-rC dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
N4 O2 H41 H42 H5 H6)
(vector dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
'rC N4 O2 H41 H42 H5 H6))
(define (rC? nuc) (eq? (vector-ref nuc 29) 'rC))
(define (rC-N4 nuc) (vector-ref nuc 30))
(define (rC-N4-set! nuc val) (vector-set! nuc 30 val))
(define (rC-O2 nuc) (vector-ref nuc 31))
(define (rC-O2-set! nuc val) (vector-set! nuc 31 val))
(define (rC-H41 nuc) (vector-ref nuc 32))
(define (rC-H41-set! nuc val) (vector-set! nuc 32 val))
(define (rC-H42 nuc) (vector-ref nuc 33))
(define (rC-H42-set! nuc val) (vector-set! nuc 33 val))
(define (rC-H5 nuc) (vector-ref nuc 34))
(define (rC-H5-set! nuc val) (vector-set! nuc 34 val))
(define (rC-H6 nuc) (vector-ref nuc 35))
(define (rC-H6-set! nuc val) (vector-set! nuc 35 val))
(define (make-rG dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
N2 N7 N9 C8 O6 H1 H21 H22 H8)
(vector dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
'rG N2 N7 N9 C8 O6 H1 H21 H22 H8))
(define (rG? nuc) (eq? (vector-ref nuc 29) 'rG))
(define (rG-N2 nuc) (vector-ref nuc 30))
(define (rG-N2-set! nuc val) (vector-set! nuc 30 val))
(define (rG-N7 nuc) (vector-ref nuc 31))
(define (rG-N7-set! nuc val) (vector-set! nuc 31 val))
(define (rG-N9 nuc) (vector-ref nuc 32))
(define (rG-N9-set! nuc val) (vector-set! nuc 32 val))
(define (rG-C8 nuc) (vector-ref nuc 33))
(define (rG-C8-set! nuc val) (vector-set! nuc 33 val))
(define (rG-O6 nuc) (vector-ref nuc 34))
(define (rG-O6-set! nuc val) (vector-set! nuc 34 val))
(define (rG-H1 nuc) (vector-ref nuc 35))
(define (rG-H1-set! nuc val) (vector-set! nuc 35 val))
(define (rG-H21 nuc) (vector-ref nuc 36))
(define (rG-H21-set! nuc val) (vector-set! nuc 36 val))
(define (rG-H22 nuc) (vector-ref nuc 37))
(define (rG-H22-set! nuc val) (vector-set! nuc 37 val))
(define (rG-H8 nuc) (vector-ref nuc 38))
(define (rG-H8-set! nuc val) (vector-set! nuc 38 val))
(define (make-rU dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
O2 O4 H3 H5 H6)
(vector dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
'rU O2 O4 H3 H5 H6))
(define (rU? nuc) (eq? (vector-ref nuc 29) 'rU))
(define (rU-O2 nuc) (vector-ref nuc 30))
(define (rU-O2-set! nuc val) (vector-set! nuc 30 val))
(define (rU-O4 nuc) (vector-ref nuc 31))
(define (rU-O4-set! nuc val) (vector-set! nuc 31 val))
(define (rU-H3 nuc) (vector-ref nuc 32))
(define (rU-H3-set! nuc val) (vector-set! nuc 32 val))
(define (rU-H5 nuc) (vector-ref nuc 33))
(define (rU-H5-set! nuc val) (vector-set! nuc 33 val))
(define (rU-H6 nuc) (vector-ref nuc 34))
(define (rU-H6-set! nuc val) (vector-set! nuc 34 val))
; Database of nucleotide conformations:
(define rA
(nuc-const
#( -0.0018 -0.8207 0.5714 ; dgf-base-tfo
0.2679 -0.5509 -0.7904
0.9634 0.1517 0.2209
0.0073 8.4030 0.6232)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 5.4550 8.2120 -2.8810) ; C5*
#( 5.4546 8.8508 -1.9978) ; H5*
#( 5.7588 8.6625 -3.8259) ; H5**
#( 6.4970 7.1480 -2.5980) ; C4*
#( 7.4896 7.5919 -2.5214) ; H4*
#( 6.1630 6.4860 -1.3440) ; O4*
#( 6.5400 5.1200 -1.4190) ; C1*
#( 7.2763 4.9681 -0.6297) ; H1*
#( 7.1940 4.8830 -2.7770) ; C2*
#( 6.8667 3.9183 -3.1647) ; H2**
#( 8.5860 5.0910 -2.6140) ; O2*
#( 8.9510 4.7626 -1.7890) ; H2*
#( 6.5720 6.0040 -3.6090) ; C3*
#( 5.5636 5.7066 -3.8966) ; H3*
#( 7.3801 6.3562 -4.7350) ; O3*
#( 4.7150 0.4910 -0.1360) ; N1
N3
C2
#( 5.2900 2.9790 -0.8260) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 6.6890 0.1903 -0.0518) ; H2
H61
#( 2.2780 -0.1080 -0.0280) ; H62
H8
))
(define rA01
(nuc-const
#( -0.0043 -0.8175 0.5759 ; dgf-base-tfo
0.2617 -0.5567 -0.7884
0.9651 0.1473 0.2164
0.0359 8.3929 0.5532)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 5.4352 8.2183 -2.7757) ; C5*
#( 5.3830 8.7883 -1.8481) ; H5*
#( 5.7729 8.7436 -3.6691) ; H5**
#( 6.4830 7.1518 -2.5252) ; C4*
#( 7.4749 7.5972 -2.4482) ; H4*
#( 6.1626 6.4620 -1.2827) ; O4*
#( 6.5431 5.0992 -1.3905) ; C1*
#( 7.2871 4.9328 -0.6114) ; H1*
#( 7.1852 4.8935 -2.7592) ; C2*
#( 6.8573 3.9363 -3.1645) ; H2**
#( 8.5780 5.1025 -2.6046) ; O2*
#( 8.9516 4.7577 -1.7902) ; H2*
#( 6.5522 6.0300 -3.5612) ; C3*
#( 5.5420 5.7356 -3.8459) ; H3*
#( 7.3487 6.4089 -4.6867) ; O3*
#( 4.7442 0.4514 -0.1390) ; N1
N3
C2
#( 5.3052 2.9471 -0.8125) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 6.7198 0.1618 -0.0547) ; H2
H61
#( 2.3107 -0.1627 -0.0373) ; H62
H8
))
(define rA02
(nuc-const
#( 0.5566 0.0449 0.8296 ; dgf-base-tfo
0.5125 0.7673 -0.3854
-0.6538 0.6397 0.4041
-9.1161 -3.7679 -2.9968)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 4.5778 6.6594 -4.0364) ; C5*
#( 4.9220 7.1963 -4.9204) ; H5*
#( 3.7996 5.9091 -4.1764) ; H5**
#( 5.7873 5.8869 -3.5482) ; C4*
#( 6.0405 5.0875 -4.2446) ; H4*
#( 6.9135 6.8036 -3.4310) ; O4*
#( 7.7293 6.4084 -2.3392) ; C1*
#( 8.7078 6.1815 -2.7624) ; H1*
#( 7.1305 5.1418 -1.7347) ; C2*
#( 7.2040 5.1982 -0.6486) ; H2**
#( 7.7417 4.0392 -2.3813) ; O2*
#( 8.6785 4.1443 -2.5630) ; H2*
#( 5.6666 5.2728 -2.1536) ; C3*
#( 5.1747 5.9805 -1.4863) ; H3*
#( 4.9997 4.0086 -2.1973) ; O3*
#( 10.3245 8.5459 1.5467) ; N1
N3
C2
#( 8.7523 7.7422 -0.4228) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 11.4063 6.9047 1.1859) ; H2
H61
#( 9.6584 10.6647 2.7198) ; H62
H8
))
(define rA03
(nuc-const
#( -0.5021 0.0731 0.8617 ; dgf-base-tfo
-0.8112 0.3054 -0.4986
-0.2996 -0.9494 -0.0940
6.4273 -5.1944 -3.7807)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 4.1214 6.7116 -1.9049) ; C5*
#( 3.3465 5.9610 -2.0607) ; H5*
#( 4.0789 7.2928 -0.9837) ; H5**
#( 5.4170 5.9293 -1.8186) ; C4*
#( 5.4506 5.3400 -0.9023) ; H4*
#( 5.5067 5.0417 -2.9703) ; O4*
#( 6.8650 4.9152 -3.3612) ; C1*
#( 7.1090 3.8577 -3.2603) ; H1*
#( 7.7152 5.7282 -2.3894) ; C2*
#( 8.5029 6.2356 -2.9463) ; H2**
#( 8.1036 4.8568 -1.3419) ; O2*
#( 8.3270 3.9651 -1.6184) ; H2*
#( 6.7003 6.7565 -1.8911) ; C3*
#( 6.5898 7.5329 -2.6482) ; H3*
#( 7.0505 7.2878 -0.6105) ; O3*
#( 9.6740 4.7656 -7.6614) ; N1
N3
C2
#( 7.9885 5.0632 -5.6446) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 10.7627 3.6375 -6.4220) ; H2
H61
#( 9.1004 5.9708 -9.7893) ; H62
H8
))
(define rA04
(nuc-const
#( -0.5426 -0.8175 0.1929 ; dgf-base-tfo
0.8304 -0.5567 -0.0237
0.1267 0.1473 0.9809
-0.5075 8.3929 0.2229)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 5.4352 8.2183 -2.7757) ; C5*
#( 5.3830 8.7883 -1.8481) ; H5*
#( 5.7729 8.7436 -3.6691) ; H5**
#( 6.4830 7.1518 -2.5252) ; C4*
#( 7.4749 7.5972 -2.4482) ; H4*
#( 6.1626 6.4620 -1.2827) ; O4*
#( 6.5431 5.0992 -1.3905) ; C1*
#( 7.2871 4.9328 -0.6114) ; H1*
#( 7.1852 4.8935 -2.7592) ; C2*
#( 6.8573 3.9363 -3.1645) ; H2**
#( 8.5780 5.1025 -2.6046) ; O2*
#( 8.9516 4.7577 -1.7902) ; H2*
#( 6.5522 6.0300 -3.5612) ; C3*
#( 5.5420 5.7356 -3.8459) ; H3*
#( 7.3487 6.4089 -4.6867) ; O3*
#( 3.6343 2.6680 2.0783) ; N1
N3
C2
#( 4.8805 3.7951 0.0354) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 5.0814 3.4352 3.2234) ; H2
H61
#( 1.5716 1.3398 1.5392) ; H62
H8
))
(define rA05
(nuc-const
#( -0.5891 0.0449 0.8068 ; dgf-base-tfo
0.5375 0.7673 0.3498
-0.6034 0.6397 -0.4762
-0.3019 -3.7679 -9.5913)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 4.5778 6.6594 -4.0364) ; C5*
#( 4.9220 7.1963 -4.9204) ; H5*
#( 3.7996 5.9091 -4.1764) ; H5**
#( 5.7873 5.8869 -3.5482) ; C4*
#( 6.0405 5.0875 -4.2446) ; H4*
#( 6.9135 6.8036 -3.4310) ; O4*
#( 7.7293 6.4084 -2.3392) ; C1*
#( 8.7078 6.1815 -2.7624) ; H1*
#( 7.1305 5.1418 -1.7347) ; C2*
#( 7.2040 5.1982 -0.6486) ; H2**
#( 7.7417 4.0392 -2.3813) ; O2*
#( 8.6785 4.1443 -2.5630) ; H2*
#( 5.6666 5.2728 -2.1536) ; C3*
#( 5.1747 5.9805 -1.4863) ; H3*
#( 4.9997 4.0086 -2.1973) ; O3*
#( 10.2594 10.6774 -1.0056) ; N1
N3
C2
#( 8.7271 8.5575 -1.3991) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 11.3132 10.0537 -2.5851) ; H2
H61
#( 9.6733 12.1368 0.9529) ; H62
H8
))
(define rA06
(nuc-const
#( -0.9815 0.0731 -0.1772 ; dgf-base-tfo
0.1912 0.3054 -0.9328
-0.0141 -0.9494 -0.3137
5.7506 -5.1944 4.7470)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 4.1214 6.7116 -1.9049) ; C5*
#( 3.3465 5.9610 -2.0607) ; H5*
#( 4.0789 7.2928 -0.9837) ; H5**
#( 5.4170 5.9293 -1.8186) ; C4*
#( 5.4506 5.3400 -0.9023) ; H4*
#( 5.5067 5.0417 -2.9703) ; O4*
#( 6.8650 4.9152 -3.3612) ; C1*
#( 7.1090 3.8577 -3.2603) ; H1*
#( 7.7152 5.7282 -2.3894) ; C2*
#( 8.5029 6.2356 -2.9463) ; H2**
#( 8.1036 4.8568 -1.3419) ; O2*
#( 8.3270 3.9651 -1.6184) ; H2*
#( 6.7003 6.7565 -1.8911) ; C3*
#( 6.5898 7.5329 -2.6482) ; H3*
#( 7.0505 7.2878 -0.6105) ; O3*
#( 6.6624 3.5061 -8.2986) ; N1
N3
C2
#( 6.8364 4.5817 -5.8882) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 6.3146 1.7741 -7.3641) ; H2
H61
#( 7.0437 5.0478 -10.2446) ; H62
H8
))
(define rA07
(nuc-const
#( 0.2379 0.1310 -0.9624 ; dgf-base-tfo
-0.5876 -0.7696 -0.2499
-0.7734 0.6249 -0.1061
30.9870 -26.9344 42.6416)
#( 0.7529 0.1548 0.6397 ; P-O3*-275-tfo
0.2952 -0.9481 -0.1180
0.5882 0.2777 -0.7595
-58.8919 -11.3095 6.0866)
#( -0.0239 0.9667 -0.2546 ; P-O3*-180-tfo
0.9731 -0.0359 -0.2275
-0.2290 -0.2532 -0.9399
3.5401 -29.7913 52.2796)
#( -0.8912 -0.4531 0.0242 ; P-O3*-60-tfo
-0.1183 0.1805 -0.9764
0.4380 -0.8730 -0.2145
19.9023 54.8054 15.2799)
#( 41.8210 8.3880 43.5890) ; P
#( 42.5400 8.0450 44.8330) ; O1P
#( 42.2470 9.6920 42.9910) ; O2P
O5 *
#( 39.3505 8.4697 42.6565) ; C5*
#( 39.1377 7.5433 42.1230) ; H5*
#( 39.7203 9.3119 42.0717) ; H5**
#( 38.0405 8.9195 43.2869) ; C4*
#( 37.3687 9.3036 42.5193) ; H4*
#( 37.4319 7.8146 43.9387) ; O4*
#( 37.1959 8.1354 45.3237) ; C1*
#( 36.1788 8.5202 45.3970) ; H1*
#( 38.1721 9.2328 45.6504) ; C2*
#( 39.1555 8.7939 45.8188) ; H2**
#( 37.7862 10.0617 46.7013) ; O2*
#( 37.3087 9.6229 47.4092) ; H2*
#( 38.1844 10.0268 44.3367) ; C3*
#( 39.1578 10.5054 44.2289) ; H3*
#( 37.0547 10.9127 44.3441) ; O3*
#( 34.8811 4.2072 47.5784) ; N1
N3
C2
#( 36.3908 6.1224 46.6053) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 33.3553 5.0152 46.4771) ; H2
H61
#( 35.9775 2.5638 49.1828) ; H62
H8
))
(define rA08
(nuc-const
#( 0.1084 -0.0895 -0.9901 ; dgf-base-tfo
0.9789 -0.1638 0.1220
-0.1731 -0.9824 0.0698
-2.9039 47.2655 33.0094)
#( 0.7529 0.1548 0.6397 ; P-O3*-275-tfo
0.2952 -0.9481 -0.1180
0.5882 0.2777 -0.7595
-58.8919 -11.3095 6.0866)
#( -0.0239 0.9667 -0.2546 ; P-O3*-180-tfo
0.9731 -0.0359 -0.2275
-0.2290 -0.2532 -0.9399
3.5401 -29.7913 52.2796)
#( -0.8912 -0.4531 0.0242 ; P-O3*-60-tfo
-0.1183 0.1805 -0.9764
0.4380 -0.8730 -0.2145
19.9023 54.8054 15.2799)
#( 41.8210 8.3880 43.5890) ; P
#( 42.5400 8.0450 44.8330) ; O1P
#( 42.2470 9.6920 42.9910) ; O2P
O5 *
#( 39.4850 8.9301 44.6977) ; C5*
#( 39.0638 9.8199 44.2296) ; H5*
#( 40.0757 9.0713 45.6029) ; H5**
#( 38.3102 8.0414 45.0789) ; C4*
#( 37.7842 8.4637 45.9351) ; H4*
#( 37.4200 7.9453 43.9769) ; O4*
#( 37.2249 6.5609 43.6273) ; C1*
#( 36.3360 6.2168 44.1561) ; H1*
#( 38.4347 5.8414 44.1590) ; C2*
#( 39.2688 5.9974 43.4749) ; H2**
#( 38.2344 4.4907 44.4348) ; O2*
#( 37.6374 4.0386 43.8341) ; H2*
#( 38.6926 6.6079 45.4637) ; C3*
#( 39.7585 6.5640 45.6877) ; H3*
#( 37.8238 6.0705 46.4723) ; O3*
#( 33.9162 6.2598 39.7758) ; N1
N3
C2
#( 35.8935 6.3324 41.5018) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 32.6830 6.6898 41.3532) ; H2
H61
#( 34.5056 5.7512 37.3528) ; H62
H8
))
(define rA09
(nuc-const
#( 0.8467 0.4166 -0.3311 ; dgf-base-tfo
-0.3962 0.9089 0.1303
0.3552 0.0209 0.9346
-42.7319 -26.6223 -29.8163)
#( 0.7529 0.1548 0.6397 ; P-O3*-275-tfo
0.2952 -0.9481 -0.1180
0.5882 0.2777 -0.7595
-58.8919 -11.3095 6.0866)
#( -0.0239 0.9667 -0.2546 ; P-O3*-180-tfo
0.9731 -0.0359 -0.2275
-0.2290 -0.2532 -0.9399
3.5401 -29.7913 52.2796)
#( -0.8912 -0.4531 0.0242 ; P-O3*-60-tfo
-0.1183 0.1805 -0.9764
0.4380 -0.8730 -0.2145
19.9023 54.8054 15.2799)
#( 41.8210 8.3880 43.5890) ; P
#( 42.5400 8.0450 44.8330) ; O1P
#( 42.2470 9.6920 42.9910) ; O2P
O5 *
#( 39.3505 8.4697 42.6565) ; C5*
#( 39.1377 7.5433 42.1230) ; H5*
#( 39.7203 9.3119 42.0717) ; H5**
#( 38.0405 8.9195 43.2869) ; C4*
#( 37.6479 8.1347 43.9335) ; H4*
#( 38.2691 10.0933 44.0524) ; O4*
#( 37.3999 11.1488 43.5973) ; C1*
#( 36.5061 11.1221 44.2206) ; H1*
#( 37.0364 10.7838 42.1836) ; C2*
#( 37.8636 11.0489 41.5252) ; H2**
#( 35.8275 11.3133 41.7379) ; O2*
#( 35.6214 12.1896 42.0714) ; H2*
#( 36.9316 9.2556 42.2837) ; C3*
#( 37.1778 8.8260 41.3127) ; H3*
#( 35.6285 8.9334 42.7926) ; O3*
#( 38.1482 15.2833 46.4641) ; N1
N3
C2
#( 37.9570 13.3377 44.7113) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 37.0731 14.0857 47.7306) ; H2
H61
#( 39.4100 17.3741 45.7478) ; H62
H8
))
(define rA10
(nuc-const
#( 0.7063 0.6317 -0.3196 ; dgf-base-tfo
-0.0403 -0.4149 -0.9090
-0.7068 0.6549 -0.2676
6.4402 -52.1496 30.8246)
#( 0.7529 0.1548 0.6397 ; P-O3*-275-tfo
0.2952 -0.9481 -0.1180
0.5882 0.2777 -0.7595
-58.8919 -11.3095 6.0866)
#( -0.0239 0.9667 -0.2546 ; P-O3*-180-tfo
0.9731 -0.0359 -0.2275
-0.2290 -0.2532 -0.9399
3.5401 -29.7913 52.2796)
#( -0.8912 -0.4531 0.0242 ; P-O3*-60-tfo
-0.1183 0.1805 -0.9764
0.4380 -0.8730 -0.2145
19.9023 54.8054 15.2799)
#( 41.8210 8.3880 43.5890) ; P
#( 42.5400 8.0450 44.8330) ; O1P
#( 42.2470 9.6920 42.9910) ; O2P
O5 *
#( 39.4850 8.9301 44.6977) ; C5*
#( 39.0638 9.8199 44.2296) ; H5*
#( 40.0757 9.0713 45.6029) ; H5**
#( 38.3102 8.0414 45.0789) ; C4*
#( 37.7099 7.8166 44.1973) ; H4*
#( 38.8012 6.8321 45.6380) ; O4*
#( 38.2431 6.6413 46.9529) ; C1*
#( 37.3505 6.0262 46.8385) ; H1*
#( 37.8484 8.0156 47.4214) ; C2*
#( 38.7381 8.5406 47.7690) ; H2**
#( 36.8286 8.0368 48.3701) ; O2*
#( 36.8392 7.3063 48.9929) ; H2*
#( 37.3576 8.6512 46.1132) ; C3*
#( 37.5207 9.7275 46.1671) ; H3*
#( 35.9985 8.2392 45.9032) ; O3*
#( 39.9117 2.2278 48.8527) ; N1
N3
C2
#( 39.2961 4.6720 48.1174) ; C4
C5
C6
rA
N6
N7
N9
C8
#( 38.5257 1.5960 47.4838) ; H2
H61
#( 41.6848 1.9687 50.6599) ; H62
H8
))
(define rAs
(list rA01 rA02 rA03 rA04 rA05 rA06 rA07 rA08 rA09 rA10))
(define rC
(nuc-const
#( -0.0359 -0.8071 0.5894 ; dgf-base-tfo
-0.2669 0.5761 0.7726
-0.9631 -0.1296 -0.2361
0.1584 8.3434 0.5434)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 5.2430 -8.2420 2.8260) ; C5*
#( 5.1974 -8.8497 1.9223) ; H5*
#( 5.5548 -8.7348 3.7469) ; H5**
#( 6.3140 -7.2060 2.5510) ; C4*
#( 7.2954 -7.6762 2.4898) ; H4*
#( 6.0140 -6.5420 1.2890) ; O4*
#( 6.4190 -5.1840 1.3620) ; C1*
#( 7.1608 -5.0495 0.5747) ; H1*
#( 7.0760 -4.9560 2.7270) ; C2*
#( 6.7770 -3.9803 3.1099) ; H2**
#( 8.4500 -5.1930 2.5810) ; O2*
#( 8.8309 -4.8755 1.7590) ; H2*
#( 6.4060 -6.0590 3.5580) ; C3*
#( 5.4021 -5.7313 3.8281) ; H3*
#( 7.1570 -6.4240 4.7070) ; O3*
#( 5.2170 -4.3260 1.1690) ; N1
N3
C2
#( 2.9930 -2.6780 0.7940) ; C4
C5
C6
rC
N4
#( 6.5470 -2.5560 0.6290) ; O2
#( 1.0684 -2.1236 0.7109) ; H41
#( 2.2344 -0.8560 0.3162) ; H42
#( 1.8797 -4.4972 1.3404) ; H5
H6
))
(define rC01
(nuc-const
#( -0.0137 -0.8012 0.5983 ; dgf-base-tfo
-0.2523 0.5817 0.7733
-0.9675 -0.1404 -0.2101
0.2031 8.3874 0.4228)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 5.2416 -8.2422 2.8181) ; C5*
#( 5.2050 -8.8128 1.8901) ; H5*
#( 5.5368 -8.7738 3.7227) ; H5**
#( 6.3232 -7.2037 2.6002) ; C4*
#( 7.3048 -7.6757 2.5577) ; H4*
#( 6.0635 -6.5092 1.3456) ; O4*
#( 6.4697 -5.1547 1.4629) ; C1*
#( 7.2354 -5.0043 0.7018) ; H1*
#( 7.0856 -4.9610 2.8521) ; C2*
#( 6.7777 -3.9935 3.2487) ; H2**
#( 8.4627 -5.1992 2.7423) ; O2*
#( 8.8693 -4.8638 1.9399) ; H2*
#( 6.3877 -6.0809 3.6362) ; C3*
#( 5.3770 -5.7562 3.8834) ; H3*
#( 7.1024 -6.4754 4.7985) ; O3*
#( 5.2764 -4.2883 1.2538) ; N1
N3
C2
#( 3.0693 -2.6246 0.8500) ; C4
C5
C6
rC
N4
#( 6.6267 -2.5166 0.7728) ; O2
#( 1.1496 -2.0600 0.7287) ; H41
#( 2.3303 -0.7921 0.3815) ; H42
#( 1.9353 -4.4465 1.3419) ; H5
H6
))
(define rC02
(nuc-const
#( 0.5141 0.0246 0.8574 ; dgf-base-tfo
-0.5547 -0.7529 0.3542
0.6542 -0.6577 -0.3734
-9.1111 -3.4598 -3.2939)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 4.3825 -6.6585 4.0489) ; C5*
#( 4.6841 -7.2019 4.9443) ; H5*
#( 3.6189 -5.8889 4.1625) ; H5**
#( 5.6255 -5.9175 3.5998) ; C4*
#( 5.8732 -5.1228 4.3034) ; H4*
#( 6.7337 -6.8605 3.5222) ; O4*
#( 7.5932 -6.4923 2.4548) ; C1*
#( 8.5661 -6.2983 2.9064) ; H1*
#( 7.0527 -5.2012 1.8322) ; C2*
#( 7.1627 -5.2525 0.7490) ; H2**
#( 7.6666 -4.1249 2.4880) ; O2*
#( 8.5944 -4.2543 2.6981) ; H2*
#( 5.5661 -5.3029 2.2009) ; C3*
#( 5.0841 -6.0018 1.5172) ; H3*
#( 4.9062 -4.0452 2.2042) ; O3*
#( 7.6298 -7.6136 1.4752) ; N1
N3
C2
#( 7.7426 -9.6987 -0.3801) ; C4
C5
C6
rC
N4
#( 9.5840 -6.8186 0.6136) ; O2
#( 7.2009 -11.3604 -1.3619) ; H41
#( 8.7058 -10.6168 -1.9140) ; H42
#( 5.8585 -10.3083 0.5822) ; H5
H6
))
(define rC03
(nuc-const
#( -0.4993 0.0476 0.8651 ; dgf-base-tfo
0.8078 -0.3353 0.4847
0.3132 0.9409 0.1290
6.2989 -5.2303 -3.8577)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 3.9938 -6.7042 1.9023) ; C5*
#( 3.2332 -5.9343 2.0319) ; H5*
#( 3.9666 -7.2863 0.9812) ; H5**
#( 5.3098 -5.9546 1.8564) ; C4*
#( 5.3863 -5.3702 0.9395) ; H4*
#( 5.3851 -5.0642 3.0076) ; O4*
#( 6.7315 -4.9724 3.4462) ; C1*
#( 7.0033 -3.9202 3.3619) ; H1*
#( 7.5997 -5.8018 2.4948) ; C2*
#( 8.3627 -6.3254 3.0707) ; H2**
#( 8.0410 -4.9501 1.4724) ; O2*
#( 8.2781 -4.0644 1.7570) ; H2*
#( 6.5701 -6.8129 1.9714) ; C3*
#( 6.4186 -7.5809 2.7299) ; H3*
#( 6.9357 -7.3841 0.7235) ; O3*
#( 6.8024 -5.4718 4.8475) ; N1
N3
C2
#( 6.9789 -6.3827 7.4823) ; C4
C5
C6
rC
N4
#( 8.7747 -4.3728 5.1568) ; O2
#( 6.4741 -7.3461 9.1662) ; H41
#( 7.9889 -6.4396 9.2429) ; H42
#( 5.0736 -7.3713 6.9922) ; H5
H6
))
(define rC04
(nuc-const
#( -0.5669 -0.8012 0.1918 ; dgf-base-tfo
-0.8129 0.5817 0.0273
-0.1334 -0.1404 -0.9811
-0.3279 8.3874 0.3355)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 5.2416 -8.2422 2.8181) ; C5*
#( 5.2050 -8.8128 1.8901) ; H5*
#( 5.5368 -8.7738 3.7227) ; H5**
#( 6.3232 -7.2037 2.6002) ; C4*
#( 7.3048 -7.6757 2.5577) ; H4*
#( 6.0635 -6.5092 1.3456) ; O4*
#( 6.4697 -5.1547 1.4629) ; C1*
#( 7.2354 -5.0043 0.7018) ; H1*
#( 7.0856 -4.9610 2.8521) ; C2*
#( 6.7777 -3.9935 3.2487) ; H2**
#( 8.4627 -5.1992 2.7423) ; O2*
#( 8.8693 -4.8638 1.9399) ; H2*
#( 6.3877 -6.0809 3.6362) ; C3*
#( 5.3770 -5.7562 3.8834) ; H3*
#( 7.1024 -6.4754 4.7985) ; O3*
#( 5.2764 -4.2883 1.2538) ; N1
N3
C2
#( 3.0480 -2.6632 0.8116) ; C4
C5
C6
rC
N4
#( 5.7005 -4.2164 -0.9842) ; O2
#( 1.4067 -1.5873 1.2205) ; H41
#( 1.8721 -1.6319 -0.4835) ; H42
#( 2.8048 -2.8507 2.9918) ; H5
H6
))
(define rC05
(nuc-const
#( -0.6298 0.0246 0.7763 ; dgf-base-tfo
-0.5226 -0.7529 -0.4001
0.5746 -0.6577 0.4870
-0.0208 -3.4598 -9.6882)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 4.3825 -6.6585 4.0489) ; C5*
#( 4.6841 -7.2019 4.9443) ; H5*
#( 3.6189 -5.8889 4.1625) ; H5**
#( 5.6255 -5.9175 3.5998) ; C4*
#( 5.8732 -5.1228 4.3034) ; H4*
#( 6.7337 -6.8605 3.5222) ; O4*
#( 7.5932 -6.4923 2.4548) ; C1*
#( 8.5661 -6.2983 2.9064) ; H1*
#( 7.0527 -5.2012 1.8322) ; C2*
#( 7.1627 -5.2525 0.7490) ; H2**
#( 7.6666 -4.1249 2.4880) ; O2*
#( 8.5944 -4.2543 2.6981) ; H2*
#( 5.5661 -5.3029 2.2009) ; C3*
#( 5.0841 -6.0018 1.5172) ; H3*
#( 4.9062 -4.0452 2.2042) ; O3*
#( 7.6298 -7.6136 1.4752) ; N1
N3
C2
#( 7.7372 -9.7371 -0.3364) ; C4
C5
C6
rC
N4
#( 9.3993 -8.5377 2.5743) ; O2
#( 7.2499 -10.8809 -1.9088) ; H41
#( 8.6122 -11.4649 -0.9468) ; H42
#( 6.0317 -8.6941 -1.2588) ; H5
H6
))
(define rC06
(nuc-const
#( -0.9837 0.0476 -0.1733 ; dgf-base-tfo
-0.1792 -0.3353 0.9249
-0.0141 0.9409 0.3384
5.7793 -5.2303 4.5997)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 3.9938 -6.7042 1.9023) ; C5*
#( 3.2332 -5.9343 2.0319) ; H5*
#( 3.9666 -7.2863 0.9812) ; H5**
#( 5.3098 -5.9546 1.8564) ; C4*
#( 5.3863 -5.3702 0.9395) ; H4*
#( 5.3851 -5.0642 3.0076) ; O4*
#( 6.7315 -4.9724 3.4462) ; C1*
#( 7.0033 -3.9202 3.3619) ; H1*
#( 7.5997 -5.8018 2.4948) ; C2*
#( 8.3627 -6.3254 3.0707) ; H2**
#( 8.0410 -4.9501 1.4724) ; O2*
#( 8.2781 -4.0644 1.7570) ; H2*
#( 6.5701 -6.8129 1.9714) ; C3*
#( 6.4186 -7.5809 2.7299) ; H3*
#( 6.9357 -7.3841 0.7235) ; O3*
#( 6.8024 -5.4718 4.8475) ; N1
N3
C2
#( 6.9254 -6.3614 7.4926) ; C4
C5
C6
rC
N4
#( 6.4083 -3.3696 5.6340) ; O2
#( 7.1329 -7.6280 9.0324) ; H41
#( 6.8204 -5.9469 9.4777) ; H42
#( 7.2954 -8.3135 6.5440) ; H5
H6
))
(define rC07
(nuc-const
#( 0.0033 0.2720 -0.9623 ; dgf-base-tfo
0.3013 -0.9179 -0.2584
-0.9535 -0.2891 -0.0850
43.0403 13.7233 34.5710)
#( 0.9187 0.2887 0.2694 ; P-O3*-275-tfo
0.0302 -0.7316 0.6811
0.3938 -0.6176 -0.6808
-48.4330 26.3254 13.6383)
#( -0.1504 0.7744 -0.6145 ; P-O3*-180-tfo
0.7581 0.4893 0.4311
0.6345 -0.4010 -0.6607
-31.9784 -13.4285 44.9650)
#( -0.6236 -0.7810 -0.0337 ; P-O3*-60-tfo
-0.6890 0.5694 -0.4484
0.3694 -0.2564 -0.8932
12.1105 30.8774 46.0946)
#( 33.3400 11.0980 46.1750) ; P
#( 34.5130 10.2320 46.4660) ; O1P
#( 33.4130 12.3960 46.9340) ; O2P
O5 *
#( 30.8152 11.1619 46.2003) ; C5*
#( 30.4519 10.9454 45.1957) ; H5*
#( 31.0379 12.2016 46.4400) ; H5**
#( 29.7081 10.7448 47.1428) ; C4*
#( 28.8710 11.4416 47.0982) ; H4*
#( 29.2550 9.4394 46.8162) ; O4*
#( 29.3907 8.5625 47.9460) ; C1*
#( 28.4416 8.5669 48.4819) ; H1*
#( 30.4468 9.2031 48.7952) ; C2*
#( 31.4222 8.9651 48.3709) ; H2**
#( 30.3701 8.9157 50.1624) ; O2*
#( 30.0652 8.0304 50.3740) ; H2*
#( 30.1622 10.6879 48.6120) ; C3*
#( 31.0952 11.2399 48.7254) ; H3*
#( 29.1076 11.1535 49.4702) ; O3*
#( 29.7883 7.2209 47.5235) ; N1
N3
C2
#( 30.4888 4.6890 46.7186) ; C4
C5
C6
rC
N4
#( 27.6171 6.5989 47.3189) ; O2
#( 31.7923 3.2301 46.2638) ; H41
#( 30.0880 2.7857 46.1215) ; H42
#( 32.5542 5.3634 46.9395) ; H5
H6
))
(define rC08
(nuc-const
#( 0.0797 -0.6026 -0.7941 ; dgf-base-tfo
0.7939 0.5201 -0.3150
0.6028 -0.6054 0.5198
-36.8341 41.5293 1.6628)
#( 0.9187 0.2887 0.2694 ; P-O3*-275-tfo
0.0302 -0.7316 0.6811
0.3938 -0.6176 -0.6808
-48.4330 26.3254 13.6383)
#( -0.1504 0.7744 -0.6145 ; P-O3*-180-tfo
0.7581 0.4893 0.4311
0.6345 -0.4010 -0.6607
-31.9784 -13.4285 44.9650)
#( -0.6236 -0.7810 -0.0337 ; P-O3*-60-tfo
-0.6890 0.5694 -0.4484
0.3694 -0.2564 -0.8932
12.1105 30.8774 46.0946)
#( 33.3400 11.0980 46.1750) ; P
#( 34.5130 10.2320 46.4660) ; O1P
#( 33.4130 12.3960 46.9340) ; O2P
O5 *
#( 31.8779 9.9369 47.8760) ; C5*
#( 31.3239 10.6931 48.4322) ; H5*
#( 32.8647 9.6624 48.2489) ; H5**
#( 31.0429 8.6773 47.9401) ; C4*
#( 31.0779 8.2331 48.9349) ; H4*
#( 29.6956 8.9669 47.5983) ; O4*
#( 29.2784 8.1700 46.4782) ; C1*
#( 28.8006 7.2731 46.8722) ; H1*
#( 30.5544 7.7940 45.7875) ; C2*
#( 30.8837 8.6410 45.1856) ; H2**
#( 30.5100 6.6007 45.0582) ; O2*
#( 29.6694 6.4168 44.6326) ; H2*
#( 31.5146 7.5954 46.9527) ; C3*
#( 32.5255 7.8261 46.6166) ; H3*
#( 31.3876 6.2951 47.5516) ; O3*
#( 28.3976 8.9302 45.5933) ; N1
N3
C2
#( 26.7044 10.3489 43.9595) ; C4
C5
C6
rC
N4
#( 26.5733 8.2371 46.7484) ; O2
#( 26.2707 11.5609 42.4177) ; H41
#( 24.8760 10.9939 43.3427) ; H42
#( 28.5089 10.9722 42.8990) ; H5
H6
))
(define rC09
(nuc-const
#( 0.8727 0.4760 -0.1091 ; dgf-base-tfo
-0.4188 0.6148 -0.6682
-0.2510 0.6289 0.7359
-8.1687 -52.0761 -25.0726)
#( 0.9187 0.2887 0.2694 ; P-O3*-275-tfo
0.0302 -0.7316 0.6811
0.3938 -0.6176 -0.6808
-48.4330 26.3254 13.6383)
#( -0.1504 0.7744 -0.6145 ; P-O3*-180-tfo
0.7581 0.4893 0.4311
0.6345 -0.4010 -0.6607
-31.9784 -13.4285 44.9650)
#( -0.6236 -0.7810 -0.0337 ; P-O3*-60-tfo
-0.6890 0.5694 -0.4484
0.3694 -0.2564 -0.8932
12.1105 30.8774 46.0946)
#( 33.3400 11.0980 46.1750) ; P
#( 34.5130 10.2320 46.4660) ; O1P
#( 33.4130 12.3960 46.9340) ; O2P
O5 *
#( 30.8152 11.1619 46.2003) ; C5*
#( 30.4519 10.9454 45.1957) ; H5*
#( 31.0379 12.2016 46.4400) ; H5**
#( 29.7081 10.7448 47.1428) ; C4*
#( 29.4506 9.6945 47.0059) ; H4*
#( 30.1045 10.9634 48.4885) ; O4*
#( 29.1794 11.8418 49.1490) ; C1*
#( 28.4388 11.2210 49.6533) ; H1*
#( 28.5211 12.6008 48.0367) ; C2*
#( 29.1947 13.3949 47.7147) ; H2**
#( 27.2316 13.0683 48.3134) ; O2*
#( 27.0851 13.3391 49.2227) ; H2*
#( 28.4131 11.5507 46.9391) ; C3*
#( 28.4451 12.0512 45.9713) ; H3*
#( 27.2707 10.6955 47.1097) ; O3*
#( 29.8751 12.7405 50.0682) ; N1
N3
C2
#( 31.1834 14.3941 51.8297) ; C4
C5
C6
rC
N4
#( 29.6470 11.2494 51.7616) ; O2
#( 32.1422 16.0774 52.3606) ; H41
#( 31.9392 14.8893 53.6527) ; H42
#( 31.3632 15.7771 50.1491) ; H5
H6
))
(define rC10
(nuc-const
#( 0.1549 0.8710 -0.4663 ; dgf-base-tfo
0.6768 -0.4374 -0.5921
-0.7197 -0.2239 -0.6572
25.2447 -14.1920 50.3201)
#( 0.9187 0.2887 0.2694 ; P-O3*-275-tfo
0.0302 -0.7316 0.6811
0.3938 -0.6176 -0.6808
-48.4330 26.3254 13.6383)
#( -0.1504 0.7744 -0.6145 ; P-O3*-180-tfo
0.7581 0.4893 0.4311
0.6345 -0.4010 -0.6607
-31.9784 -13.4285 44.9650)
#( -0.6236 -0.7810 -0.0337 ; P-O3*-60-tfo
-0.6890 0.5694 -0.4484
0.3694 -0.2564 -0.8932
12.1105 30.8774 46.0946)
#( 33.3400 11.0980 46.1750) ; P
#( 34.5130 10.2320 46.4660) ; O1P
#( 33.4130 12.3960 46.9340) ; O2P
O5 *
#( 31.8779 9.9369 47.8760) ; C5*
#( 31.3239 10.6931 48.4322) ; H5*
#( 32.8647 9.6624 48.2489) ; H5**
#( 31.0429 8.6773 47.9401) ; C4*
#( 30.0440 8.8473 47.5383) ; H4*
#( 31.6749 7.6351 47.2119) ; O4*
#( 31.9159 6.5022 48.0616) ; C1*
#( 31.0691 5.8243 47.9544) ; H1*
#( 31.9300 7.0685 49.4493) ; C2*
#( 32.9024 7.5288 49.6245) ; H2**
#( 31.5672 6.1750 50.4632) ; O2*
#( 31.8416 5.2663 50.3200) ; H2*
#( 30.8618 8.1514 49.3749) ; C3*
#( 31.1122 8.9396 50.0850) ; H3*
#( 29.5351 7.6245 49.5409) ; O3*
#( 33.1890 5.8629 47.7343) ; N1
N3
C2
#( 35.5600 4.6374 47.0822) ; C4
C5
C6
rC
N4
#( 32.1661 4.5034 46.2348) ; O2
#( 37.5405 4.3347 47.2259) ; H41
#( 36.7033 3.2923 46.0706) ; H42
#( 36.4713 5.9811 48.5428) ; H5
H6
))
(define rCs
(list rC01 rC02 rC03 rC04 rC05 rC06 rC07 rC08 rC09 rC10))
(define rG
(nuc-const
#( -0.0018 -0.8207 0.5714 ; dgf-base-tfo
0.2679 -0.5509 -0.7904
0.9634 0.1517 0.2209
0.0073 8.4030 0.6232)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 5.4550 8.2120 -2.8810) ; C5*
#( 5.4546 8.8508 -1.9978) ; H5*
#( 5.7588 8.6625 -3.8259) ; H5**
#( 6.4970 7.1480 -2.5980) ; C4*
#( 7.4896 7.5919 -2.5214) ; H4*
#( 6.1630 6.4860 -1.3440) ; O4*
#( 6.5400 5.1200 -1.4190) ; C1*
#( 7.2763 4.9681 -0.6297) ; H1*
#( 7.1940 4.8830 -2.7770) ; C2*
#( 6.8667 3.9183 -3.1647) ; H2**
#( 8.5860 5.0910 -2.6140) ; O2*
#( 8.9510 4.7626 -1.7890) ; H2*
#( 6.5720 6.0040 -3.6090) ; C3*
#( 5.5636 5.7066 -3.8966) ; H3*
#( 7.3801 6.3562 -4.7350) ; O3*
#( 4.7150 0.4910 -0.1360) ; N1
N3
C2
#( 5.2900 2.9790 -0.8260) ; C4
C5
C6
rG
#( 6.8426 0.0056 -0.0019) ; N2
N7
N9
C8
#( 2.4280 0.8450 -0.2360) ; O6
#( 4.6151 -0.4677 0.1305) ; H1
#( 6.6463 -0.9463 0.2729) ; H21
H22
H8
))
(define rG01
(nuc-const
#( -0.0043 -0.8175 0.5759 ; dgf-base-tfo
0.2617 -0.5567 -0.7884
0.9651 0.1473 0.2164
0.0359 8.3929 0.5532)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 5.4352 8.2183 -2.7757) ; C5*
#( 5.3830 8.7883 -1.8481) ; H5*
#( 5.7729 8.7436 -3.6691) ; H5**
#( 6.4830 7.1518 -2.5252) ; C4*
#( 7.4749 7.5972 -2.4482) ; H4*
#( 6.1626 6.4620 -1.2827) ; O4*
#( 6.5431 5.0992 -1.3905) ; C1*
#( 7.2871 4.9328 -0.6114) ; H1*
#( 7.1852 4.8935 -2.7592) ; C2*
#( 6.8573 3.9363 -3.1645) ; H2**
#( 8.5780 5.1025 -2.6046) ; O2*
#( 8.9516 4.7577 -1.7902) ; H2*
#( 6.5522 6.0300 -3.5612) ; C3*
#( 5.5420 5.7356 -3.8459) ; H3*
#( 7.3487 6.4089 -4.6867) ; O3*
#( 4.7442 0.4514 -0.1390) ; N1
N3
C2
#( 5.3052 2.9471 -0.8125) ; C4
C5
C6
rG
#( 6.8745 -0.0224 -0.0058) ; N2
N7
N9
C8
#( 2.4553 0.7925 -0.2390) ; O6
#( 4.6497 -0.5095 0.1212) ; H1
#( 6.6836 -0.9771 0.2627) ; H21
H22
H8
))
(define rG02
(nuc-const
#( 0.5566 0.0449 0.8296 ; dgf-base-tfo
0.5125 0.7673 -0.3854
-0.6538 0.6397 0.4041
-9.1161 -3.7679 -2.9968)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 4.5778 6.6594 -4.0364) ; C5*
#( 4.9220 7.1963 -4.9204) ; H5*
#( 3.7996 5.9091 -4.1764) ; H5**
#( 5.7873 5.8869 -3.5482) ; C4*
#( 6.0405 5.0875 -4.2446) ; H4*
#( 6.9135 6.8036 -3.4310) ; O4*
#( 7.7293 6.4084 -2.3392) ; C1*
#( 8.7078 6.1815 -2.7624) ; H1*
#( 7.1305 5.1418 -1.7347) ; C2*
#( 7.2040 5.1982 -0.6486) ; H2**
#( 7.7417 4.0392 -2.3813) ; O2*
#( 8.6785 4.1443 -2.5630) ; H2*
#( 5.6666 5.2728 -2.1536) ; C3*
#( 5.1747 5.9805 -1.4863) ; H3*
#( 4.9997 4.0086 -2.1973) ; O3*
#( 10.3245 8.5459 1.5467) ; N1
N3
C2
#( 8.7523 7.7422 -0.4228) ; C4
C5
C6
rG
#( 11.6077 6.7966 1.2752) ; N2
N7
N9
C8
#( 9.0664 10.4462 1.9610) ; O6
#( 10.9838 8.7524 2.2697) ; H1
#( 12.2274 7.0896 2.0170) ; H21
H22
H8
))
(define rG03
(nuc-const
#( -0.5021 0.0731 0.8617 ; dgf-base-tfo
-0.8112 0.3054 -0.4986
-0.2996 -0.9494 -0.0940
6.4273 -5.1944 -3.7807)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 4.1214 6.7116 -1.9049) ; C5*
#( 3.3465 5.9610 -2.0607) ; H5*
#( 4.0789 7.2928 -0.9837) ; H5**
#( 5.4170 5.9293 -1.8186) ; C4*
#( 5.4506 5.3400 -0.9023) ; H4*
#( 5.5067 5.0417 -2.9703) ; O4*
#( 6.8650 4.9152 -3.3612) ; C1*
#( 7.1090 3.8577 -3.2603) ; H1*
#( 7.7152 5.7282 -2.3894) ; C2*
#( 8.5029 6.2356 -2.9463) ; H2**
#( 8.1036 4.8568 -1.3419) ; O2*
#( 8.3270 3.9651 -1.6184) ; H2*
#( 6.7003 6.7565 -1.8911) ; C3*
#( 6.5898 7.5329 -2.6482) ; H3*
#( 7.0505 7.2878 -0.6105) ; O3*
#( 9.6740 4.7656 -7.6614) ; N1
N3
C2
#( 7.9885 5.0632 -5.6446) ; C4
C5
C6
rG
#( 10.9733 3.5117 -6.4286) ; N2
N7
N9
C8
#( 8.4084 6.0747 -9.0933) ; O6
#( 10.3759 4.5855 -8.3504) ; H1
#( 11.6254 3.3761 -7.1879) ; H21
H22
H8
))
(define rG04
(nuc-const
#( -0.5426 -0.8175 0.1929 ; dgf-base-tfo
0.8304 -0.5567 -0.0237
0.1267 0.1473 0.9809
-0.5075 8.3929 0.2229)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 5.4352 8.2183 -2.7757) ; C5*
#( 5.3830 8.7883 -1.8481) ; H5*
#( 5.7729 8.7436 -3.6691) ; H5**
#( 6.4830 7.1518 -2.5252) ; C4*
#( 7.4749 7.5972 -2.4482) ; H4*
#( 6.1626 6.4620 -1.2827) ; O4*
#( 6.5431 5.0992 -1.3905) ; C1*
#( 7.2871 4.9328 -0.6114) ; H1*
#( 7.1852 4.8935 -2.7592) ; C2*
#( 6.8573 3.9363 -3.1645) ; H2**
#( 8.5780 5.1025 -2.6046) ; O2*
#( 8.9516 4.7577 -1.7902) ; H2*
#( 6.5522 6.0300 -3.5612) ; C3*
#( 5.5420 5.7356 -3.8459) ; H3*
#( 7.3487 6.4089 -4.6867) ; O3*
#( 3.6343 2.6680 2.0783) ; N1
N3
C2
#( 4.8805 3.7951 0.0354) ; C4
C5
C6
rG
#( 5.1433 3.4373 3.4609) ; N2
N7
N9
C8
#( 1.9600 1.7805 0.7462) ; O6
#( 3.2489 2.2879 2.9191) ; H1
#( 4.6785 3.0243 4.2568) ; H21
H22
H8
))
(define rG05
(nuc-const
#( -0.5891 0.0449 0.8068 ; dgf-base-tfo
0.5375 0.7673 0.3498
-0.6034 0.6397 -0.4762
-0.3019 -3.7679 -9.5913)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 4.5778 6.6594 -4.0364) ; C5*
#( 4.9220 7.1963 -4.9204) ; H5*
#( 3.7996 5.9091 -4.1764) ; H5**
#( 5.7873 5.8869 -3.5482) ; C4*
#( 6.0405 5.0875 -4.2446) ; H4*
#( 6.9135 6.8036 -3.4310) ; O4*
#( 7.7293 6.4084 -2.3392) ; C1*
#( 8.7078 6.1815 -2.7624) ; H1*
#( 7.1305 5.1418 -1.7347) ; C2*
#( 7.2040 5.1982 -0.6486) ; H2**
#( 7.7417 4.0392 -2.3813) ; O2*
#( 8.6785 4.1443 -2.5630) ; H2*
#( 5.6666 5.2728 -2.1536) ; C3*
#( 5.1747 5.9805 -1.4863) ; H3*
#( 4.9997 4.0086 -2.1973) ; O3*
#( 10.2594 10.6774 -1.0056) ; N1
N3
C2
#( 8.7271 8.5575 -1.3991) ; C4
C5
C6
rG
#( 11.5110 10.1256 -2.7114) ; N2
N7
N9
C8
#( 9.0349 11.3951 0.8250) ; O6
#( 10.9013 11.4422 -0.9512) ; H1
#( 12.1031 10.9341 -2.5861) ; H21
H22
H8
))
(define rG06
(nuc-const
#( -0.9815 0.0731 -0.1772 ; dgf-base-tfo
0.1912 0.3054 -0.9328
-0.0141 -0.9494 -0.3137
5.7506 -5.1944 4.7470)
#( -0.8143 -0.5091 -0.2788 ; P-O3*-275-tfo
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
#( 0.3822 -0.7477 0.5430 ; P-O3*-180-tfo
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
#( 0.5640 0.8007 -0.2022 ; P-O3*-60-tfo
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
#( 2.8930 8.5380 -3.3280) ; P
#( 1.6980 7.6960 -3.5570) ; O1P
#( 3.2260 9.5010 -4.4020) ; O2P
O5 *
#( 4.1214 6.7116 -1.9049) ; C5*
#( 3.3465 5.9610 -2.0607) ; H5*
#( 4.0789 7.2928 -0.9837) ; H5**
#( 5.4170 5.9293 -1.8186) ; C4*
#( 5.4506 5.3400 -0.9023) ; H4*
#( 5.5067 5.0417 -2.9703) ; O4*
#( 6.8650 4.9152 -3.3612) ; C1*
#( 7.1090 3.8577 -3.2603) ; H1*
#( 7.7152 5.7282 -2.3894) ; C2*
#( 8.5029 6.2356 -2.9463) ; H2**
#( 8.1036 4.8568 -1.3419) ; O2*
#( 8.3270 3.9651 -1.6184) ; H2*
#( 6.7003 6.7565 -1.8911) ; C3*
#( 6.5898 7.5329 -2.6482) ; H3*
#( 7.0505 7.2878 -0.6105) ; O3*
#( 6.6624 3.5061 -8.2986) ; N1
N3
C2
#( 6.8364 4.5817 -5.8882) ; C4
C5
C6
rG
#( 6.2717 1.5402 -7.4250) ; N2
N7
N9
C8
#( 7.0668 5.5163 -9.3763) ; O6
#( 6.5754 2.9964 -9.1545) ; H1
#( 6.1908 1.1105 -8.3354) ; H21
H22
H8
))
(define rG07
(nuc-const
#( 0.0894 -0.6059 0.7905 ; dgf-base-tfo
-0.6810 0.5420 0.4924
-0.7268 -0.5824 -0.3642
34.1424 45.9610 -11.8600)
#( -0.8644 -0.4956 -0.0851 ; P-O3*-275-tfo
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
#( 0.3706 -0.6167 0.6945 ; P-O3*-180-tfo
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
#( 0.4155 0.9025 -0.1137 ; P-O3*-60-tfo
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
#( 31.3810 0.1400 47.5810) ; P
#( 29.9860 0.6630 47.6290) ; O1P
#( 31.7210 -0.6460 48.8090) ; O2P
O5 *
#( 33.8709 0.7918 47.2113) ; C5*
#( 34.1386 0.5870 46.1747) ; H5*
#( 34.0186 -0.0095 47.9353) ; H5**
#( 34.7297 1.9687 47.6685) ; C4*
#( 35.7723 1.6845 47.8113) ; H4*
#( 34.6455 2.9768 46.6660) ; O4*
#( 34.1690 4.1829 47.2627) ; C1*
#( 35.0437 4.7633 47.5560) ; H1*
#( 33.4145 3.7532 48.4954) ; C2*
#( 32.4340 3.3797 48.2001) ; H2**
#( 33.3209 4.6953 49.5217) ; O2*
#( 33.2374 5.6059 49.2295) ; H2*
#( 34.2724 2.5970 48.9773) ; C3*
#( 33.6373 1.8935 49.5157) ; H3*
#( 35.3453 3.1884 49.7285) ; O3*
#( 34.0511 7.8930 43.7791) ; N1
N3
C2
#( 33.7190 5.9650 45.5374) ; C4
C5
C6
rG
#( 36.3030 7.7827 44.1036) ; N2
N7
N9
C8
#( 31.8602 8.1000 43.3695) ; O6
#( 34.2623 8.6223 43.1283) ; H1
#( 36.5188 8.5081 43.4347) ; H21
H22
H8
))
(define rG08
(nuc-const
#( 0.2224 0.6335 0.7411 ; dgf-base-tfo
-0.3644 -0.6510 0.6659
0.9043 -0.4181 0.0861
-47.6824 -0.5823 -31.7554)
#( -0.8644 -0.4956 -0.0851 ; P-O3*-275-tfo
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
#( 0.3706 -0.6167 0.6945 ; P-O3*-180-tfo
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
#( 0.4155 0.9025 -0.1137 ; P-O3*-60-tfo
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
#( 31.3810 0.1400 47.5810) ; P
#( 29.9860 0.6630 47.6290) ; O1P
#( 31.7210 -0.6460 48.8090) ; O2P
O5 *
#( 32.5924 2.3488 48.2255) ; C5*
#( 33.3674 2.1246 48.9584) ; H5*
#( 31.5994 2.5917 48.6037) ; H5**
#( 33.0722 3.5577 47.4258) ; C4*
#( 33.0310 4.4778 48.0089) ; H4*
#( 34.4173 3.3055 47.0316) ; O4*
#( 34.5056 3.3910 45.6094) ; C1*
#( 34.7881 4.4152 45.3663) ; H1*
#( 33.1122 3.1198 45.1010) ; C2*
#( 32.9230 2.0469 45.1369) ; H2**
#( 32.7946 3.6590 43.8529) ; O2*
#( 33.5170 3.6707 43.2207) ; H2*
#( 32.2730 3.8173 46.1566) ; C3*
#( 31.3094 3.3123 46.2244) ; H3*
#( 32.2391 5.2039 45.7807) ; O3*
#( 39.3337 2.7157 44.1441) ; N1
N3
C2
#( 36.7791 2.6963 44.7704) ; C4
C5
C6
rG
#( 39.5123 4.8216 44.9936) ; N2
N7
N9
C8
#( 39.2907 0.6514 43.2796) ; O6
#( 40.3076 2.8048 43.9352) ; H1
#( 40.4994 4.9066 44.7977) ; H21
H22
H8
))
(define rG09
(nuc-const
#( -0.9699 -0.1688 -0.1753 ; dgf-base-tfo
-0.1050 -0.3598 0.9271
-0.2196 0.9176 0.3312
45.6217 -38.9484 -12.3208)
#( -0.8644 -0.4956 -0.0851 ; P-O3*-275-tfo
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
#( 0.3706 -0.6167 0.6945 ; P-O3*-180-tfo
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
#( 0.4155 0.9025 -0.1137 ; P-O3*-60-tfo
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
#( 31.3810 0.1400 47.5810) ; P
#( 29.9860 0.6630 47.6290) ; O1P
#( 31.7210 -0.6460 48.8090) ; O2P
O5 *
#( 33.8709 0.7918 47.2113) ; C5*
#( 34.1386 0.5870 46.1747) ; H5*
#( 34.0186 -0.0095 47.9353) ; H5**
#( 34.7297 1.9687 47.6685) ; C4*
#( 34.5880 2.8482 47.0404) ; H4*
#( 34.3575 2.2770 49.0081) ; O4*
#( 35.5157 2.1993 49.8389) ; C1*
#( 35.9424 3.2010 49.8893) ; H1*
#( 36.4701 1.2820 49.1169) ; C2*
#( 36.1545 0.2498 49.2683) ; H2**
#( 37.8262 1.4547 49.4008) ; O2*
#( 38.0227 1.6945 50.3094) ; H2*
#( 36.2242 1.6797 47.6725) ; C3*
#( 36.4297 0.8197 47.0351) ; H3*
#( 37.0289 2.8480 47.4426) ; O3*
#( 34.3005 3.5042 54.6070) ; N1
N3
C2
#( 34.9354 2.4584 52.2785) ; C4
C5
C6
rG
#( 34.2514 5.5708 53.6503) ; N2
N7
N9
C8
#( 34.3151 1.5317 55.6650) ; O6
#( 34.0623 3.9797 55.4539) ; H1
#( 33.9950 6.0502 54.5016) ; H21
H22
H8
))
(define rG10
(nuc-const
#( -0.0980 -0.9723 0.2122 ; dgf-base-tfo
-0.9731 0.1383 0.1841
-0.2083 -0.1885 -0.9597
17.8469 38.8265 37.0475)
#( -0.8644 -0.4956 -0.0851 ; P-O3*-275-tfo
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
#( 0.3706 -0.6167 0.6945 ; P-O3*-180-tfo
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
#( 0.4155 0.9025 -0.1137 ; P-O3*-60-tfo
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
#( 31.3810 0.1400 47.5810) ; P
#( 29.9860 0.6630 47.6290) ; O1P
#( 31.7210 -0.6460 48.8090) ; O2P
O5 *
#( 32.5924 2.3488 48.2255) ; C5*
#( 33.3674 2.1246 48.9584) ; H5*
#( 31.5994 2.5917 48.6037) ; H5**
#( 33.0722 3.5577 47.4258) ; C4*
#( 34.0333 3.3761 46.9447) ; H4*
#( 32.0890 3.8338 46.4332) ; O4*
#( 31.6377 5.1787 46.5914) ; C1*
#( 32.2499 5.8016 45.9392) ; H1*
#( 31.9167 5.5319 48.0305) ; C2*
#( 31.1507 5.0820 48.6621) ; H2**
#( 32.0865 6.8890 48.3114) ; O2*
#( 31.5363 7.4819 47.7942) ; H2*
#( 33.2398 4.8224 48.2563) ; C3*
#( 33.3166 4.5570 49.3108) ; H3*
#( 34.2528 5.7056 47.7476) ; O3*
#( 28.2782 6.3049 42.9364) ; N1
N3
C2
#( 29.7005 5.7006 45.0649) ; C4
C5
C6
rG
#( 30.1838 6.3385 41.6890) ; N2
N7
N9
C8
#( 26.3361 6.3024 44.0495) ; O6
#( 27.8122 6.5394 42.0833) ; H1
#( 29.7125 6.5595 40.8235) ; H21
H22
H8
))
(define rGs
(list rG01 rG02 rG03 rG04 rG05 rG06 rG07 rG08 rG09 rG10))
(define rU
(nuc-const
#( -0.0359 -0.8071 0.5894 ; dgf-base-tfo
-0.2669 0.5761 0.7726
-0.9631 -0.1296 -0.2361
0.1584 8.3434 0.5434)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 5.2430 -8.2420 2.8260) ; C5*
#( 5.1974 -8.8497 1.9223) ; H5*
#( 5.5548 -8.7348 3.7469) ; H5**
#( 6.3140 -7.2060 2.5510) ; C4*
#( 7.2954 -7.6762 2.4898) ; H4*
#( 6.0140 -6.5420 1.2890) ; O4*
#( 6.4190 -5.1840 1.3620) ; C1*
#( 7.1608 -5.0495 0.5747) ; H1*
#( 7.0760 -4.9560 2.7270) ; C2*
#( 6.7770 -3.9803 3.1099) ; H2**
#( 8.4500 -5.1930 2.5810) ; O2*
#( 8.8309 -4.8755 1.7590) ; H2*
#( 6.4060 -6.0590 3.5580) ; C3*
#( 5.4021 -5.7313 3.8281) ; H3*
#( 7.1570 -6.4240 4.7070) ; O3*
#( 5.2170 -4.3260 1.1690) ; N1
N3
C2
#( 2.9930 -2.6780 0.7940) ; C4
C5
C6
rU
#( 6.5470 -2.5560 0.6290) ; O2
O4
#( 4.4300 -1.3020 0.3600) ; H3
#( 1.9590 -4.4570 1.3250) ; H5
H6
))
(define rU01
(nuc-const
#( -0.0137 -0.8012 0.5983 ; dgf-base-tfo
-0.2523 0.5817 0.7733
-0.9675 -0.1404 -0.2101
0.2031 8.3874 0.4228)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 5.2416 -8.2422 2.8181) ; C5*
#( 5.2050 -8.8128 1.8901) ; H5*
#( 5.5368 -8.7738 3.7227) ; H5**
#( 6.3232 -7.2037 2.6002) ; C4*
#( 7.3048 -7.6757 2.5577) ; H4*
#( 6.0635 -6.5092 1.3456) ; O4*
#( 6.4697 -5.1547 1.4629) ; C1*
#( 7.2354 -5.0043 0.7018) ; H1*
#( 7.0856 -4.9610 2.8521) ; C2*
#( 6.7777 -3.9935 3.2487) ; H2**
#( 8.4627 -5.1992 2.7423) ; O2*
#( 8.8693 -4.8638 1.9399) ; H2*
#( 6.3877 -6.0809 3.6362) ; C3*
#( 5.3770 -5.7562 3.8834) ; H3*
#( 7.1024 -6.4754 4.7985) ; O3*
#( 5.2764 -4.2883 1.2538) ; N1
N3
C2
#( 3.0693 -2.6246 0.8500) ; C4
C5
C6
rU
#( 6.6267 -2.5166 0.7728) ; O2
O4
#( 4.5223 -1.2489 0.4716) ; H3
#( 2.0151 -4.4065 1.3290) ; H5
H6
))
(define rU02
(nuc-const
#( 0.5141 0.0246 0.8574 ; dgf-base-tfo
-0.5547 -0.7529 0.3542
0.6542 -0.6577 -0.3734
-9.1111 -3.4598 -3.2939)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 4.3825 -6.6585 4.0489) ; C5*
#( 4.6841 -7.2019 4.9443) ; H5*
#( 3.6189 -5.8889 4.1625) ; H5**
#( 5.6255 -5.9175 3.5998) ; C4*
#( 5.8732 -5.1228 4.3034) ; H4*
#( 6.7337 -6.8605 3.5222) ; O4*
#( 7.5932 -6.4923 2.4548) ; C1*
#( 8.5661 -6.2983 2.9064) ; H1*
#( 7.0527 -5.2012 1.8322) ; C2*
#( 7.1627 -5.2525 0.7490) ; H2**
#( 7.6666 -4.1249 2.4880) ; O2*
#( 8.5944 -4.2543 2.6981) ; H2*
#( 5.5661 -5.3029 2.2009) ; C3*
#( 5.0841 -6.0018 1.5172) ; H3*
#( 4.9062 -4.0452 2.2042) ; O3*
#( 7.6298 -7.6136 1.4752) ; N1
N3
C2
#( 7.7426 -9.6987 -0.3801) ; C4
C5
C6
rU
#( 9.5840 -6.8186 0.6136) ; O2
O4
#( 9.4601 -8.7514 -0.9277) ; H3
#( 5.9281 -10.2509 0.5782) ; H5
H6
))
(define rU03
(nuc-const
#( -0.4993 0.0476 0.8651 ; dgf-base-tfo
0.8078 -0.3353 0.4847
0.3132 0.9409 0.1290
6.2989 -5.2303 -3.8577)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 3.9938 -6.7042 1.9023) ; C5*
#( 3.2332 -5.9343 2.0319) ; H5*
#( 3.9666 -7.2863 0.9812) ; H5**
#( 5.3098 -5.9546 1.8564) ; C4*
#( 5.3863 -5.3702 0.9395) ; H4*
#( 5.3851 -5.0642 3.0076) ; O4*
#( 6.7315 -4.9724 3.4462) ; C1*
#( 7.0033 -3.9202 3.3619) ; H1*
#( 7.5997 -5.8018 2.4948) ; C2*
#( 8.3627 -6.3254 3.0707) ; H2**
#( 8.0410 -4.9501 1.4724) ; O2*
#( 8.2781 -4.0644 1.7570) ; H2*
#( 6.5701 -6.8129 1.9714) ; C3*
#( 6.4186 -7.5809 2.7299) ; H3*
#( 6.9357 -7.3841 0.7235) ; O3*
#( 6.8024 -5.4718 4.8475) ; N1
N3
C2
#( 6.9789 -6.3827 7.4823) ; C4
C5
C6
rU
#( 8.7747 -4.3728 5.1568) ; O2
O4
#( 8.7055 -5.3037 7.4491) ; H3
#( 5.1416 -7.3178 6.9665) ; H5
H6
))
(define rU04
(nuc-const
#( -0.5669 -0.8012 0.1918 ; dgf-base-tfo
-0.8129 0.5817 0.0273
-0.1334 -0.1404 -0.9811
-0.3279 8.3874 0.3355)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 5.2416 -8.2422 2.8181) ; C5*
#( 5.2050 -8.8128 1.8901) ; H5*
#( 5.5368 -8.7738 3.7227) ; H5**
#( 6.3232 -7.2037 2.6002) ; C4*
#( 7.3048 -7.6757 2.5577) ; H4*
#( 6.0635 -6.5092 1.3456) ; O4*
#( 6.4697 -5.1547 1.4629) ; C1*
#( 7.2354 -5.0043 0.7018) ; H1*
#( 7.0856 -4.9610 2.8521) ; C2*
#( 6.7777 -3.9935 3.2487) ; H2**
#( 8.4627 -5.1992 2.7423) ; O2*
#( 8.8693 -4.8638 1.9399) ; H2*
#( 6.3877 -6.0809 3.6362) ; C3*
#( 5.3770 -5.7562 3.8834) ; H3*
#( 7.1024 -6.4754 4.7985) ; O3*
#( 5.2764 -4.2883 1.2538) ; N1
N3
C2
#( 3.0480 -2.6632 0.8116) ; C4
C5
C6
rU
#( 5.7005 -4.2164 -0.9842) ; O2
O4
#( 3.6834 -2.7882 -1.1190) ; H3
#( 2.8508 -2.8721 2.9172) ; H5
H6
))
(define rU05
(nuc-const
#( -0.6298 0.0246 0.7763 ; dgf-base-tfo
-0.5226 -0.7529 -0.4001
0.5746 -0.6577 0.4870
-0.0208 -3.4598 -9.6882)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 4.3825 -6.6585 4.0489) ; C5*
#( 4.6841 -7.2019 4.9443) ; H5*
#( 3.6189 -5.8889 4.1625) ; H5**
#( 5.6255 -5.9175 3.5998) ; C4*
#( 5.8732 -5.1228 4.3034) ; H4*
#( 6.7337 -6.8605 3.5222) ; O4*
#( 7.5932 -6.4923 2.4548) ; C1*
#( 8.5661 -6.2983 2.9064) ; H1*
#( 7.0527 -5.2012 1.8322) ; C2*
#( 7.1627 -5.2525 0.7490) ; H2**
#( 7.6666 -4.1249 2.4880) ; O2*
#( 8.5944 -4.2543 2.6981) ; H2*
#( 5.5661 -5.3029 2.2009) ; C3*
#( 5.0841 -6.0018 1.5172) ; H3*
#( 4.9062 -4.0452 2.2042) ; O3*
#( 7.6298 -7.6136 1.4752) ; N1
N3
C2
#( 7.7372 -9.7371 -0.3364) ; C4
C5
C6
rU
#( 9.3993 -8.5377 2.5743) ; O2
O4
#( 9.2924 -10.3081 0.8477) ; H3
#( 6.0932 -8.6982 -1.1929) ; H5
H6
))
(define rU06
(nuc-const
#( -0.9837 0.0476 -0.1733 ; dgf-base-tfo
-0.1792 -0.3353 0.9249
-0.0141 0.9409 0.3384
5.7793 -5.2303 4.5997)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 3.9938 -6.7042 1.9023) ; C5*
#( 3.2332 -5.9343 2.0319) ; H5*
#( 3.9666 -7.2863 0.9812) ; H5**
#( 5.3098 -5.9546 1.8564) ; C4*
#( 5.3863 -5.3702 0.9395) ; H4*
#( 5.3851 -5.0642 3.0076) ; O4*
#( 6.7315 -4.9724 3.4462) ; C1*
#( 7.0033 -3.9202 3.3619) ; H1*
#( 7.5997 -5.8018 2.4948) ; C2*
#( 8.3627 -6.3254 3.0707) ; H2**
#( 8.0410 -4.9501 1.4724) ; O2*
#( 8.2781 -4.0644 1.7570) ; H2*
#( 6.5701 -6.8129 1.9714) ; C3*
#( 6.4186 -7.5809 2.7299) ; H3*
#( 6.9357 -7.3841 0.7235) ; O3*
#( 6.8024 -5.4718 4.8475) ; N1
N3
C2
#( 6.9254 -6.3614 7.4926) ; C4
C5
C6
rU
#( 6.4083 -3.3696 5.6340) ; O2
O4
#( 6.5626 -4.3957 7.8812) ; H3
#( 7.2781 -8.2254 6.5350) ; H5
H6
))
(define rU07
(nuc-const
#( -0.9434 0.3172 0.0971 ; dgf-base-tfo
0.2294 0.4125 0.8816
0.2396 0.8539 -0.4619
8.3625 -52.7147 1.3745)
#( 0.2765 -0.1121 -0.9545 ; P-O3*-275-tfo
-0.8297 0.4733 -0.2959
0.4850 0.8737 0.0379
-14.7774 -45.2464 21.9088)
#( 0.1063 -0.6334 -0.7665 ; P-O3*-180-tfo
-0.5932 -0.6591 0.4624
-0.7980 0.4055 -0.4458
43.7634 4.3296 28.4890)
#( 0.7136 -0.5032 -0.4873 ; P-O3*-60-tfo
0.6803 0.3317 0.6536
-0.1673 -0.7979 0.5791
-17.1858 41.4390 -27.0751)
#( 21.3880 15.0780 45.5770) ; P
#( 21.9980 14.5500 46.8210) ; O1P
#( 21.1450 14.0270 44.5420) ; O2P
O5 *
#( 21.5037 16.8594 43.7323) ; C5*
#( 20.8147 17.6663 43.9823) ; H5*
#( 21.1086 16.0230 43.1557) ; H5**
#( 22.5654 17.4874 42.8616) ; C4*
#( 22.1584 17.7243 41.8785) ; H4*
#( 23.0557 18.6826 43.4751) ; O4*
#( 24.4788 18.6151 43.6455) ; C1*
#( 24.9355 19.0840 42.7739) ; H1*
#( 24.7958 17.1427 43.6474) ; C2*
#( 24.5652 16.7400 44.6336) ; H2**
#( 26.1041 16.8773 43.2455) ; O2*
#( 26.7516 17.5328 43.5149) ; H2*
#( 23.8109 16.5979 42.6377) ; C3*
#( 23.5756 15.5686 42.9084) ; H3*
#( 24.2890 16.7447 41.2729) ; O3*
#( 24.9420 19.2174 44.8923) ; N1
N3
C2
#( 25.6911 21.1219 46.0494) ; C4
C5
C6
rU
#( 25.4692 19.0221 47.2053) ; O2
O4
#( 25.9599 22.1772 46.0966) ; H3
#( 25.5545 18.4409 48.1234) ; H5
H6
))
(define rU08
(nuc-const
#( -0.0080 -0.7928 0.6094 ; dgf-base-tfo
-0.7512 0.4071 0.5197
-0.6601 -0.4536 -0.5988
44.1482 30.7036 2.1088)
#( 0.2765 -0.1121 -0.9545 ; P-O3*-275-tfo
-0.8297 0.4733 -0.2959
0.4850 0.8737 0.0379
-14.7774 -45.2464 21.9088)
#( 0.1063 -0.6334 -0.7665 ; P-O3*-180-tfo
-0.5932 -0.6591 0.4624
-0.7980 0.4055 -0.4458
43.7634 4.3296 28.4890)
#( 0.7136 -0.5032 -0.4873 ; P-O3*-60-tfo
0.6803 0.3317 0.6536
-0.1673 -0.7979 0.5791
-17.1858 41.4390 -27.0751)
#( 21.3880 15.0780 45.5770) ; P
#( 21.9980 14.5500 46.8210) ; O1P
#( 21.1450 14.0270 44.5420) ; O2P
O5 *
#( 23.5096 16.1227 44.5783) ; C5*
#( 23.5649 15.8588 43.5222) ; H5*
#( 23.9621 15.4341 45.2919) ; H5**
#( 24.2805 17.4138 44.7151) ; C4*
#( 25.3492 17.2309 44.6030) ; H4*
#( 23.8497 18.3471 43.7208) ; O4*
#( 23.4090 19.5681 44.3321) ; C1*
#( 24.2595 20.2496 44.3524) ; H1*
#( 23.0418 19.1813 45.7407) ; C2*
#( 22.0532 18.7224 45.7273) ; H2**
#( 23.1307 20.2521 46.6291) ; O2*
#( 22.8888 21.1051 46.2611) ; H2*
#( 24.0799 18.1326 46.0700) ; C3*
#( 23.6490 17.4370 46.7900) ; H3*
#( 25.3329 18.7227 46.5109) ; O3*
#( 22.2515 20.1624 43.6698) ; N1
N3
C2
#( 21.3986 21.6081 42.0236) ; C4
C5
C6
rU
#( 19.8919 20.3745 43.4387) ; O2
O4
#( 21.5235 22.3222 41.2097) ; H3
#( 18.8732 20.1200 43.7312) ; H5
H6
))
(define rU09
(nuc-const
#( -0.0317 0.1374 0.9900 ; dgf-base-tfo
-0.3422 -0.9321 0.1184
0.9391 -0.3351 0.0765
-32.1929 25.8198 -28.5088)
#( 0.2765 -0.1121 -0.9545 ; P-O3*-275-tfo
-0.8297 0.4733 -0.2959
0.4850 0.8737 0.0379
-14.7774 -45.2464 21.9088)
#( 0.1063 -0.6334 -0.7665 ; P-O3*-180-tfo
-0.5932 -0.6591 0.4624
-0.7980 0.4055 -0.4458
43.7634 4.3296 28.4890)
#( 0.7136 -0.5032 -0.4873 ; P-O3*-60-tfo
0.6803 0.3317 0.6536
-0.1673 -0.7979 0.5791
-17.1858 41.4390 -27.0751)
#( 21.3880 15.0780 45.5770) ; P
#( 21.9980 14.5500 46.8210) ; O1P
#( 21.1450 14.0270 44.5420) ; O2P
O5 *
#( 21.5037 16.8594 43.7323) ; C5*
#( 20.8147 17.6663 43.9823) ; H5*
#( 21.1086 16.0230 43.1557) ; H5**
#( 22.5654 17.4874 42.8616) ; C4*
#( 23.0565 18.3036 43.3915) ; H4*
#( 23.5375 16.5054 42.4925) ; O4*
#( 23.6574 16.4257 41.0649) ; C1*
#( 24.4701 17.0882 40.7671) ; H1*
#( 22.3525 16.9643 40.5396) ; C2*
#( 21.5993 16.1799 40.6133) ; H2**
#( 22.4693 17.4849 39.2515) ; O2*
#( 23.0899 17.0235 38.6827) ; H2*
#( 22.0341 18.0633 41.5279) ; C3*
#( 20.9509 18.1709 41.5846) ; H3*
#( 22.7249 19.3020 41.2100) ; O3*
#( 23.8580 15.0648 40.5757) ; N1
N3
C2
#( 25.3391 13.3315 40.0020) ; C4
C5
C6
rU
#( 22.9633 12.9979 39.8053) ; O2
O4
#( 26.3414 12.9194 39.8855) ; H3
#( 22.1227 12.3533 39.5486) ; H5
H6
))
(define rU10
(nuc-const
#( -0.9674 0.1021 -0.2318 ; dgf-base-tfo
-0.2514 -0.2766 0.9275
0.0306 0.9555 0.2933
27.8571 -42.1305 -24.4563)
#( 0.2765 -0.1121 -0.9545 ; P-O3*-275-tfo
-0.8297 0.4733 -0.2959
0.4850 0.8737 0.0379
-14.7774 -45.2464 21.9088)
#( 0.1063 -0.6334 -0.7665 ; P-O3*-180-tfo
-0.5932 -0.6591 0.4624
-0.7980 0.4055 -0.4458
43.7634 4.3296 28.4890)
#( 0.7136 -0.5032 -0.4873 ; P-O3*-60-tfo
0.6803 0.3317 0.6536
-0.1673 -0.7979 0.5791
-17.1858 41.4390 -27.0751)
#( 21.3880 15.0780 45.5770) ; P
#( 21.9980 14.5500 46.8210) ; O1P
#( 21.1450 14.0270 44.5420) ; O2P
O5 *
#( 23.5096 16.1227 44.5783) ; C5*
#( 23.5649 15.8588 43.5222) ; H5*
#( 23.9621 15.4341 45.2919) ; H5**
#( 24.2805 17.4138 44.7151) ; C4*
#( 23.8509 18.1819 44.0720) ; H4*
#( 24.2506 17.8583 46.0741) ; O4*
#( 25.5830 18.0320 46.5775) ; C1*
#( 25.8569 19.0761 46.4256) ; H1*
#( 26.4410 17.1555 45.7033) ; C2*
#( 26.3459 16.1253 46.0462) ; H2**
#( 27.7649 17.5888 45.6478) ; O2*
#( 28.1004 17.9719 46.4616) ; H2*
#( 25.7796 17.2997 44.3513) ; C3*
#( 25.9478 16.3824 43.7871) ; H3*
#( 26.2154 18.4984 43.6541) ; O3*
#( 25.7321 17.6281 47.9726) ; N1
N3
C2
#( 25.6482 18.1987 50.2518) ; C4
C5
C6
rU
#( 26.2067 15.9515 49.5943) ; O2
O4
#( 25.4890 18.9105 51.0618) ; H3
#( 26.4742 14.9310 49.8682) ; H5
H6
))
(define rUs
(list rU01 rU02 rU03 rU04 rU05 rU06 rU07 rU08 rU09 rU10))
(define rG*
(nuc-const
#( -0.2067 -0.0264 0.9780 ; dgf-base-tfo
0.9770 -0.0586 0.2049
0.0519 0.9979 0.0379
1.0331 -46.8078 -36.4742)
#( -0.8644 -0.4956 -0.0851 ; P-O3*-275-tfo
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
#( 0.3706 -0.6167 0.6945 ; P-O3*-180-tfo
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
#( 0.4155 0.9025 -0.1137 ; P-O3*-60-tfo
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
#( 31.3810 0.1400 47.5810) ; P
#( 29.9860 0.6630 47.6290) ; O1P
#( 31.7210 -0.6460 48.8090) ; O2P
O5 *
#( 32.1610 2.2370 46.2560) ; C5*
#( 31.2986 2.8190 46.5812) ; H5*
#( 32.0980 1.7468 45.2845) ; H5**
#( 33.3476 3.1959 46.1947) ; C4*
#( 33.2668 3.8958 45.3630) ; H4*
#( 33.3799 3.9183 47.4216) ; O4*
#( 34.6515 3.7222 48.0398) ; C1*
#( 35.2947 4.5412 47.7180) ; H1*
#( 35.1756 2.4228 47.4827) ; C2*
#( 34.6778 1.5937 47.9856) ; H2**
#( 36.5631 2.2672 47.4798) ; O2*
#( 37.0163 2.6579 48.2305) ; H2*
#( 34.6953 2.5043 46.0448) ; C3*
#( 34.5444 1.4917 45.6706) ; H3*
#( 35.6679 3.3009 45.3487) ; O3*
#( 37.4804 4.0914 52.2559) ; N1
N3
C2
#( 35.7171 3.8264 50.3222) ; C4
C5
C6
rG
#( 39.0869 4.5552 50.7092) ; N2
N7
N9
C8
#( 35.9958 3.6512 53.8724) ; O6
#( 38.2106 4.2053 52.9295) ; H1
#( 39.8218 4.6863 51.3896) ; H21
H22
H8
))
(define rU*
(nuc-const
#( -0.0109 0.5907 0.8068 ; dgf-base-tfo
0.2217 -0.7853 0.5780
0.9751 0.1852 -0.1224
-1.4225 -11.0956 -2.5217)
#( -0.8313 -0.4738 -0.2906 ; P-O3*-275-tfo
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
#( 0.3445 -0.7630 0.5470 ; P-O3*-180-tfo
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
#( 0.5855 0.7931 -0.1682 ; P-O3*-60-tfo
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
#( 2.6760 -8.4960 3.2880) ; P
#( 1.4950 -7.6230 3.4770) ; O1P
#( 2.9490 -9.4640 4.3740) ; O2P
O5 *
#( 5.2430 -8.2420 2.8260) ; C5*
#( 5.1974 -8.8497 1.9223) ; H5*
#( 5.5548 -8.7348 3.7469) ; H5**
#( 6.3140 -7.2060 2.5510) ; C4*
#( 5.8744 -6.2116 2.4731) ; H4*
#( 7.2798 -7.2260 3.6420) ; O4*
#( 8.5733 -6.9410 3.1329) ; C1*
#( 8.9047 -6.0374 3.6446) ; H1*
#( 8.4429 -6.6596 1.6327) ; C2*
#( 9.2880 -7.1071 1.1096) ; H2**
#( 8.2502 -5.2799 1.4754) ; O2*
#( 8.7676 -4.7284 2.0667) ; H2*
#( 7.1642 -7.4416 1.3021) ; C3*
#( 7.4125 -8.5002 1.2260) ; H3*
#( 6.5160 -6.9772 0.1267) ; O3*
#( 9.4531 -8.1107 3.4087) ; N1
N3
C2
#( 11.1439 -10.2744 3.9206) ; C4
C5
C6
rU
#( 11.3013 -6.8063 3.1326) ; O2
O4
#( 12.5840 -8.8673 3.6158) ; H3
#( 9.2891 -11.2898 4.1313) ; H5
H6
))
; -- PARTIAL INSTANTIATIONS ---------------------------------------------------
(define (make-var id tfo nuc)
(vector id tfo nuc))
(define (var-id var) (vector-ref var 0))
(define (var-id-set! var val) (vector-set! var 0 val))
(define (var-tfo var) (vector-ref var 1))
(define (var-tfo-set! var val) (vector-set! var 1 val))
(define (var-nuc var) (vector-ref var 2))
(define (var-nuc-set! var val) (vector-set! var 2 val))
(define (atom-pos atom var)
(tfo-apply (var-tfo var) (atom (var-nuc var))))
(define (get-var id lst)
(let ((v (car lst)))
(if (= id (var-id v))
v
(get-var id (cdr lst)))))
(define (make-relative-nuc tfo n)
(cond ((rA? n)
(make-rA
(nuc-dgf-base-tfo n)
(nuc-P-O3*-275-tfo n)
(nuc-P-O3*-180-tfo n)
(nuc-P-O3*-60-tfo n)
(tfo-apply tfo (nuc-P n))
(tfo-apply tfo (nuc-O1P n))
(tfo-apply tfo (nuc-O2P n))
(tfo-apply tfo (nuc-O5* n))
(tfo-apply tfo (nuc-C5* n))
(tfo-apply tfo (nuc-H5* n))
(tfo-apply tfo (nuc-H5** n))
(tfo-apply tfo (nuc-C4* n))
(tfo-apply tfo (nuc-H4* n))
(tfo-apply tfo (nuc-O4* n))
(tfo-apply tfo (nuc-C1* n))
(tfo-apply tfo (nuc-H1* n))
(tfo-apply tfo (nuc-C2* n))
(tfo-apply tfo (nuc-H2** n))
(tfo-apply tfo (nuc-O2* n))
(tfo-apply tfo (nuc-H2* n))
(tfo-apply tfo (nuc-C3* n))
(tfo-apply tfo (nuc-H3* n))
(tfo-apply tfo (nuc-O3* n))
(tfo-apply tfo (nuc-N1 n))
(tfo-apply tfo (nuc-N3 n))
(tfo-apply tfo (nuc-C2 n))
(tfo-apply tfo (nuc-C4 n))
(tfo-apply tfo (nuc-C5 n))
(tfo-apply tfo (nuc-C6 n))
(tfo-apply tfo (rA-N6 n))
(tfo-apply tfo (rA-N7 n))
(tfo-apply tfo (rA-N9 n))
(tfo-apply tfo (rA-C8 n))
(tfo-apply tfo (rA-H2 n))
(tfo-apply tfo (rA-H61 n))
(tfo-apply tfo (rA-H62 n))
(tfo-apply tfo (rA-H8 n))))
((rC? n)
(make-rC
(nuc-dgf-base-tfo n)
(nuc-P-O3*-275-tfo n)
(nuc-P-O3*-180-tfo n)
(nuc-P-O3*-60-tfo n)
(tfo-apply tfo (nuc-P n))
(tfo-apply tfo (nuc-O1P n))
(tfo-apply tfo (nuc-O2P n))
(tfo-apply tfo (nuc-O5* n))
(tfo-apply tfo (nuc-C5* n))
(tfo-apply tfo (nuc-H5* n))
(tfo-apply tfo (nuc-H5** n))
(tfo-apply tfo (nuc-C4* n))
(tfo-apply tfo (nuc-H4* n))
(tfo-apply tfo (nuc-O4* n))
(tfo-apply tfo (nuc-C1* n))
(tfo-apply tfo (nuc-H1* n))
(tfo-apply tfo (nuc-C2* n))
(tfo-apply tfo (nuc-H2** n))
(tfo-apply tfo (nuc-O2* n))
(tfo-apply tfo (nuc-H2* n))
(tfo-apply tfo (nuc-C3* n))
(tfo-apply tfo (nuc-H3* n))
(tfo-apply tfo (nuc-O3* n))
(tfo-apply tfo (nuc-N1 n))
(tfo-apply tfo (nuc-N3 n))
(tfo-apply tfo (nuc-C2 n))
(tfo-apply tfo (nuc-C4 n))
(tfo-apply tfo (nuc-C5 n))
(tfo-apply tfo (nuc-C6 n))
(tfo-apply tfo (rC-N4 n))
(tfo-apply tfo (rC-O2 n))
(tfo-apply tfo (rC-H41 n))
(tfo-apply tfo (rC-H42 n))
(tfo-apply tfo (rC-H5 n))
(tfo-apply tfo (rC-H6 n))))
((rG? n)
(make-rG
(nuc-dgf-base-tfo n)
(nuc-P-O3*-275-tfo n)
(nuc-P-O3*-180-tfo n)
(nuc-P-O3*-60-tfo n)
(tfo-apply tfo (nuc-P n))
(tfo-apply tfo (nuc-O1P n))
(tfo-apply tfo (nuc-O2P n))
(tfo-apply tfo (nuc-O5* n))
(tfo-apply tfo (nuc-C5* n))
(tfo-apply tfo (nuc-H5* n))
(tfo-apply tfo (nuc-H5** n))
(tfo-apply tfo (nuc-C4* n))
(tfo-apply tfo (nuc-H4* n))
(tfo-apply tfo (nuc-O4* n))
(tfo-apply tfo (nuc-C1* n))
(tfo-apply tfo (nuc-H1* n))
(tfo-apply tfo (nuc-C2* n))
(tfo-apply tfo (nuc-H2** n))
(tfo-apply tfo (nuc-O2* n))
(tfo-apply tfo (nuc-H2* n))
(tfo-apply tfo (nuc-C3* n))
(tfo-apply tfo (nuc-H3* n))
(tfo-apply tfo (nuc-O3* n))
(tfo-apply tfo (nuc-N1 n))
(tfo-apply tfo (nuc-N3 n))
(tfo-apply tfo (nuc-C2 n))
(tfo-apply tfo (nuc-C4 n))
(tfo-apply tfo (nuc-C5 n))
(tfo-apply tfo (nuc-C6 n))
(tfo-apply tfo (rG-N2 n))
(tfo-apply tfo (rG-N7 n))
(tfo-apply tfo (rG-N9 n))
(tfo-apply tfo (rG-C8 n))
(tfo-apply tfo (rG-O6 n))
(tfo-apply tfo (rG-H1 n))
(tfo-apply tfo (rG-H21 n))
(tfo-apply tfo (rG-H22 n))
(tfo-apply tfo (rG-H8 n))))
(else
(make-rU
(nuc-dgf-base-tfo n)
(nuc-P-O3*-275-tfo n)
(nuc-P-O3*-180-tfo n)
(nuc-P-O3*-60-tfo n)
(tfo-apply tfo (nuc-P n))
(tfo-apply tfo (nuc-O1P n))
(tfo-apply tfo (nuc-O2P n))
(tfo-apply tfo (nuc-O5* n))
(tfo-apply tfo (nuc-C5* n))
(tfo-apply tfo (nuc-H5* n))
(tfo-apply tfo (nuc-H5** n))
(tfo-apply tfo (nuc-C4* n))
(tfo-apply tfo (nuc-H4* n))
(tfo-apply tfo (nuc-O4* n))
(tfo-apply tfo (nuc-C1* n))
(tfo-apply tfo (nuc-H1* n))
(tfo-apply tfo (nuc-C2* n))
(tfo-apply tfo (nuc-H2** n))
(tfo-apply tfo (nuc-O2* n))
(tfo-apply tfo (nuc-H2* n))
(tfo-apply tfo (nuc-C3* n))
(tfo-apply tfo (nuc-H3* n))
(tfo-apply tfo (nuc-O3* n))
(tfo-apply tfo (nuc-N1 n))
(tfo-apply tfo (nuc-N3 n))
(tfo-apply tfo (nuc-C2 n))
(tfo-apply tfo (nuc-C4 n))
(tfo-apply tfo (nuc-C5 n))
(tfo-apply tfo (nuc-C6 n))
(tfo-apply tfo (rU-O2 n))
(tfo-apply tfo (rU-O4 n))
(tfo-apply tfo (rU-H3 n))
(tfo-apply tfo (rU-H5 n))
(tfo-apply tfo (rU-H6 n))))))
; -- SEARCH -------------------------------------------------------------------
; Sequential backtracking algorithm
(define (search partial-inst domains constraint?)
(if (null? domains)
(list partial-inst)
(let ((remaining-domains (cdr domains)))
(define (try-assignments lst)
(if (null? lst)
'()
(let ((var (car lst)))
(if (constraint? var partial-inst)
(let* ((subsols1
(search
(cons var partial-inst)
remaining-domains
constraint?))
(subsols2
(try-assignments (cdr lst))))
(append subsols1 subsols2))
(try-assignments (cdr lst))))))
(try-assignments ((car domains) partial-inst)))))
; -- DOMAINS ------------------------------------------------------------------
; Primary structure: strand A CUGCCACGUCUG, strand B CAGACGUGGCAG
;
; Secondary structure: strand A CUGCCACGUCUG
; ||||||||||||
; GACGGUGCAGAC strand B
;
; Tertiary structure:
;
5 ' end of strand A C1 - ---G12 3 ' end of strand B
; U2-------A11
; G3-------C10
; C4-----G9
; A6
; G6-C7
; C5----G8
; A4-------U9
; G3--------C10
A2 - ------U11
; 5' end of strand B C1----G12 3' end of strand A
;
; "helix", "stacked" and "connected" describe the spatial relationship
between two consecutive nucleotides . E.g. the nucleotides C1 and U2
; from the strand A.
;
" wc " ( stands for Watson - Crick and is a type of base - pairing ) ,
; and "wc-dumas" describe the spatial relationship between
nucleotides from two chains that are growing in opposite directions .
E.g. the nucleotides C1 from strand A and G12 from strand B.
; Dynamic Domains
; Given,
; "ref" a nucleotide which is already positioned,
; "nuc" the nucleotide to be placed,
; and "tfo" a transformation matrix which expresses the desired
; relationship between "ref" and "nuc",
; the function "dgf-base" computes the transformation matrix that
; places the nucleotide "nuc" in the given relationship to "ref".
(define (dgf-base tfo ref nuc)
(let* ((ref-nuc (var-nuc ref))
(align
(tfo-inv-ortho
(cond ((rA? ref-nuc)
(tfo-align (atom-pos nuc-C1* ref)
(atom-pos rA-N9 ref)
(atom-pos nuc-C4 ref)))
((rC? ref-nuc)
(tfo-align (atom-pos nuc-C1* ref)
(atom-pos nuc-N1 ref)
(atom-pos nuc-C2 ref)))
((rG? ref-nuc)
(tfo-align (atom-pos nuc-C1* ref)
(atom-pos rG-N9 ref)
(atom-pos nuc-C4 ref)))
(else
(tfo-align (atom-pos nuc-C1* ref)
(atom-pos nuc-N1 ref)
(atom-pos nuc-C2 ref)))))))
(tfo-combine (nuc-dgf-base-tfo nuc)
(tfo-combine tfo align))))
Placement of first nucleotide .
(define (reference nuc i)
(lambda (partial-inst)
(list (make-var i tfo-id nuc))))
; The transformation matrix for wc is from:
;
( 1989 ) A Re - Examination of the Crystal
Structure of A - DNA Using Fiber Diffraction Data . .
Struct . & Dynamics 6(6):1189 - 1202 .
(define wc-tfo
(FLOATvector-const
-1.0000 0.0028 -0.0019
0.0028 0.3468 -0.9379
-0.0019 -0.9379 -0.3468
-0.0080 6.0730 8.7208))
(define (wc nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base wc-tfo ref nuc)))
(list (make-var i tfo nuc)))))
(define wc-Dumas-tfo
(FLOATvector-const
-0.9737 -0.1834 0.1352
-0.1779 0.2417 -0.9539
0.1422 -0.9529 -0.2679
0.4837 6.2649 8.0285))
(define (wc-Dumas nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base wc-Dumas-tfo ref nuc)))
(list (make-var i tfo nuc)))))
(define helix5*-tfo
(FLOATvector-const
0.9886 -0.0961 0.1156
0.1424 0.8452 -0.5152
-0.0482 0.5258 0.8492
-3.8737 0.5480 3.8024))
(define (helix5* nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base helix5*-tfo ref nuc)))
(list (make-var i tfo nuc)))))
(define helix3*-tfo
(FLOATvector-const
0.9886 0.1424 -0.0482
-0.0961 0.8452 0.5258
0.1156 -0.5152 0.8492
3.4426 2.0474 -3.7042))
(define (helix3* nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base helix3*-tfo ref nuc)))
(list (make-var i tfo nuc)))))
(define G37-A38-tfo
(FLOATvector-const
0.9991 0.0164 -0.0387
-0.0375 0.7616 -0.6470
0.0189 0.6478 0.7615
-3.3018 0.9975 2.5585))
(define (G37-A38 nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base G37-A38-tfo ref nuc)))
(make-var i tfo nuc))))
(define (stacked5* nuc i j)
(lambda (partial-inst)
(cons ((G37-A38 nuc i j) partial-inst)
((helix5* nuc i j) partial-inst))))
(define A38-G37-tfo
(FLOATvector-const
0.9991 -0.0375 0.0189
0.0164 0.7616 0.6478
-0.0387 -0.6470 0.7615
3.3819 0.7718 -2.5321))
(define (A38-G37 nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base A38-G37-tfo ref nuc)))
(make-var i tfo nuc))))
(define (stacked3* nuc i j)
(lambda (partial-inst)
(cons ((A38-G37 nuc i j) partial-inst)
((helix3* nuc i j) partial-inst))))
(define (P-O3* nucs i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(align
(tfo-inv-ortho
(tfo-align (atom-pos nuc-O3* ref)
(atom-pos nuc-C3* ref)
(atom-pos nuc-C4* ref)))))
(let loop ((lst nucs) (domains '()))
(if (null? lst)
domains
(let ((nuc (car lst)))
(let ((tfo-60 (tfo-combine (nuc-P-O3*-60-tfo nuc) align))
(tfo-180 (tfo-combine (nuc-P-O3*-180-tfo nuc) align))
(tfo-275 (tfo-combine (nuc-P-O3*-275-tfo nuc) align)))
(loop (cdr lst)
(cons (make-var i tfo-60 nuc)
(cons (make-var i tfo-180 nuc)
(cons (make-var i tfo-275 nuc) domains)))))))))))
; -- PROBLEM STATEMENT --------------------------------------------------------
Define anticodon problem -- Science 253:1255 Figure 3a , 3b and 3c
(define anticodon-domains
(list
(reference rC 27 )
(helix5* rC 28 27)
(helix5* rA 29 28)
(helix5* rG 30 29)
(helix5* rA 31 30)
(wc rU 39 31)
(helix5* rC 40 39)
(helix5* rU 41 40)
(helix5* rG 42 41)
(helix5* rG 43 42)
(stacked3* rA 38 39)
(stacked3* rG 37 38)
(stacked3* rA 36 37)
(stacked3* rA 35 36)
(stacked3* rG 34 35);<-. Distance
(P-O3* rCs 32 31); | Constraint
< - ' 3.0 Angstroms
))
constraint
(define (anticodon-constraint? v partial-inst)
(if (= (var-id v) 33)
P in nucleotide 34
O3 ' in nucl . 33
(FLOAT<= (pt-dist p o3*) 3.0)) ; check distance
#t))
(define (anticodon)
(search '() anticodon-domains anticodon-constraint?))
Define pseudoknot problem -- Science 253:1255 Figure 4a and 4b
(define pseudoknot-domains
(list
(reference rA 23 )
(wc-Dumas rU 8 23)
(helix3* rG 22 23)
(wc-Dumas rC 9 22)
(helix3* rG 21 22)
(wc-Dumas rC 10 21)
(helix3* rC 20 21)
(wc-Dumas rG 11 20)
(helix3* rU* 19 20);<-.
(wc-Dumas rA 12 19); | Distance
; ; | Constraint
Helix 1 ; | 4.0 Angstroms
(helix3* rC 3 19); |
(wc-Dumas rG 13 3); |
(helix3* rC 2 3); |
(wc-Dumas rG 14 2); |
(helix3* rC 1 2); |
(wc-Dumas rG* 15 1); |
; ; |
; L2 LOOP ; |
(P-O3* rUs 16 15); |
(P-O3* rCs 17 16); |
(P-O3* rAs 18 17);<-'
;
; L1 LOOP
(helix3* rU 7 8);<-.
(P-O3* rCs 4 3); | Constraint
| 4.5 Angstroms
(stacked5* rC 6 5);<-'
))
Pseudoknot constraint
(define (pseudoknot-constraint? v partial-inst)
(case (var-id v)
((18)
(let ((p (atom-pos nuc-P (get-var 19 partial-inst)))
(o3* (atom-pos nuc-O3* v)))
(FLOAT<= (pt-dist p o3*) 4.0)))
((6)
(let ((p (atom-pos nuc-P (get-var 7 partial-inst)))
(o3* (atom-pos nuc-O3* v)))
(FLOAT<= (pt-dist p o3*) 4.5)))
(else
#t)))
(define (pseudoknot)
(search '() pseudoknot-domains pseudoknot-constraint?))
; -- TESTING -----------------------------------------------------------------
(define (list-of-atoms n)
(append (list-of-common-atoms n)
(list-of-specific-atoms n)))
(define (list-of-common-atoms n)
(list
(nuc-P n)
(nuc-O1P n)
(nuc-O2P n)
(nuc-O5* n)
(nuc-C5* n)
(nuc-H5* n)
(nuc-H5** n)
(nuc-C4* n)
(nuc-H4* n)
(nuc-O4* n)
(nuc-C1* n)
(nuc-H1* n)
(nuc-C2* n)
(nuc-H2** n)
(nuc-O2* n)
(nuc-H2* n)
(nuc-C3* n)
(nuc-H3* n)
(nuc-O3* n)
(nuc-N1 n)
(nuc-N3 n)
(nuc-C2 n)
(nuc-C4 n)
(nuc-C5 n)
(nuc-C6 n)))
(define (list-of-specific-atoms n)
(cond ((rA? n)
(list
(rA-N6 n)
(rA-N7 n)
(rA-N9 n)
(rA-C8 n)
(rA-H2 n)
(rA-H61 n)
(rA-H62 n)
(rA-H8 n)))
((rC? n)
(list
(rC-N4 n)
(rC-O2 n)
(rC-H41 n)
(rC-H42 n)
(rC-H5 n)
(rC-H6 n)))
((rG? n)
(list
(rG-N2 n)
(rG-N7 n)
(rG-N9 n)
(rG-C8 n)
(rG-O6 n)
(rG-H1 n)
(rG-H21 n)
(rG-H22 n)
(rG-H8 n)))
(else
(list
(rU-O2 n)
(rU-O4 n)
(rU-H3 n)
(rU-H5 n)
(rU-H6 n)))))
(define (var-most-distant-atom v)
(define (distance pos)
(let ((abs-pos (tfo-apply (var-tfo v) pos)))
(let ((x (pt-x abs-pos)) (y (pt-y abs-pos)) (z (pt-z abs-pos)))
(FLOATsqrt (FLOAT+ (FLOAT* x x) (FLOAT* y y) (FLOAT* z z))))))
(maximum (map distance (list-of-atoms (var-nuc v)))))
(define (sol-most-distant-atom s)
(maximum (map var-most-distant-atom s)))
(define (most-distant-atom sols)
(maximum (map sol-most-distant-atom sols)))
(define (maximum lst)
(let loop ((m (car lst)) (l (cdr lst)))
(if (null? l)
m
(let ((x (car l)))
(loop (if (FLOAT> x m) x m) (cdr l))))))
(define (run)
(most-distant-atom (pseudoknot)))
(define (main . args)
(run-benchmark
"nucleic"
nucleic-iters
(lambda (result)
(and (number? result)
(let ((x (FLOAT/ result 33.797594890762724)))
(and (FLOAT> x 0.999999) (FLOAT< x 1.000001)))))
(lambda () (lambda () (run)))))
(main)
| null | https://raw.githubusercontent.com/bsaleil/lc/ee7867fd2bdbbe88924300e10b14ea717ee6434b/tools/benchtimes/resultVMIL-lc-gsc-lc/LC5/nucleic.scm.scm | scheme | ------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Gabriel benchmarks
C benchmarks
Other benchmarks
This program is a modified version of the program described in the paper:
Constraint Satisfaction Problems: an Application to Nucleic Acid 3D
Computation".
The differences between this program and the original are described in
the paper:
-- MATH UTILITIES -----------------------------------------------------------
-- POINTS -------------------------------------------------------------------
-- COORDINATE TRANSFORMATIONS -----------------------------------------------
matrices don't have the perspective terms and are the transpose of
The components of a transformation matrix are named like this:
a b c
d e f
tx ty tz
the identity transformation matrix
The function "tfo-apply" multiplies a transformation matrix, tfo, by a
point vector, p. The result is a new point.
The result is a new matrix which cumulates the transformations described
by A and B.
The function "tfo-inv-ortho" computes the inverse of a homogeneous
transformation matrix.
mapped to the Y axis and p3 gets mapped to the YZ plane.
-- NUCLEIC ACID CONFORMATIONS DATA BASE -------------------------------------
Numbering of atoms follows the paper:
In the atom names, we have used "*" instead of "'".
Define remaining atoms for each nucleotide type.
Database of nucleotide conformations:
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
H2
H62
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H41
H42
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
N2
O6
H1
H21
dgf-base-tfo
P-O3*-275-tfo
P-O3*-180-tfo
P-O3*-60-tfo
P
O1P
O2P
C5*
H5*
H5**
C4*
H4*
O4*
C1*
H1*
C2*
H2**
O2*
H2*
C3*
H3*
O3*
N1
C4
O2
H3
H5
-- PARTIAL INSTANTIATIONS ---------------------------------------------------
-- SEARCH -------------------------------------------------------------------
Sequential backtracking algorithm
-- DOMAINS ------------------------------------------------------------------
Primary structure: strand A CUGCCACGUCUG, strand B CAGACGUGGCAG
Secondary structure: strand A CUGCCACGUCUG
||||||||||||
GACGGUGCAGAC strand B
Tertiary structure:
U2-------A11
G3-------C10
C4-----G9
A6
G6-C7
C5----G8
A4-------U9
G3--------C10
5' end of strand B C1----G12 3' end of strand A
"helix", "stacked" and "connected" describe the spatial relationship
from the strand A.
and "wc-dumas" describe the spatial relationship between
Dynamic Domains
Given,
"ref" a nucleotide which is already positioned,
"nuc" the nucleotide to be placed,
and "tfo" a transformation matrix which expresses the desired
relationship between "ref" and "nuc",
the function "dgf-base" computes the transformation matrix that
places the nucleotide "nuc" in the given relationship to "ref".
The transformation matrix for wc is from:
-- PROBLEM STATEMENT --------------------------------------------------------
<-. Distance
| Constraint
check distance
<-.
| Distance
; | Constraint
| 4.0 Angstroms
|
|
|
|
|
|
; |
L2 LOOP ; |
|
|
<-'
L1 LOOP
<-.
| Constraint
<-'
-- TESTING ----------------------------------------------------------------- | Macros
(##define-macro (def-macro form . body)
`(##define-macro ,form (let () ,@body)))
(def-macro (FLOATvector-const . lst) `',(list->vector lst))
(def-macro (FLOATvector? x) `(vector? ,x))
(def-macro (FLOATvector . lst) `(vector ,@lst))
(def-macro (FLOATmake-vector n . init) `(make-vector ,n ,@init))
(def-macro (FLOATvector-ref v i) `(vector-ref ,v ,i))
(def-macro (FLOATvector-set! v i x) `(vector-set! ,v ,i ,x))
(def-macro (FLOATvector-length v) `(vector-length ,v))
(def-macro (nuc-const . lst)
`',(list->vector lst))
(def-macro (FLOAT+ . lst) `(+ ,@lst))
(def-macro (FLOAT- . lst) `(- ,@lst))
(def-macro (FLOAT* . lst) `(* ,@lst))
(def-macro (FLOAT/ . lst) `(/ ,@lst))
(def-macro (FLOAT= . lst) `(= ,@lst))
(def-macro (FLOAT< . lst) `(< ,@lst))
(def-macro (FLOAT<= . lst) `(<= ,@lst))
(def-macro (FLOAT> . lst) `(> ,@lst))
(def-macro (FLOAT>= . lst) `(>= ,@lst))
(def-macro (FLOATnegative? . lst) `(negative? ,@lst))
(def-macro (FLOATpositive? . lst) `(positive? ,@lst))
(def-macro (FLOATzero? . lst) `(zero? ,@lst))
(def-macro (FLOATabs . lst) `(abs ,@lst))
(def-macro (FLOATsin . lst) `(sin ,@lst))
(def-macro (FLOATcos . lst) `(cos ,@lst))
(def-macro (FLOATatan . lst) `(atan ,@lst))
(def-macro (FLOATsqrt . lst) `(sqrt ,@lst))
(def-macro (FLOATmin . lst) `(min ,@lst))
(def-macro (FLOATmax . lst) `(max ,@lst))
(def-macro (FLOATround . lst) `(round ,@lst))
(def-macro (FLOATinexact->exact . lst) `(inexact->exact ,@lst))
(def-macro (GENERIC+ . lst) `(+ ,@lst))
(def-macro (GENERIC- . lst) `(- ,@lst))
(def-macro (GENERIC* . lst) `(* ,@lst))
(def-macro (GENERIC/ . lst) `(/ ,@lst))
(def-macro (GENERICquotient . lst) `(quotient ,@lst))
(def-macro (GENERICremainder . lst) `(remainder ,@lst))
(def-macro (GENERICmodulo . lst) `(modulo ,@lst))
(def-macro (GENERIC= . lst) `(= ,@lst))
(def-macro (GENERIC< . lst) `(< ,@lst))
(def-macro (GENERIC<= . lst) `(<= ,@lst))
(def-macro (GENERIC> . lst) `(> ,@lst))
(def-macro (GENERIC>= . lst) `(>= ,@lst))
(def-macro (GENERICexpt . lst) `(expt ,@lst))
Functions used by LC to get time info
(def-macro (##lc-time expr)
(let ((sym (gensym)))
`(let ((r (##lc-exec-stats (lambda () ,expr))))
(##print-perm-string "CPU time: ")
(##print-double (+ (cdr (assoc "User time" (cdr r)))
(cdr (assoc "Sys time" (cdr r)))))
(##print-perm-string "\n")
(##print-perm-string "GC CPU time: ")
(##print-double (+ (cdr (assoc "GC user time" (cdr r)))
(cdr (assoc "GC sys time" (cdr r)))))
(##print-perm-string "\n")
(map (lambda (el)
(##print-perm-string (car el))
(##print-perm-string ": ")
(##print-double (cdr el))
(##print-perm-string "\n"))
(cdr r))
r)))
(define (##lc-exec-stats thunk)
(let* ((at-start (##process-statistics))
(result (thunk))
(at-end (##process-statistics)))
(define (get-info msg idx)
(cons msg
(- (f64vector-ref at-end idx)
(f64vector-ref at-start idx))))
(list
result
(get-info "User time" 0)
(get-info "Sys time" 1)
(get-info "Real time" 2)
(get-info "GC user time" 3)
(get-info "GC sys time" 4)
(get-info "GC real time" 5)
(get-info "Nb gcs" 6))))
(define (run-bench name count ok? run)
(let loop ((i count) (result '(undefined)))
(if (< 0 i)
(loop (- i 1) (run))
result)))
(define (run-benchmark name count ok? run-maker . args)
(let ((run (apply run-maker args)))
(let ((result (car (##lc-time (run-bench name count ok? run)))))
(if (not (ok? result))
(begin
(display "*** wrong result ***")
(newline)
(display "*** got: ")
(write result)
(newline))))))
(define boyer-iters 20)
(define browse-iters 600)
(define cpstak-iters 1000)
(define ctak-iters 100)
(define dderiv-iters 2000000)
(define deriv-iters 2000000)
(define destruc-iters 500)
(define diviter-iters 1000000)
(define divrec-iters 1000000)
(define puzzle-iters 100)
(define tak-iters 2000)
(define takl-iters 300)
(define trav1-iters 100)
(define trav2-iters 20)
(define triangl-iters 10)
and benchmarks
(define ack-iters 10)
(define array1-iters 1)
(define cat-iters 1)
(define string-iters 10)
(define sum1-iters 10)
(define sumloop-iters 10)
(define tail-iters 1)
(define wc-iters 1)
(define fft-iters 2000)
(define fib-iters 5)
(define fibfp-iters 2)
(define mbrot-iters 100)
(define nucleic-iters 5)
(define pnpoly-iters 100000)
(define sum-iters 20000)
(define sumfp-iters 20000)
(define tfib-iters 20)
(define conform-iters 40)
(define dynamic-iters 20)
(define earley-iters 200)
(define fibc-iters 500)
(define graphs-iters 300)
(define lattice-iters 1)
(define matrix-iters 400)
(define maze-iters 4000)
(define mazefun-iters 1000)
(define nqueens-iters 2000)
(define paraffins-iters 1000)
(define peval-iters 200)
(define pi-iters 2)
(define primes-iters 100000)
(define ray-iters 5)
(define scheme-iters 20000)
(define simplex-iters 100000)
(define slatex-iters 20)
(define perm9-iters 10)
(define nboyer-iters 100)
(define sboyer-iters 100)
(define gcbench-iters 1)
(define compiler-iters 300)
(define nbody-iters 1)
(define fftrad4-iters 4)
NUCLEIC -- 3D structure determination of a nucleic acid .
Author : ( )
Last modified : January 27 , 1996
, , , " Using Multilisp for Solving
Structure Determination " published in the journal " Lisp and Symbolic
" ? ? ? " published in the " Journal of Functional Programming " .
(define constant-pi 3.14159265358979323846)
(define constant-minus-pi -3.14159265358979323846)
(define constant-pi/2 1.57079632679489661923)
(define constant-minus-pi/2 -1.57079632679489661923)
(define (math-atan2 y x)
(cond ((FLOAT> x 0.0)
(FLOATatan (FLOAT/ y x)))
((FLOAT< y 0.0)
(if (FLOAT= x 0.0)
constant-minus-pi/2
(FLOAT+ (FLOATatan (FLOAT/ y x)) constant-minus-pi)))
(else
(if (FLOAT= x 0.0)
constant-pi/2
(FLOAT+ (FLOATatan (FLOAT/ y x)) constant-pi)))))
(define (make-pt x y z)
(FLOATvector x y z))
(define (pt-x pt) (FLOATvector-ref pt 0))
(define (pt-x-set! pt val) (FLOATvector-set! pt 0 val))
(define (pt-y pt) (FLOATvector-ref pt 1))
(define (pt-y-set! pt val) (FLOATvector-set! pt 1 val))
(define (pt-z pt) (FLOATvector-ref pt 2))
(define (pt-z-set! pt val) (FLOATvector-set! pt 2 val))
(define (pt-sub p1 p2)
(make-pt (FLOAT- (pt-x p1) (pt-x p2))
(FLOAT- (pt-y p1) (pt-y p2))
(FLOAT- (pt-z p1) (pt-z p2))))
(define (pt-dist p1 p2)
(let ((dx (FLOAT- (pt-x p1) (pt-x p2)))
(dy (FLOAT- (pt-y p1) (pt-y p2)))
(dz (FLOAT- (pt-z p1) (pt-z p2))))
(FLOATsqrt (FLOAT+ (FLOAT* dx dx) (FLOAT* dy dy) (FLOAT* dz dz)))))
(define (pt-phi p)
(let* ((x (pt-x p))
(y (pt-y p))
(z (pt-z p))
(b (math-atan2 x z)))
(math-atan2 (FLOAT+ (FLOAT* (FLOATcos b) z) (FLOAT* (FLOATsin b) x)) y)))
(define (pt-theta p)
(math-atan2 (pt-x p) (pt-z p)))
The notation for the transformations follows " , R.P. ( 1981 ) Robot
Manipulators . MIT Press . " with the exception that our transformation
's one . See also " M\"antyl\"a , M. ( 1985 ) An Introduction to
Solid Modeling , Computer Science Press " Appendix A.
The components tx , ty , and tz are the translation vector .
(define (make-tfo a b c d e f g h i tx ty tz)
(FLOATvector a b c d e f g h i tx ty tz))
(define (tfo-a tfo) (FLOATvector-ref tfo 0))
(define (tfo-a-set! tfo val) (FLOATvector-set! tfo 0 val))
(define (tfo-b tfo) (FLOATvector-ref tfo 1))
(define (tfo-b-set! tfo val) (FLOATvector-set! tfo 1 val))
(define (tfo-c tfo) (FLOATvector-ref tfo 2))
(define (tfo-c-set! tfo val) (FLOATvector-set! tfo 2 val))
(define (tfo-d tfo) (FLOATvector-ref tfo 3))
(define (tfo-d-set! tfo val) (FLOATvector-set! tfo 3 val))
(define (tfo-e tfo) (FLOATvector-ref tfo 4))
(define (tfo-e-set! tfo val) (FLOATvector-set! tfo 4 val))
(define (tfo-f tfo) (FLOATvector-ref tfo 5))
(define (tfo-f-set! tfo val) (FLOATvector-set! tfo 5 val))
(define (tfo-g tfo) (FLOATvector-ref tfo 6))
(define (tfo-g-set! tfo val) (FLOATvector-set! tfo 6 val))
(define (tfo-h tfo) (FLOATvector-ref tfo 7))
(define (tfo-h-set! tfo val) (FLOATvector-set! tfo 7 val))
(define (tfo-i tfo) (FLOATvector-ref tfo 8))
(define (tfo-i-set! tfo val) (FLOATvector-set! tfo 8 val))
(define (tfo-tx tfo) (FLOATvector-ref tfo 9))
(define (tfo-tx-set! tfo val) (FLOATvector-set! tfo 9 val))
(define (tfo-ty tfo) (FLOATvector-ref tfo 10))
(define (tfo-ty-set! tfo val) (FLOATvector-set! tfo 10 val))
(define (tfo-tz tfo) (FLOATvector-ref tfo 11))
(define (tfo-tz-set! tfo val) (FLOATvector-set! tfo 11 val))
(FLOATvector-const
1.0 0.0 0.0
0.0 1.0 0.0
0.0 0.0 1.0
0.0 0.0 0.0))
(define (tfo-apply tfo p)
(let ((x (pt-x p))
(y (pt-y p))
(z (pt-z p)))
(make-pt
(FLOAT+ (FLOAT* x (tfo-a tfo))
(FLOAT* y (tfo-d tfo))
(FLOAT* z (tfo-g tfo))
(tfo-tx tfo))
(FLOAT+ (FLOAT* x (tfo-b tfo))
(FLOAT* y (tfo-e tfo))
(FLOAT* z (tfo-h tfo))
(tfo-ty tfo))
(FLOAT+ (FLOAT* x (tfo-c tfo))
(FLOAT* y (tfo-f tfo))
(FLOAT* z (tfo-i tfo))
(tfo-tz tfo)))))
The function " tfo - combine " multiplies two transformation matrices A and B.
(define (tfo-combine A B)
(make-tfo
(FLOAT+ (FLOAT* (tfo-a A) (tfo-a B))
(FLOAT* (tfo-b A) (tfo-d B))
(FLOAT* (tfo-c A) (tfo-g B)))
(FLOAT+ (FLOAT* (tfo-a A) (tfo-b B))
(FLOAT* (tfo-b A) (tfo-e B))
(FLOAT* (tfo-c A) (tfo-h B)))
(FLOAT+ (FLOAT* (tfo-a A) (tfo-c B))
(FLOAT* (tfo-b A) (tfo-f B))
(FLOAT* (tfo-c A) (tfo-i B)))
(FLOAT+ (FLOAT* (tfo-d A) (tfo-a B))
(FLOAT* (tfo-e A) (tfo-d B))
(FLOAT* (tfo-f A) (tfo-g B)))
(FLOAT+ (FLOAT* (tfo-d A) (tfo-b B))
(FLOAT* (tfo-e A) (tfo-e B))
(FLOAT* (tfo-f A) (tfo-h B)))
(FLOAT+ (FLOAT* (tfo-d A) (tfo-c B))
(FLOAT* (tfo-e A) (tfo-f B))
(FLOAT* (tfo-f A) (tfo-i B)))
(FLOAT+ (FLOAT* (tfo-g A) (tfo-a B))
(FLOAT* (tfo-h A) (tfo-d B))
(FLOAT* (tfo-i A) (tfo-g B)))
(FLOAT+ (FLOAT* (tfo-g A) (tfo-b B))
(FLOAT* (tfo-h A) (tfo-e B))
(FLOAT* (tfo-i A) (tfo-h B)))
(FLOAT+ (FLOAT* (tfo-g A) (tfo-c B))
(FLOAT* (tfo-h A) (tfo-f B))
(FLOAT* (tfo-i A) (tfo-i B)))
(FLOAT+ (FLOAT* (tfo-tx A) (tfo-a B))
(FLOAT* (tfo-ty A) (tfo-d B))
(FLOAT* (tfo-tz A) (tfo-g B))
(tfo-tx B))
(FLOAT+ (FLOAT* (tfo-tx A) (tfo-b B))
(FLOAT* (tfo-ty A) (tfo-e B))
(FLOAT* (tfo-tz A) (tfo-h B))
(tfo-ty B))
(FLOAT+ (FLOAT* (tfo-tx A) (tfo-c B))
(FLOAT* (tfo-ty A) (tfo-f B))
(FLOAT* (tfo-tz A) (tfo-i B))
(tfo-tz B))))
(define (tfo-inv-ortho tfo)
(let* ((tx (tfo-tx tfo))
(ty (tfo-ty tfo))
(tz (tfo-tz tfo)))
(make-tfo
(tfo-a tfo) (tfo-d tfo) (tfo-g tfo)
(tfo-b tfo) (tfo-e tfo) (tfo-h tfo)
(tfo-c tfo) (tfo-f tfo) (tfo-i tfo)
(FLOAT- (FLOAT+ (FLOAT* (tfo-a tfo) tx)
(FLOAT* (tfo-b tfo) ty)
(FLOAT* (tfo-c tfo) tz)))
(FLOAT- (FLOAT+ (FLOAT* (tfo-d tfo) tx)
(FLOAT* (tfo-e tfo) ty)
(FLOAT* (tfo-f tfo) tz)))
(FLOAT- (FLOAT+ (FLOAT* (tfo-g tfo) tx)
(FLOAT* (tfo-h tfo) ty)
(FLOAT* (tfo-i tfo) tz))))))
Given three points p1 , p2 , and p3 , the function " tfo - align " computes
a transformation matrix such that point p1 gets mapped to ( 0,0,0 ) , p2 gets
(define (tfo-align p1 p2 p3)
(let* ((x1 (pt-x p1)) (y1 (pt-y p1)) (z1 (pt-z p1))
(x3 (pt-x p3)) (y3 (pt-y p3)) (z3 (pt-z p3))
(x31 (FLOAT- x3 x1)) (y31 (FLOAT- y3 y1)) (z31 (FLOAT- z3 z1))
(rotpY (pt-sub p2 p1))
(Phi (pt-phi rotpY))
(Theta (pt-theta rotpY))
(sinP (FLOATsin Phi))
(sinT (FLOATsin Theta))
(cosP (FLOATcos Phi))
(cosT (FLOATcos Theta))
(sinPsinT (FLOAT* sinP sinT))
(sinPcosT (FLOAT* sinP cosT))
(cosPsinT (FLOAT* cosP sinT))
(cosPcosT (FLOAT* cosP cosT))
(rotpZ
(make-pt
(FLOAT- (FLOAT* cosT x31)
(FLOAT* sinT z31))
(FLOAT+ (FLOAT* sinPsinT x31)
(FLOAT* cosP y31)
(FLOAT* sinPcosT z31))
(FLOAT+ (FLOAT* cosPsinT x31)
(FLOAT- (FLOAT* sinP y31))
(FLOAT* cosPcosT z31))))
(Rho (pt-theta rotpZ))
(cosR (FLOATcos Rho))
(sinR (FLOATsin Rho))
(x (FLOAT+ (FLOAT- (FLOAT* x1 cosT))
(FLOAT* z1 sinT)))
(y (FLOAT- (FLOAT- (FLOAT- (FLOAT* x1 sinPsinT))
(FLOAT* y1 cosP))
(FLOAT* z1 sinPcosT)))
(z (FLOAT- (FLOAT+ (FLOAT- (FLOAT* x1 cosPsinT))
(FLOAT* y1 sinP))
(FLOAT* z1 cosPcosT))))
(make-tfo
(FLOAT- (FLOAT* cosT cosR) (FLOAT* cosPsinT sinR))
sinPsinT
(FLOAT+ (FLOAT* cosT sinR) (FLOAT* cosPsinT cosR))
(FLOAT* sinP sinR)
cosP
(FLOAT- (FLOAT* sinP cosR))
(FLOAT- (FLOAT- (FLOAT* sinT cosR)) (FLOAT* cosPcosT sinR))
sinPcosT
(FLOAT+ (FLOAT- (FLOAT* sinT sinR)) (FLOAT* cosPcosT cosR))
(FLOAT- (FLOAT* x cosR) (FLOAT* z sinR))
y
(FLOAT+ (FLOAT* x sinR) (FLOAT* z cosR)))))
IUPAC - IUB Joint Commission on Biochemical Nomenclature ( JCBN )
( 1983 ) Abbreviations and Symbols for the Description of
Conformations of Polynucleotide Chains . Eur . J. Biochem 131 ,
9 - 15 .
Define part common to all 4 nucleotide types .
(define (nuc-dgf-base-tfo nuc) (vector-ref nuc 0))
(define (nuc-dgf-base-tfo-set! nuc val) (vector-set! nuc 0 val))
(define (nuc-P-O3*-275-tfo nuc) (vector-ref nuc 1))
(define (nuc-P-O3*-275-tfo-set! nuc val) (vector-set! nuc 1 val))
(define (nuc-P-O3*-180-tfo nuc) (vector-ref nuc 2))
(define (nuc-P-O3*-180-tfo-set! nuc val) (vector-set! nuc 2 val))
(define (nuc-P-O3*-60-tfo nuc) (vector-ref nuc 3))
(define (nuc-P-O3*-60-tfo-set! nuc val) (vector-set! nuc 3 val))
(define (nuc-P nuc) (vector-ref nuc 4))
(define (nuc-P-set! nuc val) (vector-set! nuc 4 val))
(define (nuc-O1P nuc) (vector-ref nuc 5))
(define (nuc-O1P-set! nuc val) (vector-set! nuc 5 val))
(define (nuc-O2P nuc) (vector-ref nuc 6))
(define (nuc-O2P-set! nuc val) (vector-set! nuc 6 val))
(define (nuc-O5* nuc) (vector-ref nuc 7))
(define (nuc-O5*-set! nuc val) (vector-set! nuc 7 val))
(define (nuc-C5* nuc) (vector-ref nuc 8))
(define (nuc-C5*-set! nuc val) (vector-set! nuc 8 val))
(define (nuc-H5* nuc) (vector-ref nuc 9))
(define (nuc-H5*-set! nuc val) (vector-set! nuc 9 val))
(define (nuc-H5** nuc) (vector-ref nuc 10))
(define (nuc-H5**-set! nuc val) (vector-set! nuc 10 val))
(define (nuc-C4* nuc) (vector-ref nuc 11))
(define (nuc-C4*-set! nuc val) (vector-set! nuc 11 val))
(define (nuc-H4* nuc) (vector-ref nuc 12))
(define (nuc-H4*-set! nuc val) (vector-set! nuc 12 val))
(define (nuc-O4* nuc) (vector-ref nuc 13))
(define (nuc-O4*-set! nuc val) (vector-set! nuc 13 val))
(define (nuc-C1* nuc) (vector-ref nuc 14))
(define (nuc-C1*-set! nuc val) (vector-set! nuc 14 val))
(define (nuc-H1* nuc) (vector-ref nuc 15))
(define (nuc-H1*-set! nuc val) (vector-set! nuc 15 val))
(define (nuc-C2* nuc) (vector-ref nuc 16))
(define (nuc-C2*-set! nuc val) (vector-set! nuc 16 val))
(define (nuc-H2** nuc) (vector-ref nuc 17))
(define (nuc-H2**-set! nuc val) (vector-set! nuc 17 val))
(define (nuc-O2* nuc) (vector-ref nuc 18))
(define (nuc-O2*-set! nuc val) (vector-set! nuc 18 val))
(define (nuc-H2* nuc) (vector-ref nuc 19))
(define (nuc-H2*-set! nuc val) (vector-set! nuc 19 val))
(define (nuc-C3* nuc) (vector-ref nuc 20))
(define (nuc-C3*-set! nuc val) (vector-set! nuc 20 val))
(define (nuc-H3* nuc) (vector-ref nuc 21))
(define (nuc-H3*-set! nuc val) (vector-set! nuc 21 val))
(define (nuc-O3* nuc) (vector-ref nuc 22))
(define (nuc-O3*-set! nuc val) (vector-set! nuc 22 val))
(define (nuc-N1 nuc) (vector-ref nuc 23))
(define (nuc-N1-set! nuc val) (vector-set! nuc 23 val))
(define (nuc-N3 nuc) (vector-ref nuc 24))
(define (nuc-N3-set! nuc val) (vector-set! nuc 24 val))
(define (nuc-C2 nuc) (vector-ref nuc 25))
(define (nuc-C2-set! nuc val) (vector-set! nuc 25 val))
(define (nuc-C4 nuc) (vector-ref nuc 26))
(define (nuc-C4-set! nuc val) (vector-set! nuc 26 val))
(define (nuc-C5 nuc) (vector-ref nuc 27))
(define (nuc-C5-set! nuc val) (vector-set! nuc 27 val))
(define (nuc-C6 nuc) (vector-ref nuc 28))
(define (nuc-C6-set! nuc val) (vector-set! nuc 28 val))
(define (make-rA dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
N6 N7 N9 C8 H2 H61 H62 H8)
(vector dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
'rA N6 N7 N9 C8 H2 H61 H62 H8))
(define (rA? nuc) (eq? (vector-ref nuc 29) 'rA))
(define (rA-N6 nuc) (vector-ref nuc 30))
(define (rA-N6-set! nuc val) (vector-set! nuc 30 val))
(define (rA-N7 nuc) (vector-ref nuc 31))
(define (rA-N7-set! nuc val) (vector-set! nuc 31 val))
(define (rA-N9 nuc) (vector-ref nuc 32))
(define (rA-N9-set! nuc val) (vector-set! nuc 32 val))
(define (rA-C8 nuc) (vector-ref nuc 33))
(define (rA-C8-set! nuc val) (vector-set! nuc 33 val))
(define (rA-H2 nuc) (vector-ref nuc 34))
(define (rA-H2-set! nuc val) (vector-set! nuc 34 val))
(define (rA-H61 nuc) (vector-ref nuc 35))
(define (rA-H61-set! nuc val) (vector-set! nuc 35 val))
(define (rA-H62 nuc) (vector-ref nuc 36))
(define (rA-H62-set! nuc val) (vector-set! nuc 36 val))
(define (rA-H8 nuc) (vector-ref nuc 37))
(define (rA-H8-set! nuc val) (vector-set! nuc 37 val))
(define (make-rC dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
N4 O2 H41 H42 H5 H6)
(vector dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
'rC N4 O2 H41 H42 H5 H6))
(define (rC? nuc) (eq? (vector-ref nuc 29) 'rC))
(define (rC-N4 nuc) (vector-ref nuc 30))
(define (rC-N4-set! nuc val) (vector-set! nuc 30 val))
(define (rC-O2 nuc) (vector-ref nuc 31))
(define (rC-O2-set! nuc val) (vector-set! nuc 31 val))
(define (rC-H41 nuc) (vector-ref nuc 32))
(define (rC-H41-set! nuc val) (vector-set! nuc 32 val))
(define (rC-H42 nuc) (vector-ref nuc 33))
(define (rC-H42-set! nuc val) (vector-set! nuc 33 val))
(define (rC-H5 nuc) (vector-ref nuc 34))
(define (rC-H5-set! nuc val) (vector-set! nuc 34 val))
(define (rC-H6 nuc) (vector-ref nuc 35))
(define (rC-H6-set! nuc val) (vector-set! nuc 35 val))
(define (make-rG dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
N2 N7 N9 C8 O6 H1 H21 H22 H8)
(vector dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
'rG N2 N7 N9 C8 O6 H1 H21 H22 H8))
(define (rG? nuc) (eq? (vector-ref nuc 29) 'rG))
(define (rG-N2 nuc) (vector-ref nuc 30))
(define (rG-N2-set! nuc val) (vector-set! nuc 30 val))
(define (rG-N7 nuc) (vector-ref nuc 31))
(define (rG-N7-set! nuc val) (vector-set! nuc 31 val))
(define (rG-N9 nuc) (vector-ref nuc 32))
(define (rG-N9-set! nuc val) (vector-set! nuc 32 val))
(define (rG-C8 nuc) (vector-ref nuc 33))
(define (rG-C8-set! nuc val) (vector-set! nuc 33 val))
(define (rG-O6 nuc) (vector-ref nuc 34))
(define (rG-O6-set! nuc val) (vector-set! nuc 34 val))
(define (rG-H1 nuc) (vector-ref nuc 35))
(define (rG-H1-set! nuc val) (vector-set! nuc 35 val))
(define (rG-H21 nuc) (vector-ref nuc 36))
(define (rG-H21-set! nuc val) (vector-set! nuc 36 val))
(define (rG-H22 nuc) (vector-ref nuc 37))
(define (rG-H22-set! nuc val) (vector-set! nuc 37 val))
(define (rG-H8 nuc) (vector-ref nuc 38))
(define (rG-H8-set! nuc val) (vector-set! nuc 38 val))
(define (make-rU dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
O2 O4 H3 H5 H6)
(vector dgf-base-tfo P-O3*-275-tfo P-O3*-180-tfo P-O3*-60-tfo
P O1P O2P O5* C5* H5* H5** C4* H4* O4* C1* H1* C2*
H2** O2* H2* C3* H3* O3* N1 N3 C2 C4 C5 C6
'rU O2 O4 H3 H5 H6))
(define (rU? nuc) (eq? (vector-ref nuc 29) 'rU))
(define (rU-O2 nuc) (vector-ref nuc 30))
(define (rU-O2-set! nuc val) (vector-set! nuc 30 val))
(define (rU-O4 nuc) (vector-ref nuc 31))
(define (rU-O4-set! nuc val) (vector-set! nuc 31 val))
(define (rU-H3 nuc) (vector-ref nuc 32))
(define (rU-H3-set! nuc val) (vector-set! nuc 32 val))
(define (rU-H5 nuc) (vector-ref nuc 33))
(define (rU-H5-set! nuc val) (vector-set! nuc 33 val))
(define (rU-H6 nuc) (vector-ref nuc 34))
(define (rU-H6-set! nuc val) (vector-set! nuc 34 val))
(define rA
(nuc-const
0.2679 -0.5509 -0.7904
0.9634 0.1517 0.2209
0.0073 8.4030 0.6232)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA01
(nuc-const
0.2617 -0.5567 -0.7884
0.9651 0.1473 0.2164
0.0359 8.3929 0.5532)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA02
(nuc-const
0.5125 0.7673 -0.3854
-0.6538 0.6397 0.4041
-9.1161 -3.7679 -2.9968)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA03
(nuc-const
-0.8112 0.3054 -0.4986
-0.2996 -0.9494 -0.0940
6.4273 -5.1944 -3.7807)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA04
(nuc-const
0.8304 -0.5567 -0.0237
0.1267 0.1473 0.9809
-0.5075 8.3929 0.2229)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA05
(nuc-const
0.5375 0.7673 0.3498
-0.6034 0.6397 -0.4762
-0.3019 -3.7679 -9.5913)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA06
(nuc-const
0.1912 0.3054 -0.9328
-0.0141 -0.9494 -0.3137
5.7506 -5.1944 4.7470)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA07
(nuc-const
-0.5876 -0.7696 -0.2499
-0.7734 0.6249 -0.1061
30.9870 -26.9344 42.6416)
0.2952 -0.9481 -0.1180
0.5882 0.2777 -0.7595
-58.8919 -11.3095 6.0866)
0.9731 -0.0359 -0.2275
-0.2290 -0.2532 -0.9399
3.5401 -29.7913 52.2796)
-0.1183 0.1805 -0.9764
0.4380 -0.8730 -0.2145
19.9023 54.8054 15.2799)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA08
(nuc-const
0.9789 -0.1638 0.1220
-0.1731 -0.9824 0.0698
-2.9039 47.2655 33.0094)
0.2952 -0.9481 -0.1180
0.5882 0.2777 -0.7595
-58.8919 -11.3095 6.0866)
0.9731 -0.0359 -0.2275
-0.2290 -0.2532 -0.9399
3.5401 -29.7913 52.2796)
-0.1183 0.1805 -0.9764
0.4380 -0.8730 -0.2145
19.9023 54.8054 15.2799)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA09
(nuc-const
-0.3962 0.9089 0.1303
0.3552 0.0209 0.9346
-42.7319 -26.6223 -29.8163)
0.2952 -0.9481 -0.1180
0.5882 0.2777 -0.7595
-58.8919 -11.3095 6.0866)
0.9731 -0.0359 -0.2275
-0.2290 -0.2532 -0.9399
3.5401 -29.7913 52.2796)
-0.1183 0.1805 -0.9764
0.4380 -0.8730 -0.2145
19.9023 54.8054 15.2799)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rA10
(nuc-const
-0.0403 -0.4149 -0.9090
-0.7068 0.6549 -0.2676
6.4402 -52.1496 30.8246)
0.2952 -0.9481 -0.1180
0.5882 0.2777 -0.7595
-58.8919 -11.3095 6.0866)
0.9731 -0.0359 -0.2275
-0.2290 -0.2532 -0.9399
3.5401 -29.7913 52.2796)
-0.1183 0.1805 -0.9764
0.4380 -0.8730 -0.2145
19.9023 54.8054 15.2799)
O5 *
N3
C2
C5
C6
rA
N6
N7
N9
C8
H61
H8
))
(define rAs
(list rA01 rA02 rA03 rA04 rA05 rA06 rA07 rA08 rA09 rA10))
(define rC
(nuc-const
-0.2669 0.5761 0.7726
-0.9631 -0.1296 -0.2361
0.1584 8.3434 0.5434)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC01
(nuc-const
-0.2523 0.5817 0.7733
-0.9675 -0.1404 -0.2101
0.2031 8.3874 0.4228)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC02
(nuc-const
-0.5547 -0.7529 0.3542
0.6542 -0.6577 -0.3734
-9.1111 -3.4598 -3.2939)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC03
(nuc-const
0.8078 -0.3353 0.4847
0.3132 0.9409 0.1290
6.2989 -5.2303 -3.8577)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC04
(nuc-const
-0.8129 0.5817 0.0273
-0.1334 -0.1404 -0.9811
-0.3279 8.3874 0.3355)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC05
(nuc-const
-0.5226 -0.7529 -0.4001
0.5746 -0.6577 0.4870
-0.0208 -3.4598 -9.6882)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC06
(nuc-const
-0.1792 -0.3353 0.9249
-0.0141 0.9409 0.3384
5.7793 -5.2303 4.5997)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC07
(nuc-const
0.3013 -0.9179 -0.2584
-0.9535 -0.2891 -0.0850
43.0403 13.7233 34.5710)
0.0302 -0.7316 0.6811
0.3938 -0.6176 -0.6808
-48.4330 26.3254 13.6383)
0.7581 0.4893 0.4311
0.6345 -0.4010 -0.6607
-31.9784 -13.4285 44.9650)
-0.6890 0.5694 -0.4484
0.3694 -0.2564 -0.8932
12.1105 30.8774 46.0946)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC08
(nuc-const
0.7939 0.5201 -0.3150
0.6028 -0.6054 0.5198
-36.8341 41.5293 1.6628)
0.0302 -0.7316 0.6811
0.3938 -0.6176 -0.6808
-48.4330 26.3254 13.6383)
0.7581 0.4893 0.4311
0.6345 -0.4010 -0.6607
-31.9784 -13.4285 44.9650)
-0.6890 0.5694 -0.4484
0.3694 -0.2564 -0.8932
12.1105 30.8774 46.0946)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC09
(nuc-const
-0.4188 0.6148 -0.6682
-0.2510 0.6289 0.7359
-8.1687 -52.0761 -25.0726)
0.0302 -0.7316 0.6811
0.3938 -0.6176 -0.6808
-48.4330 26.3254 13.6383)
0.7581 0.4893 0.4311
0.6345 -0.4010 -0.6607
-31.9784 -13.4285 44.9650)
-0.6890 0.5694 -0.4484
0.3694 -0.2564 -0.8932
12.1105 30.8774 46.0946)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rC10
(nuc-const
0.6768 -0.4374 -0.5921
-0.7197 -0.2239 -0.6572
25.2447 -14.1920 50.3201)
0.0302 -0.7316 0.6811
0.3938 -0.6176 -0.6808
-48.4330 26.3254 13.6383)
0.7581 0.4893 0.4311
0.6345 -0.4010 -0.6607
-31.9784 -13.4285 44.9650)
-0.6890 0.5694 -0.4484
0.3694 -0.2564 -0.8932
12.1105 30.8774 46.0946)
O5 *
N3
C2
C5
C6
rC
N4
H6
))
(define rCs
(list rC01 rC02 rC03 rC04 rC05 rC06 rC07 rC08 rC09 rC10))
(define rG
(nuc-const
0.2679 -0.5509 -0.7904
0.9634 0.1517 0.2209
0.0073 8.4030 0.6232)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG01
(nuc-const
0.2617 -0.5567 -0.7884
0.9651 0.1473 0.2164
0.0359 8.3929 0.5532)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG02
(nuc-const
0.5125 0.7673 -0.3854
-0.6538 0.6397 0.4041
-9.1161 -3.7679 -2.9968)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG03
(nuc-const
-0.8112 0.3054 -0.4986
-0.2996 -0.9494 -0.0940
6.4273 -5.1944 -3.7807)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG04
(nuc-const
0.8304 -0.5567 -0.0237
0.1267 0.1473 0.9809
-0.5075 8.3929 0.2229)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG05
(nuc-const
0.5375 0.7673 0.3498
-0.6034 0.6397 -0.4762
-0.3019 -3.7679 -9.5913)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG06
(nuc-const
0.1912 0.3054 -0.9328
-0.0141 -0.9494 -0.3137
5.7506 -5.1944 4.7470)
-0.0433 -0.4257 0.9038
-0.5788 0.7480 0.3246
1.5227 6.9114 -7.0765)
0.4552 0.6637 0.5935
-0.8042 0.0203 0.5941
-6.9472 -4.1186 -5.9108)
-0.8247 0.5587 -0.0878
0.0426 0.2162 0.9754
6.2694 -7.0540 3.3316)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG07
(nuc-const
-0.6810 0.5420 0.4924
-0.7268 -0.5824 -0.3642
34.1424 45.9610 -11.8600)
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG08
(nuc-const
-0.3644 -0.6510 0.6659
0.9043 -0.4181 0.0861
-47.6824 -0.5823 -31.7554)
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG09
(nuc-const
-0.1050 -0.3598 0.9271
-0.2196 0.9176 0.3312
45.6217 -38.9484 -12.3208)
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rG10
(nuc-const
-0.9731 0.1383 0.1841
-0.2083 -0.1885 -0.9597
17.8469 38.8265 37.0475)
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rGs
(list rG01 rG02 rG03 rG04 rG05 rG06 rG07 rG08 rG09 rG10))
(define rU
(nuc-const
-0.2669 0.5761 0.7726
-0.9631 -0.1296 -0.2361
0.1584 8.3434 0.5434)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU01
(nuc-const
-0.2523 0.5817 0.7733
-0.9675 -0.1404 -0.2101
0.2031 8.3874 0.4228)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU02
(nuc-const
-0.5547 -0.7529 0.3542
0.6542 -0.6577 -0.3734
-9.1111 -3.4598 -3.2939)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU03
(nuc-const
0.8078 -0.3353 0.4847
0.3132 0.9409 0.1290
6.2989 -5.2303 -3.8577)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU04
(nuc-const
-0.8129 0.5817 0.0273
-0.1334 -0.1404 -0.9811
-0.3279 8.3874 0.3355)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU05
(nuc-const
-0.5226 -0.7529 -0.4001
0.5746 -0.6577 0.4870
-0.0208 -3.4598 -9.6882)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU06
(nuc-const
-0.1792 -0.3353 0.9249
-0.0141 0.9409 0.3384
5.7793 -5.2303 4.5997)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU07
(nuc-const
0.2294 0.4125 0.8816
0.2396 0.8539 -0.4619
8.3625 -52.7147 1.3745)
-0.8297 0.4733 -0.2959
0.4850 0.8737 0.0379
-14.7774 -45.2464 21.9088)
-0.5932 -0.6591 0.4624
-0.7980 0.4055 -0.4458
43.7634 4.3296 28.4890)
0.6803 0.3317 0.6536
-0.1673 -0.7979 0.5791
-17.1858 41.4390 -27.0751)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU08
(nuc-const
-0.7512 0.4071 0.5197
-0.6601 -0.4536 -0.5988
44.1482 30.7036 2.1088)
-0.8297 0.4733 -0.2959
0.4850 0.8737 0.0379
-14.7774 -45.2464 21.9088)
-0.5932 -0.6591 0.4624
-0.7980 0.4055 -0.4458
43.7634 4.3296 28.4890)
0.6803 0.3317 0.6536
-0.1673 -0.7979 0.5791
-17.1858 41.4390 -27.0751)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU09
(nuc-const
-0.3422 -0.9321 0.1184
0.9391 -0.3351 0.0765
-32.1929 25.8198 -28.5088)
-0.8297 0.4733 -0.2959
0.4850 0.8737 0.0379
-14.7774 -45.2464 21.9088)
-0.5932 -0.6591 0.4624
-0.7980 0.4055 -0.4458
43.7634 4.3296 28.4890)
0.6803 0.3317 0.6536
-0.1673 -0.7979 0.5791
-17.1858 41.4390 -27.0751)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rU10
(nuc-const
-0.2514 -0.2766 0.9275
0.0306 0.9555 0.2933
27.8571 -42.1305 -24.4563)
-0.8297 0.4733 -0.2959
0.4850 0.8737 0.0379
-14.7774 -45.2464 21.9088)
-0.5932 -0.6591 0.4624
-0.7980 0.4055 -0.4458
43.7634 4.3296 28.4890)
0.6803 0.3317 0.6536
-0.1673 -0.7979 0.5791
-17.1858 41.4390 -27.0751)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define rUs
(list rU01 rU02 rU03 rU04 rU05 rU06 rU07 rU08 rU09 rU10))
(define rG*
(nuc-const
0.9770 -0.0586 0.2049
0.0519 0.9979 0.0379
1.0331 -46.8078 -36.4742)
-0.0427 0.2409 -0.9696
0.5010 -0.8345 -0.2294
4.0167 54.5377 12.4779)
-0.2867 -0.7872 -0.5460
0.8834 0.0032 -0.4686
-52.9020 18.6313 -0.6709)
0.9040 -0.4236 -0.0582
-0.1007 -0.0786 -0.9918
-7.6624 -25.2080 49.5181)
O5 *
N3
C2
C5
C6
rG
N7
N9
C8
H22
H8
))
(define rU*
(nuc-const
0.2217 -0.7853 0.5780
0.9751 0.1852 -0.1224
-1.4225 -11.0956 -2.5217)
0.0649 0.4366 -0.8973
0.5521 -0.7648 -0.3322
1.6833 6.8060 -7.0011)
-0.4628 -0.6450 -0.6082
0.8168 -0.0436 -0.5753
-6.8179 -3.9778 -5.9887)
0.8103 -0.5790 0.0906
-0.0255 -0.1894 -0.9816
6.1203 -7.1051 3.1984)
O5 *
N3
C2
C5
C6
rU
O4
H6
))
(define (make-var id tfo nuc)
(vector id tfo nuc))
(define (var-id var) (vector-ref var 0))
(define (var-id-set! var val) (vector-set! var 0 val))
(define (var-tfo var) (vector-ref var 1))
(define (var-tfo-set! var val) (vector-set! var 1 val))
(define (var-nuc var) (vector-ref var 2))
(define (var-nuc-set! var val) (vector-set! var 2 val))
(define (atom-pos atom var)
(tfo-apply (var-tfo var) (atom (var-nuc var))))
(define (get-var id lst)
(let ((v (car lst)))
(if (= id (var-id v))
v
(get-var id (cdr lst)))))
(define (make-relative-nuc tfo n)
(cond ((rA? n)
(make-rA
(nuc-dgf-base-tfo n)
(nuc-P-O3*-275-tfo n)
(nuc-P-O3*-180-tfo n)
(nuc-P-O3*-60-tfo n)
(tfo-apply tfo (nuc-P n))
(tfo-apply tfo (nuc-O1P n))
(tfo-apply tfo (nuc-O2P n))
(tfo-apply tfo (nuc-O5* n))
(tfo-apply tfo (nuc-C5* n))
(tfo-apply tfo (nuc-H5* n))
(tfo-apply tfo (nuc-H5** n))
(tfo-apply tfo (nuc-C4* n))
(tfo-apply tfo (nuc-H4* n))
(tfo-apply tfo (nuc-O4* n))
(tfo-apply tfo (nuc-C1* n))
(tfo-apply tfo (nuc-H1* n))
(tfo-apply tfo (nuc-C2* n))
(tfo-apply tfo (nuc-H2** n))
(tfo-apply tfo (nuc-O2* n))
(tfo-apply tfo (nuc-H2* n))
(tfo-apply tfo (nuc-C3* n))
(tfo-apply tfo (nuc-H3* n))
(tfo-apply tfo (nuc-O3* n))
(tfo-apply tfo (nuc-N1 n))
(tfo-apply tfo (nuc-N3 n))
(tfo-apply tfo (nuc-C2 n))
(tfo-apply tfo (nuc-C4 n))
(tfo-apply tfo (nuc-C5 n))
(tfo-apply tfo (nuc-C6 n))
(tfo-apply tfo (rA-N6 n))
(tfo-apply tfo (rA-N7 n))
(tfo-apply tfo (rA-N9 n))
(tfo-apply tfo (rA-C8 n))
(tfo-apply tfo (rA-H2 n))
(tfo-apply tfo (rA-H61 n))
(tfo-apply tfo (rA-H62 n))
(tfo-apply tfo (rA-H8 n))))
((rC? n)
(make-rC
(nuc-dgf-base-tfo n)
(nuc-P-O3*-275-tfo n)
(nuc-P-O3*-180-tfo n)
(nuc-P-O3*-60-tfo n)
(tfo-apply tfo (nuc-P n))
(tfo-apply tfo (nuc-O1P n))
(tfo-apply tfo (nuc-O2P n))
(tfo-apply tfo (nuc-O5* n))
(tfo-apply tfo (nuc-C5* n))
(tfo-apply tfo (nuc-H5* n))
(tfo-apply tfo (nuc-H5** n))
(tfo-apply tfo (nuc-C4* n))
(tfo-apply tfo (nuc-H4* n))
(tfo-apply tfo (nuc-O4* n))
(tfo-apply tfo (nuc-C1* n))
(tfo-apply tfo (nuc-H1* n))
(tfo-apply tfo (nuc-C2* n))
(tfo-apply tfo (nuc-H2** n))
(tfo-apply tfo (nuc-O2* n))
(tfo-apply tfo (nuc-H2* n))
(tfo-apply tfo (nuc-C3* n))
(tfo-apply tfo (nuc-H3* n))
(tfo-apply tfo (nuc-O3* n))
(tfo-apply tfo (nuc-N1 n))
(tfo-apply tfo (nuc-N3 n))
(tfo-apply tfo (nuc-C2 n))
(tfo-apply tfo (nuc-C4 n))
(tfo-apply tfo (nuc-C5 n))
(tfo-apply tfo (nuc-C6 n))
(tfo-apply tfo (rC-N4 n))
(tfo-apply tfo (rC-O2 n))
(tfo-apply tfo (rC-H41 n))
(tfo-apply tfo (rC-H42 n))
(tfo-apply tfo (rC-H5 n))
(tfo-apply tfo (rC-H6 n))))
((rG? n)
(make-rG
(nuc-dgf-base-tfo n)
(nuc-P-O3*-275-tfo n)
(nuc-P-O3*-180-tfo n)
(nuc-P-O3*-60-tfo n)
(tfo-apply tfo (nuc-P n))
(tfo-apply tfo (nuc-O1P n))
(tfo-apply tfo (nuc-O2P n))
(tfo-apply tfo (nuc-O5* n))
(tfo-apply tfo (nuc-C5* n))
(tfo-apply tfo (nuc-H5* n))
(tfo-apply tfo (nuc-H5** n))
(tfo-apply tfo (nuc-C4* n))
(tfo-apply tfo (nuc-H4* n))
(tfo-apply tfo (nuc-O4* n))
(tfo-apply tfo (nuc-C1* n))
(tfo-apply tfo (nuc-H1* n))
(tfo-apply tfo (nuc-C2* n))
(tfo-apply tfo (nuc-H2** n))
(tfo-apply tfo (nuc-O2* n))
(tfo-apply tfo (nuc-H2* n))
(tfo-apply tfo (nuc-C3* n))
(tfo-apply tfo (nuc-H3* n))
(tfo-apply tfo (nuc-O3* n))
(tfo-apply tfo (nuc-N1 n))
(tfo-apply tfo (nuc-N3 n))
(tfo-apply tfo (nuc-C2 n))
(tfo-apply tfo (nuc-C4 n))
(tfo-apply tfo (nuc-C5 n))
(tfo-apply tfo (nuc-C6 n))
(tfo-apply tfo (rG-N2 n))
(tfo-apply tfo (rG-N7 n))
(tfo-apply tfo (rG-N9 n))
(tfo-apply tfo (rG-C8 n))
(tfo-apply tfo (rG-O6 n))
(tfo-apply tfo (rG-H1 n))
(tfo-apply tfo (rG-H21 n))
(tfo-apply tfo (rG-H22 n))
(tfo-apply tfo (rG-H8 n))))
(else
(make-rU
(nuc-dgf-base-tfo n)
(nuc-P-O3*-275-tfo n)
(nuc-P-O3*-180-tfo n)
(nuc-P-O3*-60-tfo n)
(tfo-apply tfo (nuc-P n))
(tfo-apply tfo (nuc-O1P n))
(tfo-apply tfo (nuc-O2P n))
(tfo-apply tfo (nuc-O5* n))
(tfo-apply tfo (nuc-C5* n))
(tfo-apply tfo (nuc-H5* n))
(tfo-apply tfo (nuc-H5** n))
(tfo-apply tfo (nuc-C4* n))
(tfo-apply tfo (nuc-H4* n))
(tfo-apply tfo (nuc-O4* n))
(tfo-apply tfo (nuc-C1* n))
(tfo-apply tfo (nuc-H1* n))
(tfo-apply tfo (nuc-C2* n))
(tfo-apply tfo (nuc-H2** n))
(tfo-apply tfo (nuc-O2* n))
(tfo-apply tfo (nuc-H2* n))
(tfo-apply tfo (nuc-C3* n))
(tfo-apply tfo (nuc-H3* n))
(tfo-apply tfo (nuc-O3* n))
(tfo-apply tfo (nuc-N1 n))
(tfo-apply tfo (nuc-N3 n))
(tfo-apply tfo (nuc-C2 n))
(tfo-apply tfo (nuc-C4 n))
(tfo-apply tfo (nuc-C5 n))
(tfo-apply tfo (nuc-C6 n))
(tfo-apply tfo (rU-O2 n))
(tfo-apply tfo (rU-O4 n))
(tfo-apply tfo (rU-H3 n))
(tfo-apply tfo (rU-H5 n))
(tfo-apply tfo (rU-H6 n))))))
(define (search partial-inst domains constraint?)
(if (null? domains)
(list partial-inst)
(let ((remaining-domains (cdr domains)))
(define (try-assignments lst)
(if (null? lst)
'()
(let ((var (car lst)))
(if (constraint? var partial-inst)
(let* ((subsols1
(search
(cons var partial-inst)
remaining-domains
constraint?))
(subsols2
(try-assignments (cdr lst))))
(append subsols1 subsols2))
(try-assignments (cdr lst))))))
(try-assignments ((car domains) partial-inst)))))
5 ' end of strand A C1 - ---G12 3 ' end of strand B
A2 - ------U11
between two consecutive nucleotides . E.g. the nucleotides C1 and U2
" wc " ( stands for Watson - Crick and is a type of base - pairing ) ,
nucleotides from two chains that are growing in opposite directions .
E.g. the nucleotides C1 from strand A and G12 from strand B.
(define (dgf-base tfo ref nuc)
(let* ((ref-nuc (var-nuc ref))
(align
(tfo-inv-ortho
(cond ((rA? ref-nuc)
(tfo-align (atom-pos nuc-C1* ref)
(atom-pos rA-N9 ref)
(atom-pos nuc-C4 ref)))
((rC? ref-nuc)
(tfo-align (atom-pos nuc-C1* ref)
(atom-pos nuc-N1 ref)
(atom-pos nuc-C2 ref)))
((rG? ref-nuc)
(tfo-align (atom-pos nuc-C1* ref)
(atom-pos rG-N9 ref)
(atom-pos nuc-C4 ref)))
(else
(tfo-align (atom-pos nuc-C1* ref)
(atom-pos nuc-N1 ref)
(atom-pos nuc-C2 ref)))))))
(tfo-combine (nuc-dgf-base-tfo nuc)
(tfo-combine tfo align))))
Placement of first nucleotide .
(define (reference nuc i)
(lambda (partial-inst)
(list (make-var i tfo-id nuc))))
( 1989 ) A Re - Examination of the Crystal
Structure of A - DNA Using Fiber Diffraction Data . .
Struct . & Dynamics 6(6):1189 - 1202 .
(define wc-tfo
(FLOATvector-const
-1.0000 0.0028 -0.0019
0.0028 0.3468 -0.9379
-0.0019 -0.9379 -0.3468
-0.0080 6.0730 8.7208))
(define (wc nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base wc-tfo ref nuc)))
(list (make-var i tfo nuc)))))
(define wc-Dumas-tfo
(FLOATvector-const
-0.9737 -0.1834 0.1352
-0.1779 0.2417 -0.9539
0.1422 -0.9529 -0.2679
0.4837 6.2649 8.0285))
(define (wc-Dumas nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base wc-Dumas-tfo ref nuc)))
(list (make-var i tfo nuc)))))
(define helix5*-tfo
(FLOATvector-const
0.9886 -0.0961 0.1156
0.1424 0.8452 -0.5152
-0.0482 0.5258 0.8492
-3.8737 0.5480 3.8024))
(define (helix5* nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base helix5*-tfo ref nuc)))
(list (make-var i tfo nuc)))))
(define helix3*-tfo
(FLOATvector-const
0.9886 0.1424 -0.0482
-0.0961 0.8452 0.5258
0.1156 -0.5152 0.8492
3.4426 2.0474 -3.7042))
(define (helix3* nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base helix3*-tfo ref nuc)))
(list (make-var i tfo nuc)))))
(define G37-A38-tfo
(FLOATvector-const
0.9991 0.0164 -0.0387
-0.0375 0.7616 -0.6470
0.0189 0.6478 0.7615
-3.3018 0.9975 2.5585))
(define (G37-A38 nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base G37-A38-tfo ref nuc)))
(make-var i tfo nuc))))
(define (stacked5* nuc i j)
(lambda (partial-inst)
(cons ((G37-A38 nuc i j) partial-inst)
((helix5* nuc i j) partial-inst))))
(define A38-G37-tfo
(FLOATvector-const
0.9991 -0.0375 0.0189
0.0164 0.7616 0.6478
-0.0387 -0.6470 0.7615
3.3819 0.7718 -2.5321))
(define (A38-G37 nuc i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(tfo (dgf-base A38-G37-tfo ref nuc)))
(make-var i tfo nuc))))
(define (stacked3* nuc i j)
(lambda (partial-inst)
(cons ((A38-G37 nuc i j) partial-inst)
((helix3* nuc i j) partial-inst))))
(define (P-O3* nucs i j)
(lambda (partial-inst)
(let* ((ref (get-var j partial-inst))
(align
(tfo-inv-ortho
(tfo-align (atom-pos nuc-O3* ref)
(atom-pos nuc-C3* ref)
(atom-pos nuc-C4* ref)))))
(let loop ((lst nucs) (domains '()))
(if (null? lst)
domains
(let ((nuc (car lst)))
(let ((tfo-60 (tfo-combine (nuc-P-O3*-60-tfo nuc) align))
(tfo-180 (tfo-combine (nuc-P-O3*-180-tfo nuc) align))
(tfo-275 (tfo-combine (nuc-P-O3*-275-tfo nuc) align)))
(loop (cdr lst)
(cons (make-var i tfo-60 nuc)
(cons (make-var i tfo-180 nuc)
(cons (make-var i tfo-275 nuc) domains)))))))))))
Define anticodon problem -- Science 253:1255 Figure 3a , 3b and 3c
(define anticodon-domains
(list
(reference rC 27 )
(helix5* rC 28 27)
(helix5* rA 29 28)
(helix5* rG 30 29)
(helix5* rA 31 30)
(wc rU 39 31)
(helix5* rC 40 39)
(helix5* rU 41 40)
(helix5* rG 42 41)
(helix5* rG 43 42)
(stacked3* rA 38 39)
(stacked3* rG 37 38)
(stacked3* rA 36 37)
(stacked3* rA 35 36)
< - ' 3.0 Angstroms
))
constraint
(define (anticodon-constraint? v partial-inst)
(if (= (var-id v) 33)
P in nucleotide 34
O3 ' in nucl . 33
#t))
(define (anticodon)
(search '() anticodon-domains anticodon-constraint?))
Define pseudoknot problem -- Science 253:1255 Figure 4a and 4b
(define pseudoknot-domains
(list
(reference rA 23 )
(wc-Dumas rU 8 23)
(helix3* rG 22 23)
(wc-Dumas rC 9 22)
(helix3* rG 21 22)
(wc-Dumas rC 10 21)
(helix3* rC 20 21)
(wc-Dumas rG 11 20)
| 4.5 Angstroms
))
Pseudoknot constraint
(define (pseudoknot-constraint? v partial-inst)
(case (var-id v)
((18)
(let ((p (atom-pos nuc-P (get-var 19 partial-inst)))
(o3* (atom-pos nuc-O3* v)))
(FLOAT<= (pt-dist p o3*) 4.0)))
((6)
(let ((p (atom-pos nuc-P (get-var 7 partial-inst)))
(o3* (atom-pos nuc-O3* v)))
(FLOAT<= (pt-dist p o3*) 4.5)))
(else
#t)))
(define (pseudoknot)
(search '() pseudoknot-domains pseudoknot-constraint?))
(define (list-of-atoms n)
(append (list-of-common-atoms n)
(list-of-specific-atoms n)))
(define (list-of-common-atoms n)
(list
(nuc-P n)
(nuc-O1P n)
(nuc-O2P n)
(nuc-O5* n)
(nuc-C5* n)
(nuc-H5* n)
(nuc-H5** n)
(nuc-C4* n)
(nuc-H4* n)
(nuc-O4* n)
(nuc-C1* n)
(nuc-H1* n)
(nuc-C2* n)
(nuc-H2** n)
(nuc-O2* n)
(nuc-H2* n)
(nuc-C3* n)
(nuc-H3* n)
(nuc-O3* n)
(nuc-N1 n)
(nuc-N3 n)
(nuc-C2 n)
(nuc-C4 n)
(nuc-C5 n)
(nuc-C6 n)))
(define (list-of-specific-atoms n)
(cond ((rA? n)
(list
(rA-N6 n)
(rA-N7 n)
(rA-N9 n)
(rA-C8 n)
(rA-H2 n)
(rA-H61 n)
(rA-H62 n)
(rA-H8 n)))
((rC? n)
(list
(rC-N4 n)
(rC-O2 n)
(rC-H41 n)
(rC-H42 n)
(rC-H5 n)
(rC-H6 n)))
((rG? n)
(list
(rG-N2 n)
(rG-N7 n)
(rG-N9 n)
(rG-C8 n)
(rG-O6 n)
(rG-H1 n)
(rG-H21 n)
(rG-H22 n)
(rG-H8 n)))
(else
(list
(rU-O2 n)
(rU-O4 n)
(rU-H3 n)
(rU-H5 n)
(rU-H6 n)))))
(define (var-most-distant-atom v)
(define (distance pos)
(let ((abs-pos (tfo-apply (var-tfo v) pos)))
(let ((x (pt-x abs-pos)) (y (pt-y abs-pos)) (z (pt-z abs-pos)))
(FLOATsqrt (FLOAT+ (FLOAT* x x) (FLOAT* y y) (FLOAT* z z))))))
(maximum (map distance (list-of-atoms (var-nuc v)))))
(define (sol-most-distant-atom s)
(maximum (map var-most-distant-atom s)))
(define (most-distant-atom sols)
(maximum (map sol-most-distant-atom sols)))
(define (maximum lst)
(let loop ((m (car lst)) (l (cdr lst)))
(if (null? l)
m
(let ((x (car l)))
(loop (if (FLOAT> x m) x m) (cdr l))))))
(define (run)
(most-distant-atom (pseudoknot)))
(define (main . args)
(run-benchmark
"nucleic"
nucleic-iters
(lambda (result)
(and (number? result)
(let ((x (FLOAT/ result 33.797594890762724)))
(and (FLOAT> x 0.999999) (FLOAT< x 1.000001)))))
(lambda () (lambda () (run)))))
(main)
|
c117de28ce24a9897e0bb2a02901f8a1947b80d1bb56d99e419c0467ad656544 | facebook/pyre-check | issue.ml |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
(* Issue: implements the logic that matches sources against sinks, using the
* current set of rules, and convert them into issues.
* It also defines a handle that uniquely represents issues.
*)
open Core
open Ast
open Domains
open Interprocedural
open Pyre
module Flow = struct
type t = {
source_taint: ForwardTaint.t;
sink_taint: BackwardTaint.t;
}
[@@deriving show]
let bottom = { source_taint = ForwardTaint.bottom; sink_taint = BackwardTaint.bottom }
let is_bottom { source_taint; sink_taint } =
ForwardTaint.is_bottom source_taint || BackwardTaint.is_bottom sink_taint
let join
{ source_taint = left_source_taint; sink_taint = left_sink_taint }
{ source_taint = right_source_taint; sink_taint = right_sink_taint }
=
{
source_taint = ForwardTaint.join left_source_taint right_source_taint;
sink_taint = BackwardTaint.join left_sink_taint right_sink_taint;
}
end
module LocationSet = Stdlib.Set.Make (Location.WithModule)
type t = {
flow: Flow.t;
handle: IssueHandle.t;
locations: LocationSet.t;
define: Statement.Define.t Node.t;
}
let join
{ flow = flow_left; handle; locations = locations_left; define }
{ flow = flow_right; handle = _; locations = locations_right; define = _ }
=
{
flow = Flow.join flow_left flow_right;
handle;
locations = LocationSet.union locations_left locations_right;
define;
}
let canonical_location { locations; _ } =
Option.value_exn ~message:"issue has no location" (LocationSet.min_elt_opt locations)
(* Define how to group issue candidates for a given function. *)
module CandidateKey = struct
module T = struct
type t = {
location: Location.WithModule.t;
sink_handle: IssueHandle.Sink.t;
}
[@@deriving compare, sexp, hash]
end
include T
include Hashable.Make (T)
end
module Candidate = struct
type t = {
flows: Flow.t list;
key: CandidateKey.t;
}
let is_empty = function
| { flows = []; _ } -> true
| _ -> false
let join { flows = left_flows; key } { flows = right_flows; _ } =
{ flows = List.rev_append left_flows right_flows; key }
end
Compute all flows from paths in ~source tree to corresponding paths in ~sink tree , while avoiding
duplication as much as possible .
Strategy :
Let F and B for forward and backward taint respectively . For each path p in B from the root to
some node with non - empty taint T , we match T with the join of taint in the upward and downward
closure from node at path p in F.
duplication as much as possible.
Strategy:
Let F and B for forward and backward taint respectively. For each path p in B from the root to
some node with non-empty taint T, we match T with the join of taint in the upward and downward
closure from node at path p in F. *)
let generate_source_sink_matches ~location ~sink_handle ~source_tree ~sink_tree =
let make_source_sink_matches (path, sink_taint) matches =
let source_taint =
ForwardState.Tree.read path source_tree
|> ForwardState.Tree.collapse ~breadcrumbs:(Features.issue_broadening_set ())
in
if ForwardTaint.is_bottom source_taint then
matches
else
{ Flow.source_taint; sink_taint } :: matches
in
let flows =
if ForwardState.Tree.is_empty source_tree then
[]
else
BackwardState.Tree.fold BackwardState.Tree.Path ~init:[] ~f:make_source_sink_matches sink_tree
in
{ Candidate.flows; key = { location; sink_handle } }
module PartitionedFlow = struct
type t = {
source_partition: (Sources.t, ForwardTaint.t) Map.Poly.t;
sink_partition: (Sinks.t, BackwardTaint.t) Map.Poly.t;
}
end
let generate_issues
~taint_configuration
~define
{ Candidate.flows; key = { location; sink_handle } }
=
let partitions =
let partition { Flow.source_taint; sink_taint } =
{
PartitionedFlow.source_partition =
ForwardTaint.partition ForwardTaint.kind By source_taint ~f:(fun kind ->
kind |> Sources.discard_transforms |> Sources.discard_subkind);
sink_partition =
BackwardTaint.partition BackwardTaint.kind By sink_taint ~f:(fun kind ->
kind |> Sinks.discard_transforms |> Sinks.discard_subkind);
}
in
List.map flows ~f:partition
in
let apply_rule_on_flow
{ Rule.sources; sinks; transforms; _ }
{ PartitionedFlow.source_partition; sink_partition }
=
let add_source_taint source_taint source =
match Map.Poly.find source_partition (Sources.discard_subkind source) with
| Some taint -> ForwardTaint.join source_taint taint
| None -> source_taint
in
let add_sink_taint sink_taint sink =
match Map.Poly.find sink_partition (Sinks.discard_subkind sink) with
| Some taint -> BackwardTaint.join sink_taint taint
| None -> sink_taint
in
let source_taint = List.fold sources ~f:add_source_taint ~init:ForwardTaint.bottom in
let sink_taint = List.fold sinks ~f:add_sink_taint ~init:BackwardTaint.bottom in
let rec apply_sanitizers
?(previous_sanitized_sources = Sources.Set.empty)
?(previous_sanitized_sinks = Sinks.Set.empty)
?(previous_single_base_source = None)
?(previous_single_base_sink = None)
{ Flow.source_taint; sink_taint }
=
This needs a fixpoint since refining sinks might sanitize more sources etc .
* For instance :
* Sources : { Not[X]@A , Not[X]:Not[Y]@C }
* Sinks : { X , Not[A]@Y }
* After one iteration , we still have { Not[X]:Not[Y]@C } and { Not[A]@Y } ,
* which can be refined further to an invalid flow .
* For instance:
* Sources: {Not[X]@A, Not[X]:Not[Y]@C}
* Sinks: {X, Not[A]@Y}
* After one iteration, we still have {Not[X]:Not[Y]@C} and {Not[A]@Y},
* which can be refined further to an invalid flow.
*)
let gather_sanitized_sinks kind sofar =
let sanitized =
kind
|> Sources.extract_sanitize_transforms
|> (fun { sinks; _ } -> sinks)
|> Sinks.extract_sanitized_sinks_from_transforms
in
match sofar with
| None -> Some sanitized
| Some sofar -> Some (Sinks.Set.inter sofar sanitized)
in
let sanitized_sinks =
ForwardTaint.fold ForwardTaint.kind ~init:None ~f:gather_sanitized_sinks source_taint
|> Option.value ~default:Sinks.Set.empty
in
let sink_taint = BackwardTaint.sanitize_taint_kinds sanitized_sinks sink_taint in
let gather_sanitized_sources kind sofar =
let sanitized =
kind
|> Sinks.extract_sanitize_transforms
|> (fun { sources; _ } -> sources)
|> Sources.extract_sanitized_sources_from_transforms
in
match sofar with
| None -> Some sanitized
| Some sofar -> Some (Sources.Set.inter sofar sanitized)
in
let sanitized_sources =
BackwardTaint.fold BackwardTaint.kind ~init:None ~f:gather_sanitized_sources sink_taint
|> Option.value ~default:Sources.Set.empty
in
let source_taint = ForwardTaint.sanitize_taint_kinds sanitized_sources source_taint in
(* If all sources have the same base, we can remove sink flows that sanitize
* that base (and vice versa). *)
let gather_base_sources kind sofar =
Sources.Set.add
(kind |> Sources.discard_sanitize_transforms |> Sources.discard_subkind)
sofar
in
let single_base_source =
ForwardTaint.fold
ForwardTaint.kind
~init:Sources.Set.empty
~f:gather_base_sources
source_taint
|> Sources.Set.as_singleton
in
let sink_taint =
match single_base_source with
| Some (Sources.NamedSource source) ->
let sanitize_transforms =
SanitizeTransform.Source.Named source
|> SanitizeTransform.SourceSet.singleton
|> SanitizeTransformSet.from_sources
in
BackwardTaint.transform
BackwardTaint.kind
Filter
~f:(fun kind -> not (Sinks.contains_sanitize_transforms kind sanitize_transforms))
sink_taint
| _ -> sink_taint
in
let gather_base_sinks kind sofar =
Sinks.Set.add (kind |> Sinks.discard_sanitize_transforms |> Sinks.discard_subkind) sofar
in
let single_base_sink =
BackwardTaint.fold BackwardTaint.kind ~init:Sinks.Set.empty ~f:gather_base_sinks sink_taint
|> Sinks.Set.as_singleton
in
let source_taint =
match single_base_sink with
| Some (Sinks.NamedSink sink) ->
let sanitize_transforms =
SanitizeTransform.Sink.Named sink
|> SanitizeTransform.SinkSet.singleton
|> SanitizeTransformSet.from_sinks
in
ForwardTaint.transform
ForwardTaint.kind
Filter
~f:(fun kind -> not (Sources.contains_sanitize_transforms kind sanitize_transforms))
source_taint
| _ -> source_taint
in
if
Sources.Set.equal sanitized_sources previous_sanitized_sources
&& Sinks.Set.equal sanitized_sinks previous_sanitized_sinks
&& Option.equal Sources.equal single_base_source previous_single_base_source
&& Option.equal Sinks.equal single_base_sink previous_single_base_sink
then
{ Flow.source_taint; sink_taint }
else
apply_sanitizers
~previous_sanitized_sources:sanitized_sources
~previous_sanitized_sinks:sanitized_sinks
~previous_single_base_source:single_base_source
~previous_single_base_sink:single_base_sink
{ source_taint; sink_taint }
in
let apply_transforms { Flow.source_taint; sink_taint } =
let taint_by_source_transforms =
ForwardTaint.partition ForwardTaint.kind By source_taint ~f:Sources.get_named_transforms
in
let taint_by_sink_transforms =
BackwardTaint.partition BackwardTaint.kind By sink_taint ~f:Sinks.get_named_transforms
in
let find_flow source_transforms sink_transforms =
Map.Poly.find taint_by_source_transforms source_transforms
>>= fun source_taint ->
Map.Poly.find taint_by_sink_transforms sink_transforms
>>| fun sink_taint -> { Flow.source_taint; sink_taint }
in
let add_and_sanitize_flow sofar (source_transforms, sink_transforms) =
find_flow source_transforms sink_transforms
>>| apply_sanitizers
|> Option.value_map ~default:sofar ~f:(Flow.join sofar)
in
Rule.transform_splits transforms |> List.fold ~init:Flow.bottom ~f:add_and_sanitize_flow
in
let partition_flow = apply_transforms { source_taint; sink_taint } in
if Flow.is_bottom partition_flow then
None
else
Some partition_flow
in
let apply_rule_separate_access_path issues_so_far (rule : Rule.t) =
let fold_partitions issues candidate =
match apply_rule_on_flow rule candidate with
| Some flow ->
{
flow;
handle = { code = rule.code; callable = Target.create define; sink = sink_handle };
locations = LocationSet.singleton location;
define;
}
:: issues
| None -> issues
in
List.fold partitions ~init:issues_so_far ~f:fold_partitions
in
let apply_rule_merge_access_path rule =
let fold_partitions flow_so_far candidate =
match apply_rule_on_flow rule candidate with
| Some flow -> Flow.join flow_so_far flow
| None -> flow_so_far
in
let flow =
List.fold
partitions
~init:{ Flow.source_taint = ForwardTaint.bottom; sink_taint = BackwardTaint.bottom }
~f:fold_partitions
in
if Flow.is_bottom flow then
None
else
Some
{
flow;
handle = { code = rule.code; callable = Target.create define; sink = sink_handle };
locations = LocationSet.singleton location;
define;
}
in
let group_by_handle map issue =
SAPP invariant : There should be a single issue per issue handle .
* The configuration might have multiple rules with the same code due to
* multi source - sink rules , hence we need to merge issues here .
* The configuration might have multiple rules with the same code due to
* multi source-sink rules, hence we need to merge issues here. *)
let update = function
| None -> Some issue
| Some previous_issue -> Some (join previous_issue issue)
in
IssueHandle.SerializableMap.update issue.handle update map
in
if taint_configuration.TaintConfiguration.Heap.lineage_analysis then
(* Create different issues for same access path, e.g, Issue{[a] -> [b]}, Issue {[c] -> [d]}. *)
Note that this breaks a SAPP invariant because there might be multiple issues with the same
handle . This is fine because in that configuration we do not use SAPP .
handle. This is fine because in that configuration we do not use SAPP. *)
List.fold taint_configuration.rules ~init:[] ~f:apply_rule_separate_access_path
else (* Create single issue for same access path, e.g, Issue{[a],[c] -> [b], [d]}. *)
List.filter_map ~f:apply_rule_merge_access_path taint_configuration.rules
|> List.fold ~init:IssueHandle.SerializableMap.empty ~f:group_by_handle
|> IssueHandle.SerializableMap.data
(* A map from triggered sink kinds (which is a string) to the handles of the flows that are detected
when creating these triggered sinks. The issue handles will be propagated in the backward
analysis. A triggered sink here means we must find its matching source, in order to file an issue
for a multi-source rule. *)
module TriggeredSinkHashMap = struct
module Hashable = Core.Hashable.Make (String)
module HashMap = Hashable.Table
type t = IssueHandleSet.t HashMap.t
let create () = HashMap.create ()
let is_empty map = HashMap.is_empty map
let convert_to_key partial_sink = Sinks.show_partial_sink partial_sink
let mem map partial_sink = HashMap.mem map (convert_to_key partial_sink)
let get_issue_handles map partial_sink =
HashMap.find map (convert_to_key partial_sink) |> Option.value ~default:IssueHandleSet.bottom
let add map ~triggered_sink ~issue_handles =
let update = function
| Some existing_issue_handles -> IssueHandleSet.join existing_issue_handles issue_handles
| None -> issue_handles
in
HashMap.update map (convert_to_key triggered_sink) ~f:update
let find map partial_sink = HashMap.find map (convert_to_key partial_sink)
end
(* A map from locations to a set of triggered sinks.
* This is used to store triggered sinks found in the forward analysis,
* and propagate them up in the backward analysis. *)
module TriggeredSinkLocationMap = struct
type t = BackwardState.t Location.Table.t
let create () = Location.Table.create ()
let add map ~location ~taint =
Hashtbl.update map location ~f:(function
| Some existing -> BackwardState.join existing taint
| None -> taint)
let get map ~location = Hashtbl.find map location |> Option.value ~default:BackwardState.bottom
end
let compute_triggered_flows
~taint_configuration
~triggered_sinks_for_call
~location
~sink_handle
~source_tree
~sink_tree
~define
=
let partial_sinks =
if ForwardState.Tree.is_bottom source_tree then
[]
else
BackwardState.Tree.fold
BackwardTaint.kind
~f:(fun sink sofar ->
match Sinks.extract_partial_sink sink with
| Some partial_sink -> partial_sink :: sofar
| None -> sofar)
~init:[]
sink_tree
in
let sources =
if List.is_empty partial_sinks then
[]
else
ForwardState.Tree.fold ForwardTaint.kind ~f:List.cons ~init:[] source_tree
in
let check_source_sink_flows ~candidates ~source ~partial_sink =
TaintConfiguration.get_triggered_sink taint_configuration ~partial_sink ~source
|> function
| Some (Sinks.TriggeredPartialSink triggered_sink) ->
For a multi - source rule , the main issue could be the first candidate that is discovered ,
* or the second . We consider both situations as valid issues here , but after the global
* fixpoint computation is done , we will remove the secondary issue .
* Invariant : Any multi - source issue must refer to the known issues under the same multi - source
* rule , such that if there exists no known issue , then this issue is incomplete and thus needs
* to be discarded :
* - Case A : We have already found both issues .
* - Case B : We have just found the first issue . We will propagate the triggered sink , which
* may eventually lead to finding a second issue .
* or the second. We consider both situations as valid issues here, but after the global
* fixpoint computation is done, we will remove the secondary issue.
* Invariant: Any multi-source issue must refer to the known issues under the same multi-source
* rule, such that if there exists no known issue, then this issue is incomplete and thus needs
* to be discarded:
* - Case A: We have already found both issues.
* - Case B: We have just found the first issue. We will propagate the triggered sink, which
* may eventually lead to finding a second issue.
*)
let candidate =
let related_issues =
TriggeredSinkHashMap.get_issue_handles triggered_sinks_for_call partial_sink
in
let frame =
(* Case A above *)
Frame.update Frame.Slots.MultiSourceIssueHandle related_issues Frame.initial
in
generate_source_sink_matches
~location
~sink_handle
~source_tree
~sink_tree:
(BackwardState.Tree.create_leaf
(BackwardTaint.singleton
(CallInfo.Origin location)
(Sinks.TriggeredPartialSink partial_sink)
frame))
in
if Candidate.is_empty candidate then
candidates
else
let issues = generate_issues ~taint_configuration ~define candidate in
let issue_handles =
List.fold issues ~init:IssueHandleSet.bottom ~f:(fun so_far issue ->
IssueHandleSet.add issue.handle so_far)
in
TriggeredSinkHashMap.add
triggered_sinks_for_call
~triggered_sink
~issue_handles (* Case B above *);
candidate :: candidates
| _ -> candidates
in
let check_sink_flows candidates partial_sink =
List.fold
~f:(fun candidates source -> check_source_sink_flows ~candidates ~source ~partial_sink)
~init:candidates
sources
in
List.fold ~f:check_sink_flows ~init:[] partial_sinks
module Candidates = struct
type issue = t
type t = Candidate.t CandidateKey.Table.t
let create () = CandidateKey.Table.create ()
let add_candidate candidates ({ Candidate.key; _ } as candidate) =
if not (Candidate.is_empty candidate) then
CandidateKey.Table.update candidates key ~f:(function
| None -> candidate
| Some current_candidate -> Candidate.join current_candidate candidate)
Check for issues in flows from the ` source_tree ` to the ` sink_tree ` , updating
* issue ` candidates ` .
* issue `candidates`. *)
let check_flow candidates ~location ~sink_handle ~source_tree ~sink_tree =
generate_source_sink_matches ~location ~sink_handle ~source_tree ~sink_tree
|> add_candidate candidates
Check for issues for combined source rules .
* For flows where both sources are present , this adds the flow to issue ` candidates ` .
* If only one source is present , this creates a triggered sink in ` triggered_sinks_for_call ` .
* For flows where both sources are present, this adds the flow to issue `candidates`.
* If only one source is present, this creates a triggered sink in `triggered_sinks_for_call`.
*)
let check_triggered_flows
candidates
~taint_configuration
~triggered_sinks_for_call
~location
~sink_handle
~source_tree
~sink_tree
~define
=
let new_candidates =
compute_triggered_flows
~taint_configuration
~triggered_sinks_for_call
~sink_handle
~location
~source_tree
~sink_tree
~define
in
List.iter new_candidates ~f:(add_candidate candidates)
let generate_issues candidates ~taint_configuration ~define =
let add_or_merge_issue issues_so_far new_issue =
IssueHandle.SerializableMap.update
new_issue.handle
(function
| Some existing_issue -> Some (join existing_issue new_issue)
| None -> Some new_issue)
issues_so_far
in
let accumulate ~key:_ ~data:candidate issues =
let new_issues = generate_issues ~taint_configuration ~define candidate in
List.fold new_issues ~init:issues ~f:add_or_merge_issue
in
CandidateKey.Table.fold candidates ~f:accumulate ~init:IssueHandle.SerializableMap.empty
end
type features = {
breadcrumbs: Features.BreadcrumbSet.t;
first_indices: Features.FirstIndexSet.t;
first_fields: Features.FirstFieldSet.t;
}
let get_issue_features { Flow.source_taint; sink_taint } =
let breadcrumbs =
let source_breadcrumbs = ForwardTaint.joined_breadcrumbs source_taint in
let sink_breadcrumbs = BackwardTaint.joined_breadcrumbs sink_taint in
Features.BreadcrumbSet.sequence_join source_breadcrumbs sink_breadcrumbs
in
let first_indices =
let source_indices = ForwardTaint.first_indices source_taint in
let sink_indices = BackwardTaint.first_indices sink_taint in
Features.FirstIndexSet.join source_indices sink_indices
in
let first_fields =
let source_fields = ForwardTaint.first_fields source_taint in
let sink_fields = BackwardTaint.first_fields sink_taint in
Features.FirstFieldSet.join source_fields sink_fields
in
{ breadcrumbs; first_indices; first_fields }
let sinks_regexp = Str.regexp_string "{$sinks}"
let sources_regexp = Str.regexp_string "{$sources}"
let transforms_regexp = Str.regexp_string "{$transforms}"
let get_name_and_detailed_message
~taint_configuration:{ TaintConfiguration.Heap.rules; _ }
{ flow; handle = { code; _ }; _ }
=
match List.find ~f:(fun { code = rule_code; _ } -> code = rule_code) rules with
| None -> failwith "issue with code that has no rule"
| Some { name; message_format; transforms; _ } ->
let sources =
ForwardTaint.kinds flow.source_taint
|> List.map ~f:Sources.discard_transforms
|> List.dedup_and_sort ~compare:Sources.compare
|> List.map ~f:Sources.show
|> String.concat ~sep:", "
in
let sinks =
BackwardTaint.kinds flow.sink_taint
|> List.map ~f:Sinks.discard_transforms
|> List.dedup_and_sort ~compare:Sinks.compare
|> List.map ~f:Sinks.show
|> String.concat ~sep:", "
in
let transforms = List.map transforms ~f:TaintTransform.show |> String.concat ~sep:", " in
let message =
Str.global_replace sources_regexp sources message_format
|> Str.global_replace sinks_regexp sinks
|> Str.global_replace transforms_regexp transforms
in
name, message
let to_error
~taint_configuration:({ TaintConfiguration.Heap.rules; _ } as taint_configuration)
({ handle = { code; _ }; define; _ } as issue)
=
match List.find ~f:(fun { code = rule_code; _ } -> code = rule_code) rules with
| None -> failwith "issue with code that has no rule"
| Some _ ->
let name, detail = get_name_and_detailed_message ~taint_configuration issue in
let kind = { Error.name; messages = [detail]; code } in
let location = canonical_location issue in
Error.create ~location ~define ~kind
let to_json ~taint_configuration ~expand_overrides ~is_valid_callee ~filename_lookup issue =
let callable_name = Target.external_name issue.handle.callable in
let _, message = get_name_and_detailed_message ~taint_configuration issue in
let source_traces =
ForwardTaint.to_json
~expand_overrides
~is_valid_callee
~filename_lookup:(Some filename_lookup)
issue.flow.source_taint
in
let sink_traces =
BackwardTaint.to_json
~expand_overrides
~is_valid_callee
~filename_lookup:(Some filename_lookup)
issue.flow.sink_taint
in
let features = get_issue_features issue.flow in
let json_features =
let get_feature_json { Abstract.OverUnderSetDomain.element; in_under } breadcrumbs =
let element = Features.BreadcrumbInterned.unintern element in
let breadcrumb_json = Features.Breadcrumb.to_json element ~on_all_paths:in_under in
breadcrumb_json :: breadcrumbs
in
Features.BreadcrumbSet.fold
Features.BreadcrumbSet.ElementAndUnder
~f:get_feature_json
~init:[]
features.breadcrumbs
in
let json_features =
List.concat
[
features.first_indices
|> Features.FirstIndexSet.elements
|> List.map ~f:Features.FirstIndexInterned.unintern
|> Features.FirstIndex.to_json;
features.first_fields
|> Features.FirstFieldSet.elements
|> List.map ~f:Features.FirstFieldInterned.unintern
|> Features.FirstField.to_json;
json_features;
]
in
let traces : Yojson.Safe.t =
`List
[
`Assoc ["name", `String "forward"; "roots", source_traces];
`Assoc ["name", `String "backward"; "roots", sink_traces];
]
in
let {
Location.WithPath.path;
start = { line; column = start_column };
stop = { column = stop_column; _ };
}
=
canonical_location issue |> Location.WithModule.instantiate ~lookup:filename_lookup
in
let callable_line = Ast.(Location.line issue.define.location) in
let sink_handle = IssueHandle.Sink.to_json issue.handle.sink in
let master_handle = IssueHandle.master_handle issue.handle in
`Assoc
[
"callable", `String callable_name;
"callable_line", `Int callable_line;
"code", `Int issue.handle.code;
"line", `Int line;
"start", `Int start_column;
"end", `Int stop_column;
"filename", `String path;
"message", `String message;
"traces", traces;
"features", `List json_features;
"sink_handle", sink_handle;
"master_handle", `String master_handle;
]
module MultiSource = struct
type issue = t
(* Get all triggered sink kinds from the sink taint of the issue. *)
let get_triggered_sinks { flow = { Flow.sink_taint; _ }; _ } =
BackwardTaint.fold
BackwardTaint.kind
~f:(fun sink sofar ->
(* For now, if a partial sink is transformed, we do not consider it as a sink for a
multi-source rule. *)
match Sinks.discard_sanitize_transforms sink with
| Sinks.TriggeredPartialSink _ as partial_sink -> Sinks.Set.add partial_sink sofar
| _ -> sofar)
~init:Sinks.Set.empty
sink_taint
let is_multi_source issue = not (Sinks.Set.is_empty (get_triggered_sinks issue))
(* Get all triggered sink kind labels from the sink taint of the issue that match the given sink
kind. *)
let get_triggered_sink_labels ~sink_kind issue =
get_triggered_sinks issue
|> Sinks.Set.elements
|> List.filter_map ~f:(function
| Sinks.TriggeredPartialSink { Sinks.kind; label } ->
if String.equal kind sink_kind then
Some label
else
None
| _ -> failwith "Expect triggered sinks")
(* Get issue handles sharing the same partial sink kind with `triggered_sink`. *)
let get_issue_handles ~triggered_sink:{ Sinks.kind; _ } { flow = { Flow.sink_taint; _ }; _ } =
BackwardTaint.reduce
IssueHandleSet.Self
~using:(Context (BackwardTaint.kind, Acc))
~f:(fun sink_kind issue_handles so_far ->
match sink_kind with
| Sinks.TriggeredPartialSink { Sinks.kind = sink_kind; _ } ->
if String.equal kind sink_kind then
IssueHandleSet.join so_far issue_handles
else
so_far
| _ -> so_far)
~init:IssueHandleSet.bottom
sink_taint
(* When the combination of the given issue alongwith other issues that it relates to (under the
same partial sink kind) constitutes all issues required for reporting an issue of the
corresponding multi-source rule, return a pair of the partial sink kind and the related issues.
Fact: There exists a valid issue for a multi-source rule iff. there exists a non-empty set of
related issues (under a partial sink kind). *)
let find_related_issues ~taint_configuration ~issue_handle_map issue =
let is_related ~triggered_sink:{ Sinks.kind; label } ~main_label ~secondary_label related_issue =
let missing_label = if String.equal main_label label then secondary_label else main_label in
get_triggered_sink_labels ~sink_kind:kind related_issue
|> List.exists ~f:(String.equal missing_label)
in
let accumulate_related_issues triggered_sink so_far =
match triggered_sink with
| Sinks.TriggeredPartialSink triggered_sink ->
(* Issues that are known to be related to the given issue, due to sharing the same partial
sink kind and matching the labels under this partial sink kind. *)
let { TaintConfiguration.Heap.partial_sink_labels; _ } = taint_configuration in
let {
TaintConfiguration.PartialSinkLabelsMap.main = main_label;
secondary = secondary_label;
}
=
TaintConfiguration.PartialSinkLabelsMap.find_opt triggered_sink.kind partial_sink_labels
|> Option.value_exn
in
let related_issues =
get_issue_handles ~triggered_sink issue
|> IssueHandleSet.elements
|> List.map ~f:(fun issue_handle ->
IssueHandle.SerializableMap.find issue_handle issue_handle_map)
|> List.filter ~f:(is_related ~triggered_sink ~main_label ~secondary_label)
in
Sinks.Map.add (Sinks.TriggeredPartialSink triggered_sink) related_issues so_far
| _ -> so_far
in
Sinks.Set.fold accumulate_related_issues (get_triggered_sinks issue) Sinks.Map.empty
let is_main_issue ~sink ~taint_configuration issue =
let is_main_label ~kind label =
let { TaintConfiguration.Heap.partial_sink_labels; _ } = taint_configuration in
match TaintConfiguration.PartialSinkLabelsMap.find_opt kind partial_sink_labels with
| Some { main; _ } -> String.equal main label
| None -> false
in
match sink with
| Sinks.TriggeredPartialSink { kind; _ } ->
get_triggered_sink_labels ~sink_kind:kind issue |> List.exists ~f:(is_main_label ~kind)
| _ -> false
let get_first_sink_hops { flow = { Flow.sink_taint; _ }; _ } =
BackwardTaint.reduce
BackwardTaint.kind
~using:(Context (BackwardTaint.call_info, Acc))
~f:(fun call_info sink_kind so_far ->
let extra_trace =
{
ExtraTraceFirstHop.call_info;
leaf_kind = Sink sink_kind;
message =
Some (Format.asprintf "Sink trace of the secondary flow: %s" (Sinks.show sink_kind));
}
in
ExtraTraceFirstHop.Set.add extra_trace so_far)
~init:ExtraTraceFirstHop.Set.bottom
sink_taint
let get_first_source_hops { flow = { Flow.source_taint; _ }; _ } =
ForwardTaint.reduce
ForwardTaint.kind
~using:(Context (ForwardTaint.call_info, Acc))
~f:(fun call_info source_kind so_far ->
let extra_trace =
{
ExtraTraceFirstHop.call_info;
leaf_kind = Source source_kind;
message =
Some
(Format.asprintf
"Source trace of the secondary flow: %s"
(Sources.show source_kind));
}
in
ExtraTraceFirstHop.Set.add extra_trace so_far)
~init:ExtraTraceFirstHop.Set.bottom
source_taint
let attach_extra_traces
~source_traces
~sink_traces
({ flow = { Flow.source_taint; sink_taint }; _ } as issue)
=
let sink_taint =
BackwardTaint.add_extra_traces
~extra_traces:(ExtraTraceFirstHop.Set.join source_traces sink_traces)
sink_taint
in
{ issue with flow = { Flow.source_taint; sink_taint } }
end
| null | https://raw.githubusercontent.com/facebook/pyre-check/bcbe47da04118b6ece778483b30c638685e2d570/source/interprocedural_analyses/taint/issue.ml | ocaml | Issue: implements the logic that matches sources against sinks, using the
* current set of rules, and convert them into issues.
* It also defines a handle that uniquely represents issues.
Define how to group issue candidates for a given function.
If all sources have the same base, we can remove sink flows that sanitize
* that base (and vice versa).
Create different issues for same access path, e.g, Issue{[a] -> [b]}, Issue {[c] -> [d]}.
Create single issue for same access path, e.g, Issue{[a],[c] -> [b], [d]}.
A map from triggered sink kinds (which is a string) to the handles of the flows that are detected
when creating these triggered sinks. The issue handles will be propagated in the backward
analysis. A triggered sink here means we must find its matching source, in order to file an issue
for a multi-source rule.
A map from locations to a set of triggered sinks.
* This is used to store triggered sinks found in the forward analysis,
* and propagate them up in the backward analysis.
Case A above
Case B above
Get all triggered sink kinds from the sink taint of the issue.
For now, if a partial sink is transformed, we do not consider it as a sink for a
multi-source rule.
Get all triggered sink kind labels from the sink taint of the issue that match the given sink
kind.
Get issue handles sharing the same partial sink kind with `triggered_sink`.
When the combination of the given issue alongwith other issues that it relates to (under the
same partial sink kind) constitutes all issues required for reporting an issue of the
corresponding multi-source rule, return a pair of the partial sink kind and the related issues.
Fact: There exists a valid issue for a multi-source rule iff. there exists a non-empty set of
related issues (under a partial sink kind).
Issues that are known to be related to the given issue, due to sharing the same partial
sink kind and matching the labels under this partial sink kind. |
* Copyright ( c ) Meta Platforms , Inc. and affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open Core
open Ast
open Domains
open Interprocedural
open Pyre
module Flow = struct
type t = {
source_taint: ForwardTaint.t;
sink_taint: BackwardTaint.t;
}
[@@deriving show]
let bottom = { source_taint = ForwardTaint.bottom; sink_taint = BackwardTaint.bottom }
let is_bottom { source_taint; sink_taint } =
ForwardTaint.is_bottom source_taint || BackwardTaint.is_bottom sink_taint
let join
{ source_taint = left_source_taint; sink_taint = left_sink_taint }
{ source_taint = right_source_taint; sink_taint = right_sink_taint }
=
{
source_taint = ForwardTaint.join left_source_taint right_source_taint;
sink_taint = BackwardTaint.join left_sink_taint right_sink_taint;
}
end
module LocationSet = Stdlib.Set.Make (Location.WithModule)
type t = {
flow: Flow.t;
handle: IssueHandle.t;
locations: LocationSet.t;
define: Statement.Define.t Node.t;
}
let join
{ flow = flow_left; handle; locations = locations_left; define }
{ flow = flow_right; handle = _; locations = locations_right; define = _ }
=
{
flow = Flow.join flow_left flow_right;
handle;
locations = LocationSet.union locations_left locations_right;
define;
}
let canonical_location { locations; _ } =
Option.value_exn ~message:"issue has no location" (LocationSet.min_elt_opt locations)
module CandidateKey = struct
module T = struct
type t = {
location: Location.WithModule.t;
sink_handle: IssueHandle.Sink.t;
}
[@@deriving compare, sexp, hash]
end
include T
include Hashable.Make (T)
end
module Candidate = struct
type t = {
flows: Flow.t list;
key: CandidateKey.t;
}
let is_empty = function
| { flows = []; _ } -> true
| _ -> false
let join { flows = left_flows; key } { flows = right_flows; _ } =
{ flows = List.rev_append left_flows right_flows; key }
end
Compute all flows from paths in ~source tree to corresponding paths in ~sink tree , while avoiding
duplication as much as possible .
Strategy :
Let F and B for forward and backward taint respectively . For each path p in B from the root to
some node with non - empty taint T , we match T with the join of taint in the upward and downward
closure from node at path p in F.
duplication as much as possible.
Strategy:
Let F and B for forward and backward taint respectively. For each path p in B from the root to
some node with non-empty taint T, we match T with the join of taint in the upward and downward
closure from node at path p in F. *)
let generate_source_sink_matches ~location ~sink_handle ~source_tree ~sink_tree =
let make_source_sink_matches (path, sink_taint) matches =
let source_taint =
ForwardState.Tree.read path source_tree
|> ForwardState.Tree.collapse ~breadcrumbs:(Features.issue_broadening_set ())
in
if ForwardTaint.is_bottom source_taint then
matches
else
{ Flow.source_taint; sink_taint } :: matches
in
let flows =
if ForwardState.Tree.is_empty source_tree then
[]
else
BackwardState.Tree.fold BackwardState.Tree.Path ~init:[] ~f:make_source_sink_matches sink_tree
in
{ Candidate.flows; key = { location; sink_handle } }
module PartitionedFlow = struct
type t = {
source_partition: (Sources.t, ForwardTaint.t) Map.Poly.t;
sink_partition: (Sinks.t, BackwardTaint.t) Map.Poly.t;
}
end
let generate_issues
~taint_configuration
~define
{ Candidate.flows; key = { location; sink_handle } }
=
let partitions =
let partition { Flow.source_taint; sink_taint } =
{
PartitionedFlow.source_partition =
ForwardTaint.partition ForwardTaint.kind By source_taint ~f:(fun kind ->
kind |> Sources.discard_transforms |> Sources.discard_subkind);
sink_partition =
BackwardTaint.partition BackwardTaint.kind By sink_taint ~f:(fun kind ->
kind |> Sinks.discard_transforms |> Sinks.discard_subkind);
}
in
List.map flows ~f:partition
in
let apply_rule_on_flow
{ Rule.sources; sinks; transforms; _ }
{ PartitionedFlow.source_partition; sink_partition }
=
let add_source_taint source_taint source =
match Map.Poly.find source_partition (Sources.discard_subkind source) with
| Some taint -> ForwardTaint.join source_taint taint
| None -> source_taint
in
let add_sink_taint sink_taint sink =
match Map.Poly.find sink_partition (Sinks.discard_subkind sink) with
| Some taint -> BackwardTaint.join sink_taint taint
| None -> sink_taint
in
let source_taint = List.fold sources ~f:add_source_taint ~init:ForwardTaint.bottom in
let sink_taint = List.fold sinks ~f:add_sink_taint ~init:BackwardTaint.bottom in
let rec apply_sanitizers
?(previous_sanitized_sources = Sources.Set.empty)
?(previous_sanitized_sinks = Sinks.Set.empty)
?(previous_single_base_source = None)
?(previous_single_base_sink = None)
{ Flow.source_taint; sink_taint }
=
This needs a fixpoint since refining sinks might sanitize more sources etc .
* For instance :
* Sources : { Not[X]@A , Not[X]:Not[Y]@C }
* Sinks : { X , Not[A]@Y }
* After one iteration , we still have { Not[X]:Not[Y]@C } and { Not[A]@Y } ,
* which can be refined further to an invalid flow .
* For instance:
* Sources: {Not[X]@A, Not[X]:Not[Y]@C}
* Sinks: {X, Not[A]@Y}
* After one iteration, we still have {Not[X]:Not[Y]@C} and {Not[A]@Y},
* which can be refined further to an invalid flow.
*)
let gather_sanitized_sinks kind sofar =
let sanitized =
kind
|> Sources.extract_sanitize_transforms
|> (fun { sinks; _ } -> sinks)
|> Sinks.extract_sanitized_sinks_from_transforms
in
match sofar with
| None -> Some sanitized
| Some sofar -> Some (Sinks.Set.inter sofar sanitized)
in
let sanitized_sinks =
ForwardTaint.fold ForwardTaint.kind ~init:None ~f:gather_sanitized_sinks source_taint
|> Option.value ~default:Sinks.Set.empty
in
let sink_taint = BackwardTaint.sanitize_taint_kinds sanitized_sinks sink_taint in
let gather_sanitized_sources kind sofar =
let sanitized =
kind
|> Sinks.extract_sanitize_transforms
|> (fun { sources; _ } -> sources)
|> Sources.extract_sanitized_sources_from_transforms
in
match sofar with
| None -> Some sanitized
| Some sofar -> Some (Sources.Set.inter sofar sanitized)
in
let sanitized_sources =
BackwardTaint.fold BackwardTaint.kind ~init:None ~f:gather_sanitized_sources sink_taint
|> Option.value ~default:Sources.Set.empty
in
let source_taint = ForwardTaint.sanitize_taint_kinds sanitized_sources source_taint in
let gather_base_sources kind sofar =
Sources.Set.add
(kind |> Sources.discard_sanitize_transforms |> Sources.discard_subkind)
sofar
in
let single_base_source =
ForwardTaint.fold
ForwardTaint.kind
~init:Sources.Set.empty
~f:gather_base_sources
source_taint
|> Sources.Set.as_singleton
in
let sink_taint =
match single_base_source with
| Some (Sources.NamedSource source) ->
let sanitize_transforms =
SanitizeTransform.Source.Named source
|> SanitizeTransform.SourceSet.singleton
|> SanitizeTransformSet.from_sources
in
BackwardTaint.transform
BackwardTaint.kind
Filter
~f:(fun kind -> not (Sinks.contains_sanitize_transforms kind sanitize_transforms))
sink_taint
| _ -> sink_taint
in
let gather_base_sinks kind sofar =
Sinks.Set.add (kind |> Sinks.discard_sanitize_transforms |> Sinks.discard_subkind) sofar
in
let single_base_sink =
BackwardTaint.fold BackwardTaint.kind ~init:Sinks.Set.empty ~f:gather_base_sinks sink_taint
|> Sinks.Set.as_singleton
in
let source_taint =
match single_base_sink with
| Some (Sinks.NamedSink sink) ->
let sanitize_transforms =
SanitizeTransform.Sink.Named sink
|> SanitizeTransform.SinkSet.singleton
|> SanitizeTransformSet.from_sinks
in
ForwardTaint.transform
ForwardTaint.kind
Filter
~f:(fun kind -> not (Sources.contains_sanitize_transforms kind sanitize_transforms))
source_taint
| _ -> source_taint
in
if
Sources.Set.equal sanitized_sources previous_sanitized_sources
&& Sinks.Set.equal sanitized_sinks previous_sanitized_sinks
&& Option.equal Sources.equal single_base_source previous_single_base_source
&& Option.equal Sinks.equal single_base_sink previous_single_base_sink
then
{ Flow.source_taint; sink_taint }
else
apply_sanitizers
~previous_sanitized_sources:sanitized_sources
~previous_sanitized_sinks:sanitized_sinks
~previous_single_base_source:single_base_source
~previous_single_base_sink:single_base_sink
{ source_taint; sink_taint }
in
let apply_transforms { Flow.source_taint; sink_taint } =
let taint_by_source_transforms =
ForwardTaint.partition ForwardTaint.kind By source_taint ~f:Sources.get_named_transforms
in
let taint_by_sink_transforms =
BackwardTaint.partition BackwardTaint.kind By sink_taint ~f:Sinks.get_named_transforms
in
let find_flow source_transforms sink_transforms =
Map.Poly.find taint_by_source_transforms source_transforms
>>= fun source_taint ->
Map.Poly.find taint_by_sink_transforms sink_transforms
>>| fun sink_taint -> { Flow.source_taint; sink_taint }
in
let add_and_sanitize_flow sofar (source_transforms, sink_transforms) =
find_flow source_transforms sink_transforms
>>| apply_sanitizers
|> Option.value_map ~default:sofar ~f:(Flow.join sofar)
in
Rule.transform_splits transforms |> List.fold ~init:Flow.bottom ~f:add_and_sanitize_flow
in
let partition_flow = apply_transforms { source_taint; sink_taint } in
if Flow.is_bottom partition_flow then
None
else
Some partition_flow
in
let apply_rule_separate_access_path issues_so_far (rule : Rule.t) =
let fold_partitions issues candidate =
match apply_rule_on_flow rule candidate with
| Some flow ->
{
flow;
handle = { code = rule.code; callable = Target.create define; sink = sink_handle };
locations = LocationSet.singleton location;
define;
}
:: issues
| None -> issues
in
List.fold partitions ~init:issues_so_far ~f:fold_partitions
in
let apply_rule_merge_access_path rule =
let fold_partitions flow_so_far candidate =
match apply_rule_on_flow rule candidate with
| Some flow -> Flow.join flow_so_far flow
| None -> flow_so_far
in
let flow =
List.fold
partitions
~init:{ Flow.source_taint = ForwardTaint.bottom; sink_taint = BackwardTaint.bottom }
~f:fold_partitions
in
if Flow.is_bottom flow then
None
else
Some
{
flow;
handle = { code = rule.code; callable = Target.create define; sink = sink_handle };
locations = LocationSet.singleton location;
define;
}
in
let group_by_handle map issue =
SAPP invariant : There should be a single issue per issue handle .
* The configuration might have multiple rules with the same code due to
* multi source - sink rules , hence we need to merge issues here .
* The configuration might have multiple rules with the same code due to
* multi source-sink rules, hence we need to merge issues here. *)
let update = function
| None -> Some issue
| Some previous_issue -> Some (join previous_issue issue)
in
IssueHandle.SerializableMap.update issue.handle update map
in
if taint_configuration.TaintConfiguration.Heap.lineage_analysis then
Note that this breaks a SAPP invariant because there might be multiple issues with the same
handle . This is fine because in that configuration we do not use SAPP .
handle. This is fine because in that configuration we do not use SAPP. *)
List.fold taint_configuration.rules ~init:[] ~f:apply_rule_separate_access_path
List.filter_map ~f:apply_rule_merge_access_path taint_configuration.rules
|> List.fold ~init:IssueHandle.SerializableMap.empty ~f:group_by_handle
|> IssueHandle.SerializableMap.data
module TriggeredSinkHashMap = struct
module Hashable = Core.Hashable.Make (String)
module HashMap = Hashable.Table
type t = IssueHandleSet.t HashMap.t
let create () = HashMap.create ()
let is_empty map = HashMap.is_empty map
let convert_to_key partial_sink = Sinks.show_partial_sink partial_sink
let mem map partial_sink = HashMap.mem map (convert_to_key partial_sink)
let get_issue_handles map partial_sink =
HashMap.find map (convert_to_key partial_sink) |> Option.value ~default:IssueHandleSet.bottom
let add map ~triggered_sink ~issue_handles =
let update = function
| Some existing_issue_handles -> IssueHandleSet.join existing_issue_handles issue_handles
| None -> issue_handles
in
HashMap.update map (convert_to_key triggered_sink) ~f:update
let find map partial_sink = HashMap.find map (convert_to_key partial_sink)
end
module TriggeredSinkLocationMap = struct
type t = BackwardState.t Location.Table.t
let create () = Location.Table.create ()
let add map ~location ~taint =
Hashtbl.update map location ~f:(function
| Some existing -> BackwardState.join existing taint
| None -> taint)
let get map ~location = Hashtbl.find map location |> Option.value ~default:BackwardState.bottom
end
let compute_triggered_flows
~taint_configuration
~triggered_sinks_for_call
~location
~sink_handle
~source_tree
~sink_tree
~define
=
let partial_sinks =
if ForwardState.Tree.is_bottom source_tree then
[]
else
BackwardState.Tree.fold
BackwardTaint.kind
~f:(fun sink sofar ->
match Sinks.extract_partial_sink sink with
| Some partial_sink -> partial_sink :: sofar
| None -> sofar)
~init:[]
sink_tree
in
let sources =
if List.is_empty partial_sinks then
[]
else
ForwardState.Tree.fold ForwardTaint.kind ~f:List.cons ~init:[] source_tree
in
let check_source_sink_flows ~candidates ~source ~partial_sink =
TaintConfiguration.get_triggered_sink taint_configuration ~partial_sink ~source
|> function
| Some (Sinks.TriggeredPartialSink triggered_sink) ->
For a multi - source rule , the main issue could be the first candidate that is discovered ,
* or the second . We consider both situations as valid issues here , but after the global
* fixpoint computation is done , we will remove the secondary issue .
* Invariant : Any multi - source issue must refer to the known issues under the same multi - source
* rule , such that if there exists no known issue , then this issue is incomplete and thus needs
* to be discarded :
* - Case A : We have already found both issues .
* - Case B : We have just found the first issue . We will propagate the triggered sink , which
* may eventually lead to finding a second issue .
* or the second. We consider both situations as valid issues here, but after the global
* fixpoint computation is done, we will remove the secondary issue.
* Invariant: Any multi-source issue must refer to the known issues under the same multi-source
* rule, such that if there exists no known issue, then this issue is incomplete and thus needs
* to be discarded:
* - Case A: We have already found both issues.
* - Case B: We have just found the first issue. We will propagate the triggered sink, which
* may eventually lead to finding a second issue.
*)
let candidate =
let related_issues =
TriggeredSinkHashMap.get_issue_handles triggered_sinks_for_call partial_sink
in
let frame =
Frame.update Frame.Slots.MultiSourceIssueHandle related_issues Frame.initial
in
generate_source_sink_matches
~location
~sink_handle
~source_tree
~sink_tree:
(BackwardState.Tree.create_leaf
(BackwardTaint.singleton
(CallInfo.Origin location)
(Sinks.TriggeredPartialSink partial_sink)
frame))
in
if Candidate.is_empty candidate then
candidates
else
let issues = generate_issues ~taint_configuration ~define candidate in
let issue_handles =
List.fold issues ~init:IssueHandleSet.bottom ~f:(fun so_far issue ->
IssueHandleSet.add issue.handle so_far)
in
TriggeredSinkHashMap.add
triggered_sinks_for_call
~triggered_sink
candidate :: candidates
| _ -> candidates
in
let check_sink_flows candidates partial_sink =
List.fold
~f:(fun candidates source -> check_source_sink_flows ~candidates ~source ~partial_sink)
~init:candidates
sources
in
List.fold ~f:check_sink_flows ~init:[] partial_sinks
module Candidates = struct
type issue = t
type t = Candidate.t CandidateKey.Table.t
let create () = CandidateKey.Table.create ()
let add_candidate candidates ({ Candidate.key; _ } as candidate) =
if not (Candidate.is_empty candidate) then
CandidateKey.Table.update candidates key ~f:(function
| None -> candidate
| Some current_candidate -> Candidate.join current_candidate candidate)
Check for issues in flows from the ` source_tree ` to the ` sink_tree ` , updating
* issue ` candidates ` .
* issue `candidates`. *)
let check_flow candidates ~location ~sink_handle ~source_tree ~sink_tree =
generate_source_sink_matches ~location ~sink_handle ~source_tree ~sink_tree
|> add_candidate candidates
Check for issues for combined source rules .
* For flows where both sources are present , this adds the flow to issue ` candidates ` .
* If only one source is present , this creates a triggered sink in ` triggered_sinks_for_call ` .
* For flows where both sources are present, this adds the flow to issue `candidates`.
* If only one source is present, this creates a triggered sink in `triggered_sinks_for_call`.
*)
let check_triggered_flows
candidates
~taint_configuration
~triggered_sinks_for_call
~location
~sink_handle
~source_tree
~sink_tree
~define
=
let new_candidates =
compute_triggered_flows
~taint_configuration
~triggered_sinks_for_call
~sink_handle
~location
~source_tree
~sink_tree
~define
in
List.iter new_candidates ~f:(add_candidate candidates)
let generate_issues candidates ~taint_configuration ~define =
let add_or_merge_issue issues_so_far new_issue =
IssueHandle.SerializableMap.update
new_issue.handle
(function
| Some existing_issue -> Some (join existing_issue new_issue)
| None -> Some new_issue)
issues_so_far
in
let accumulate ~key:_ ~data:candidate issues =
let new_issues = generate_issues ~taint_configuration ~define candidate in
List.fold new_issues ~init:issues ~f:add_or_merge_issue
in
CandidateKey.Table.fold candidates ~f:accumulate ~init:IssueHandle.SerializableMap.empty
end
type features = {
breadcrumbs: Features.BreadcrumbSet.t;
first_indices: Features.FirstIndexSet.t;
first_fields: Features.FirstFieldSet.t;
}
let get_issue_features { Flow.source_taint; sink_taint } =
let breadcrumbs =
let source_breadcrumbs = ForwardTaint.joined_breadcrumbs source_taint in
let sink_breadcrumbs = BackwardTaint.joined_breadcrumbs sink_taint in
Features.BreadcrumbSet.sequence_join source_breadcrumbs sink_breadcrumbs
in
let first_indices =
let source_indices = ForwardTaint.first_indices source_taint in
let sink_indices = BackwardTaint.first_indices sink_taint in
Features.FirstIndexSet.join source_indices sink_indices
in
let first_fields =
let source_fields = ForwardTaint.first_fields source_taint in
let sink_fields = BackwardTaint.first_fields sink_taint in
Features.FirstFieldSet.join source_fields sink_fields
in
{ breadcrumbs; first_indices; first_fields }
let sinks_regexp = Str.regexp_string "{$sinks}"
let sources_regexp = Str.regexp_string "{$sources}"
let transforms_regexp = Str.regexp_string "{$transforms}"
let get_name_and_detailed_message
~taint_configuration:{ TaintConfiguration.Heap.rules; _ }
{ flow; handle = { code; _ }; _ }
=
match List.find ~f:(fun { code = rule_code; _ } -> code = rule_code) rules with
| None -> failwith "issue with code that has no rule"
| Some { name; message_format; transforms; _ } ->
let sources =
ForwardTaint.kinds flow.source_taint
|> List.map ~f:Sources.discard_transforms
|> List.dedup_and_sort ~compare:Sources.compare
|> List.map ~f:Sources.show
|> String.concat ~sep:", "
in
let sinks =
BackwardTaint.kinds flow.sink_taint
|> List.map ~f:Sinks.discard_transforms
|> List.dedup_and_sort ~compare:Sinks.compare
|> List.map ~f:Sinks.show
|> String.concat ~sep:", "
in
let transforms = List.map transforms ~f:TaintTransform.show |> String.concat ~sep:", " in
let message =
Str.global_replace sources_regexp sources message_format
|> Str.global_replace sinks_regexp sinks
|> Str.global_replace transforms_regexp transforms
in
name, message
let to_error
~taint_configuration:({ TaintConfiguration.Heap.rules; _ } as taint_configuration)
({ handle = { code; _ }; define; _ } as issue)
=
match List.find ~f:(fun { code = rule_code; _ } -> code = rule_code) rules with
| None -> failwith "issue with code that has no rule"
| Some _ ->
let name, detail = get_name_and_detailed_message ~taint_configuration issue in
let kind = { Error.name; messages = [detail]; code } in
let location = canonical_location issue in
Error.create ~location ~define ~kind
let to_json ~taint_configuration ~expand_overrides ~is_valid_callee ~filename_lookup issue =
let callable_name = Target.external_name issue.handle.callable in
let _, message = get_name_and_detailed_message ~taint_configuration issue in
let source_traces =
ForwardTaint.to_json
~expand_overrides
~is_valid_callee
~filename_lookup:(Some filename_lookup)
issue.flow.source_taint
in
let sink_traces =
BackwardTaint.to_json
~expand_overrides
~is_valid_callee
~filename_lookup:(Some filename_lookup)
issue.flow.sink_taint
in
let features = get_issue_features issue.flow in
let json_features =
let get_feature_json { Abstract.OverUnderSetDomain.element; in_under } breadcrumbs =
let element = Features.BreadcrumbInterned.unintern element in
let breadcrumb_json = Features.Breadcrumb.to_json element ~on_all_paths:in_under in
breadcrumb_json :: breadcrumbs
in
Features.BreadcrumbSet.fold
Features.BreadcrumbSet.ElementAndUnder
~f:get_feature_json
~init:[]
features.breadcrumbs
in
let json_features =
List.concat
[
features.first_indices
|> Features.FirstIndexSet.elements
|> List.map ~f:Features.FirstIndexInterned.unintern
|> Features.FirstIndex.to_json;
features.first_fields
|> Features.FirstFieldSet.elements
|> List.map ~f:Features.FirstFieldInterned.unintern
|> Features.FirstField.to_json;
json_features;
]
in
let traces : Yojson.Safe.t =
`List
[
`Assoc ["name", `String "forward"; "roots", source_traces];
`Assoc ["name", `String "backward"; "roots", sink_traces];
]
in
let {
Location.WithPath.path;
start = { line; column = start_column };
stop = { column = stop_column; _ };
}
=
canonical_location issue |> Location.WithModule.instantiate ~lookup:filename_lookup
in
let callable_line = Ast.(Location.line issue.define.location) in
let sink_handle = IssueHandle.Sink.to_json issue.handle.sink in
let master_handle = IssueHandle.master_handle issue.handle in
`Assoc
[
"callable", `String callable_name;
"callable_line", `Int callable_line;
"code", `Int issue.handle.code;
"line", `Int line;
"start", `Int start_column;
"end", `Int stop_column;
"filename", `String path;
"message", `String message;
"traces", traces;
"features", `List json_features;
"sink_handle", sink_handle;
"master_handle", `String master_handle;
]
module MultiSource = struct
type issue = t
let get_triggered_sinks { flow = { Flow.sink_taint; _ }; _ } =
BackwardTaint.fold
BackwardTaint.kind
~f:(fun sink sofar ->
match Sinks.discard_sanitize_transforms sink with
| Sinks.TriggeredPartialSink _ as partial_sink -> Sinks.Set.add partial_sink sofar
| _ -> sofar)
~init:Sinks.Set.empty
sink_taint
let is_multi_source issue = not (Sinks.Set.is_empty (get_triggered_sinks issue))
let get_triggered_sink_labels ~sink_kind issue =
get_triggered_sinks issue
|> Sinks.Set.elements
|> List.filter_map ~f:(function
| Sinks.TriggeredPartialSink { Sinks.kind; label } ->
if String.equal kind sink_kind then
Some label
else
None
| _ -> failwith "Expect triggered sinks")
let get_issue_handles ~triggered_sink:{ Sinks.kind; _ } { flow = { Flow.sink_taint; _ }; _ } =
BackwardTaint.reduce
IssueHandleSet.Self
~using:(Context (BackwardTaint.kind, Acc))
~f:(fun sink_kind issue_handles so_far ->
match sink_kind with
| Sinks.TriggeredPartialSink { Sinks.kind = sink_kind; _ } ->
if String.equal kind sink_kind then
IssueHandleSet.join so_far issue_handles
else
so_far
| _ -> so_far)
~init:IssueHandleSet.bottom
sink_taint
let find_related_issues ~taint_configuration ~issue_handle_map issue =
let is_related ~triggered_sink:{ Sinks.kind; label } ~main_label ~secondary_label related_issue =
let missing_label = if String.equal main_label label then secondary_label else main_label in
get_triggered_sink_labels ~sink_kind:kind related_issue
|> List.exists ~f:(String.equal missing_label)
in
let accumulate_related_issues triggered_sink so_far =
match triggered_sink with
| Sinks.TriggeredPartialSink triggered_sink ->
let { TaintConfiguration.Heap.partial_sink_labels; _ } = taint_configuration in
let {
TaintConfiguration.PartialSinkLabelsMap.main = main_label;
secondary = secondary_label;
}
=
TaintConfiguration.PartialSinkLabelsMap.find_opt triggered_sink.kind partial_sink_labels
|> Option.value_exn
in
let related_issues =
get_issue_handles ~triggered_sink issue
|> IssueHandleSet.elements
|> List.map ~f:(fun issue_handle ->
IssueHandle.SerializableMap.find issue_handle issue_handle_map)
|> List.filter ~f:(is_related ~triggered_sink ~main_label ~secondary_label)
in
Sinks.Map.add (Sinks.TriggeredPartialSink triggered_sink) related_issues so_far
| _ -> so_far
in
Sinks.Set.fold accumulate_related_issues (get_triggered_sinks issue) Sinks.Map.empty
let is_main_issue ~sink ~taint_configuration issue =
let is_main_label ~kind label =
let { TaintConfiguration.Heap.partial_sink_labels; _ } = taint_configuration in
match TaintConfiguration.PartialSinkLabelsMap.find_opt kind partial_sink_labels with
| Some { main; _ } -> String.equal main label
| None -> false
in
match sink with
| Sinks.TriggeredPartialSink { kind; _ } ->
get_triggered_sink_labels ~sink_kind:kind issue |> List.exists ~f:(is_main_label ~kind)
| _ -> false
let get_first_sink_hops { flow = { Flow.sink_taint; _ }; _ } =
BackwardTaint.reduce
BackwardTaint.kind
~using:(Context (BackwardTaint.call_info, Acc))
~f:(fun call_info sink_kind so_far ->
let extra_trace =
{
ExtraTraceFirstHop.call_info;
leaf_kind = Sink sink_kind;
message =
Some (Format.asprintf "Sink trace of the secondary flow: %s" (Sinks.show sink_kind));
}
in
ExtraTraceFirstHop.Set.add extra_trace so_far)
~init:ExtraTraceFirstHop.Set.bottom
sink_taint
let get_first_source_hops { flow = { Flow.source_taint; _ }; _ } =
ForwardTaint.reduce
ForwardTaint.kind
~using:(Context (ForwardTaint.call_info, Acc))
~f:(fun call_info source_kind so_far ->
let extra_trace =
{
ExtraTraceFirstHop.call_info;
leaf_kind = Source source_kind;
message =
Some
(Format.asprintf
"Source trace of the secondary flow: %s"
(Sources.show source_kind));
}
in
ExtraTraceFirstHop.Set.add extra_trace so_far)
~init:ExtraTraceFirstHop.Set.bottom
source_taint
let attach_extra_traces
~source_traces
~sink_traces
({ flow = { Flow.source_taint; sink_taint }; _ } as issue)
=
let sink_taint =
BackwardTaint.add_extra_traces
~extra_traces:(ExtraTraceFirstHop.Set.join source_traces sink_traces)
sink_taint
in
{ issue with flow = { Flow.source_taint; sink_taint } }
end
|
f85a5bf67044733a9ba4f8233a41601e70af4dbef61d3cb8d497cad641c67b20 | avsm/mirage-duniverse | tar_lwt_unix.mli |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
(** Lwt_unix I/O for tar-formatted data *)
val really_read: Lwt_unix.file_descr -> Cstruct.t -> unit Lwt.t
* [ really_read fd buf ] fills [ buf ] with data from [ fd ] or fails
with End_of_file
with End_of_file *)
val really_write: Lwt_unix.file_descr -> Cstruct.t -> unit Lwt.t
* [ really_write fd buf ] writes the full contents of [ buf ] to
[ fd ] or fails with End_of_file
[fd] or fails with End_of_file *)
module Header : sig
include module type of Tar.Header
* Returns the next header block or None if two consecutive
zero - filled blocks are discovered . Assumes stream is positioned at the
possible start of a header block . Unix . End_of_file is thrown if the stream
unexpectedly fails
zero-filled blocks are discovered. Assumes stream is positioned at the
possible start of a header block. Unix.End_of_file is thrown if the stream
unexpectedly fails *)
val get_next_header : ?level:compatibility -> Lwt_unix.file_descr -> t option Lwt.t
(** Return the header needed for a particular file on disk *)
val of_file : ?level:compatibility -> string -> t Lwt.t
end
module Archive : sig
(** Utility functions for operating over whole tar archives *)
* Read the next header , apply the function ' f ' to the fd and the header . The function
should leave the fd positioned immediately after the datablock . Finally the function
skips past the zero padding to the next header
should leave the fd positioned immediately after the datablock. Finally the function
skips past the zero padding to the next header *)
val with_next_file : Lwt_unix.file_descr -> (Lwt_unix.file_descr -> Header.t -> 'a Lwt.t) -> 'a option Lwt.t
(** List the contents of a tar to stdout *)
val list : ?level:Header.compatibility -> Lwt_unix.file_descr -> Header.t list Lwt.t
(** [extract dest] extract the contents of a tar.
Apply 'dest' on each source filename to know the destination filename *)
val extract : (string -> string) -> Lwt_unix.file_descr -> unit Lwt.t
(** Create a tar on file descriptor fd from the filename list 'files' *)
val create : string list -> Lwt_unix.file_descr -> unit Lwt.t
end
| null | https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/tar/unix/tar_lwt_unix.mli | ocaml | * Lwt_unix I/O for tar-formatted data
* Return the header needed for a particular file on disk
* Utility functions for operating over whole tar archives
* List the contents of a tar to stdout
* [extract dest] extract the contents of a tar.
Apply 'dest' on each source filename to know the destination filename
* Create a tar on file descriptor fd from the filename list 'files' |
* Copyright ( C ) 2006 - 2009 Citrix Systems Inc.
*
* Permission to use , copy , modify , and distribute this software for any
* purpose with or without fee is hereby granted , provided that the above
* copyright notice and this permission notice appear in all copies .
*
* THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS . IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
* ACTION OF CONTRACT , NEGLIGENCE OR OTHER TORTIOUS ACTION , ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE .
* Copyright (C) 2006-2009 Citrix Systems Inc.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*)
val really_read: Lwt_unix.file_descr -> Cstruct.t -> unit Lwt.t
* [ really_read fd buf ] fills [ buf ] with data from [ fd ] or fails
with End_of_file
with End_of_file *)
val really_write: Lwt_unix.file_descr -> Cstruct.t -> unit Lwt.t
* [ really_write fd buf ] writes the full contents of [ buf ] to
[ fd ] or fails with End_of_file
[fd] or fails with End_of_file *)
module Header : sig
include module type of Tar.Header
* Returns the next header block or None if two consecutive
zero - filled blocks are discovered . Assumes stream is positioned at the
possible start of a header block . Unix . End_of_file is thrown if the stream
unexpectedly fails
zero-filled blocks are discovered. Assumes stream is positioned at the
possible start of a header block. Unix.End_of_file is thrown if the stream
unexpectedly fails *)
val get_next_header : ?level:compatibility -> Lwt_unix.file_descr -> t option Lwt.t
val of_file : ?level:compatibility -> string -> t Lwt.t
end
module Archive : sig
* Read the next header , apply the function ' f ' to the fd and the header . The function
should leave the fd positioned immediately after the datablock . Finally the function
skips past the zero padding to the next header
should leave the fd positioned immediately after the datablock. Finally the function
skips past the zero padding to the next header *)
val with_next_file : Lwt_unix.file_descr -> (Lwt_unix.file_descr -> Header.t -> 'a Lwt.t) -> 'a option Lwt.t
val list : ?level:Header.compatibility -> Lwt_unix.file_descr -> Header.t list Lwt.t
val extract : (string -> string) -> Lwt_unix.file_descr -> unit Lwt.t
val create : string list -> Lwt_unix.file_descr -> unit Lwt.t
end
|
57c8030f5b049d4b576f1701c6d6fd01c8e7b9c3808ddbc74b30416be98eef80 | spurious/sagittarius-scheme-mirror | enums.sps | #!r6rs
(import (tests r6rs enums)
(tests r6rs test)
(rnrs io simple))
(display "Running tests for (rnrs enums)\n")
(run-enums-tests)
(report-test-results)
| null | https://raw.githubusercontent.com/spurious/sagittarius-scheme-mirror/53f104188934109227c01b1e9a9af5312f9ce997/test/r6rs-test-suite/tests/r6rs/run/enums.sps | scheme | #!r6rs
(import (tests r6rs enums)
(tests r6rs test)
(rnrs io simple))
(display "Running tests for (rnrs enums)\n")
(run-enums-tests)
(report-test-results)
| |
ec82956c595f382405af766ab9c82adb254a5950ed258080adf243688a1ff2f9 | dubrousky/mockmma | init2.lisp | for non - allegro CL systems .
#+Allegro (excl::set-case-mode :case-sensitive-lower)
(load "mma")
(use-package :mma)
(load "uconsalt")
(load "parser")
(load "stack1")
(load "disp1")
(load "eval")
(load "poly")
(load "rat1")
(load "simp1")
(load "pf")
(load "match")
(load "diffrat")
| null | https://raw.githubusercontent.com/dubrousky/mockmma/036e7ba0773e43da50438a4f93774966cf82011f/init2.lisp | lisp | for non - allegro CL systems .
#+Allegro (excl::set-case-mode :case-sensitive-lower)
(load "mma")
(use-package :mma)
(load "uconsalt")
(load "parser")
(load "stack1")
(load "disp1")
(load "eval")
(load "poly")
(load "rat1")
(load "simp1")
(load "pf")
(load "match")
(load "diffrat")
| |
549c17677f152fb8eea42889ca6162e47beb136f9851073dd6bd45fb88813d07 | ocaml/ocaml-lsp | document_text_command.ml | open Import
open Fiber.O
let command_name = "ocamllsp/show-document-text"
let command_run server store args =
let uri =
match args with
| Some [ `String arg ] -> arg
| _ -> assert false
in
let doc =
Document_store.get store (Uri.t_of_yojson (`String uri)) |> Document.text
in
let uri, chan =
Filename.open_temp_file
(sprintf "ocamllsp-document.%d" (Unix.getpid ()))
(Filename.extension uri)
in
output_string chan doc;
close_out_noerr chan;
let req =
let uri = Uri.of_path uri in
Server_request.ShowDocumentRequest
(ShowDocumentParams.create ~uri ~takeFocus:true ())
in
let+ { ShowDocumentResult.success = _ } = Server.request server req in
()
| null | https://raw.githubusercontent.com/ocaml/ocaml-lsp/0d798b6a848f54cc4a09778335e42a4e0db3d4ef/ocaml-lsp-server/src/document_text_command.ml | ocaml | open Import
open Fiber.O
let command_name = "ocamllsp/show-document-text"
let command_run server store args =
let uri =
match args with
| Some [ `String arg ] -> arg
| _ -> assert false
in
let doc =
Document_store.get store (Uri.t_of_yojson (`String uri)) |> Document.text
in
let uri, chan =
Filename.open_temp_file
(sprintf "ocamllsp-document.%d" (Unix.getpid ()))
(Filename.extension uri)
in
output_string chan doc;
close_out_noerr chan;
let req =
let uri = Uri.of_path uri in
Server_request.ShowDocumentRequest
(ShowDocumentParams.create ~uri ~takeFocus:true ())
in
let+ { ShowDocumentResult.success = _ } = Server.request server req in
()
| |
1c7f564a0c2b6b376f2dbfbd26bd591884adf51130f23edc09af064340daa32f | acieroid/scala-am | icp_8_compiler.scm |
;;
;;toegevoegd
;;
(define true #t)
(define false #f)
(define (expand-clauses clauses)
(if (null? clauses)
'false
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last -- COND->IF"
))
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))
(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq) (first-exp seq))
(else (make-begin seq))))
(define (make-if predicate consequent alternative)
(list 'if predicate consequent alternative))
(define (make-begin seq) (cons 'begin seq))
(define (primitive-implementation proc) (cadr proc))
(define (cond->if exp)
(expand-clauses (cond-clauses exp)))
;;
;; zie deel 1.1 p52
;;
(define (apply-in-underlying-scheme op args)
(cond
((null? args) (op))
((null? (cdr args)) (op (car args)))
((null? (cddr args)) (op (car args) (cadr args)))
(else (error "apply"))))
;;
;; zie deel 1.1 p24
;;
(define (true? x)
(not (eq? x false)))
;;
;; zie deel 1.1 p18
;;
(define (self-evaluating? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
;;
;; zie deel 1.1 p19
;;
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (quoted? exp)
(tagged-list? exp 'quote))
(define (text-of-quotation exp) (cadr exp))
;;
;; zie deel 1.1 p18
;;
(define (variable? exp) (symbol? exp))
;;
;; zie deel 1.1 p21
;;
(define (assignment? exp)
(tagged-list? exp 'set!))
(define (assignment-variable exp) (cadr exp))
(define (assignment-value exp) (caddr exp))
;;
;; zie deel 1.1 p22
;;
(define (definition? exp)
(tagged-list? exp 'define))
(define (definition-variable exp)
(if (symbol? (cadr exp))
(cadr exp)
(caadr exp)))
(define (definition-value exp)
(if (symbol? (cadr exp))
(caddr exp)
(make-lambda (cdadr exp)
(cddr exp))))
;;
;; zie deel 1.1 p24
;;
(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
(define (if-alternative exp)
(if (not (null? (cdddr exp)))
(cadddr exp)
'false))
(define (cond? exp) (tagged-list? exp 'cond))
(define (cond-clauses exp) (cdr exp))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))
;;
;; zie deel 1.1 p28
;;
(define (lambda? exp) (tagged-list? exp 'lambda))
(define (lambda-parameters exp) (cadr exp))
(define (lambda-body exp) (cddr exp))
(define (make-lambda parameters body)
(cons 'lambda (cons parameters body)))
;;
zie deel 1.1 p42
;;
(define (begin? exp) (tagged-list? exp 'begin))
(define (begin-actions exp) (cdr exp))
(define (last-exp? seq) (null? (cdr seq)))
(define (first-exp seq) (car seq))
(define (rest-exps seq) (cdr seq))
;;
;; zie deel 1.1 p32
;;
(define (application? exp) (pair? exp))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
(define (no-operands? ops) (null? ops))
(define (first-operand ops) (car ops))
(define (rest-operands ops) (cdr ops))
;;
;; zie deel 1.1 p44
;;
(define (enclosing-environment env) (cdr env))
(define (first-frame env) (car env))
(define the-empty-environment '())
;;
;; zie deel 1.1 p45
;;
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
;;
;; zie deel 1.1 p44
;;
(define (make-frame variables values)
(cons variables values))
(define (frame-variables frame) (car frame))
(define (frame-values frame) (cdr frame))
(define (add-binding-to-frame! var val frame)
(set-car! frame (cons var (car frame)))
(set-cdr! frame (cons val (cdr frame))))
;;
;; zie deel 1.1 p46
;;
(define (lookup-variable-value var env)
(define (env-loop env)
(define (scan vars vals)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars))
(car vals))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
;;
;; zie deel 1.1 p48
;;
(define (set-variable-value! var val env)
(define (env-loop env)
(define (scan vars vals)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars))
(set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable -- SET!" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
;;
;; zie deel 1.1 p49
;;
(define (define-variable! var val env)
(let ((frame (first-frame env)))
(define (scan vars vals)
(cond ((null? vars)
(add-binding-to-frame! var val frame))
((eq? var (car vars))
(set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(scan (frame-variables frame)
(frame-values frame))))
;;
;; zie deel 1.1 p52
;;
(define (apply-primitive-procedure proc args)
(apply-in-underlying-scheme
(primitive-implementation proc) args))
;; =======================
;; begin van compiler code
;; =======================
;;
;; zie deel 8 p3
;;
(define (compile exp target linkage)
(cond ((self-evaluating? exp)
(compile-self-evaluating exp target linkage))
((quoted? exp) (compile-quoted exp target linkage))
((variable? exp)
(compile-variable exp target linkage))
((assignment? exp)
(compile-assignment exp target linkage))
((definition? exp)
(compile-definition exp target linkage))
((if? exp)
(compile-if exp target linkage))
((lambda? exp)
(compile-lambda exp target linkage))
((begin? exp)
(compile-sequence (begin-actions exp) target linkage))
((cond? exp) (compile (cond->if exp) target linkage))
((application? exp)
(compile-application exp target linkage))
(else
(error "Unknown expression type -- COMPILE" exp))))
;;
;; zie deel 8 p6
;;
(define (make-instruction-sequence needs modifies statements)
(list needs modifies statements))
(define (empty-instruction-sequence)
(make-instruction-sequence '() '() '()))
;;
;; zie deel 8 p4
;;
(define (compile-linkage linkage)
(cond ((eq? linkage 'return)
(make-instruction-sequence
'(continue) '()
'((goto (reg continue)))))
((eq? linkage 'next)
(empty-instruction-sequence))
(else
(make-instruction-sequence
'() '()
`((goto (label ,linkage)))))))
(define (end-with-linkage linkage instruction-sequence)
(preserving '(continue)
instruction-sequence
(compile-linkage linkage)))
;;
;; zie deel 8 p13
;;
(define (compile-self-evaluating exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence
'() (list target)
`((assign ,target (const ,exp))))))
(define (compile-quoted exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence
'() (list target)
`((assign ,target (const ,(text-of-quotation exp)))))))
(define (compile-variable exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence
'(env) (list target)
`((assign ,target (op lookup-variable-value)
(const ,exp) (reg env))))))
;;
;; zie deel 8 p15
;;
(define (compile-assignment exp target linkage)
(let ((var (assignment-variable exp))
(get-value-code
(compile (assignment-value exp) 'val 'next)))
(end-with-linkage linkage
(preserving '(env)
get-value-code
(make-instruction-sequence
'(env val) (list target)
`((perform (op set-variable-value!)
(const ,var)
(reg val)
(reg env))
(assign ,target (const ok))))))))
;;
;; zie deel 8 p17
;;
(define (compile-definition exp target linkage)
(let ((var (definition-variable exp))
(get-value-code
(compile (definition-value exp) 'val 'next)))
(end-with-linkage linkage
(preserving '(env)
get-value-code
(make-instruction-sequence
'(env val) (list target)
`((perform (op define-variable!)
(const ,var)
(reg val)
(reg env))
(assign ,target (const ok))))))))
;;
;; zie deel 8 p21
;;
(define label-counter 0)
(define (new-label-number)
(set! label-counter (+ 1 label-counter))
label-counter)
(define (make-label name)
(string->symbol
(string-append (symbol->string name)
(number->string (new-label-number)))))
;;
;; zie deel 8 p19
;;
(define (compile-if exp target linkage)
(let ((t-branch (make-label 'true-branch))
(f-branch (make-label 'false-branch))
(after-if (make-label 'after-if)))
(let ((consequent-linkage
(if (eq? linkage 'next) after-if linkage)))
(let ((p-code (compile (if-predicate exp) 'val 'next))
(c-code
(compile
(if-consequent exp) target consequent-linkage))
(a-code
(compile (if-alternative exp) target linkage)))
(preserving '(env continue)
p-code
(append-instruction-sequences
(make-instruction-sequence
'(val) '()
`((test (op false?) (reg val))
(branch (label ,f-branch))))
(parallel-instruction-sequences
(append-instruction-sequences t-branch c-code)
(append-instruction-sequences f-branch a-code))
after-if))))))
;;
;; zie deel 8 p24
;;
(define (compile-sequence seq target linkage)
(if (last-exp? seq)
(compile (first-exp seq) target linkage)
(preserving '(env continue)
(compile (first-exp seq) target 'next)
(compile-sequence (rest-exps seq) target linkage))))
;;
;; zie deel 8 p26
;;
(define (compile-lambda exp target linkage)
(let ((proc-entry (make-label 'entry))
(after-lambda (make-label 'after-lambda)))
(let ((lambda-linkage
(if (eq? linkage 'next) after-lambda linkage)))
(append-instruction-sequences
(tack-on-instruction-sequence
(end-with-linkage lambda-linkage
(make-instruction-sequence
'(env) (list target)
`((assign ,target (op make-compiled-procedure)
(label ,proc-entry) (reg env)))))
(compile-lambda-body exp proc-entry))
after-lambda))))
;;
;; zie deel 8 p28
;;
(define (compile-lambda-body exp proc-entry)
(let ((formals (lambda-parameters exp)))
(append-instruction-sequences
(make-instruction-sequence
'(env proc argl) '(env)
`(,proc-entry
(assign env (op compiled-procedure-env) (reg proc))
(assign env (op extend-environment)
(const ,formals) (reg argl) (reg env))))
(compile-sequence (lambda-body exp) 'val 'return))))
;;
;; zie deel 8 p30
;;
(define (compile-application exp target linkage)
(let ((proc-code (compile (operator exp) 'proc 'next))
(operand-codes
(map (lambda (operand) (compile operand 'val 'next))
(operands exp))))
(preserving '(env continue)
proc-code
(preserving '(proc continue)
(construct-arglist operand-codes)
(compile-procedure-call target linkage)))))
;;
zie deel 8 p31
;;
(define (construct-arglist operand-codes)
(let ((operand-codes (reverse operand-codes)))
(if (null? operand-codes)
(make-instruction-sequence '() '(argl)
'((assign argl (const ()))))
(let ((code-to-get-last-arg
(append-instruction-sequences
(car operand-codes)
(make-instruction-sequence
'(val) '(argl)
'((assign argl (op list) (reg val)))))))
(if (null? (cdr operand-codes))
code-to-get-last-arg
(preserving '(env)
code-to-get-last-arg
(code-to-get-rest-args
(cdr operand-codes))))))))
;;
;; zie deel 8 p32
;;
(define (code-to-get-rest-args operand-codes)
(let ((code-for-next-arg
(preserving '(argl)
(car operand-codes)
(make-instruction-sequence
'(val argl) '(argl)
'((assign argl
(op cons) (reg val) (reg argl)))))))
(if (null? (cdr operand-codes))
code-for-next-arg
(preserving '(env)
code-for-next-arg
(code-to-get-rest-args (cdr operand-codes))))))
;;
;; zie deel 8 p34
;;
(define (compile-procedure-call target linkage)
(let ((primitive-branch (make-label 'primitive-branch))
(compiled-branch (make-label 'compiled-branch))
(after-call (make-label 'after-call)))
(let ((compiled-linkage
(if (eq? linkage 'next) after-call linkage)))
(append-instruction-sequences
(make-instruction-sequence
'(proc) '()
`((test (op primitive-procedure?) (reg proc))
(branch (label ,primitive-branch))))
(parallel-instruction-sequences
(append-instruction-sequences
compiled-branch
(compile-proc-appl target compiled-linkage))
(append-instruction-sequences
primitive-branch
(end-with-linkage linkage
(make-instruction-sequence
'(proc argl)
(list target)
`((assign ,target (op apply-primitive-procedure)
(reg proc) (reg argl)))))))
after-call))))
;;
;; zie deel 8 p36
;;
(define (compile-proc-appl target linkage)
(cond ((and (eq? target 'val) (not (eq? linkage 'return)))
(make-instruction-sequence
'(proc) all-regs
`((assign continue (label ,linkage))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val)))))
((and (not (eq? target 'val))
(not (eq? linkage 'return)))
(let ((proc-return (make-label 'proc-return)))
(make-instruction-sequence
'(proc) all-regs
`((assign continue (label ,proc-return))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
,proc-return
(assign ,target (reg val))
(goto (label ,linkage))))))
((and (eq? target 'val) (eq? linkage 'return))
(make-instruction-sequence
'(proc continue) all-regs
'((assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val)))))
((and (not (eq? target 'val)) (eq? linkage 'return))
(error "return linkage, target not val -- COMPILE" target))))
(define all-regs '(env proc val argl continue))
;;
zie deel 8 p7
;;
(define (registers-needed s)
(if (symbol? s) '() (car s)))
(define (registers-modified s)
(if (symbol? s) '() (cadr s)))
(define (statements s)
(if (symbol? s) (list s) (caddr s)))
(define (needs-register? seq reg)
(memq reg (registers-needed seq)))
(define (modifies-register? seq reg)
(memq reg (registers-modified seq)))
;;
;; zie deel 8 p10
;;
(define (append-instruction-sequences . seqs)
(define (append-2-sequences seq1 seq2)
(make-instruction-sequence
(list-union (registers-needed seq1)
(list-difference (registers-needed seq2)
(registers-modified seq1)))
(list-union (registers-modified seq1)
(registers-modified seq2))
(append (statements seq1) (statements seq2))))
(define (append-seq-list seqs)
(if (null? seqs)
(empty-instruction-sequence)
(append-2-sequences (car seqs)
(append-seq-list (cdr seqs)))))
(append-seq-list seqs))
;;
;; zie deel 8 p11
;;
(define (list-union s1 s2)
(cond ((null? s1) s2)
((memq (car s1) s2) (list-union (cdr s1) s2))
(else (cons (car s1) (list-union (cdr s1) s2)))))
(define (list-difference s1 s2)
(cond ((null? s1) '())
((memq (car s1) s2) (list-difference (cdr s1) s2))
(else (cons (car s1)
(list-difference (cdr s1) s2)))))
;;
;; zie deel 8 p8
;;
(define (preserving regs seq1 seq2)
(if (null? regs)
(append-instruction-sequences seq1 seq2)
(let ((first-reg (car regs)))
(if (and (needs-register? seq2 first-reg)
(modifies-register? seq1 first-reg))
(preserving (cdr regs)
(make-instruction-sequence
(list-union (list first-reg)
(registers-needed seq1))
(list-difference (registers-modified seq1)
(list first-reg))
(append `((save ,first-reg))
(append (statements seq1)
`((restore ,first-reg)))))
seq2)
(preserving (cdr regs) seq1 seq2)))))
;;
;; zie deel 8 p22
;;
(define (tack-on-instruction-sequence seq body-seq)
(make-instruction-sequence
(registers-needed seq)
(registers-modified seq)
(append (statements seq) (statements body-seq))))
(define (parallel-instruction-sequences seq1 seq2)
(make-instruction-sequence
(list-union (registers-needed seq1)
(registers-needed seq2))
(list-union (registers-modified seq1)
(registers-modified seq2))
(append (statements seq1) (statements seq2))))
(define (make-compiled-procedure entry env)
(list 'compiled-procedure entry env))
(define (compiled-procedure? proc)
(tagged-list? proc 'compiled-procedure))
(define (compiled-procedure-entry c-proc)
(cadr c-proc))
(define (compiled-procedure-env c-proc)
(caddr c-proc))
;; =======================
;; einde van compiler code
;; =======================
(compile
'(begin (define (id x)
x)
(id 2))
'val
'next)
(compile
'(begin (define (fac n)
(if (= n 0)
1
(* n (fac (- n 1)))))
(fac 5))
'val
'next)
| null | https://raw.githubusercontent.com/acieroid/scala-am/13ef3befbfc664b77f31f56847c30d60f4ee7dfe/test/R5RS/icp/icp_8_compiler.scm | scheme |
toegevoegd
zie deel 1.1 p52
zie deel 1.1 p24
zie deel 1.1 p18
zie deel 1.1 p19
zie deel 1.1 p18
zie deel 1.1 p21
zie deel 1.1 p22
zie deel 1.1 p24
zie deel 1.1 p28
zie deel 1.1 p32
zie deel 1.1 p44
zie deel 1.1 p45
zie deel 1.1 p44
zie deel 1.1 p46
zie deel 1.1 p48
zie deel 1.1 p49
zie deel 1.1 p52
=======================
begin van compiler code
=======================
zie deel 8 p3
zie deel 8 p6
zie deel 8 p4
zie deel 8 p13
zie deel 8 p15
zie deel 8 p17
zie deel 8 p21
zie deel 8 p19
zie deel 8 p24
zie deel 8 p26
zie deel 8 p28
zie deel 8 p30
zie deel 8 p32
zie deel 8 p34
zie deel 8 p36
zie deel 8 p10
zie deel 8 p11
zie deel 8 p8
zie deel 8 p22
=======================
einde van compiler code
======================= |
(define true #t)
(define false #f)
(define (expand-clauses clauses)
(if (null? clauses)
'false
(let ((first (car clauses))
(rest (cdr clauses)))
(if (cond-else-clause? first)
(if (null? rest)
(sequence->exp (cond-actions first))
(error "ELSE clause isn't last -- COND->IF"
))
(make-if (cond-predicate first)
(sequence->exp (cond-actions first))
(expand-clauses rest))))))
(define (sequence->exp seq)
(cond ((null? seq) seq)
((last-exp? seq) (first-exp seq))
(else (make-begin seq))))
(define (make-if predicate consequent alternative)
(list 'if predicate consequent alternative))
(define (make-begin seq) (cons 'begin seq))
(define (primitive-implementation proc) (cadr proc))
(define (cond->if exp)
(expand-clauses (cond-clauses exp)))
(define (apply-in-underlying-scheme op args)
(cond
((null? args) (op))
((null? (cdr args)) (op (car args)))
((null? (cddr args)) (op (car args) (cadr args)))
(else (error "apply"))))
(define (true? x)
(not (eq? x false)))
(define (self-evaluating? exp)
(cond ((number? exp) true)
((string? exp) true)
(else false)))
(define (tagged-list? exp tag)
(if (pair? exp)
(eq? (car exp) tag)
false))
(define (quoted? exp)
(tagged-list? exp 'quote))
(define (text-of-quotation exp) (cadr exp))
(define (variable? exp) (symbol? exp))
(define (assignment? exp)
(tagged-list? exp 'set!))
(define (assignment-variable exp) (cadr exp))
(define (assignment-value exp) (caddr exp))
(define (definition? exp)
(tagged-list? exp 'define))
(define (definition-variable exp)
(if (symbol? (cadr exp))
(cadr exp)
(caadr exp)))
(define (definition-value exp)
(if (symbol? (cadr exp))
(caddr exp)
(make-lambda (cdadr exp)
(cddr exp))))
(define (if? exp) (tagged-list? exp 'if))
(define (if-predicate exp) (cadr exp))
(define (if-consequent exp) (caddr exp))
(define (if-alternative exp)
(if (not (null? (cdddr exp)))
(cadddr exp)
'false))
(define (cond? exp) (tagged-list? exp 'cond))
(define (cond-clauses exp) (cdr exp))
(define (cond-else-clause? clause)
(eq? (cond-predicate clause) 'else))
(define (cond-predicate clause) (car clause))
(define (cond-actions clause) (cdr clause))
(define (lambda? exp) (tagged-list? exp 'lambda))
(define (lambda-parameters exp) (cadr exp))
(define (lambda-body exp) (cddr exp))
(define (make-lambda parameters body)
(cons 'lambda (cons parameters body)))
zie deel 1.1 p42
(define (begin? exp) (tagged-list? exp 'begin))
(define (begin-actions exp) (cdr exp))
(define (last-exp? seq) (null? (cdr seq)))
(define (first-exp seq) (car seq))
(define (rest-exps seq) (cdr seq))
(define (application? exp) (pair? exp))
(define (operator exp) (car exp))
(define (operands exp) (cdr exp))
(define (no-operands? ops) (null? ops))
(define (first-operand ops) (car ops))
(define (rest-operands ops) (cdr ops))
(define (enclosing-environment env) (cdr env))
(define (first-frame env) (car env))
(define the-empty-environment '())
(define (extend-environment vars vals base-env)
(if (= (length vars) (length vals))
(cons (make-frame vars vals) base-env)
(if (< (length vars) (length vals))
(error "Too many arguments supplied" vars vals)
(error "Too few arguments supplied" vars vals))))
(define (make-frame variables values)
(cons variables values))
(define (frame-variables frame) (car frame))
(define (frame-values frame) (cdr frame))
(define (add-binding-to-frame! var val frame)
(set-car! frame (cons var (car frame)))
(set-cdr! frame (cons val (cdr frame))))
(define (lookup-variable-value var env)
(define (env-loop env)
(define (scan vars vals)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars))
(car vals))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
(define (set-variable-value! var val env)
(define (env-loop env)
(define (scan vars vals)
(cond ((null? vars)
(env-loop (enclosing-environment env)))
((eq? var (car vars))
(set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(if (eq? env the-empty-environment)
(error "Unbound variable -- SET!" var)
(let ((frame (first-frame env)))
(scan (frame-variables frame)
(frame-values frame)))))
(env-loop env))
(define (define-variable! var val env)
(let ((frame (first-frame env)))
(define (scan vars vals)
(cond ((null? vars)
(add-binding-to-frame! var val frame))
((eq? var (car vars))
(set-car! vals val))
(else (scan (cdr vars) (cdr vals)))))
(scan (frame-variables frame)
(frame-values frame))))
(define (apply-primitive-procedure proc args)
(apply-in-underlying-scheme
(primitive-implementation proc) args))
(define (compile exp target linkage)
(cond ((self-evaluating? exp)
(compile-self-evaluating exp target linkage))
((quoted? exp) (compile-quoted exp target linkage))
((variable? exp)
(compile-variable exp target linkage))
((assignment? exp)
(compile-assignment exp target linkage))
((definition? exp)
(compile-definition exp target linkage))
((if? exp)
(compile-if exp target linkage))
((lambda? exp)
(compile-lambda exp target linkage))
((begin? exp)
(compile-sequence (begin-actions exp) target linkage))
((cond? exp) (compile (cond->if exp) target linkage))
((application? exp)
(compile-application exp target linkage))
(else
(error "Unknown expression type -- COMPILE" exp))))
(define (make-instruction-sequence needs modifies statements)
(list needs modifies statements))
(define (empty-instruction-sequence)
(make-instruction-sequence '() '() '()))
(define (compile-linkage linkage)
(cond ((eq? linkage 'return)
(make-instruction-sequence
'(continue) '()
'((goto (reg continue)))))
((eq? linkage 'next)
(empty-instruction-sequence))
(else
(make-instruction-sequence
'() '()
`((goto (label ,linkage)))))))
(define (end-with-linkage linkage instruction-sequence)
(preserving '(continue)
instruction-sequence
(compile-linkage linkage)))
(define (compile-self-evaluating exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence
'() (list target)
`((assign ,target (const ,exp))))))
(define (compile-quoted exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence
'() (list target)
`((assign ,target (const ,(text-of-quotation exp)))))))
(define (compile-variable exp target linkage)
(end-with-linkage linkage
(make-instruction-sequence
'(env) (list target)
`((assign ,target (op lookup-variable-value)
(const ,exp) (reg env))))))
(define (compile-assignment exp target linkage)
(let ((var (assignment-variable exp))
(get-value-code
(compile (assignment-value exp) 'val 'next)))
(end-with-linkage linkage
(preserving '(env)
get-value-code
(make-instruction-sequence
'(env val) (list target)
`((perform (op set-variable-value!)
(const ,var)
(reg val)
(reg env))
(assign ,target (const ok))))))))
(define (compile-definition exp target linkage)
(let ((var (definition-variable exp))
(get-value-code
(compile (definition-value exp) 'val 'next)))
(end-with-linkage linkage
(preserving '(env)
get-value-code
(make-instruction-sequence
'(env val) (list target)
`((perform (op define-variable!)
(const ,var)
(reg val)
(reg env))
(assign ,target (const ok))))))))
(define label-counter 0)
(define (new-label-number)
(set! label-counter (+ 1 label-counter))
label-counter)
(define (make-label name)
(string->symbol
(string-append (symbol->string name)
(number->string (new-label-number)))))
(define (compile-if exp target linkage)
(let ((t-branch (make-label 'true-branch))
(f-branch (make-label 'false-branch))
(after-if (make-label 'after-if)))
(let ((consequent-linkage
(if (eq? linkage 'next) after-if linkage)))
(let ((p-code (compile (if-predicate exp) 'val 'next))
(c-code
(compile
(if-consequent exp) target consequent-linkage))
(a-code
(compile (if-alternative exp) target linkage)))
(preserving '(env continue)
p-code
(append-instruction-sequences
(make-instruction-sequence
'(val) '()
`((test (op false?) (reg val))
(branch (label ,f-branch))))
(parallel-instruction-sequences
(append-instruction-sequences t-branch c-code)
(append-instruction-sequences f-branch a-code))
after-if))))))
(define (compile-sequence seq target linkage)
(if (last-exp? seq)
(compile (first-exp seq) target linkage)
(preserving '(env continue)
(compile (first-exp seq) target 'next)
(compile-sequence (rest-exps seq) target linkage))))
(define (compile-lambda exp target linkage)
(let ((proc-entry (make-label 'entry))
(after-lambda (make-label 'after-lambda)))
(let ((lambda-linkage
(if (eq? linkage 'next) after-lambda linkage)))
(append-instruction-sequences
(tack-on-instruction-sequence
(end-with-linkage lambda-linkage
(make-instruction-sequence
'(env) (list target)
`((assign ,target (op make-compiled-procedure)
(label ,proc-entry) (reg env)))))
(compile-lambda-body exp proc-entry))
after-lambda))))
(define (compile-lambda-body exp proc-entry)
(let ((formals (lambda-parameters exp)))
(append-instruction-sequences
(make-instruction-sequence
'(env proc argl) '(env)
`(,proc-entry
(assign env (op compiled-procedure-env) (reg proc))
(assign env (op extend-environment)
(const ,formals) (reg argl) (reg env))))
(compile-sequence (lambda-body exp) 'val 'return))))
(define (compile-application exp target linkage)
(let ((proc-code (compile (operator exp) 'proc 'next))
(operand-codes
(map (lambda (operand) (compile operand 'val 'next))
(operands exp))))
(preserving '(env continue)
proc-code
(preserving '(proc continue)
(construct-arglist operand-codes)
(compile-procedure-call target linkage)))))
zie deel 8 p31
(define (construct-arglist operand-codes)
(let ((operand-codes (reverse operand-codes)))
(if (null? operand-codes)
(make-instruction-sequence '() '(argl)
'((assign argl (const ()))))
(let ((code-to-get-last-arg
(append-instruction-sequences
(car operand-codes)
(make-instruction-sequence
'(val) '(argl)
'((assign argl (op list) (reg val)))))))
(if (null? (cdr operand-codes))
code-to-get-last-arg
(preserving '(env)
code-to-get-last-arg
(code-to-get-rest-args
(cdr operand-codes))))))))
(define (code-to-get-rest-args operand-codes)
(let ((code-for-next-arg
(preserving '(argl)
(car operand-codes)
(make-instruction-sequence
'(val argl) '(argl)
'((assign argl
(op cons) (reg val) (reg argl)))))))
(if (null? (cdr operand-codes))
code-for-next-arg
(preserving '(env)
code-for-next-arg
(code-to-get-rest-args (cdr operand-codes))))))
(define (compile-procedure-call target linkage)
(let ((primitive-branch (make-label 'primitive-branch))
(compiled-branch (make-label 'compiled-branch))
(after-call (make-label 'after-call)))
(let ((compiled-linkage
(if (eq? linkage 'next) after-call linkage)))
(append-instruction-sequences
(make-instruction-sequence
'(proc) '()
`((test (op primitive-procedure?) (reg proc))
(branch (label ,primitive-branch))))
(parallel-instruction-sequences
(append-instruction-sequences
compiled-branch
(compile-proc-appl target compiled-linkage))
(append-instruction-sequences
primitive-branch
(end-with-linkage linkage
(make-instruction-sequence
'(proc argl)
(list target)
`((assign ,target (op apply-primitive-procedure)
(reg proc) (reg argl)))))))
after-call))))
(define (compile-proc-appl target linkage)
(cond ((and (eq? target 'val) (not (eq? linkage 'return)))
(make-instruction-sequence
'(proc) all-regs
`((assign continue (label ,linkage))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val)))))
((and (not (eq? target 'val))
(not (eq? linkage 'return)))
(let ((proc-return (make-label 'proc-return)))
(make-instruction-sequence
'(proc) all-regs
`((assign continue (label ,proc-return))
(assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val))
,proc-return
(assign ,target (reg val))
(goto (label ,linkage))))))
((and (eq? target 'val) (eq? linkage 'return))
(make-instruction-sequence
'(proc continue) all-regs
'((assign val (op compiled-procedure-entry) (reg proc))
(goto (reg val)))))
((and (not (eq? target 'val)) (eq? linkage 'return))
(error "return linkage, target not val -- COMPILE" target))))
(define all-regs '(env proc val argl continue))
zie deel 8 p7
(define (registers-needed s)
(if (symbol? s) '() (car s)))
(define (registers-modified s)
(if (symbol? s) '() (cadr s)))
(define (statements s)
(if (symbol? s) (list s) (caddr s)))
(define (needs-register? seq reg)
(memq reg (registers-needed seq)))
(define (modifies-register? seq reg)
(memq reg (registers-modified seq)))
(define (append-instruction-sequences . seqs)
(define (append-2-sequences seq1 seq2)
(make-instruction-sequence
(list-union (registers-needed seq1)
(list-difference (registers-needed seq2)
(registers-modified seq1)))
(list-union (registers-modified seq1)
(registers-modified seq2))
(append (statements seq1) (statements seq2))))
(define (append-seq-list seqs)
(if (null? seqs)
(empty-instruction-sequence)
(append-2-sequences (car seqs)
(append-seq-list (cdr seqs)))))
(append-seq-list seqs))
(define (list-union s1 s2)
(cond ((null? s1) s2)
((memq (car s1) s2) (list-union (cdr s1) s2))
(else (cons (car s1) (list-union (cdr s1) s2)))))
(define (list-difference s1 s2)
(cond ((null? s1) '())
((memq (car s1) s2) (list-difference (cdr s1) s2))
(else (cons (car s1)
(list-difference (cdr s1) s2)))))
(define (preserving regs seq1 seq2)
(if (null? regs)
(append-instruction-sequences seq1 seq2)
(let ((first-reg (car regs)))
(if (and (needs-register? seq2 first-reg)
(modifies-register? seq1 first-reg))
(preserving (cdr regs)
(make-instruction-sequence
(list-union (list first-reg)
(registers-needed seq1))
(list-difference (registers-modified seq1)
(list first-reg))
(append `((save ,first-reg))
(append (statements seq1)
`((restore ,first-reg)))))
seq2)
(preserving (cdr regs) seq1 seq2)))))
(define (tack-on-instruction-sequence seq body-seq)
(make-instruction-sequence
(registers-needed seq)
(registers-modified seq)
(append (statements seq) (statements body-seq))))
(define (parallel-instruction-sequences seq1 seq2)
(make-instruction-sequence
(list-union (registers-needed seq1)
(registers-needed seq2))
(list-union (registers-modified seq1)
(registers-modified seq2))
(append (statements seq1) (statements seq2))))
(define (make-compiled-procedure entry env)
(list 'compiled-procedure entry env))
(define (compiled-procedure? proc)
(tagged-list? proc 'compiled-procedure))
(define (compiled-procedure-entry c-proc)
(cadr c-proc))
(define (compiled-procedure-env c-proc)
(caddr c-proc))
(compile
'(begin (define (id x)
x)
(id 2))
'val
'next)
(compile
'(begin (define (fac n)
(if (= n 0)
1
(* n (fac (- n 1)))))
(fac 5))
'val
'next)
|
3010da1f7249fc30c3ce9c150245f630b7ff1652d7a5a97d8282bf81575c0c97 | Mushy-pea/Game-Dangerous | AssmGplc.hs | Game : : Dangerous code by . You are free to use this software and view its source code .
-- If you wish to redistribute it or use it as part of your own work, this is permitted as long as you acknowledge the work is by the abovementioned author.
This is a development tool that generates bytecode from GPLC source code .
module Main where
import System.IO
import System.IO.Unsafe
import System.Environment
import Data.Maybe
import Data.List.Split
import Control.Exception
data Bytecode_gen_error = Invalid_opcode | Undefined_value_used deriving (Show)
instance Exception Bytecode_gen_error
init_ :: [a] -> [a]
init_ x = take ((length x) - 2) x
show_ints :: [Int] -> [Char]
show_ints [] = []
show_ints (x:xs) = (show x) ++ ", " ++ show_ints xs
proc_ints :: [[Char]] -> [Int]
proc_ints [] = []
proc_ints (x:xs) = (read x :: Int) : proc_ints xs
fst__ (a, b, c) = a
snd__ (a, b, c) = b
third_ (a, b, c) = c
fst' (a, b, c, d) = a
snd' (a, b, c, d) = b
third' (a, b, c, d) = c
fourth (a, b, c, d) = d
These six functions are part of a pipeline that transforms keywords into op - codes and their reference arguments into the data block pointers used by the interpreter .
assm_gplc5 :: [[Char]] -> [Int] -> Int -> [Int]
assm_gplc5 [] size_block size = (size_block ++ [size])
assm_gplc5 (x:xs) size_block size =
if x == "--signal" then assm_gplc5 (drop 1 xs) (size_block ++ [size]) 0
else if x == "pass_msg" then assm_gplc5 (drop 1 xs) size_block (size + 1)
else if x == "block" then assm_gplc5 xs size_block (size + 3)
else if x == "npc_damage" then assm_gplc5 xs size_block (size + 1)
else assm_gplc5 xs size_block (size + 1)
assm_gplc4 :: [[Char]] -> [Int]
assm_gplc4 [] = []
assm_gplc4 (x0:x1:xs) = (read x1) : assm_gplc4 xs
assm_gplc3 :: Int -> [Char] -> [[Char]] -> [(Int, Int)] -> Int
assm_gplc3 t symbol [] [] = error ("Undeclared op - code reference argument used: " ++ symbol)
assm_gplc3 t symbol (x:xs) (y:ys) =
if symbol == x then
if t == 0 then fst y
else (snd y)
else assm_gplc3 t symbol xs ys
assm_gplc2 :: Int -> [[Char]] -> [[Char]] -> [(Int, Int)] -> [Int]
assm_gplc2 1 (x0:x1:x2:x3:x4:xs) sym ind = (read x0) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (read x3) : [read x4]
assm_gplc2 2 (x0:x1:x2:x3:x4:x5:x6:x7:x8:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : (assm_gplc3 0 x6 sym ind) : (assm_gplc3 0 x7 sym ind) : [assm_gplc3 0 x8 sym ind]
assm_gplc2 3 (x0:x1:x2:x3:x4:x5:x6:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : [assm_gplc3 0 x6 sym ind]
assm_gplc2 4 (x0:x1:x2:x3:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : [assm_gplc3 0 x3 sym ind]
assm_gplc2 5 (x0:x1:x2:x3:x4:x5:xs) sym ind = (assm_gplc3 1 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : [assm_gplc3 0 x5 sym ind]
assm_gplc2 6 (x0:x1:x2:x3:x4:x5:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : [assm_gplc3 0 x5 sym ind]
assm_gplc2 7 (x0:x1:x2:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : [assm_gplc3 0 x2 sym ind]
assm_gplc2 8 (x0:x1:x2:x3:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : [assm_gplc3 0 x3 sym ind]
assm_gplc2 9 (x0:xs) sym ind = [assm_gplc3 0 x0 sym ind]
assm_gplc2 10 (x0:x1:x2:x3:x4:x5:x6:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : [assm_gplc3 0 x6 sym ind]
assm_gplc2 11 (x0:x1:x2:x3:xs) sym ind = (read x0) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : [assm_gplc3 0 x3 sym ind]
assm_gplc2 12 (x0:x1:x2:x3:x4:x5:x6:xs) sym ind = (read x0) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : [assm_gplc3 0 x6 sym ind]
assm_gplc2 13 (x0:x1:xs) sym ind = (assm_gplc3 0 x1 sym ind) : proc_ints xs
assm_gplc2 14 (x0:x1:x2:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : [assm_gplc3 0 x2 sym ind]
assm_gplc2 15 (x0:x1:x2:x3:xs) sym ind = (read x0) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : [assm_gplc3 0 x3 sym ind]
assm_gplc2 16 (x0:x1:x2:x3:x4:x5:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : [read x5]
assm_gplc2 17 (x0:x1:x2:x3:x4:x5:x6:x7:x8:x9:x10:x11:x12:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : (assm_gplc3 0 x6 sym ind) : (assm_gplc3 0 x7 sym ind) : (assm_gplc3 0 x8 sym ind) : (assm_gplc3 0 x9 sym ind) : (assm_gplc3 0 x10 sym ind) : (read x11) : [assm_gplc3 0 x12 sym ind]
assm_gplc2 18 (x0:x1:x2:x3:x4:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 1 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : [assm_gplc3 0 x4 sym ind]
assm_gplc2 19 (x0:x1:xs) sym ind = (assm_gplc3 0 x0 sym ind) : [assm_gplc3 0 x1 sym ind]
assm_gplc2 20 (x0:xs) sym ind = [assm_gplc3 1 x0 sym ind]
assm_gplc2 21 (x0:xs) sym ind = [assm_gplc3 1 x0 sym ind]
assm_gplc2 22 (x0:xs) sym ind = [read x0]
assm_gplc2 23 (x0:x1:xs) sym ind = (assm_gplc3 1 x0 sym ind) : [read x1]
assm_gplc1 :: [[Char]] -> Int -> Int -> [[Char]] -> [(Int, Int)] -> [Char] -> [Char] -> Int -> ([[Char]], [(Int, Int)], [Char])
assm_gplc1 [] offset i acc0 acc1 log prog_name mode = (acc0, acc1, log)
assm_gplc1 (x0:x1:xs) offset i acc0 acc1 log prog_name mode =
if mode == 1 then
if i == 0 then assm_gplc1 xs offset (i + 1) (acc0 ++ [x0]) (acc1 ++ [(i, offset + i)]) (log ++ "\n\nProgram " ++ prog_name ++ " starts here...\n\nSymbol: " ++ x0 ++ " Read binding: " ++ show i ++ " Write binding: " ++ show (offset + i)) prog_name mode
else assm_gplc1 xs offset (i + 1) (acc0 ++ [x0]) (acc1 ++ [(i, offset + i)]) (log ++ "\n\nSymbol: " ++ x0 ++ " Read binding: " ++ show i ++ " Write binding: " ++ show (offset + i)) prog_name mode
else assm_gplc1 xs offset (i + 1) (acc0 ++ [x0]) (acc1 ++ [(i, offset + i)]) log prog_name mode
assm_gplc1 (x0:xs) offset i acc0 acc1 log prog_name mode = error ("\n\nassm_gplc1: " ++ x0 ++ "...")
-- This function recognises the keywords that correspond to op - codes and is the beginning of the pipeline that transforms them and their arguments into bytecode.
assm_gplc0 :: [[Char]] -> [[Char]] -> [(Int, Int)] -> [Int] -> [Int] -> [Int] -> [Char] -> Int -> [Int]
assm_gplc0 [] sym ind size_block sig_block code_block prog_name c = sig_block ++ [536870911] ++ code_block ++ [536870911]
assm_gplc0 (x:xs) sym ind size_block sig_block code_block prog_name c =
let msg_length = (read (xs !! 0))
in
if x == "if" then assm_gplc0 (drop 5 xs) sym ind size_block sig_block (code_block ++ [1] ++ (assm_gplc2 1 (take 5 xs) sym ind)) prog_name (c + 6)
else if x == "chg_state" then assm_gplc0 (drop 9 xs) sym ind size_block sig_block (code_block ++ [2] ++ (assm_gplc2 2 (take 9 xs) sym ind)) prog_name (c + 10)
else if x == "chg_grid" then assm_gplc0 (drop 7 xs) sym ind size_block sig_block (code_block ++ [3] ++ (assm_gplc2 3 (take 7 xs) sym ind)) prog_name (c + 8)
else if x == "send_signal" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [4] ++ (assm_gplc2 4 (take 4 xs) sym ind)) prog_name (c + 5)
else if x == "chg_value" then assm_gplc0 (drop 6 xs) sym ind size_block sig_block (code_block ++ [5] ++ (assm_gplc2 5 (take 6 xs) sym ind)) prog_name (c + 7)
else if x == "chg_floor" then assm_gplc0 (drop 6 xs) sym ind size_block sig_block (code_block ++ [6] ++ (assm_gplc2 6 (take 6 xs) sym ind)) prog_name (c + 7)
else if x == "chg_ps1" then assm_gplc0 (drop 3 xs) sym ind size_block sig_block (code_block ++ [7] ++ (assm_gplc2 7 (take 3 xs) sym ind)) prog_name (c + 4)
else if x == "chg_obj_type" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [8] ++ (assm_gplc2 8 (take 4 xs) sym ind)) prog_name (c + 5)
else if x == "place_hold" then assm_gplc0 (drop 1 xs) sym ind size_block sig_block (code_block ++ [9] ++ (assm_gplc2 9 (take 1 xs) sym ind)) prog_name (c + 2)
else if x == "chg_grid_" then assm_gplc0 (drop 7 xs) sym ind size_block sig_block (code_block ++ [10] ++ (assm_gplc2 10 (take 7 xs) sym ind)) prog_name (c + 8)
else if x == "copy_ps1" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [11] ++ (assm_gplc2 11 (take 4 xs) sym ind)) prog_name (c + 5)
else if x == "copy_lstate" then assm_gplc0 (drop 7 xs) sym ind size_block sig_block (code_block ++ [12] ++ (assm_gplc2 12 (take 7 xs) sym ind)) prog_name (c + 8)
else if x == "pass_msg" then assm_gplc0 (drop msg_length xs) sym ind size_block sig_block (code_block ++ [13] ++ (assm_gplc2 13 (take msg_length xs) sym ind)) prog_name (c + msg_length)
else if x == "chg_ps0" then assm_gplc0 (drop 3 xs) sym ind size_block sig_block (code_block ++ [14] ++ (assm_gplc2 14 (take 3 xs) sym ind)) prog_name (c + 4)
else if x == "copy_ps0" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [15] ++ (assm_gplc2 15 (take 4 xs) sym ind)) prog_name (c + 5)
else if x == "block" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [5, 536870910, 0, read (xs !! 0), assm_gplc3 0 (xs !! 1) sym ind, assm_gplc3 0 (xs !! 2) sym ind, assm_gplc3 0 (xs !! 3) sym ind]) prog_name (c + 7)
else if x == "binary_dice" then assm_gplc0 (drop 6 xs) sym ind size_block sig_block (code_block ++ [16] ++ (assm_gplc2 16 (take 6 xs) sym ind)) prog_name (c + 7)
else if x == "project_init" then assm_gplc0 (drop 13 xs) sym ind size_block sig_block (code_block ++ [17] ++ (assm_gplc2 17 (take 13 xs) sym ind)) prog_name (c + 14)
else if x == "project_update" then assm_gplc0 (drop 5 xs) sym ind size_block sig_block (code_block ++ [18] ++ (assm_gplc2 18 (take 5 xs) sym ind)) prog_name (c + 6)
else if x == "init_npc" then assm_gplc0 (drop 2 xs) sym ind size_block sig_block (code_block ++ [19] ++ assm_gplc2 19 (take 2 xs) sym ind) prog_name (c + 3)
else if x == "npc_decision" then assm_gplc0 (tail xs) sym ind size_block sig_block (code_block ++ [20] ++ assm_gplc2 20 (take 1 xs) sym ind) prog_name (c + 2)
else if x == "npc_move" then assm_gplc0 (tail xs) sym ind size_block sig_block (code_block ++ [21] ++ assm_gplc2 21 (take 1 xs) sym ind) prog_name (c + 2)
else if x == "npc_damage" then assm_gplc0 (drop 1 xs) sym ind size_block sig_block (code_block ++ [22] ++ assm_gplc2 22 (take 1 xs) sym ind) prog_name (c + 2)
else if x == "cpede_move" then assm_gplc0 (drop 2 xs) sym ind size_block sig_block (code_block ++ [23] ++ assm_gplc2 23 (take 2 xs) sym ind) prog_name (c + 3)
else if x == "--signal" then assm_gplc0 (drop 1 xs) sym ind (tail size_block) (sig_block ++ [read (xs !! 0), c, head size_block]) code_block prog_name c
else error ("\nprog_name: " ++ prog_name ++ "\nc: " ++ show c ++ "\nInvalid op_code: " ++ x)
This function is used for program instancing . The map structure data is used to specify where each GPLC program is placed in the map . A single program can be placed in multiple
-- locations with its value block patched to different states in each case.
patch_code :: [Int] -> [[Char]] -> [[Char]] -> [(Int, Int)] -> [Int]
patch_code code [] sym ind = code
patch_code code (x0:x1:xs) sym ind =
let offset = assm_gplc3 1 x0 sym ind
in
patch_code (take (offset + 1) code ++ [read x1] ++ drop (offset + 2) code) xs sym ind
place_gplc :: [[Char]] -> [[Int]] -> [[[Char]]] -> [[(Int, Int)]] -> [Char]
place_gplc [] code sym ind = []
place_gplc (x0:x1:x2:x3:x4:x5:xs) code sym ind =
if read x4 == 0 then x0 ++ ", " ++ x1 ++ ", " ++ x2 ++ ", " ++ x3 ++ ", " ++ x4 ++ ", " ++ place_gplc xs code sym ind
else if x5 == "y" then x0 ++ ", " ++ x1 ++ ", " ++ x2 ++ ", " ++ x3 ++ ", " ++ show_ints (patch_code (code !! ((read x4) - 1)) (take (read (xs !! 0)) (tail xs)) (sym !! ((read x4) - 1)) (ind !! ((read x4) - 1))) ++ place_gplc (drop (read (xs !! 0)) (tail xs)) code sym ind
else x0 ++ ", " ++ x1 ++ ", " ++ x2 ++ ", " ++ x3 ++ ", " ++ show_ints (code !! ((read x4) - 1)) ++ place_gplc xs code sym ind
build_gplc :: [Char] -> [Char] -> [Char] -> [Int] -> Int -> ([Int], [[Char]], [(Int, Int)], [Char])
build_gplc prog_name source0 source1 fst_pass c =
let block_sizes = assm_gplc5 (drop 2 (splitOneOf "\n " source1)) [] 0
bindings = assm_gplc1 (splitOneOf "\n " source0) ((length fst_pass) + 2) 0 [] [] [] prog_name 1
bindings' = assm_gplc1 (splitOneOf "\n " source0) 0 0 [] [] [] prog_name 0
d_list_len = length (fst__ bindings)
out = (assm_gplc0 (splitOneOf "\n " source1) (fst__ bindings) (snd__ bindings) block_sizes [] [] prog_name 0)
out' = (assm_gplc0 (splitOneOf "\n " source1) (fst__ bindings') (snd__ bindings') block_sizes [] [] prog_name 0)
in
if c == 0 then build_gplc prog_name source0 source1 out' 1
else (((length out) + 2 + d_list_len) : 0 : 0 : out, fst__ bindings, snd__ bindings, third_ bindings)
main = do
args <- getArgs
h0 <- openFile (args !! 0) ReadMode
h1 <- openFile (args !! 1) ReadMode
h2 <- openFile (args !! 2) WriteMode
source <- hGetContents h0
structure <- hGetContents h1
code <- prep_gplc (splitOn "\n~\n" source) [] [] [] 0
hPutStr h2 (place_gplc (filter (/= "~") (splitOneOf " \n" structure)) (fst__ code) (snd__ code) (third_ code))
hClose h0
hClose h1
hClose h2
prep_gplc :: [[Char]] -> [[Int]] -> [[[Char]]] -> [[(Int, Int)]] -> Int -> IO ([[Int]], [[[Char]]], [[(Int, Int)]])
prep_gplc [] code_acc sym_acc ind_acc c = return (code_acc, sym_acc, ind_acc)
prep_gplc (x0:x1:x2:xs) code_acc sym_acc ind_acc c =
let build_gplc' = build_gplc x0 x1 x2 [] 0
code = fst' build_gplc' ++ assm_gplc4 (splitOneOf " \n" x1)
sym = snd' build_gplc'
ind = third' build_gplc'
in do
putStr ("\n\nGPLC program " ++ x0 ++ " starts at index " ++ show c)
prep_gplc xs (code_acc ++ [code]) (sym_acc ++ [sym]) (ind_acc ++ [ind]) (c + ((head (fst' build_gplc')) + 5))
| null | https://raw.githubusercontent.com/Mushy-pea/Game-Dangerous/d11de34d655c28ced6fbe120d8acb955bebd7e2d/app/AssmGplc.hs | haskell | If you wish to redistribute it or use it as part of your own work, this is permitted as long as you acknowledge the work is by the abovementioned author.
This function recognises the keywords that correspond to op - codes and is the beginning of the pipeline that transforms them and their arguments into bytecode.
locations with its value block patched to different states in each case. | Game : : Dangerous code by . You are free to use this software and view its source code .
This is a development tool that generates bytecode from GPLC source code .
module Main where
import System.IO
import System.IO.Unsafe
import System.Environment
import Data.Maybe
import Data.List.Split
import Control.Exception
data Bytecode_gen_error = Invalid_opcode | Undefined_value_used deriving (Show)
instance Exception Bytecode_gen_error
init_ :: [a] -> [a]
init_ x = take ((length x) - 2) x
show_ints :: [Int] -> [Char]
show_ints [] = []
show_ints (x:xs) = (show x) ++ ", " ++ show_ints xs
proc_ints :: [[Char]] -> [Int]
proc_ints [] = []
proc_ints (x:xs) = (read x :: Int) : proc_ints xs
fst__ (a, b, c) = a
snd__ (a, b, c) = b
third_ (a, b, c) = c
fst' (a, b, c, d) = a
snd' (a, b, c, d) = b
third' (a, b, c, d) = c
fourth (a, b, c, d) = d
These six functions are part of a pipeline that transforms keywords into op - codes and their reference arguments into the data block pointers used by the interpreter .
assm_gplc5 :: [[Char]] -> [Int] -> Int -> [Int]
assm_gplc5 [] size_block size = (size_block ++ [size])
assm_gplc5 (x:xs) size_block size =
if x == "--signal" then assm_gplc5 (drop 1 xs) (size_block ++ [size]) 0
else if x == "pass_msg" then assm_gplc5 (drop 1 xs) size_block (size + 1)
else if x == "block" then assm_gplc5 xs size_block (size + 3)
else if x == "npc_damage" then assm_gplc5 xs size_block (size + 1)
else assm_gplc5 xs size_block (size + 1)
assm_gplc4 :: [[Char]] -> [Int]
assm_gplc4 [] = []
assm_gplc4 (x0:x1:xs) = (read x1) : assm_gplc4 xs
assm_gplc3 :: Int -> [Char] -> [[Char]] -> [(Int, Int)] -> Int
assm_gplc3 t symbol [] [] = error ("Undeclared op - code reference argument used: " ++ symbol)
assm_gplc3 t symbol (x:xs) (y:ys) =
if symbol == x then
if t == 0 then fst y
else (snd y)
else assm_gplc3 t symbol xs ys
assm_gplc2 :: Int -> [[Char]] -> [[Char]] -> [(Int, Int)] -> [Int]
assm_gplc2 1 (x0:x1:x2:x3:x4:xs) sym ind = (read x0) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (read x3) : [read x4]
assm_gplc2 2 (x0:x1:x2:x3:x4:x5:x6:x7:x8:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : (assm_gplc3 0 x6 sym ind) : (assm_gplc3 0 x7 sym ind) : [assm_gplc3 0 x8 sym ind]
assm_gplc2 3 (x0:x1:x2:x3:x4:x5:x6:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : [assm_gplc3 0 x6 sym ind]
assm_gplc2 4 (x0:x1:x2:x3:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : [assm_gplc3 0 x3 sym ind]
assm_gplc2 5 (x0:x1:x2:x3:x4:x5:xs) sym ind = (assm_gplc3 1 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : [assm_gplc3 0 x5 sym ind]
assm_gplc2 6 (x0:x1:x2:x3:x4:x5:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : [assm_gplc3 0 x5 sym ind]
assm_gplc2 7 (x0:x1:x2:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : [assm_gplc3 0 x2 sym ind]
assm_gplc2 8 (x0:x1:x2:x3:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : [assm_gplc3 0 x3 sym ind]
assm_gplc2 9 (x0:xs) sym ind = [assm_gplc3 0 x0 sym ind]
assm_gplc2 10 (x0:x1:x2:x3:x4:x5:x6:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : [assm_gplc3 0 x6 sym ind]
assm_gplc2 11 (x0:x1:x2:x3:xs) sym ind = (read x0) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : [assm_gplc3 0 x3 sym ind]
assm_gplc2 12 (x0:x1:x2:x3:x4:x5:x6:xs) sym ind = (read x0) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : [assm_gplc3 0 x6 sym ind]
assm_gplc2 13 (x0:x1:xs) sym ind = (assm_gplc3 0 x1 sym ind) : proc_ints xs
assm_gplc2 14 (x0:x1:x2:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : [assm_gplc3 0 x2 sym ind]
assm_gplc2 15 (x0:x1:x2:x3:xs) sym ind = (read x0) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : [assm_gplc3 0 x3 sym ind]
assm_gplc2 16 (x0:x1:x2:x3:x4:x5:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : [read x5]
assm_gplc2 17 (x0:x1:x2:x3:x4:x5:x6:x7:x8:x9:x10:x11:x12:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 0 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : (assm_gplc3 0 x4 sym ind) : (assm_gplc3 0 x5 sym ind) : (assm_gplc3 0 x6 sym ind) : (assm_gplc3 0 x7 sym ind) : (assm_gplc3 0 x8 sym ind) : (assm_gplc3 0 x9 sym ind) : (assm_gplc3 0 x10 sym ind) : (read x11) : [assm_gplc3 0 x12 sym ind]
assm_gplc2 18 (x0:x1:x2:x3:x4:xs) sym ind = (assm_gplc3 0 x0 sym ind) : (assm_gplc3 1 x1 sym ind) : (assm_gplc3 0 x2 sym ind) : (assm_gplc3 0 x3 sym ind) : [assm_gplc3 0 x4 sym ind]
assm_gplc2 19 (x0:x1:xs) sym ind = (assm_gplc3 0 x0 sym ind) : [assm_gplc3 0 x1 sym ind]
assm_gplc2 20 (x0:xs) sym ind = [assm_gplc3 1 x0 sym ind]
assm_gplc2 21 (x0:xs) sym ind = [assm_gplc3 1 x0 sym ind]
assm_gplc2 22 (x0:xs) sym ind = [read x0]
assm_gplc2 23 (x0:x1:xs) sym ind = (assm_gplc3 1 x0 sym ind) : [read x1]
assm_gplc1 :: [[Char]] -> Int -> Int -> [[Char]] -> [(Int, Int)] -> [Char] -> [Char] -> Int -> ([[Char]], [(Int, Int)], [Char])
assm_gplc1 [] offset i acc0 acc1 log prog_name mode = (acc0, acc1, log)
assm_gplc1 (x0:x1:xs) offset i acc0 acc1 log prog_name mode =
if mode == 1 then
if i == 0 then assm_gplc1 xs offset (i + 1) (acc0 ++ [x0]) (acc1 ++ [(i, offset + i)]) (log ++ "\n\nProgram " ++ prog_name ++ " starts here...\n\nSymbol: " ++ x0 ++ " Read binding: " ++ show i ++ " Write binding: " ++ show (offset + i)) prog_name mode
else assm_gplc1 xs offset (i + 1) (acc0 ++ [x0]) (acc1 ++ [(i, offset + i)]) (log ++ "\n\nSymbol: " ++ x0 ++ " Read binding: " ++ show i ++ " Write binding: " ++ show (offset + i)) prog_name mode
else assm_gplc1 xs offset (i + 1) (acc0 ++ [x0]) (acc1 ++ [(i, offset + i)]) log prog_name mode
assm_gplc1 (x0:xs) offset i acc0 acc1 log prog_name mode = error ("\n\nassm_gplc1: " ++ x0 ++ "...")
assm_gplc0 :: [[Char]] -> [[Char]] -> [(Int, Int)] -> [Int] -> [Int] -> [Int] -> [Char] -> Int -> [Int]
assm_gplc0 [] sym ind size_block sig_block code_block prog_name c = sig_block ++ [536870911] ++ code_block ++ [536870911]
assm_gplc0 (x:xs) sym ind size_block sig_block code_block prog_name c =
let msg_length = (read (xs !! 0))
in
if x == "if" then assm_gplc0 (drop 5 xs) sym ind size_block sig_block (code_block ++ [1] ++ (assm_gplc2 1 (take 5 xs) sym ind)) prog_name (c + 6)
else if x == "chg_state" then assm_gplc0 (drop 9 xs) sym ind size_block sig_block (code_block ++ [2] ++ (assm_gplc2 2 (take 9 xs) sym ind)) prog_name (c + 10)
else if x == "chg_grid" then assm_gplc0 (drop 7 xs) sym ind size_block sig_block (code_block ++ [3] ++ (assm_gplc2 3 (take 7 xs) sym ind)) prog_name (c + 8)
else if x == "send_signal" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [4] ++ (assm_gplc2 4 (take 4 xs) sym ind)) prog_name (c + 5)
else if x == "chg_value" then assm_gplc0 (drop 6 xs) sym ind size_block sig_block (code_block ++ [5] ++ (assm_gplc2 5 (take 6 xs) sym ind)) prog_name (c + 7)
else if x == "chg_floor" then assm_gplc0 (drop 6 xs) sym ind size_block sig_block (code_block ++ [6] ++ (assm_gplc2 6 (take 6 xs) sym ind)) prog_name (c + 7)
else if x == "chg_ps1" then assm_gplc0 (drop 3 xs) sym ind size_block sig_block (code_block ++ [7] ++ (assm_gplc2 7 (take 3 xs) sym ind)) prog_name (c + 4)
else if x == "chg_obj_type" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [8] ++ (assm_gplc2 8 (take 4 xs) sym ind)) prog_name (c + 5)
else if x == "place_hold" then assm_gplc0 (drop 1 xs) sym ind size_block sig_block (code_block ++ [9] ++ (assm_gplc2 9 (take 1 xs) sym ind)) prog_name (c + 2)
else if x == "chg_grid_" then assm_gplc0 (drop 7 xs) sym ind size_block sig_block (code_block ++ [10] ++ (assm_gplc2 10 (take 7 xs) sym ind)) prog_name (c + 8)
else if x == "copy_ps1" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [11] ++ (assm_gplc2 11 (take 4 xs) sym ind)) prog_name (c + 5)
else if x == "copy_lstate" then assm_gplc0 (drop 7 xs) sym ind size_block sig_block (code_block ++ [12] ++ (assm_gplc2 12 (take 7 xs) sym ind)) prog_name (c + 8)
else if x == "pass_msg" then assm_gplc0 (drop msg_length xs) sym ind size_block sig_block (code_block ++ [13] ++ (assm_gplc2 13 (take msg_length xs) sym ind)) prog_name (c + msg_length)
else if x == "chg_ps0" then assm_gplc0 (drop 3 xs) sym ind size_block sig_block (code_block ++ [14] ++ (assm_gplc2 14 (take 3 xs) sym ind)) prog_name (c + 4)
else if x == "copy_ps0" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [15] ++ (assm_gplc2 15 (take 4 xs) sym ind)) prog_name (c + 5)
else if x == "block" then assm_gplc0 (drop 4 xs) sym ind size_block sig_block (code_block ++ [5, 536870910, 0, read (xs !! 0), assm_gplc3 0 (xs !! 1) sym ind, assm_gplc3 0 (xs !! 2) sym ind, assm_gplc3 0 (xs !! 3) sym ind]) prog_name (c + 7)
else if x == "binary_dice" then assm_gplc0 (drop 6 xs) sym ind size_block sig_block (code_block ++ [16] ++ (assm_gplc2 16 (take 6 xs) sym ind)) prog_name (c + 7)
else if x == "project_init" then assm_gplc0 (drop 13 xs) sym ind size_block sig_block (code_block ++ [17] ++ (assm_gplc2 17 (take 13 xs) sym ind)) prog_name (c + 14)
else if x == "project_update" then assm_gplc0 (drop 5 xs) sym ind size_block sig_block (code_block ++ [18] ++ (assm_gplc2 18 (take 5 xs) sym ind)) prog_name (c + 6)
else if x == "init_npc" then assm_gplc0 (drop 2 xs) sym ind size_block sig_block (code_block ++ [19] ++ assm_gplc2 19 (take 2 xs) sym ind) prog_name (c + 3)
else if x == "npc_decision" then assm_gplc0 (tail xs) sym ind size_block sig_block (code_block ++ [20] ++ assm_gplc2 20 (take 1 xs) sym ind) prog_name (c + 2)
else if x == "npc_move" then assm_gplc0 (tail xs) sym ind size_block sig_block (code_block ++ [21] ++ assm_gplc2 21 (take 1 xs) sym ind) prog_name (c + 2)
else if x == "npc_damage" then assm_gplc0 (drop 1 xs) sym ind size_block sig_block (code_block ++ [22] ++ assm_gplc2 22 (take 1 xs) sym ind) prog_name (c + 2)
else if x == "cpede_move" then assm_gplc0 (drop 2 xs) sym ind size_block sig_block (code_block ++ [23] ++ assm_gplc2 23 (take 2 xs) sym ind) prog_name (c + 3)
else if x == "--signal" then assm_gplc0 (drop 1 xs) sym ind (tail size_block) (sig_block ++ [read (xs !! 0), c, head size_block]) code_block prog_name c
else error ("\nprog_name: " ++ prog_name ++ "\nc: " ++ show c ++ "\nInvalid op_code: " ++ x)
This function is used for program instancing . The map structure data is used to specify where each GPLC program is placed in the map . A single program can be placed in multiple
patch_code :: [Int] -> [[Char]] -> [[Char]] -> [(Int, Int)] -> [Int]
patch_code code [] sym ind = code
patch_code code (x0:x1:xs) sym ind =
let offset = assm_gplc3 1 x0 sym ind
in
patch_code (take (offset + 1) code ++ [read x1] ++ drop (offset + 2) code) xs sym ind
place_gplc :: [[Char]] -> [[Int]] -> [[[Char]]] -> [[(Int, Int)]] -> [Char]
place_gplc [] code sym ind = []
place_gplc (x0:x1:x2:x3:x4:x5:xs) code sym ind =
if read x4 == 0 then x0 ++ ", " ++ x1 ++ ", " ++ x2 ++ ", " ++ x3 ++ ", " ++ x4 ++ ", " ++ place_gplc xs code sym ind
else if x5 == "y" then x0 ++ ", " ++ x1 ++ ", " ++ x2 ++ ", " ++ x3 ++ ", " ++ show_ints (patch_code (code !! ((read x4) - 1)) (take (read (xs !! 0)) (tail xs)) (sym !! ((read x4) - 1)) (ind !! ((read x4) - 1))) ++ place_gplc (drop (read (xs !! 0)) (tail xs)) code sym ind
else x0 ++ ", " ++ x1 ++ ", " ++ x2 ++ ", " ++ x3 ++ ", " ++ show_ints (code !! ((read x4) - 1)) ++ place_gplc xs code sym ind
build_gplc :: [Char] -> [Char] -> [Char] -> [Int] -> Int -> ([Int], [[Char]], [(Int, Int)], [Char])
build_gplc prog_name source0 source1 fst_pass c =
let block_sizes = assm_gplc5 (drop 2 (splitOneOf "\n " source1)) [] 0
bindings = assm_gplc1 (splitOneOf "\n " source0) ((length fst_pass) + 2) 0 [] [] [] prog_name 1
bindings' = assm_gplc1 (splitOneOf "\n " source0) 0 0 [] [] [] prog_name 0
d_list_len = length (fst__ bindings)
out = (assm_gplc0 (splitOneOf "\n " source1) (fst__ bindings) (snd__ bindings) block_sizes [] [] prog_name 0)
out' = (assm_gplc0 (splitOneOf "\n " source1) (fst__ bindings') (snd__ bindings') block_sizes [] [] prog_name 0)
in
if c == 0 then build_gplc prog_name source0 source1 out' 1
else (((length out) + 2 + d_list_len) : 0 : 0 : out, fst__ bindings, snd__ bindings, third_ bindings)
main = do
args <- getArgs
h0 <- openFile (args !! 0) ReadMode
h1 <- openFile (args !! 1) ReadMode
h2 <- openFile (args !! 2) WriteMode
source <- hGetContents h0
structure <- hGetContents h1
code <- prep_gplc (splitOn "\n~\n" source) [] [] [] 0
hPutStr h2 (place_gplc (filter (/= "~") (splitOneOf " \n" structure)) (fst__ code) (snd__ code) (third_ code))
hClose h0
hClose h1
hClose h2
prep_gplc :: [[Char]] -> [[Int]] -> [[[Char]]] -> [[(Int, Int)]] -> Int -> IO ([[Int]], [[[Char]]], [[(Int, Int)]])
prep_gplc [] code_acc sym_acc ind_acc c = return (code_acc, sym_acc, ind_acc)
prep_gplc (x0:x1:x2:xs) code_acc sym_acc ind_acc c =
let build_gplc' = build_gplc x0 x1 x2 [] 0
code = fst' build_gplc' ++ assm_gplc4 (splitOneOf " \n" x1)
sym = snd' build_gplc'
ind = third' build_gplc'
in do
putStr ("\n\nGPLC program " ++ x0 ++ " starts at index " ++ show c)
prep_gplc xs (code_acc ++ [code]) (sym_acc ++ [sym]) (ind_acc ++ [ind]) (c + ((head (fst' build_gplc')) + 5))
|
849d34ea20ed455701f78a990b460f1b3a5d595b83c0746deb6e6f06b02935c3 | divipp/lensref | DotPlugin.hs | #!/home/divip/bin/runhaskell
module Main where
import Numeric
import Text.Pandoc
import Text.Pandoc.Shared
import Text.Pandoc.JSON
import System.Process
import Data.Maybe
import Data.List
-- from the utf8-string package on HackageDB:
import Data.ByteString.Lazy.UTF8 (fromString)
from the SHA package on HackageDB :
import Data.Digest.Pure.SHA
import GHC.IO.Handle
import System.IO
import System.Exit
-- from package hint
import Language.Haskell.Interpreter
-- This plugin allows you to include a graphviz "dot" diagram
-- in a document like this:
--
-- ~~~ {.dot name="diagram1"}
-- digraph G {Hello->World}
-- ~~~
transform :: Block -> IO [Block]
transform (CodeBlock (id, classes, namevals) contents) | "dot" `elem` classes = tr "dot" id namevals contents
transform (CodeBlock (id, classes, namevals) contents) | "fdp" `elem` classes = tr "fdp" id namevals contents
transform (CodeBlock (id, classes, namevals) contents) | "ghci" `elem` classes = ghci id namevals contents
transform x = return [x]
ghci id namevals contents = do
let file = case lookup "name" namevals of
Just fn -> fn
Nothing -> uniqueName contents
infile = file ++ ".in"
outfile = file ++ ".out"
let (Just modname) = lookup "module" namevals
cs = lines contents
format a b = ["> " ++ a, b]
writeFile infile contents
writeFile "out" ""
res <- runInterpreter $ do
set [searchPath := ["../src"]]
loadModules [modname]
setTopLevelModules [modname]
interpret ("do {" ++ intercalate ";" (concat
[["appendFile " ++ show "out" ++ " " ++ show ("> " ++ l ++ "\n"), l] | l <- lines contents]
) ++ "}") (as :: IO ())
case res of
Left e -> error $ "ghci plugin: " ++ show e
Right r -> r
result <- readFile "out"
let result' = trans result
writeFile outfile result'
return [RawBlock (Format "latex") $ unlines $ begin ++ [result'] ++ end]
where
begin = ["\\begin{Shaded}","\\begin{Highlighting}[]"]
end = ["\\end{Highlighting}","\\end{Shaded}\n"]
trans :: String -> String
trans ('\x1b':'[':cs) = case reads cs :: [(Int, String)] of
[(col, 'm': cs)] -> trans' col [] cs
trans (c:cs) = c: trans cs
trans [] = []
trans' col acc ('\x1b':'[':'0':'m':cs) = color col (reverse acc) ++ trans cs
trans' col acc (c:cs) = trans' col (c:acc) cs
trans ' [ ] = [ ]
--color c s = "\x1b[" ++ show c ++ "m" ++ s ++ "\x1b[0m"
color c s = "\\" ++ c' ++ "Tok{" ++ esc s ++ "}"
" \\textcolor[rgb ] { " + + sh r + + " , " + + sh g + + " , " + + sh b + + " } { { " + + esc s + + " } } "
where
sh r = showFFloat ( Just 2 ) r " "
( r , , b ) = case c of
_ - > ( 0.5,0.5,0.5 )
where
sh r = showFFloat (Just 2) r ""
(r,g,b) = case c of
_ -> (0.5,0.5,0.5)
-}
where
c' = case c of
31 -> "BaseN" -- bars
33 -> "Comment" -- index
37 -> "DecVal" -- button
42 -> "String" -- entry
dyn label
32 -> "Char" -- selected
35 -> "DataType" -- not active
41 -> "Alert" -- error
i -> error $ "color " ++ show i
-- Error Alert Comment Keyword
Normal RegionMarker Function DataType Other String Char Float DecVal BaseN
esc = escapeStringUsing latexesc
latexesc = backslashEscapes "{}"
tr dot id namevals contents = do
let (name, name', file) = case lookup "name" namevals of
Just fn -> ([Str fn], fn, fn)
Nothing -> ([], "", uniqueName contents)
infile = file ++ "." ++ dot
outfile = file ++ ".pdf"
margin = maybe (0.1 :: Double) read (lookup "margin" namevals)
size = fmap ((+ margin) . read) (lookup "size" namevals)
margin' = ["-Gmargin=" ++ show margin]
size' = maybe [] ((:[]) . ("-Gsize="++) . show) size
writeFile infile contents
(Just inh, Just outh, Just errh, ph) <- createProcess
(proc dot $ ["-Tpdf"] ++ margin' ++ size')
{ std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
}
hSetBinaryMode outh True
result <- hGetContents outh
err <- hGetContents errh
hPutStr inh contents
hClose inh
errc <- waitForProcess ph
case errc of
ExitFailure i -> print i
_ -> return ()
putStrLn err
outh' <- openBinaryFile outfile WriteMode
hPutStr outh' result
hClose outh'
return [ RawBlock (Format "latex") "\\begin{centering}"
, Para [Image name (outfile, name')]
, RawBlock (Format "latex") "\\end{centering}"
]
-- | Generate a unique filename given the file's contents.
uniqueName :: String -> String
uniqueName = showDigest . sha1 . fromString
main :: IO ()
main = toJSONFilter transform
| null | https://raw.githubusercontent.com/divipp/lensref/2f0b9a36ac8853780e2b09ad0769464dd3837dab/docs/DotPlugin.hs | haskell | from the utf8-string package on HackageDB:
from package hint
This plugin allows you to include a graphviz "dot" diagram
in a document like this:
~~~ {.dot name="diagram1"}
digraph G {Hello->World}
~~~
color c s = "\x1b[" ++ show c ++ "m" ++ s ++ "\x1b[0m"
bars
index
button
entry
selected
not active
error
Error Alert Comment Keyword
| Generate a unique filename given the file's contents. | #!/home/divip/bin/runhaskell
module Main where
import Numeric
import Text.Pandoc
import Text.Pandoc.Shared
import Text.Pandoc.JSON
import System.Process
import Data.Maybe
import Data.List
import Data.ByteString.Lazy.UTF8 (fromString)
from the SHA package on HackageDB :
import Data.Digest.Pure.SHA
import GHC.IO.Handle
import System.IO
import System.Exit
import Language.Haskell.Interpreter
transform :: Block -> IO [Block]
transform (CodeBlock (id, classes, namevals) contents) | "dot" `elem` classes = tr "dot" id namevals contents
transform (CodeBlock (id, classes, namevals) contents) | "fdp" `elem` classes = tr "fdp" id namevals contents
transform (CodeBlock (id, classes, namevals) contents) | "ghci" `elem` classes = ghci id namevals contents
transform x = return [x]
ghci id namevals contents = do
let file = case lookup "name" namevals of
Just fn -> fn
Nothing -> uniqueName contents
infile = file ++ ".in"
outfile = file ++ ".out"
let (Just modname) = lookup "module" namevals
cs = lines contents
format a b = ["> " ++ a, b]
writeFile infile contents
writeFile "out" ""
res <- runInterpreter $ do
set [searchPath := ["../src"]]
loadModules [modname]
setTopLevelModules [modname]
interpret ("do {" ++ intercalate ";" (concat
[["appendFile " ++ show "out" ++ " " ++ show ("> " ++ l ++ "\n"), l] | l <- lines contents]
) ++ "}") (as :: IO ())
case res of
Left e -> error $ "ghci plugin: " ++ show e
Right r -> r
result <- readFile "out"
let result' = trans result
writeFile outfile result'
return [RawBlock (Format "latex") $ unlines $ begin ++ [result'] ++ end]
where
begin = ["\\begin{Shaded}","\\begin{Highlighting}[]"]
end = ["\\end{Highlighting}","\\end{Shaded}\n"]
trans :: String -> String
trans ('\x1b':'[':cs) = case reads cs :: [(Int, String)] of
[(col, 'm': cs)] -> trans' col [] cs
trans (c:cs) = c: trans cs
trans [] = []
trans' col acc ('\x1b':'[':'0':'m':cs) = color col (reverse acc) ++ trans cs
trans' col acc (c:cs) = trans' col (c:acc) cs
trans ' [ ] = [ ]
color c s = "\\" ++ c' ++ "Tok{" ++ esc s ++ "}"
" \\textcolor[rgb ] { " + + sh r + + " , " + + sh g + + " , " + + sh b + + " } { { " + + esc s + + " } } "
where
sh r = showFFloat ( Just 2 ) r " "
( r , , b ) = case c of
_ - > ( 0.5,0.5,0.5 )
where
sh r = showFFloat (Just 2) r ""
(r,g,b) = case c of
_ -> (0.5,0.5,0.5)
-}
where
c' = case c of
dyn label
i -> error $ "color " ++ show i
Normal RegionMarker Function DataType Other String Char Float DecVal BaseN
esc = escapeStringUsing latexesc
latexesc = backslashEscapes "{}"
tr dot id namevals contents = do
let (name, name', file) = case lookup "name" namevals of
Just fn -> ([Str fn], fn, fn)
Nothing -> ([], "", uniqueName contents)
infile = file ++ "." ++ dot
outfile = file ++ ".pdf"
margin = maybe (0.1 :: Double) read (lookup "margin" namevals)
size = fmap ((+ margin) . read) (lookup "size" namevals)
margin' = ["-Gmargin=" ++ show margin]
size' = maybe [] ((:[]) . ("-Gsize="++) . show) size
writeFile infile contents
(Just inh, Just outh, Just errh, ph) <- createProcess
(proc dot $ ["-Tpdf"] ++ margin' ++ size')
{ std_in = CreatePipe
, std_out = CreatePipe
, std_err = CreatePipe
}
hSetBinaryMode outh True
result <- hGetContents outh
err <- hGetContents errh
hPutStr inh contents
hClose inh
errc <- waitForProcess ph
case errc of
ExitFailure i -> print i
_ -> return ()
putStrLn err
outh' <- openBinaryFile outfile WriteMode
hPutStr outh' result
hClose outh'
return [ RawBlock (Format "latex") "\\begin{centering}"
, Para [Image name (outfile, name')]
, RawBlock (Format "latex") "\\end{centering}"
]
uniqueName :: String -> String
uniqueName = showDigest . sha1 . fromString
main :: IO ()
main = toJSONFilter transform
|
312f7d11c6b467783f02a9898854943158ac8eb7fedc265cd793d5da7c804370 | xmonad/xmonad-contrib | CustomKeys.hs | --------------------------------------------------------------------
-- |
-- Module : XMonad.Util.CustomKeys
-- Description : Configure key bindings.
Copyright : ( c ) 2007
-- License : BSD3-style (see LICENSE)
--
-- Customized key bindings.
--
See also " XMonad . Util . EZConfig " in xmonad - contrib .
--------------------------------------------------------------------
module XMonad.Util.CustomKeys (
-- * Usage
-- $usage
customKeys
, customKeysFrom
) where
import XMonad
import XMonad.Prelude ((<&>))
import Control.Monad.Reader
import qualified Data.Map as M
-- $usage
--
-- In @~\/.xmonad\/xmonad.hs@ add:
--
> import XMonad . Util . CustomKeys
--
-- Set key bindings with 'customKeys':
--
> main = xmonad def { keys = customKeys delkeys inskeys }
-- > where
> delkeys : : XConfig l - > [ ( KeyMask , KeySym ) ]
-- > delkeys XConfig {modMask = modm} =
> [ ( modm .| . shiftMask , xK_Return ) -- > terminal
-- > , (modm .|. shiftMask, xK_c) -- > close the focused window
-- > ]
-- > ++
> [ ( modm .| . m , k ) | m < - [ 0 , shiftMask ] , k < - [ xK_w , , xK_r ] ]
-- >
> inskeys : : XConfig l - > [ ( ( KeyMask , KeySym ) , X ( ) ) ]
-- > inskeys conf@(XConfig {modMask = modm}) =
-- > [ ((mod1Mask, xK_F2 ), spawn $ terminal conf) -- mod1-f2 %! Run a terminal emulator
> , ( ( modm , xK_Delete ) , kill ) -- % ! Close the focused window
> , ( ( modm .| . controlMask , ) , spawn " xscreensaver - command -lock " )
-- > , ((mod1Mask, xK_Down), spawn "amixer set Master 1-")
-- > , ((mod1Mask, xK_Up ), spawn "amixer set Master 1+")
-- > ]
-- | Customize 'XMonad.Config.def' -- delete needless
-- shortcuts and insert those you will use.
customKeys :: (XConfig Layout -> [(KeyMask, KeySym)]) -- ^ shortcuts to delete
-> (XConfig Layout -> [((KeyMask, KeySym), X ())]) -- ^ key bindings to insert
-> XConfig Layout -> M.Map (KeyMask, KeySym) (X ())
customKeys = customKeysFrom def
-- | General variant of 'customKeys': customize key bindings of
third - party configuration .
customKeysFrom :: XConfig l -- ^ original configuration
-> (XConfig Layout -> [(KeyMask, KeySym)]) -- ^ shortcuts to delete
-> (XConfig Layout -> [((KeyMask, KeySym), X ())]) -- ^ key bindings to insert
-> XConfig Layout -> M.Map (KeyMask, KeySym) (X ())
customKeysFrom conf = (runReader .) . customize conf
customize :: XConfig l
-> (XConfig Layout -> [(KeyMask, KeySym)])
-> (XConfig Layout -> [((KeyMask, KeySym), X ())])
-> Reader (XConfig Layout) (M.Map (KeyMask, KeySym) (X ()))
customize conf ds is = asks (keys conf) >>= delete ds >>= insert is
delete :: (MonadReader r m, Ord a) => (r -> [a]) -> M.Map a b -> m (M.Map a b)
delete dels kmap = asks dels <&> foldr M.delete kmap
insert :: (MonadReader r m, Ord a) =>
(r -> [(a, b)]) -> M.Map a b -> m (M.Map a b)
insert ins kmap = asks ins <&> foldr (uncurry M.insert) kmap
| null | https://raw.githubusercontent.com/xmonad/xmonad-contrib/3058d1ca22d565b2fa93227fdde44d8626d6f75d/XMonad/Util/CustomKeys.hs | haskell | ------------------------------------------------------------------
|
Module : XMonad.Util.CustomKeys
Description : Configure key bindings.
License : BSD3-style (see LICENSE)
Customized key bindings.
------------------------------------------------------------------
* Usage
$usage
$usage
In @~\/.xmonad\/xmonad.hs@ add:
Set key bindings with 'customKeys':
> where
> delkeys XConfig {modMask = modm} =
> terminal
> , (modm .|. shiftMask, xK_c) -- > close the focused window
> ]
> ++
>
> inskeys conf@(XConfig {modMask = modm}) =
> [ ((mod1Mask, xK_F2 ), spawn $ terminal conf) -- mod1-f2 %! Run a terminal emulator
% ! Close the focused window
> , ((mod1Mask, xK_Down), spawn "amixer set Master 1-")
> , ((mod1Mask, xK_Up ), spawn "amixer set Master 1+")
> ]
| Customize 'XMonad.Config.def' -- delete needless
shortcuts and insert those you will use.
^ shortcuts to delete
^ key bindings to insert
| General variant of 'customKeys': customize key bindings of
^ original configuration
^ shortcuts to delete
^ key bindings to insert | Copyright : ( c ) 2007
See also " XMonad . Util . EZConfig " in xmonad - contrib .
module XMonad.Util.CustomKeys (
customKeys
, customKeysFrom
) where
import XMonad
import XMonad.Prelude ((<&>))
import Control.Monad.Reader
import qualified Data.Map as M
> import XMonad . Util . CustomKeys
> main = xmonad def { keys = customKeys delkeys inskeys }
> delkeys : : XConfig l - > [ ( KeyMask , KeySym ) ]
> [ ( modm .| . m , k ) | m < - [ 0 , shiftMask ] , k < - [ xK_w , , xK_r ] ]
> inskeys : : XConfig l - > [ ( ( KeyMask , KeySym ) , X ( ) ) ]
> , ( ( modm .| . controlMask , ) , spawn " xscreensaver - command -lock " )
-> XConfig Layout -> M.Map (KeyMask, KeySym) (X ())
customKeys = customKeysFrom def
third - party configuration .
-> XConfig Layout -> M.Map (KeyMask, KeySym) (X ())
customKeysFrom conf = (runReader .) . customize conf
customize :: XConfig l
-> (XConfig Layout -> [(KeyMask, KeySym)])
-> (XConfig Layout -> [((KeyMask, KeySym), X ())])
-> Reader (XConfig Layout) (M.Map (KeyMask, KeySym) (X ()))
customize conf ds is = asks (keys conf) >>= delete ds >>= insert is
delete :: (MonadReader r m, Ord a) => (r -> [a]) -> M.Map a b -> m (M.Map a b)
delete dels kmap = asks dels <&> foldr M.delete kmap
insert :: (MonadReader r m, Ord a) =>
(r -> [(a, b)]) -> M.Map a b -> m (M.Map a b)
insert ins kmap = asks ins <&> foldr (uncurry M.insert) kmap
|
b40854c8039b9fd3b3adf9b8567af2b610c5f2b7226bc8d6424b49adee6b5182 | caisah/sicp-exercises-and-examples | unordered_lists.scm | (define (element-of-set? x set)
(cond ((null? set) false)
((equal? x (car set)) true)
(else (element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1) set2)))
(else
(intersection-set (cdr set1) set2))))
(define set1 (list 1 3 5 7))
(define set2 (list 3 4 5 6 7))
(element-of-set? 1 set1)
(element-of-set? 1 set2)
(adjoin-set 8 set1)
(intersection-set set1 set2)
| null | https://raw.githubusercontent.com/caisah/sicp-exercises-and-examples/605c698d7495aa3474c2b6edcd1312cb16c5b5cb/2.3.3-representing_sets/unordered_lists.scm | scheme | (define (element-of-set? x set)
(cond ((null? set) false)
((equal? x (car set)) true)
(else (element-of-set? x (cdr set)))))
(define (adjoin-set x set)
(if (element-of-set? x set)
set
(cons x set)))
(define (intersection-set set1 set2)
(cond ((or (null? set1) (null? set2)) '())
((element-of-set? (car set1) set2)
(cons (car set1)
(intersection-set (cdr set1) set2)))
(else
(intersection-set (cdr set1) set2))))
(define set1 (list 1 3 5 7))
(define set2 (list 3 4 5 6 7))
(element-of-set? 1 set1)
(element-of-set? 1 set2)
(adjoin-set 8 set1)
(intersection-set set1 set2)
| |
b24b292c630bf72a82ebf4d6044d31d74957e262d2a2f17582dcf43cd6dcf7dd | zwizwa/erl_tools | hs.erl | Convert Erlang type annotations to .
%% FIXME:
1 . dump syntax to erlang term
2 . parse erlang in haskel and perform embedding there
-module(hs).
-export([parse/1,type/1,x/1]).
parse(Str) ->
{ok,Toks,_} = erl_scan:string(Str),
{ok, Form} = erl_parse:parse_form(Toks),
Form.
x({attribute,_,type,{Name , T,_Vars } } ) - > { Name , type(T ) } ;
x(Str) ->
Top = parse(Str),
iolist_to_binary(typedef(Top)).
%% {atom(),_} is interpreted as a constructor for a new data type.
Unions take constructor names from tags .
typedef({attribute,L,type,{Name,{type,_,union,Ts},Vs}}) ->
["data ", type({type,L,Name,Vs})," = ",
lists:join(" | ", [cons(T) || T <- Ts])];
%% Special case for single-constructor types.
typedef({attribute,L,type,{Name,Alt={type,_,tuple,[{atom,_,_},_]},Vs}}) ->
["data ", type({type,L,Name,Vs})," = ", cons(Alt)];
%% Other forms are treated as aliases. Unions are not allowed inside type nesting.
typedef({attribute,L,type,{Name,T,Vs}}) ->
["type ", type({type,L,Name,Vs})," = ", type(T)];
%% Function specs
typedef({attribute,_,spec,{{Fname,_Nargs},[FunType]}}) ->
[atom_to_list(Fname), " :: ", type(FunType)].
Constructor syntax for sum types .
cons({type,_,tuple,[{atom,_,Cons},T]}) ->
[type_name(Cons), " (", type(T), ")"].
Erlang syntax structure is good enough for direct translation .
FIXME : tuple
No single - element tuple in Haskell
type({type,_,'tuple',Ts}) -> ["(", lists:join(",",[type(T) || T<-Ts]),")"];
type({type,_,'list',[T]}) -> ["[", type(T), "]"];
type({type,_,'fun',[A,R]}) -> [type(A)," -> ",type(R)];
type({type,L,'product',As}) -> type({type,L,'tuple',As});
type({type,_,'union',_}=T) -> throw({only_toplevel_union,T});
type({type,_,T,[]}) -> type_name(T); %% Otherwise this is unit ().
type({type,_,T,Ts}) -> [type_name(T), "(", lists:join(" ", [type(T0) || T0 <- Ts]), ")"];
type({var,_,Var}) -> var_name(Var);
type({user_type,L,T,Vs}) -> type({type, L, T, Vs}). %% Same
%% Base type conversion.
%%type_name(nil) -> "[]";
type_name(Type) ->
Bs = re:split(atom_to_list(Type),"_"),
[to_upper_first(binary_to_list(B)) || B <- Bs].
to_upper_first([H|T]) ->
[H1] = string:to_upper([H]),
[H1|T].
var_name(Var) ->
string:to_lower(atom_to_list(Var)).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-include("../test/hs.expect").
expect_test() ->
expect:run_form(
filename:dirname(?FILE)++"/../test/hs.expect",
fun hs_expect/0).
-endif.
| null | https://raw.githubusercontent.com/zwizwa/erl_tools/affd4060ab5b963e0cc8fcfd4a1ca5023aa518d3/src/hs.erl | erlang | FIXME:
{atom(),_} is interpreted as a constructor for a new data type.
Special case for single-constructor types.
Other forms are treated as aliases. Unions are not allowed inside type nesting.
Function specs
Otherwise this is unit ().
Same
Base type conversion.
type_name(nil) -> "[]"; | Convert Erlang type annotations to .
1 . dump syntax to erlang term
2 . parse erlang in haskel and perform embedding there
-module(hs).
-export([parse/1,type/1,x/1]).
parse(Str) ->
{ok,Toks,_} = erl_scan:string(Str),
{ok, Form} = erl_parse:parse_form(Toks),
Form.
x({attribute,_,type,{Name , T,_Vars } } ) - > { Name , type(T ) } ;
x(Str) ->
Top = parse(Str),
iolist_to_binary(typedef(Top)).
Unions take constructor names from tags .
typedef({attribute,L,type,{Name,{type,_,union,Ts},Vs}}) ->
["data ", type({type,L,Name,Vs})," = ",
lists:join(" | ", [cons(T) || T <- Ts])];
typedef({attribute,L,type,{Name,Alt={type,_,tuple,[{atom,_,_},_]},Vs}}) ->
["data ", type({type,L,Name,Vs})," = ", cons(Alt)];
typedef({attribute,L,type,{Name,T,Vs}}) ->
["type ", type({type,L,Name,Vs})," = ", type(T)];
typedef({attribute,_,spec,{{Fname,_Nargs},[FunType]}}) ->
[atom_to_list(Fname), " :: ", type(FunType)].
Constructor syntax for sum types .
cons({type,_,tuple,[{atom,_,Cons},T]}) ->
[type_name(Cons), " (", type(T), ")"].
Erlang syntax structure is good enough for direct translation .
FIXME : tuple
No single - element tuple in Haskell
type({type,_,'tuple',Ts}) -> ["(", lists:join(",",[type(T) || T<-Ts]),")"];
type({type,_,'list',[T]}) -> ["[", type(T), "]"];
type({type,_,'fun',[A,R]}) -> [type(A)," -> ",type(R)];
type({type,L,'product',As}) -> type({type,L,'tuple',As});
type({type,_,'union',_}=T) -> throw({only_toplevel_union,T});
type({type,_,T,Ts}) -> [type_name(T), "(", lists:join(" ", [type(T0) || T0 <- Ts]), ")"];
type({var,_,Var}) -> var_name(Var);
type_name(Type) ->
Bs = re:split(atom_to_list(Type),"_"),
[to_upper_first(binary_to_list(B)) || B <- Bs].
to_upper_first([H|T]) ->
[H1] = string:to_upper([H]),
[H1|T].
var_name(Var) ->
string:to_lower(atom_to_list(Var)).
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
-include("../test/hs.expect").
expect_test() ->
expect:run_form(
filename:dirname(?FILE)++"/../test/hs.expect",
fun hs_expect/0).
-endif.
|
c245e5fa68e9f679f1e6f45d38e1ee8a90e085a8343aca84554182c89594fd08 | stackbuilders/openssh-github-keys | OpensshGithubKeys.hs | -- |
Module : System . OpensshGithubKeys
Copyright : © 2015 - 2017 Stack Builders
License : MIT
--
-- Maintainer :
-- Stability : experimental
-- Portability : portable
--
The module allows to fetch list of per - teammate SSH public keys given
GitHub organization name and team name .
# LANGUAGE CPP #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE RecordWildCards #
module System.OpensshGithubKeys
( fetchTeamKeys )
where
import Control.Monad
import Data.Aeson
import Data.ByteString (ByteString)
import Data.List (find)
import Data.Monoid ((<>))
import Data.Text (Text)
import Network.HTTP.Req
import qualified Data.ByteString.Char8 as B8
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
import Data.Monoid (mempty)
#endif
| Get pairs of user names and corresponding SSH keys for team members .
fetchTeamKeys :: MonadHttp m
^ GitHub authorization token
^ GitHub organization name
-> Text -- ^ Team of interest in that organization
-> m [(Text, [ByteString])] -- ^ Username — SSH keys
fetchTeamKeys token orgName teamName' = do
let gitHubApi = https "api.github.com"
listTeamsUrl = gitHubApi /: "orgs" /: orgName /: "teams"
params =
"page_size" =: (100 :: Int) <>
header "User-Agent" "openssh-github-keys" <>
oAuth2Token token <>
header "Accept" "application/vnd.github.v3.raw"
teams <- req GET listTeamsUrl NoReqBody jsonResponse params
let team = teamId <$> find
((== teamName') . teamName)
(responseBody teams :: [Team])
case team of
Nothing -> return []
Just teamId -> do
let teamMembersUrl = gitHubApi /: "teams" /~ teamId /: "members"
ms <- req GET teamMembersUrl NoReqBody jsonResponse params
forM (memberLogin <$> responseBody ms) $ \login -> do
keys <- req GET (https "github.com" /: (login <> ".keys"))
NoReqBody bsResponse mempty
return (login, B8.lines (responseBody keys))
----------------------------------------------------------------------------
-- Helpers
data Team = Team
{ teamId :: Integer
, teamName :: Text }
instance FromJSON Team where
parseJSON = withObject "team in org" $ \o -> do
teamId <- o .: "id"
teamName <- o .: "name"
return Team {..}
data Member = Member
{ memberLogin :: Text }
instance FromJSON Member where
parseJSON = withObject "team member" $ \o ->
Member <$> (o .: "login")
| null | https://raw.githubusercontent.com/stackbuilders/openssh-github-keys/627d201fc9d67311a19a0e7d925a6107564482d6/src/System/OpensshGithubKeys.hs | haskell | |
Maintainer :
Stability : experimental
Portability : portable
# LANGUAGE OverloadedStrings #
^ Team of interest in that organization
^ Username — SSH keys
--------------------------------------------------------------------------
Helpers | Module : System . OpensshGithubKeys
Copyright : © 2015 - 2017 Stack Builders
License : MIT
The module allows to fetch list of per - teammate SSH public keys given
GitHub organization name and team name .
# LANGUAGE CPP #
# LANGUAGE RecordWildCards #
module System.OpensshGithubKeys
( fetchTeamKeys )
where
import Control.Monad
import Data.Aeson
import Data.ByteString (ByteString)
import Data.List (find)
import Data.Monoid ((<>))
import Data.Text (Text)
import Network.HTTP.Req
import qualified Data.ByteString.Char8 as B8
#if !MIN_VERSION_base(4,8,0)
import Control.Applicative
import Data.Monoid (mempty)
#endif
| Get pairs of user names and corresponding SSH keys for team members .
fetchTeamKeys :: MonadHttp m
^ GitHub authorization token
^ GitHub organization name
fetchTeamKeys token orgName teamName' = do
let gitHubApi = https "api.github.com"
listTeamsUrl = gitHubApi /: "orgs" /: orgName /: "teams"
params =
"page_size" =: (100 :: Int) <>
header "User-Agent" "openssh-github-keys" <>
oAuth2Token token <>
header "Accept" "application/vnd.github.v3.raw"
teams <- req GET listTeamsUrl NoReqBody jsonResponse params
let team = teamId <$> find
((== teamName') . teamName)
(responseBody teams :: [Team])
case team of
Nothing -> return []
Just teamId -> do
let teamMembersUrl = gitHubApi /: "teams" /~ teamId /: "members"
ms <- req GET teamMembersUrl NoReqBody jsonResponse params
forM (memberLogin <$> responseBody ms) $ \login -> do
keys <- req GET (https "github.com" /: (login <> ".keys"))
NoReqBody bsResponse mempty
return (login, B8.lines (responseBody keys))
data Team = Team
{ teamId :: Integer
, teamName :: Text }
instance FromJSON Team where
parseJSON = withObject "team in org" $ \o -> do
teamId <- o .: "id"
teamName <- o .: "name"
return Team {..}
data Member = Member
{ memberLogin :: Text }
instance FromJSON Member where
parseJSON = withObject "team member" $ \o ->
Member <$> (o .: "login")
|
a5775ecea89f91f12b21dd354a90819ebaa211c8ef4136035aa7e4e3b0404abe | areuu/ilcompiler | translate.ml | open ProgramBuilder
let flow_binaryassign_op_to_progbuilder_binop (op : Flow_ast.Expression.Assignment.operator) =
let res : binary_op = match op with
PlusAssign -> Plus
| MinusAssign -> Minus
| MultAssign -> Mult
| DivAssign -> Div
| ModAssign -> Mod
| BitXorAssign -> Xor
| LShiftAssign -> LShift
| RShiftAssign -> RShift
| ExpAssign -> Exp
| RShift3Assign -> RShift3
| BitAndAssign -> BitAnd
| BitOrAssign -> BitOr in
res
let hoist_id var_name builder =
let result_temp, inst = build_load_undefined builder in
add_new_var_identifier var_name result_temp builder;
add_hoisted_var var_name builder;
inst
let hoist_functions_to_top (statements: (Loc.t, Loc.t) Flow_ast.Statement.t list) =
let partition_func (s:(Loc.t, Loc.t) Flow_ast.Statement.t) = match s with
(_, Flow_ast.Statement.FunctionDeclaration _) -> true
| _ -> false in
let function_list, rest_list = List.partition partition_func statements in
function_list @ rest_list
(* Designed to be called on the statements of a function *)
let handle_varHoist (statements: (Loc.t, Loc.t) Flow_ast.Statement.t list) (builder: builder) =
let hoisted_functions = hoist_functions_to_top statements in
let var_useData, func_useData = VariableScope.get_vars_to_hoist hoisted_functions in
let is_not_builtin s = Util.is_supported_builtin s (include_v8_natives builder) |> not in
let funcs_to_hoist = List.filter is_not_builtin func_useData in
let hoist_func var = hoist_id var builder in
let hoist_vars = List.map hoist_func var_useData in
let hoist_funcs = List.map hoist_func funcs_to_hoist in
hoist_vars @ hoist_funcs
(* Handle the various types of literal*)
let proc_exp_literal (lit_val: ('T) Flow_ast.Literal.t) (builder: builder) =
let (temp_val, inst) = match lit_val.value with
(Flow_ast.Literal.String s) ->
TODO : This may be the cause of the issue where some files fail Fuzzilli import due to a UTF-8 error
let newString = Util.encode_newline s in
build_load_string newString builder
| (Flow_ast.Literal.Boolean b) ->
build_load_bool b builder
| (Flow_ast.Literal.Null) ->
build_load_null builder
| (Flow_ast.Literal.Number num) ->
Flow_ast only has one type for a number , while has several , each with its own protobuf type
if Float.is_integer num && not (String.contains lit_val.raw '.') && Int64.of_float num >= Int64.min_int && Int64.of_float num <= Int64.max_int then
build_load_integer (Int64.of_float num) builder
else
build_load_float num builder
| (Flow_ast.Literal.BigInt b) ->
build_load_bigInt b builder
| (Flow_ast.Literal.RegExp r) ->
let pattern = r.pattern in
let flags = r.flags in
build_load_regex pattern flags builder in
(temp_val, [inst])
(* Handle the various unary types*)
let rec proc_exp_unary (u_val: ('M, 'T) Flow_ast.Expression.Unary.t) (builder: builder) =
match u_val.operator with
Flow_ast.Expression.Unary.Not ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_unary_op arg_result_var Not builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.BitNot ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_unary_op arg_result_var BitNot builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Minus ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_unary_op arg_result_var Minus builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Plus ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_unary_op arg_result_var Plus builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Typeof ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_typeof_op arg_result_var builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Await ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_await_op arg_result_var builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Delete ->
(* Need to determine between computed delete, and named delete*)
let _, unwrapped_arg = u_val.argument in
let del_temp, del_inst = match unwrapped_arg with
Flow_ast.Expression.Member mem ->
let obj_temp, obj_inst = proc_expression mem._object builder in
( match mem.property with
Flow_ast.Expression.Member.PropertyIdentifier (_, id) ->
let name = id.name in
let obj, del_inst = build_delete_prop obj_temp name builder in
obj, obj_inst @ [del_inst]
| Flow_ast.Expression.Member.PropertyExpression exp ->
let sub_temp, sub_inst = proc_expression exp builder in
let (obj, com_del_inst) = build_delete_computed_prop obj_temp sub_temp builder in
obj_temp, obj_inst @ sub_inst @ [com_del_inst]
| _ -> raise (Invalid_argument "Unhandled delete member property") )
| Identifier id -> raise (Invalid_argument "Deleting an ID isn't supported in Fuzzilli")
| _ -> raise (Invalid_argument "Unsupported delete expression ") in
del_temp, del_inst
| Flow_ast.Expression.Unary.Void ->
let _, argument = proc_expression u_val.argument builder in
let result_var, inst = build_void_op builder in
result_var, argument @ [inst]
First , check against various edge cases . Otherwise , check the context , and handle the result appropriately
and proc_exp_id (id_val: ('M, 'T) Flow_ast.Identifier.t) builder =
let (_, unwraped_id_val) = id_val in
let name = unwraped_id_val.name in
if String.equal name "Infinity" then (* TODO: What other values go here? *)
let (result_var, inst) = build_load_float Float.infinity builder in
result_var, [inst]
else if String.equal name "undefined" then
let result_var, inst = build_load_undefined builder in
result_var, [inst]
else match lookup_var_name builder name with
InScope x -> (x, [])
| NotFound ->
if Util.is_supported_builtin name (include_v8_natives builder) then
let (result_var, inst) = build_load_builtin name builder in
if (should_emit_builtins builder) then print_endline ("Builtin: " ^ name) else ();
(result_var, [inst])
else if use_placeholder builder then
let (result_var, inst) = build_load_builtin "placeholder" builder in
(result_var, [inst])
else
raise (Invalid_argument ("Unhandled builtin " ^ name))
and proc_exp_bin_op (bin_op: ('M, 'T) Flow_ast.Expression.Binary.t) builder =
let (lvar, linsts) = proc_expression bin_op.left builder in
let (rvar, rinsts) = proc_expression bin_op.right builder in
let build_binary_op_func op = build_binary_op lvar rvar op builder in
let build_compare_op_func op = build_compare_op lvar rvar op builder in
let (result_var, inst) = match bin_op.operator with
Plus -> build_binary_op_func Plus
| Minus -> build_binary_op_func Minus
| Mult -> build_binary_op_func Mult
| Div -> build_binary_op_func Div
| Mod -> build_binary_op_func Mod
| Xor -> build_binary_op_func Xor
| LShift -> build_binary_op_func LShift
| RShift -> build_binary_op_func RShift
| Exp -> build_binary_op_func Exp
| RShift3 -> build_binary_op_func RShift3
| BitAnd -> build_binary_op_func BitAnd
| BitOr -> build_binary_op_func BitOr
| Equal -> build_compare_op_func Equal
| NotEqual -> build_compare_op_func NotEqual
| StrictEqual -> build_compare_op_func StrictEqual
| StrictNotEqual -> build_compare_op_func StrictNotEqual
| LessThan -> build_compare_op_func LessThan
| LessThanEqual -> build_compare_op_func LessThanEqual
| GreaterThan -> build_compare_op_func GreaterThan
| GreaterThanEqual -> build_compare_op_func GreaterThanEqual
| Instanceof -> build_test_instanceof_op lvar rvar builder
| In -> build_test_in_op lvar rvar builder in
(result_var, linsts @ rinsts @ [inst])
and proc_exp_logical (log_op: ('M, 'T) Flow_ast.Expression.Logical.t) builder =
let (lvar, linsts) = proc_expression log_op.left builder in
let (rvar, rinsts) = proc_expression log_op.right builder in
let op = match log_op.operator with
Flow_ast.Expression.Logical.And -> LogicalAnd
| Flow_ast.Expression.Logical.Or -> LogicalOr
| x -> raise (Invalid_argument ("Unhandled logical expression type" ^ (Util.trim_flow_ast_string (Util.print_logical_operator x)))) in
let (result_var, inst) = build_binary_op lvar rvar op builder in
(result_var, linsts @ rinsts @ [inst])
(* There are various different expression types, so pattern match on each time, and ccall the appropriate, more specific, function*)
and proc_exp_assignment (assign_exp: ('M, 'T) Flow_ast.Expression.Assignment.t) (builder: builder) =
match assign_exp.left with
(_, (Flow_ast.Pattern.Identifier id)) -> proc_exp_assignment_norm_id assign_exp id.name builder
| (_, (Flow_ast.Pattern.Expression (_, exp))) ->
(match exp with
Flow_ast.Expression.Member mem ->
let obj = mem._object in
(match mem.property with
Flow_ast.Expression.Member.PropertyExpression pex -> proc_exp_assignment_prod_exp pex obj assign_exp.right assign_exp.operator builder
| Flow_ast.Expression.Member.PropertyIdentifier pid -> proc_exp_assignment_prod_id pid obj assign_exp.right assign_exp.operator builder
| _ -> raise (Invalid_argument "Unhandled member property in exp assignment"))
| _ -> raise (Invalid_argument "Unhandled assignment expression left member"))
| _ -> raise (Invalid_argument "Unhandled assignment expressesion left ")
and proc_exp_assignment_prod_id
(prop_id: (Loc.t, Loc.t) Flow_ast.Identifier.t)
(obj: (Loc.t, Loc.t) Flow_ast.Expression.t)
(right_exp: (Loc.t, Loc.t) Flow_ast.Expression.t)
(op: Flow_ast.Expression.Assignment.operator option)
(builder: builder) =
let obj_temp, obj_inst = proc_expression obj builder in
let (_, unwapped_id) = prop_id in
let name = unwapped_id.name in
let right_exp_temp, right_exp_inst = proc_expression right_exp builder in
let (sugared_assignment_temp, assigment_insts) = match op with
None -> (right_exp_temp, [])
| Some op ->
let (initial_prop_var, load_inst) = build_load_prop obj_temp name builder in
let bin_op = flow_binaryassign_op_to_progbuilder_binop op in
let result_var, assignment_inst = build_binary_op initial_prop_var right_exp_temp bin_op builder in
(result_var, [load_inst; assignment_inst]) in
let store_inst = build_store_prop obj_temp sugared_assignment_temp name builder in
(sugared_assignment_temp, obj_inst @ right_exp_inst @ assigment_insts @ [store_inst])
(* Handle assignments to property expressions *)
and proc_exp_assignment_prod_exp
(prop_exp: (Loc.t, Loc.t) Flow_ast.Expression.t)
(obj: (Loc.t, Loc.t) Flow_ast.Expression.t)
(right_exp: (Loc.t, Loc.t) Flow_ast.Expression.t)
(op: Flow_ast.Expression.Assignment.operator option)
(builder: builder) =
let obj_temp, obj_inst = proc_expression obj builder in
let index_exp_temp, index_exp_inst = proc_expression prop_exp builder in
let right_exp_temp, right_exp_inst = proc_expression right_exp builder in
let (lval_var, assigment_insts) = match op with
None -> (right_exp_temp, [])
| Some op ->
let load_temp_var, load_inst = build_load_computed_prop obj_temp index_exp_temp builder in
let bin_op = flow_binaryassign_op_to_progbuilder_binop op in
let result_var, assignment_inst = build_binary_op load_temp_var right_exp_temp bin_op builder in
(result_var, [load_inst; assignment_inst]) in
let store_inst = build_store_computed_prop obj_temp index_exp_temp lval_var builder in
(lval_var, obj_inst @ index_exp_inst @ right_exp_inst @ assigment_insts @ [store_inst])
(* Handle assignments to normal identifiers*)
and proc_exp_assignment_norm_id (assign_exp: ('M, 'T) Flow_ast.Expression.Assignment.t) (id: (Loc.t, Loc.t) Flow_ast.Identifier.t) builder =
let (_, act_name) = id in
let (exp_output_loc, exp_insts) = proc_expression assign_exp.right builder in
let (sugared_assignment_temp, sugared_assigment_exp) = match assign_exp.operator with
None -> (exp_output_loc, [])
| Some op ->
let source, source_inst = match lookup_var_name builder act_name.name with
InScope x -> (x, [])
| NotFound ->
raise (Invalid_argument "Variable not found") in
let bin_op = flow_binaryassign_op_to_progbuilder_binop op in
let result_var, assignment_inst = build_binary_op source exp_output_loc bin_op builder in
(result_var, source_inst @ [assignment_inst])
in
let var_temp, add_inst = match lookup_var_name builder act_name.name with
(* This case is where a variable is being declared, without a let/const/var.*)
NotFound ->
let result_var, inst = build_dup_op sugared_assignment_temp builder in
add_new_var_identifier act_name.name result_var builder;
(result_var, [inst])
| InScope existing_temp ->
let inst = build_reassign_op existing_temp sugared_assignment_temp builder in
(existing_temp, [inst])
in
(var_temp, exp_insts @ sugared_assigment_exp @ add_inst)
(* Handle a list of arguments to a function call*)
and proc_arg_list (arg_list: ('M, 'T) Flow_ast.Expression.ArgList.t) builder =
let _, unwrapped = arg_list in
let arguments = unwrapped.arguments in
let proc_exp_or_spread (exp_or_spread: ('M, 'T) Flow_ast.Expression.expression_or_spread) =
match exp_or_spread with
Expression exp ->
proc_expression exp builder
| Spread spread ->
let (_, unwrapped) = spread in
proc_expression unwrapped.argument builder in
let reg_list, unflattened_inst_list = List.split (List.map proc_exp_or_spread arguments) in
reg_list, List.flatten unflattened_inst_list
and arg_list_get_spread_list (arg_list: ('M, 'T) Flow_ast.Expression.ArgList.t) =
let _, unwrapped = arg_list in
let arguments = unwrapped.arguments in
let proc_exp_or_spread (exp_or_spread: ('M, 'T) Flow_ast.Expression.expression_or_spread) =
match exp_or_spread with
Expression exp -> false
| Spread spread -> true in
List.map proc_exp_or_spread arguments
and proc_exp_call (call_exp: ('M, 'T) Flow_ast.Expression.Call.t) builder =
let _ : unit = match call_exp.targs with
None -> ()
| Some a -> raise (Invalid_argument "Unhandled targs in call") in
let is_spread_list = arg_list_get_spread_list call_exp.arguments in
let is_spread = List.fold_left (||) false is_spread_list in
let (_, callee) = call_exp.callee in
match callee with
(* Handle the method call case explicity*)
Flow_ast.Expression.Member member ->
(match member.property with
(* Handle method calls seperately for all other cases *)
Flow_ast.Expression.Member.PropertyIdentifier (_, id) ->
let sub_exp_temp, sub_exp_inst = proc_expression member._object builder in
if is_spread then raise (Invalid_argument "Unhandled spread in member call") else ();
let arg_regs, arg_inst = proc_arg_list call_exp.arguments builder in
let result_var, inst = build_call_method sub_exp_temp arg_regs id.name builder in
(result_var, sub_exp_inst @ arg_inst @ [inst])
| _ ->
let callee_reg, callee_inst = proc_expression call_exp.callee builder in
let arg_regs, arg_inst = proc_arg_list call_exp.arguments builder in
let result_reg, inst = if is_spread
then
build_call_with_spread callee_reg arg_regs is_spread_list builder
else
build_call callee_reg arg_regs builder in
(result_reg, callee_inst @ arg_inst @ [inst]))
(* Otherwise, run the callee sub expression as normal*)
| _ -> let callee_reg, callee_inst = proc_expression call_exp.callee builder in
let arg_regs, arg_inst = proc_arg_list call_exp.arguments builder in
let result_reg, inst = if is_spread
then
build_call_with_spread callee_reg arg_regs is_spread_list builder
else
build_call callee_reg arg_regs builder in
(result_reg, callee_inst @ arg_inst @ [inst])
and proc_array_elem (elem: ('M, 'T) Flow_ast.Expression.Array.element) (builder: builder) =
match elem with
Expression e ->
let temp, inst = proc_expression e builder in
false, (temp, inst)
| Spread spread ->
let _, unwrapped = spread in
let temp, inst = proc_expression unwrapped.argument builder in
true, (temp, inst)
| Hole h ->
(* Fuzzilli doesn't support array holes, so load undefined instead *)
let result_var, inst = build_load_undefined builder in
false, (result_var, [inst])
and proc_create_array (exp: ('M, 'T) Flow_ast.Expression.Array.t) (builder: builder) =
let temp_func a = proc_array_elem a builder in
let is_spread_list, temp_list = List.split (List.map temp_func exp.elements) in
let arg_regs, arg_inst = List.split temp_list in
let flat_inst = List.flatten arg_inst in
let is_spread = List.fold_left (||) false is_spread_list in
let result_var, create_array_inst = if is_spread
then
build_create_array_with_spread arg_regs is_spread_list builder
else
build_create_array arg_regs builder
in
(result_var, flat_inst @ [create_array_inst])
and proc_create_object_property (prop_val: ('M, 'T) Flow_ast.Expression.Object.property) builder =
match prop_val with
Property (_, prop) ->
let temp_reg, prop_name_key, inst = match prop with
Init init_val ->
let temp, exp_inst = proc_expression init_val.value builder in
temp, init_val.key, exp_inst
| Set func ->
let _, act_func = func.value in
let temp, inst = proc_func act_func builder false in
temp, func.key, inst
| Get func ->
let (_, act_func) = func.value in
let temp, inst = proc_func act_func builder false in
temp, func.key, inst
| Method func ->
let (_, act_func) = func.value in
let temp, inst = proc_func act_func builder false in
temp, func.key, inst in
let prop_name : string = match prop_name_key with
Literal (_, l) -> l.raw
| Identifier (_, i) -> i.name
| PrivateName (_, p) ->
p.name
| Computed _ -> raise (Invalid_argument "Unhandled Object key type Computed Key in object creation") in
(temp_reg, [prop_name]), inst
| SpreadProperty (_, spreadProp) ->
let temp_reg, exp_inst = proc_expression spreadProp.argument builder in
(temp_reg, []), exp_inst
and proc_create_object (exp : ('M, 'T) Flow_ast.Expression.Object.t) (builder: builder) =
let props = exp.properties in
let temp_func a = proc_create_object_property a builder in
let obj_temp_tuple, create_obj_inst = List.split (List.map temp_func props) in
let obj_temp_list, obj_key_list_unflattened = List.split obj_temp_tuple in
let obj_key_list_flat = List.flatten obj_key_list_unflattened in
let flat_inst = List.flatten create_obj_inst in
let result_var, create_obj_inst = if List.length obj_key_list_flat == List.length obj_temp_list then
build_create_object obj_key_list_flat obj_temp_list builder
else
build_create_object_with_spread obj_key_list_flat obj_temp_list builder
in
(result_var, flat_inst @ [create_obj_inst])
and proc_exp_member (memb_exp: ('M, 'T) Flow_ast.Expression.Member.t) (builder: builder) =
let (sub_exp_temp, sub_exp_inst) = proc_expression memb_exp._object builder in
let return_temp, insts = match memb_exp.property with
PropertyIdentifier (_, i) ->
let result_var, load_prop_inst = build_load_prop sub_exp_temp i.name builder in
(result_var, [load_prop_inst])
| PropertyPrivateName (_, p) ->
let result_var, load_prop_inst = build_load_prop sub_exp_temp p.name builder in
(result_var, [load_prop_inst])
| PropertyExpression pe ->
let (_, unwrapped) = pe in
let opt_index = match unwrapped with
Flow_ast.Expression.Literal l ->
(match l.value with
Number n ->
if Float.is_integer n then Some (Float.to_int n) else None
| _ -> None)
| _ -> None in
match opt_index with
Some n -> (* Do a load element with the number*)
let result_var, load_element_inst = build_load_element sub_exp_temp n builder in
result_var, [load_element_inst]
| _ ->
(* Do a loadComputed with the expression*)
(* TODO: Is this the right operation here? *)
let member_exp_temp, member_exp_inst = proc_expression pe builder in
let result_var, load_computed_prop_inst = build_load_computed_prop sub_exp_temp member_exp_temp builder in
(result_var, member_exp_inst @ [load_computed_prop_inst]) in
(return_temp, sub_exp_inst @ insts)
and proc_exp_new (new_exp: ('M, 'T) Flow_ast.Expression.New.t) (builder: builder) =
let callee = new_exp.callee in
let (callee_reg, callee_inst) = proc_expression callee builder in
let _ : unit = match new_exp.targs with
None -> ()
| Some a -> raise (Invalid_argument "Unhandled targs in call") in
let arguments = new_exp.arguments in
let (arg_regs, arg_inst) = match arguments with
None -> ([], [])
| Some act_args ->
(let is_spread = List.fold_left (||) false ( arg_list_get_spread_list act_args ) in
let temp, insts = proc_arg_list act_args builder in
if is_spread then raise (Invalid_argument "Unhandled spread in new")
else temp, insts)
in
let result_var, create_obj_inst = build_new_object callee_reg arg_regs builder in
(result_var, callee_inst @ arg_inst @ [create_obj_inst])
and proc_exp_this this_exp builder =
let (result_var, inst) = build_load_builtin "this" builder in
result_var, [inst]
and proc_exp_update (update_exp: (Loc.t, Loc.t) Flow_ast.Expression.Update.t) (builder: builder) =
let (sub_exp_temp, sub_exp_inst) = proc_expression update_exp.argument builder in
let update_op : unary_op = match update_exp.operator with
Increment -> if update_exp.prefix then PreInc else PostInc
| Decrement -> if update_exp.prefix then PreDec else PostDec in
let result_var, update_inst = build_unary_op sub_exp_temp update_op builder in
result_var, sub_exp_inst @ [update_inst]
and proc_exp_yield (yield_exp: (Loc.t, Loc.t) Flow_ast.Expression.Yield.t) (builder: builder) =
let sub_exp_temp, sub_exp_insts = match yield_exp.argument with
| Some exp -> proc_expression exp builder
| _ -> raise (Invalid_argument "Unhandled yield without argument") in
let yield_inst = if yield_exp.delegate
then
build_yield_each_op sub_exp_temp builder
else
build_yield_op sub_exp_temp builder
in
sub_exp_temp, sub_exp_insts @ [yield_inst]
Ternary expressions are not handled by , so convert them to an if - else
and proc_exp_conditional (cond_exp: (Loc.t, Loc.t) Flow_ast.Expression.Conditional.t) (builder: builder) =
let result_temp, zero_temp_inst = build_load_integer 0L builder in
let (test_temp, test_inst) = proc_expression cond_exp.test builder in
let begin_if_inst = build_begin_if test_temp builder in
let consequent_temp, consequest_inst = proc_expression cond_exp.consequent builder in
let consequent_reassign_inst = build_reassign_op result_temp consequent_temp builder in
let begin_else_inst = build_begin_else builder in
let alternative_temp, alternative_inst = proc_expression cond_exp.alternate builder in
let alternative_reassign_inst = build_reassign_op result_temp alternative_temp builder in
let end_if_inst = build_end_if builder in
(result_temp, [zero_temp_inst] @ test_inst @ [begin_if_inst] @ consequest_inst @ [consequent_reassign_inst] @ [begin_else_inst] @
alternative_inst @ [alternative_reassign_inst; end_if_inst])
and proc_class_method class_proto_temp builder (m: (Loc.t, Loc.t) Flow_ast.Class.Method.t) =
let _, unwrapped_method = m in
let key = unwrapped_method.key in
let method_name = match key with
Literal (_, l) -> l.raw
| Identifier (_, i) -> i.name
| PrivateName (_, p) ->
p.name
| Computed _ -> raise (Invalid_argument "Unhandled method name in class creation") in
let _, func = unwrapped_method.value in
let method_temp, method_inst = proc_func func builder false in
(* TODO: Double check if this is the right operation *)
let load_propotype_inst = build_store_prop class_proto_temp method_temp method_name builder in
method_inst @ [load_propotype_inst]
and proc_expression (exp: ('M, 'T) Flow_ast.Expression.t) (builder: builder) =
let (_, unwrapped_exp) = exp in
match unwrapped_exp with
| (Flow_ast.Expression.Array array_op) ->
proc_create_array array_op builder
| (Flow_ast.Expression.ArrowFunction arrow_func) ->
proc_func arrow_func builder true
| (Flow_ast.Expression.Assignment assign_op) ->
proc_exp_assignment assign_op builder
| (Flow_ast.Expression.Binary bin_op) ->
proc_exp_bin_op bin_op builder
| (Flow_ast.Expression.Call call_op) ->
proc_exp_call call_op builder
| (Flow_ast.Expression.Conditional cond_exp) ->
proc_exp_conditional cond_exp builder
| (Flow_ast.Expression.Function func_exp) ->
proc_func func_exp builder false
| (Flow_ast.Expression.Identifier id_val) ->
proc_exp_id id_val builder
| (Flow_ast.Expression.Import _) ->
(* Fuzzilli doesn't support imports, so effectively nop this out *)
let var, inst = build_load_undefined builder in
var, [inst]
| (Flow_ast.Expression.Literal lit_val) ->
proc_exp_literal lit_val builder
| (Flow_ast.Expression.Logical log_op) ->
proc_exp_logical log_op builder
| (Flow_ast.Expression.Member memb_exp) ->
proc_exp_member memb_exp builder
| (Flow_ast.Expression.New new_exp) ->
proc_exp_new new_exp builder
| (Flow_ast.Expression.Object create_obj_op) ->
proc_create_object create_obj_op builder
| (Flow_ast.Expression.This this_exp) ->
proc_exp_this this_exp builder
| (Flow_ast.Expression.Unary u_val) ->
proc_exp_unary u_val builder
| (Flow_ast.Expression.Update update_exp) ->
proc_exp_update update_exp builder
| (Flow_ast.Expression.Yield yield_exp) ->
proc_exp_yield yield_exp builder
| x -> raise (Invalid_argument ("Unhandled expression type " ^ (Util.trim_flow_ast_string (Util.print_expression exp))))
(* Process a single actual declaration *)
and proc_var_declaration_actual (var_name: string) (init: (Loc.t, Loc.t) Flow_ast.Expression.t option) (kind: Flow_ast.Statement.VariableDeclaration.kind) (builder : builder) =
let temp_var_num, new_insts = match init with
None ->
(* Handle a declaration without a definition *)
(match kind with
Flow_ast.Statement.VariableDeclaration.Var ->
let undef_temp, undef_inst = build_load_undefined builder in
let result_var, dup_inst = build_dup_op undef_temp builder in
add_new_var_identifier var_name result_var builder;
result_var, [undef_inst; dup_inst]
| Flow_ast.Statement.VariableDeclaration.Let ->
let undef_temp, undef_inst = build_load_undefined builder in
add_new_var_identifier var_name undef_temp builder;
undef_temp, [undef_inst]
| _ -> raise (Invalid_argument "Empty const declaration"))
| Some exp -> proc_expression exp builder in
let reassign_inst = (match kind with
Flow_ast.Statement.VariableDeclaration.Var ->
let is_hoisted = is_hoisted_var var_name builder in
if is_hoisted then
let hoisted_temp = lookup_var_name builder var_name in
match hoisted_temp with
NotFound -> raise (Invalid_argument "Unfound hoisted temp")
| InScope temp ->
let inst = build_reassign_op temp temp_var_num builder in
[inst]
else
(add_new_var_identifier var_name temp_var_num builder;
[])
| _ ->
add_new_var_identifier var_name temp_var_num builder;
[])
in
new_insts @ reassign_inst
and proc_handle_single_var_declaration (dec : (Loc.t, Loc.t) Flow_ast.Statement.VariableDeclaration.Declarator.t') (kind: Flow_ast.Statement.VariableDeclaration.kind) (builder : builder) =
let foo = match dec.id, dec.init with
(_, (Flow_ast.Pattern.Identifier id)), exp ->
let (_, act_name) = id.name in
proc_var_declaration_actual act_name.name exp kind builder
| (_, (Flow_ast.Pattern.Array arr)), (Some (_, Flow_ast.Expression.Array exp)) ->
let get_name (a: ('M, 'T) Flow_ast.Pattern.Array.element) =
match a with
Element (_, e) ->
(match e.argument with
(_, (Flow_ast.Pattern.Identifier x)) ->
let var_id = x.name in
let (_, act_name) = var_id in
act_name.name
| _ -> raise (Invalid_argument "Improper args in variable declaration"))
| _ -> raise (Invalid_argument "Improper args in variable declaration") in
let id_elems = List.map get_name arr.elements in
let get_elem (e: (Loc.t, Loc.t) Flow_ast.Expression.Array.element) =
match e with
Expression exp -> exp
| _ -> raise (Invalid_argument "Improper args in variable declaration") in
let elems = List.map get_elem exp.elements in
let process id elem = proc_var_declaration_actual id (Some elem) kind builder in
List.map2 process id_elems elems |> List.flatten
| _, _ -> raise (Invalid_argument "Improper args in variable declaration") in
foo
(* Process a single variable declaration *)
and proc_var_dec_declarators (decs : (Loc.t, Loc.t) Flow_ast.Statement.VariableDeclaration.Declarator.t list) (kind: Flow_ast.Statement.VariableDeclaration.kind) (builder : builder) =
match decs with
[] -> []
| (_, declarator) :: tl ->
proc_handle_single_var_declaration declarator kind builder @ (proc_var_dec_declarators tl kind builder)
(* Processes a variable declaration statement, which can be made up of multiple vars *)
and proc_var_decl_statement (var_decl: (Loc.t, Loc.t) Flow_ast.Statement.VariableDeclaration.t) (builder: builder) =
let decs = var_decl.declarations in
let kind = var_decl.kind in
proc_var_dec_declarators decs kind builder
and proc_if_statement (if_statement: (Loc.t, Loc.t) Flow_ast.Statement.If.t) (builder: builder) =
let test = if_statement.test in
let (test_temp_val, test_inst) = proc_expression test builder in
let begin_if_inst = build_begin_if test_temp_val builder in
push_local_scope builder;
let consequent_statements = proc_single_statement if_statement.consequent builder in
pop_local_scope builder;
Fuzzilli requires an else for each if , due to how AbstractInterpreter works
let begin_else_inst = build_begin_else builder in
push_local_scope builder;
let fin_statement = match if_statement.alternate with
None -> []
| Some (_, alt) ->
let alt_inst = proc_single_statement alt.body builder in
alt_inst in
pop_local_scope builder;
let end_if_inst = build_end_if builder in
test_inst @ begin_if_inst :: consequent_statements @ [begin_else_inst] @ fin_statement @ [end_if_inst]
(* TODO: Improve this. Puts all expressions into a temp, and compares with 0. Could be better*)
and proc_while (while_statement: (Loc.t, Loc.t) Flow_ast.Statement.While.t) (builder: builder) =
(* Build initial check, put into temp*)
let test_exp_reg, test_exp_inst = proc_expression while_statement.test builder in
let pre_loop_inst = test_exp_inst in
(* Build begin while *)
let zero_temp, zero_temp_inst = build_load_integer 0L builder in
let begin_while_inst = build_begin_while test_exp_reg zero_temp NotEqual builder in
let begin_loop_inst = zero_temp_inst :: [begin_while_inst] in
push_local_scope builder;
(* Build body *)
let body_statement = proc_single_statement while_statement.body builder in
pop_local_scope builder;
(* Reexecute comparison, and load into temp*)
let test_exp_reg_internal, test_exp_inst_internal = proc_expression while_statement.test builder in
let reassign_inst = build_reassign_op test_exp_reg test_exp_reg_internal builder in
let re_exec_test_exp = test_exp_inst_internal @ [reassign_inst] in
let end_while_inst = build_end_while builder in
pre_loop_inst @ begin_loop_inst @ body_statement @ re_exec_test_exp @ [end_while_inst]
and proc_do_while (do_while_statement: (Loc.t, Loc.t) Flow_ast.Statement.DoWhile.t) (builder: builder) =
(* Build initial check, put into temp*)
(* let test_exp_reg, test_exp_inst = proc_expression do_while_statement.test builder in *)
let zero_temp, zero_temp_inst = build_load_integer 0L builder in
let intermed, dup_inst = build_dup_op zero_temp builder in
(* Build begin while *)
let begin_while_inst = build_begin_do_while intermed zero_temp NotEqual builder in
push_local_scope builder;
(* Build body *)
let body_statement = proc_single_statement do_while_statement.body builder in
pop_local_scope builder;
(* Execute comparison, and load into temp*)
let test_exp_reg_internal, test_exp_inst_internal = proc_expression do_while_statement.test builder in
let reassign_inst = build_reassign_op intermed test_exp_reg_internal builder in
let re_exec_test_exp = test_exp_inst_internal @ [reassign_inst] in
let end_while_inst = build_end_do_while builder in
[zero_temp_inst; dup_inst; begin_while_inst] @ body_statement @ re_exec_test_exp @ [end_while_inst]
and proc_try (try_statement: (Loc.t, Loc.t) Flow_ast.Statement.Try.t) (builder: builder) =
let try_inst = build_begin_try_op builder in
push_local_scope builder;
let (_, try_block) = try_statement.block in
let block_inst = proc_statements try_block.body builder in
let catch_inst, catch_body_inst = match try_statement.handler with
None -> raise (Invalid_argument "Empty catch")
| Some (_, catch_clause) ->
let temp_name = match catch_clause.param with
| Some (_, (Flow_ast.Pattern.Identifier var_identifier)) ->
let (_, act_name) = var_identifier.name in
act_name.name
| _ -> raise (Invalid_argument "Unsupported catch type")
in
let (_, catch_cause_block) = catch_clause.body in
let catch_body_inst = proc_statements catch_cause_block.body builder in
let catch_inst = build_begin_catch_op temp_name builder in
(catch_inst, catch_body_inst)
in
let finalizer_inst = match try_statement.finalizer with
None -> []
| Some (_, fin_block) -> proc_statements fin_block.body builder in
pop_local_scope builder;
let end_try_catch_inst = build_end_try_catch_op builder in
[try_inst] @ block_inst @ [catch_inst] @ catch_body_inst @ [end_try_catch_inst] @ finalizer_inst
and proc_func (func: (Loc.t, Loc.t) Flow_ast.Function.t) (builder : builder) (is_arrow: bool) =
(* Get func name*)
let func_name_opt = match func.id with
None -> None
| Some (_, id) ->
Some id.name
in
(* Unwraps a flow_ast paramter to a string identifier *)
let param_to_id (input: ('M, 'T) Flow_ast.Function.Param.t) =
let (_, unwrapped_input) = input in
let pattern = unwrapped_input.argument in
let (_, act_name) = match pattern with
(_, (Flow_ast.Pattern.Identifier x)) -> x.name
| _ -> raise (Invalid_argument "Didn't get an Identifier when expected in function declaration") in
act_name.name in
(* Process function parameters*)
let (_, unwrapped_param) = func.params in
let param_ids = List.map param_to_id unwrapped_param.params in
let rest_arg_name_opt = match unwrapped_param.rest with
None -> None
| Some (_, rest_id) ->
let act_id = rest_id.argument in
let (_, id_string) = match act_id with
(_, (Flow_ast.Pattern.Identifier x)) -> x.name
| _ -> raise (Invalid_argument "Unhandled rest temp") in
Some id_string.name
in
let func_temp = get_new_intermed_temp builder in
(match func_name_opt with
Some name ->
if is_hoisted_var name builder then
()
else
add_new_var_identifier name func_temp builder;
| _ -> ());
push_local_scope builder;
let func_temp, begin_func_inst, end_func_inst = build_func_ops func_temp param_ids rest_arg_name_opt is_arrow func.async func.generator builder in
(* Process func body*)
let func_inst = match func.body with
BodyBlock body_block ->
let _, state_block = body_block in
let hoisted_statements = handle_varHoist state_block.body builder in
hoisted_statements @ proc_statements state_block.body builder
| BodyExpression body_exp ->
let _, inst = proc_expression body_exp builder in
inst
in
pop_local_scope builder;
let reassign_inst = (match func_name_opt with
Some name ->
if is_hoisted_var name builder then
match (lookup_var_name builder name) with
NotFound -> raise (Invalid_argument "Hoisted func not found")
| InScope x -> [build_reassign_op x func_temp builder]
else
[]
| _ -> []) in
func_temp, [begin_func_inst] @ func_inst @ [end_func_inst] @ reassign_inst
(* TODO: Fuzzilli return statements currently only allow variables. Add the ability to return without a value *)
and proc_return (ret_state: (Loc.t, Loc.t) Flow_ast.Statement.Return.t) (builder: builder) =
let return_var, return_insts = match ret_state.argument with
None ->
let temp, inst = build_load_undefined builder in
temp, [inst]
| Some exp ->
let temp_num, insts = proc_expression exp builder in
temp_num, insts
in
let return_inst = build_return_op return_var builder in
return_insts @ [return_inst]
and proc_with (with_state: (Loc.t, Loc.t) Flow_ast.Statement.With.t) (builder: builder) =
let result_var, with_insts = proc_expression with_state._object builder in
let begin_with_inst = build_begin_with_op result_var builder in
let body_insts = proc_single_statement with_state.body builder in
let end_with_inst = build_end_with_op builder in
with_insts @ [begin_with_inst] @ body_insts @ [end_with_inst]
and proc_throw (throw_state: (Loc.t, Loc.t) Flow_ast.Statement.Throw.t) (builder: builder) =
let temp, inst = proc_expression throw_state.argument builder in
let throw_inst = build_throw_op temp builder in
inst @ [throw_inst]
and proc_break builder =
TODO switch_break_op
(* Both for-in and for-of only allow creation of a new variable on the left side *)
and proc_for_in (for_in_state: (Loc.t, Loc.t) Flow_ast.Statement.ForIn.t) (builder: builder) =
let right_temp, right_inst = proc_expression for_in_state.right builder in
push_local_scope builder;
let var_temp, end_of_loop_cleanup_inst = match for_in_state.left with
LeftDeclaration (_, d) ->
let decs = d.declarations in
(match decs with
[(_, declarator)] -> ( match declarator.id with
(_, (Flow_ast.Pattern.Identifier id)) ->
let (_, id_type) = id.name in
let left_temp = get_new_intermed_temp builder in
add_new_var_identifier id_type.name left_temp builder;
left_temp, []
| _ -> raise (Invalid_argument ("Improper declaration in for-in loop")))
| _ -> raise (Invalid_argument "Improper declaration in for-in loop"))
| LeftPattern p -> (match p with
(_, (Flow_ast.Pattern.Identifier id)) ->
let (_, id_type) = id.name in
let lookup = lookup_var_name builder id_type.name in
(match lookup with
InScope x ->
(* Fuzzilli does not support reusing a variable in a for-in loop, so we have to make a new one and reassign it*)
let left_temp = get_new_intermed_temp builder in
add_new_var_identifier id_type.name left_temp builder;
let reassign_inst = build_reassign_op x left_temp builder in
left_temp, [reassign_inst]
| NotFound ->
let left_temp = get_new_intermed_temp builder in
add_new_var_identifier id_type.name left_temp builder;
left_temp, [] )
| _ -> raise (Invalid_argument ("Inproper left pattern in for-in loop"))) in
let _, start_for_in_inst = build_begin_for_in_op var_temp right_temp builder in
let body_inst = proc_single_statement for_in_state.body builder in
let end_for_in = build_end_for_in_op builder in
pop_local_scope builder;
right_inst @ [start_for_in_inst] @ body_inst @ end_of_loop_cleanup_inst @ [end_for_in];
and proc_for_of (for_of_state: (Loc.t, Loc.t) Flow_ast.Statement.ForOf.t) (builder: builder) =
let right_temp, right_inst = proc_expression for_of_state.right builder in
push_local_scope builder;
let var_id = match for_of_state.left with
LeftDeclaration (_, d) ->
let decs = d.declarations in
(match decs with
[(_, declarator)] -> ( match declarator.id with
(_, (Flow_ast.Pattern.Identifier x)) -> x
| _ -> raise (Invalid_argument ("Improper declaration in for-of loop")))
| _ -> raise (Invalid_argument "Improper declaration in for-of loop"))
| LeftPattern p -> (match p with
(* TODO: Fuzzilli does not support reusing a variable in a for-of loop *)
(_, (Flow_ast.Pattern.Identifier id)) -> id
| _ -> raise (Invalid_argument ("Inproper left pattern in for-of loop"))) in
let (_, act_name) = var_id.name in
let left_temp, start_for_of_inst = build_begin_for_of_op right_temp builder in
add_new_var_identifier act_name.name left_temp builder;
let body_inst = proc_single_statement for_of_state.body builder in
let end_for_of_inst = build_end_for_of_op builder in
right_inst @ [start_for_of_inst] @ body_inst @ [end_for_of_inst];
Fuzzilli For loops in only
and proc_for (for_state: (Loc.t, Loc.t) Flow_ast.Statement.For.t) (builder: builder) =
let init_inst = match for_state.init with
None -> []
| Some (InitDeclaration (_, decl)) -> proc_var_decl_statement decl builder
| Some (InitExpression exp) ->
let (_, exp_insts) = proc_expression exp builder in
exp_insts
in
(* Variables used in the condition need to be declared outside the while loop*)
let test_exp_reg, test_exp_inst = match for_state.test with
Some exp -> proc_expression exp builder
| None -> raise (Invalid_argument "Unhandled empty for-loop test") in
let pre_loop_inst = test_exp_inst in
push_local_scope builder;
(*start while loop*)
let zero_temp, zero_temp_inst = build_load_integer 0L builder in
let begin_while_inst = build_begin_while test_exp_reg zero_temp NotEqual builder in
let begin_loop_inst = zero_temp_inst :: [begin_while_inst] in
(*Body instructions*)
let body_insts = proc_single_statement for_state.body builder in
(* Update*)
let update_insts = match for_state.update with
None -> []
| Some exp ->
let (_, exp_insts) = proc_expression exp builder
in exp_insts in
Redo the check
let test_exp_reg_internal, test_exp_inst_internal = match for_state.test with
Some exp -> proc_expression exp builder
| None -> raise (Invalid_argument "Unhandled empty for-loop test") in
let reassign_inst = build_reassign_op test_exp_reg test_exp_reg_internal builder in
let re_exec_test_exp = test_exp_inst_internal @ [reassign_inst] in
(* End while*)
let end_while_inst = build_end_while builder in
pop_local_scope builder;
init_inst @ pre_loop_inst @ begin_loop_inst @ body_insts @ update_insts @ re_exec_test_exp @ [end_while_inst]
and proc_continue builder =
[build_continue builder]
and proc_single_statement (statement: (Loc.t, Loc.t) Flow_ast.Statement.t) builder =
match statement with
(_, Flow_ast.Statement.Block state_block) -> proc_statements state_block.body builder
| (_, Flow_ast.Statement.Break _) -> proc_break builder
| (_, Flow_ast.Statement.Continue state_continue) -> proc_continue builder
| (_, Flow_ast.Statement.DoWhile state_do_while) -> proc_do_while state_do_while builder
| (_, Flow_ast.Statement.Empty _) -> []
| (_, Flow_ast.Statement.Expression state_exp) ->
let (_, inst) = proc_expression state_exp.expression builder in
inst
| (_, Flow_ast.Statement.For state_for) -> proc_for state_for builder
| (_, Flow_ast.Statement.ForIn state_foin) -> proc_for_in state_foin builder
| (_, Flow_ast.Statement.ForOf state_forof) -> proc_for_of state_forof builder
| (_, Flow_ast.Statement.FunctionDeclaration func_def) ->
let (_, res) = proc_func func_def builder false in
res
| (_, Flow_ast.Statement.If state_if) -> proc_if_statement state_if builder
(* Fuzzilli doesn't support imports *)
| (_, Flow_ast.Statement.ImportDeclaration _) -> []
| (_, Flow_ast.Statement.Return state_return) -> proc_return state_return builder
| (_, Flow_ast.Statement.Throw state_throw) -> proc_throw state_throw builder
| (_, Flow_ast.Statement.Try state_try) -> proc_try state_try builder
| (_ , VariableDeclaration decl) -> proc_var_decl_statement decl builder
| (_, Flow_ast.Statement.While state_while) -> proc_while state_while builder
| (_, Flow_ast.Statement.With state_with) -> proc_with state_with builder
| _ as s -> raise (Invalid_argument (Printf.sprintf "Unhandled statement type %s" (Util.trim_flow_ast_string (Util.print_statement s))))
and proc_statements (statements: (Loc.t, Loc.t) Flow_ast.Statement.t list) (var_builder: builder) =
match statements with
[] -> []
| hd :: tl ->
let new_statement = proc_single_statement hd var_builder in
new_statement @ proc_statements tl var_builder
let flow_ast_to_inst_list (prog: (Loc.t, Loc.t) Flow_ast.Program.t) emit_builtins include_v8_natives use_placeholder =
let init_var_builder = init_builder emit_builtins include_v8_natives use_placeholder in
let (_, prog_t) = prog in
let hoisted_funcs = handle_varHoist prog_t.statements init_var_builder in
let proced_statements = hoisted_funcs @ proc_statements prog_t.statements init_var_builder in
let proced_statements_converted = List.map inst_to_prog_inst proced_statements in
proced_statements_converted
| null | https://raw.githubusercontent.com/areuu/ilcompiler/c6f0bc809fe165947b8c7004dc1ed94414038002/src/translate.ml | ocaml | Designed to be called on the statements of a function
Handle the various types of literal
Handle the various unary types
Need to determine between computed delete, and named delete
TODO: What other values go here?
There are various different expression types, so pattern match on each time, and ccall the appropriate, more specific, function
Handle assignments to property expressions
Handle assignments to normal identifiers
This case is where a variable is being declared, without a let/const/var.
Handle a list of arguments to a function call
Handle the method call case explicity
Handle method calls seperately for all other cases
Otherwise, run the callee sub expression as normal
Fuzzilli doesn't support array holes, so load undefined instead
Do a load element with the number
Do a loadComputed with the expression
TODO: Is this the right operation here?
TODO: Double check if this is the right operation
Fuzzilli doesn't support imports, so effectively nop this out
Process a single actual declaration
Handle a declaration without a definition
Process a single variable declaration
Processes a variable declaration statement, which can be made up of multiple vars
TODO: Improve this. Puts all expressions into a temp, and compares with 0. Could be better
Build initial check, put into temp
Build begin while
Build body
Reexecute comparison, and load into temp
Build initial check, put into temp
let test_exp_reg, test_exp_inst = proc_expression do_while_statement.test builder in
Build begin while
Build body
Execute comparison, and load into temp
Get func name
Unwraps a flow_ast paramter to a string identifier
Process function parameters
Process func body
TODO: Fuzzilli return statements currently only allow variables. Add the ability to return without a value
Both for-in and for-of only allow creation of a new variable on the left side
Fuzzilli does not support reusing a variable in a for-in loop, so we have to make a new one and reassign it
TODO: Fuzzilli does not support reusing a variable in a for-of loop
Variables used in the condition need to be declared outside the while loop
start while loop
Body instructions
Update
End while
Fuzzilli doesn't support imports | open ProgramBuilder
let flow_binaryassign_op_to_progbuilder_binop (op : Flow_ast.Expression.Assignment.operator) =
let res : binary_op = match op with
PlusAssign -> Plus
| MinusAssign -> Minus
| MultAssign -> Mult
| DivAssign -> Div
| ModAssign -> Mod
| BitXorAssign -> Xor
| LShiftAssign -> LShift
| RShiftAssign -> RShift
| ExpAssign -> Exp
| RShift3Assign -> RShift3
| BitAndAssign -> BitAnd
| BitOrAssign -> BitOr in
res
let hoist_id var_name builder =
let result_temp, inst = build_load_undefined builder in
add_new_var_identifier var_name result_temp builder;
add_hoisted_var var_name builder;
inst
let hoist_functions_to_top (statements: (Loc.t, Loc.t) Flow_ast.Statement.t list) =
let partition_func (s:(Loc.t, Loc.t) Flow_ast.Statement.t) = match s with
(_, Flow_ast.Statement.FunctionDeclaration _) -> true
| _ -> false in
let function_list, rest_list = List.partition partition_func statements in
function_list @ rest_list
let handle_varHoist (statements: (Loc.t, Loc.t) Flow_ast.Statement.t list) (builder: builder) =
let hoisted_functions = hoist_functions_to_top statements in
let var_useData, func_useData = VariableScope.get_vars_to_hoist hoisted_functions in
let is_not_builtin s = Util.is_supported_builtin s (include_v8_natives builder) |> not in
let funcs_to_hoist = List.filter is_not_builtin func_useData in
let hoist_func var = hoist_id var builder in
let hoist_vars = List.map hoist_func var_useData in
let hoist_funcs = List.map hoist_func funcs_to_hoist in
hoist_vars @ hoist_funcs
let proc_exp_literal (lit_val: ('T) Flow_ast.Literal.t) (builder: builder) =
let (temp_val, inst) = match lit_val.value with
(Flow_ast.Literal.String s) ->
TODO : This may be the cause of the issue where some files fail Fuzzilli import due to a UTF-8 error
let newString = Util.encode_newline s in
build_load_string newString builder
| (Flow_ast.Literal.Boolean b) ->
build_load_bool b builder
| (Flow_ast.Literal.Null) ->
build_load_null builder
| (Flow_ast.Literal.Number num) ->
Flow_ast only has one type for a number , while has several , each with its own protobuf type
if Float.is_integer num && not (String.contains lit_val.raw '.') && Int64.of_float num >= Int64.min_int && Int64.of_float num <= Int64.max_int then
build_load_integer (Int64.of_float num) builder
else
build_load_float num builder
| (Flow_ast.Literal.BigInt b) ->
build_load_bigInt b builder
| (Flow_ast.Literal.RegExp r) ->
let pattern = r.pattern in
let flags = r.flags in
build_load_regex pattern flags builder in
(temp_val, [inst])
let rec proc_exp_unary (u_val: ('M, 'T) Flow_ast.Expression.Unary.t) (builder: builder) =
match u_val.operator with
Flow_ast.Expression.Unary.Not ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_unary_op arg_result_var Not builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.BitNot ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_unary_op arg_result_var BitNot builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Minus ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_unary_op arg_result_var Minus builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Plus ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_unary_op arg_result_var Plus builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Typeof ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_typeof_op arg_result_var builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Await ->
let arg_result_var, argument = proc_expression u_val.argument builder in
let result_var, inst = build_await_op arg_result_var builder in
result_var, argument @ [inst]
| Flow_ast.Expression.Unary.Delete ->
let _, unwrapped_arg = u_val.argument in
let del_temp, del_inst = match unwrapped_arg with
Flow_ast.Expression.Member mem ->
let obj_temp, obj_inst = proc_expression mem._object builder in
( match mem.property with
Flow_ast.Expression.Member.PropertyIdentifier (_, id) ->
let name = id.name in
let obj, del_inst = build_delete_prop obj_temp name builder in
obj, obj_inst @ [del_inst]
| Flow_ast.Expression.Member.PropertyExpression exp ->
let sub_temp, sub_inst = proc_expression exp builder in
let (obj, com_del_inst) = build_delete_computed_prop obj_temp sub_temp builder in
obj_temp, obj_inst @ sub_inst @ [com_del_inst]
| _ -> raise (Invalid_argument "Unhandled delete member property") )
| Identifier id -> raise (Invalid_argument "Deleting an ID isn't supported in Fuzzilli")
| _ -> raise (Invalid_argument "Unsupported delete expression ") in
del_temp, del_inst
| Flow_ast.Expression.Unary.Void ->
let _, argument = proc_expression u_val.argument builder in
let result_var, inst = build_void_op builder in
result_var, argument @ [inst]
First , check against various edge cases . Otherwise , check the context , and handle the result appropriately
and proc_exp_id (id_val: ('M, 'T) Flow_ast.Identifier.t) builder =
let (_, unwraped_id_val) = id_val in
let name = unwraped_id_val.name in
let (result_var, inst) = build_load_float Float.infinity builder in
result_var, [inst]
else if String.equal name "undefined" then
let result_var, inst = build_load_undefined builder in
result_var, [inst]
else match lookup_var_name builder name with
InScope x -> (x, [])
| NotFound ->
if Util.is_supported_builtin name (include_v8_natives builder) then
let (result_var, inst) = build_load_builtin name builder in
if (should_emit_builtins builder) then print_endline ("Builtin: " ^ name) else ();
(result_var, [inst])
else if use_placeholder builder then
let (result_var, inst) = build_load_builtin "placeholder" builder in
(result_var, [inst])
else
raise (Invalid_argument ("Unhandled builtin " ^ name))
and proc_exp_bin_op (bin_op: ('M, 'T) Flow_ast.Expression.Binary.t) builder =
let (lvar, linsts) = proc_expression bin_op.left builder in
let (rvar, rinsts) = proc_expression bin_op.right builder in
let build_binary_op_func op = build_binary_op lvar rvar op builder in
let build_compare_op_func op = build_compare_op lvar rvar op builder in
let (result_var, inst) = match bin_op.operator with
Plus -> build_binary_op_func Plus
| Minus -> build_binary_op_func Minus
| Mult -> build_binary_op_func Mult
| Div -> build_binary_op_func Div
| Mod -> build_binary_op_func Mod
| Xor -> build_binary_op_func Xor
| LShift -> build_binary_op_func LShift
| RShift -> build_binary_op_func RShift
| Exp -> build_binary_op_func Exp
| RShift3 -> build_binary_op_func RShift3
| BitAnd -> build_binary_op_func BitAnd
| BitOr -> build_binary_op_func BitOr
| Equal -> build_compare_op_func Equal
| NotEqual -> build_compare_op_func NotEqual
| StrictEqual -> build_compare_op_func StrictEqual
| StrictNotEqual -> build_compare_op_func StrictNotEqual
| LessThan -> build_compare_op_func LessThan
| LessThanEqual -> build_compare_op_func LessThanEqual
| GreaterThan -> build_compare_op_func GreaterThan
| GreaterThanEqual -> build_compare_op_func GreaterThanEqual
| Instanceof -> build_test_instanceof_op lvar rvar builder
| In -> build_test_in_op lvar rvar builder in
(result_var, linsts @ rinsts @ [inst])
and proc_exp_logical (log_op: ('M, 'T) Flow_ast.Expression.Logical.t) builder =
let (lvar, linsts) = proc_expression log_op.left builder in
let (rvar, rinsts) = proc_expression log_op.right builder in
let op = match log_op.operator with
Flow_ast.Expression.Logical.And -> LogicalAnd
| Flow_ast.Expression.Logical.Or -> LogicalOr
| x -> raise (Invalid_argument ("Unhandled logical expression type" ^ (Util.trim_flow_ast_string (Util.print_logical_operator x)))) in
let (result_var, inst) = build_binary_op lvar rvar op builder in
(result_var, linsts @ rinsts @ [inst])
and proc_exp_assignment (assign_exp: ('M, 'T) Flow_ast.Expression.Assignment.t) (builder: builder) =
match assign_exp.left with
(_, (Flow_ast.Pattern.Identifier id)) -> proc_exp_assignment_norm_id assign_exp id.name builder
| (_, (Flow_ast.Pattern.Expression (_, exp))) ->
(match exp with
Flow_ast.Expression.Member mem ->
let obj = mem._object in
(match mem.property with
Flow_ast.Expression.Member.PropertyExpression pex -> proc_exp_assignment_prod_exp pex obj assign_exp.right assign_exp.operator builder
| Flow_ast.Expression.Member.PropertyIdentifier pid -> proc_exp_assignment_prod_id pid obj assign_exp.right assign_exp.operator builder
| _ -> raise (Invalid_argument "Unhandled member property in exp assignment"))
| _ -> raise (Invalid_argument "Unhandled assignment expression left member"))
| _ -> raise (Invalid_argument "Unhandled assignment expressesion left ")
and proc_exp_assignment_prod_id
(prop_id: (Loc.t, Loc.t) Flow_ast.Identifier.t)
(obj: (Loc.t, Loc.t) Flow_ast.Expression.t)
(right_exp: (Loc.t, Loc.t) Flow_ast.Expression.t)
(op: Flow_ast.Expression.Assignment.operator option)
(builder: builder) =
let obj_temp, obj_inst = proc_expression obj builder in
let (_, unwapped_id) = prop_id in
let name = unwapped_id.name in
let right_exp_temp, right_exp_inst = proc_expression right_exp builder in
let (sugared_assignment_temp, assigment_insts) = match op with
None -> (right_exp_temp, [])
| Some op ->
let (initial_prop_var, load_inst) = build_load_prop obj_temp name builder in
let bin_op = flow_binaryassign_op_to_progbuilder_binop op in
let result_var, assignment_inst = build_binary_op initial_prop_var right_exp_temp bin_op builder in
(result_var, [load_inst; assignment_inst]) in
let store_inst = build_store_prop obj_temp sugared_assignment_temp name builder in
(sugared_assignment_temp, obj_inst @ right_exp_inst @ assigment_insts @ [store_inst])
and proc_exp_assignment_prod_exp
(prop_exp: (Loc.t, Loc.t) Flow_ast.Expression.t)
(obj: (Loc.t, Loc.t) Flow_ast.Expression.t)
(right_exp: (Loc.t, Loc.t) Flow_ast.Expression.t)
(op: Flow_ast.Expression.Assignment.operator option)
(builder: builder) =
let obj_temp, obj_inst = proc_expression obj builder in
let index_exp_temp, index_exp_inst = proc_expression prop_exp builder in
let right_exp_temp, right_exp_inst = proc_expression right_exp builder in
let (lval_var, assigment_insts) = match op with
None -> (right_exp_temp, [])
| Some op ->
let load_temp_var, load_inst = build_load_computed_prop obj_temp index_exp_temp builder in
let bin_op = flow_binaryassign_op_to_progbuilder_binop op in
let result_var, assignment_inst = build_binary_op load_temp_var right_exp_temp bin_op builder in
(result_var, [load_inst; assignment_inst]) in
let store_inst = build_store_computed_prop obj_temp index_exp_temp lval_var builder in
(lval_var, obj_inst @ index_exp_inst @ right_exp_inst @ assigment_insts @ [store_inst])
and proc_exp_assignment_norm_id (assign_exp: ('M, 'T) Flow_ast.Expression.Assignment.t) (id: (Loc.t, Loc.t) Flow_ast.Identifier.t) builder =
let (_, act_name) = id in
let (exp_output_loc, exp_insts) = proc_expression assign_exp.right builder in
let (sugared_assignment_temp, sugared_assigment_exp) = match assign_exp.operator with
None -> (exp_output_loc, [])
| Some op ->
let source, source_inst = match lookup_var_name builder act_name.name with
InScope x -> (x, [])
| NotFound ->
raise (Invalid_argument "Variable not found") in
let bin_op = flow_binaryassign_op_to_progbuilder_binop op in
let result_var, assignment_inst = build_binary_op source exp_output_loc bin_op builder in
(result_var, source_inst @ [assignment_inst])
in
let var_temp, add_inst = match lookup_var_name builder act_name.name with
NotFound ->
let result_var, inst = build_dup_op sugared_assignment_temp builder in
add_new_var_identifier act_name.name result_var builder;
(result_var, [inst])
| InScope existing_temp ->
let inst = build_reassign_op existing_temp sugared_assignment_temp builder in
(existing_temp, [inst])
in
(var_temp, exp_insts @ sugared_assigment_exp @ add_inst)
and proc_arg_list (arg_list: ('M, 'T) Flow_ast.Expression.ArgList.t) builder =
let _, unwrapped = arg_list in
let arguments = unwrapped.arguments in
let proc_exp_or_spread (exp_or_spread: ('M, 'T) Flow_ast.Expression.expression_or_spread) =
match exp_or_spread with
Expression exp ->
proc_expression exp builder
| Spread spread ->
let (_, unwrapped) = spread in
proc_expression unwrapped.argument builder in
let reg_list, unflattened_inst_list = List.split (List.map proc_exp_or_spread arguments) in
reg_list, List.flatten unflattened_inst_list
and arg_list_get_spread_list (arg_list: ('M, 'T) Flow_ast.Expression.ArgList.t) =
let _, unwrapped = arg_list in
let arguments = unwrapped.arguments in
let proc_exp_or_spread (exp_or_spread: ('M, 'T) Flow_ast.Expression.expression_or_spread) =
match exp_or_spread with
Expression exp -> false
| Spread spread -> true in
List.map proc_exp_or_spread arguments
and proc_exp_call (call_exp: ('M, 'T) Flow_ast.Expression.Call.t) builder =
let _ : unit = match call_exp.targs with
None -> ()
| Some a -> raise (Invalid_argument "Unhandled targs in call") in
let is_spread_list = arg_list_get_spread_list call_exp.arguments in
let is_spread = List.fold_left (||) false is_spread_list in
let (_, callee) = call_exp.callee in
match callee with
Flow_ast.Expression.Member member ->
(match member.property with
Flow_ast.Expression.Member.PropertyIdentifier (_, id) ->
let sub_exp_temp, sub_exp_inst = proc_expression member._object builder in
if is_spread then raise (Invalid_argument "Unhandled spread in member call") else ();
let arg_regs, arg_inst = proc_arg_list call_exp.arguments builder in
let result_var, inst = build_call_method sub_exp_temp arg_regs id.name builder in
(result_var, sub_exp_inst @ arg_inst @ [inst])
| _ ->
let callee_reg, callee_inst = proc_expression call_exp.callee builder in
let arg_regs, arg_inst = proc_arg_list call_exp.arguments builder in
let result_reg, inst = if is_spread
then
build_call_with_spread callee_reg arg_regs is_spread_list builder
else
build_call callee_reg arg_regs builder in
(result_reg, callee_inst @ arg_inst @ [inst]))
| _ -> let callee_reg, callee_inst = proc_expression call_exp.callee builder in
let arg_regs, arg_inst = proc_arg_list call_exp.arguments builder in
let result_reg, inst = if is_spread
then
build_call_with_spread callee_reg arg_regs is_spread_list builder
else
build_call callee_reg arg_regs builder in
(result_reg, callee_inst @ arg_inst @ [inst])
and proc_array_elem (elem: ('M, 'T) Flow_ast.Expression.Array.element) (builder: builder) =
match elem with
Expression e ->
let temp, inst = proc_expression e builder in
false, (temp, inst)
| Spread spread ->
let _, unwrapped = spread in
let temp, inst = proc_expression unwrapped.argument builder in
true, (temp, inst)
| Hole h ->
let result_var, inst = build_load_undefined builder in
false, (result_var, [inst])
and proc_create_array (exp: ('M, 'T) Flow_ast.Expression.Array.t) (builder: builder) =
let temp_func a = proc_array_elem a builder in
let is_spread_list, temp_list = List.split (List.map temp_func exp.elements) in
let arg_regs, arg_inst = List.split temp_list in
let flat_inst = List.flatten arg_inst in
let is_spread = List.fold_left (||) false is_spread_list in
let result_var, create_array_inst = if is_spread
then
build_create_array_with_spread arg_regs is_spread_list builder
else
build_create_array arg_regs builder
in
(result_var, flat_inst @ [create_array_inst])
and proc_create_object_property (prop_val: ('M, 'T) Flow_ast.Expression.Object.property) builder =
match prop_val with
Property (_, prop) ->
let temp_reg, prop_name_key, inst = match prop with
Init init_val ->
let temp, exp_inst = proc_expression init_val.value builder in
temp, init_val.key, exp_inst
| Set func ->
let _, act_func = func.value in
let temp, inst = proc_func act_func builder false in
temp, func.key, inst
| Get func ->
let (_, act_func) = func.value in
let temp, inst = proc_func act_func builder false in
temp, func.key, inst
| Method func ->
let (_, act_func) = func.value in
let temp, inst = proc_func act_func builder false in
temp, func.key, inst in
let prop_name : string = match prop_name_key with
Literal (_, l) -> l.raw
| Identifier (_, i) -> i.name
| PrivateName (_, p) ->
p.name
| Computed _ -> raise (Invalid_argument "Unhandled Object key type Computed Key in object creation") in
(temp_reg, [prop_name]), inst
| SpreadProperty (_, spreadProp) ->
let temp_reg, exp_inst = proc_expression spreadProp.argument builder in
(temp_reg, []), exp_inst
and proc_create_object (exp : ('M, 'T) Flow_ast.Expression.Object.t) (builder: builder) =
let props = exp.properties in
let temp_func a = proc_create_object_property a builder in
let obj_temp_tuple, create_obj_inst = List.split (List.map temp_func props) in
let obj_temp_list, obj_key_list_unflattened = List.split obj_temp_tuple in
let obj_key_list_flat = List.flatten obj_key_list_unflattened in
let flat_inst = List.flatten create_obj_inst in
let result_var, create_obj_inst = if List.length obj_key_list_flat == List.length obj_temp_list then
build_create_object obj_key_list_flat obj_temp_list builder
else
build_create_object_with_spread obj_key_list_flat obj_temp_list builder
in
(result_var, flat_inst @ [create_obj_inst])
and proc_exp_member (memb_exp: ('M, 'T) Flow_ast.Expression.Member.t) (builder: builder) =
let (sub_exp_temp, sub_exp_inst) = proc_expression memb_exp._object builder in
let return_temp, insts = match memb_exp.property with
PropertyIdentifier (_, i) ->
let result_var, load_prop_inst = build_load_prop sub_exp_temp i.name builder in
(result_var, [load_prop_inst])
| PropertyPrivateName (_, p) ->
let result_var, load_prop_inst = build_load_prop sub_exp_temp p.name builder in
(result_var, [load_prop_inst])
| PropertyExpression pe ->
let (_, unwrapped) = pe in
let opt_index = match unwrapped with
Flow_ast.Expression.Literal l ->
(match l.value with
Number n ->
if Float.is_integer n then Some (Float.to_int n) else None
| _ -> None)
| _ -> None in
match opt_index with
let result_var, load_element_inst = build_load_element sub_exp_temp n builder in
result_var, [load_element_inst]
| _ ->
let member_exp_temp, member_exp_inst = proc_expression pe builder in
let result_var, load_computed_prop_inst = build_load_computed_prop sub_exp_temp member_exp_temp builder in
(result_var, member_exp_inst @ [load_computed_prop_inst]) in
(return_temp, sub_exp_inst @ insts)
and proc_exp_new (new_exp: ('M, 'T) Flow_ast.Expression.New.t) (builder: builder) =
let callee = new_exp.callee in
let (callee_reg, callee_inst) = proc_expression callee builder in
let _ : unit = match new_exp.targs with
None -> ()
| Some a -> raise (Invalid_argument "Unhandled targs in call") in
let arguments = new_exp.arguments in
let (arg_regs, arg_inst) = match arguments with
None -> ([], [])
| Some act_args ->
(let is_spread = List.fold_left (||) false ( arg_list_get_spread_list act_args ) in
let temp, insts = proc_arg_list act_args builder in
if is_spread then raise (Invalid_argument "Unhandled spread in new")
else temp, insts)
in
let result_var, create_obj_inst = build_new_object callee_reg arg_regs builder in
(result_var, callee_inst @ arg_inst @ [create_obj_inst])
and proc_exp_this this_exp builder =
let (result_var, inst) = build_load_builtin "this" builder in
result_var, [inst]
and proc_exp_update (update_exp: (Loc.t, Loc.t) Flow_ast.Expression.Update.t) (builder: builder) =
let (sub_exp_temp, sub_exp_inst) = proc_expression update_exp.argument builder in
let update_op : unary_op = match update_exp.operator with
Increment -> if update_exp.prefix then PreInc else PostInc
| Decrement -> if update_exp.prefix then PreDec else PostDec in
let result_var, update_inst = build_unary_op sub_exp_temp update_op builder in
result_var, sub_exp_inst @ [update_inst]
and proc_exp_yield (yield_exp: (Loc.t, Loc.t) Flow_ast.Expression.Yield.t) (builder: builder) =
let sub_exp_temp, sub_exp_insts = match yield_exp.argument with
| Some exp -> proc_expression exp builder
| _ -> raise (Invalid_argument "Unhandled yield without argument") in
let yield_inst = if yield_exp.delegate
then
build_yield_each_op sub_exp_temp builder
else
build_yield_op sub_exp_temp builder
in
sub_exp_temp, sub_exp_insts @ [yield_inst]
Ternary expressions are not handled by , so convert them to an if - else
and proc_exp_conditional (cond_exp: (Loc.t, Loc.t) Flow_ast.Expression.Conditional.t) (builder: builder) =
let result_temp, zero_temp_inst = build_load_integer 0L builder in
let (test_temp, test_inst) = proc_expression cond_exp.test builder in
let begin_if_inst = build_begin_if test_temp builder in
let consequent_temp, consequest_inst = proc_expression cond_exp.consequent builder in
let consequent_reassign_inst = build_reassign_op result_temp consequent_temp builder in
let begin_else_inst = build_begin_else builder in
let alternative_temp, alternative_inst = proc_expression cond_exp.alternate builder in
let alternative_reassign_inst = build_reassign_op result_temp alternative_temp builder in
let end_if_inst = build_end_if builder in
(result_temp, [zero_temp_inst] @ test_inst @ [begin_if_inst] @ consequest_inst @ [consequent_reassign_inst] @ [begin_else_inst] @
alternative_inst @ [alternative_reassign_inst; end_if_inst])
and proc_class_method class_proto_temp builder (m: (Loc.t, Loc.t) Flow_ast.Class.Method.t) =
let _, unwrapped_method = m in
let key = unwrapped_method.key in
let method_name = match key with
Literal (_, l) -> l.raw
| Identifier (_, i) -> i.name
| PrivateName (_, p) ->
p.name
| Computed _ -> raise (Invalid_argument "Unhandled method name in class creation") in
let _, func = unwrapped_method.value in
let method_temp, method_inst = proc_func func builder false in
let load_propotype_inst = build_store_prop class_proto_temp method_temp method_name builder in
method_inst @ [load_propotype_inst]
and proc_expression (exp: ('M, 'T) Flow_ast.Expression.t) (builder: builder) =
let (_, unwrapped_exp) = exp in
match unwrapped_exp with
| (Flow_ast.Expression.Array array_op) ->
proc_create_array array_op builder
| (Flow_ast.Expression.ArrowFunction arrow_func) ->
proc_func arrow_func builder true
| (Flow_ast.Expression.Assignment assign_op) ->
proc_exp_assignment assign_op builder
| (Flow_ast.Expression.Binary bin_op) ->
proc_exp_bin_op bin_op builder
| (Flow_ast.Expression.Call call_op) ->
proc_exp_call call_op builder
| (Flow_ast.Expression.Conditional cond_exp) ->
proc_exp_conditional cond_exp builder
| (Flow_ast.Expression.Function func_exp) ->
proc_func func_exp builder false
| (Flow_ast.Expression.Identifier id_val) ->
proc_exp_id id_val builder
| (Flow_ast.Expression.Import _) ->
let var, inst = build_load_undefined builder in
var, [inst]
| (Flow_ast.Expression.Literal lit_val) ->
proc_exp_literal lit_val builder
| (Flow_ast.Expression.Logical log_op) ->
proc_exp_logical log_op builder
| (Flow_ast.Expression.Member memb_exp) ->
proc_exp_member memb_exp builder
| (Flow_ast.Expression.New new_exp) ->
proc_exp_new new_exp builder
| (Flow_ast.Expression.Object create_obj_op) ->
proc_create_object create_obj_op builder
| (Flow_ast.Expression.This this_exp) ->
proc_exp_this this_exp builder
| (Flow_ast.Expression.Unary u_val) ->
proc_exp_unary u_val builder
| (Flow_ast.Expression.Update update_exp) ->
proc_exp_update update_exp builder
| (Flow_ast.Expression.Yield yield_exp) ->
proc_exp_yield yield_exp builder
| x -> raise (Invalid_argument ("Unhandled expression type " ^ (Util.trim_flow_ast_string (Util.print_expression exp))))
and proc_var_declaration_actual (var_name: string) (init: (Loc.t, Loc.t) Flow_ast.Expression.t option) (kind: Flow_ast.Statement.VariableDeclaration.kind) (builder : builder) =
let temp_var_num, new_insts = match init with
None ->
(match kind with
Flow_ast.Statement.VariableDeclaration.Var ->
let undef_temp, undef_inst = build_load_undefined builder in
let result_var, dup_inst = build_dup_op undef_temp builder in
add_new_var_identifier var_name result_var builder;
result_var, [undef_inst; dup_inst]
| Flow_ast.Statement.VariableDeclaration.Let ->
let undef_temp, undef_inst = build_load_undefined builder in
add_new_var_identifier var_name undef_temp builder;
undef_temp, [undef_inst]
| _ -> raise (Invalid_argument "Empty const declaration"))
| Some exp -> proc_expression exp builder in
let reassign_inst = (match kind with
Flow_ast.Statement.VariableDeclaration.Var ->
let is_hoisted = is_hoisted_var var_name builder in
if is_hoisted then
let hoisted_temp = lookup_var_name builder var_name in
match hoisted_temp with
NotFound -> raise (Invalid_argument "Unfound hoisted temp")
| InScope temp ->
let inst = build_reassign_op temp temp_var_num builder in
[inst]
else
(add_new_var_identifier var_name temp_var_num builder;
[])
| _ ->
add_new_var_identifier var_name temp_var_num builder;
[])
in
new_insts @ reassign_inst
and proc_handle_single_var_declaration (dec : (Loc.t, Loc.t) Flow_ast.Statement.VariableDeclaration.Declarator.t') (kind: Flow_ast.Statement.VariableDeclaration.kind) (builder : builder) =
let foo = match dec.id, dec.init with
(_, (Flow_ast.Pattern.Identifier id)), exp ->
let (_, act_name) = id.name in
proc_var_declaration_actual act_name.name exp kind builder
| (_, (Flow_ast.Pattern.Array arr)), (Some (_, Flow_ast.Expression.Array exp)) ->
let get_name (a: ('M, 'T) Flow_ast.Pattern.Array.element) =
match a with
Element (_, e) ->
(match e.argument with
(_, (Flow_ast.Pattern.Identifier x)) ->
let var_id = x.name in
let (_, act_name) = var_id in
act_name.name
| _ -> raise (Invalid_argument "Improper args in variable declaration"))
| _ -> raise (Invalid_argument "Improper args in variable declaration") in
let id_elems = List.map get_name arr.elements in
let get_elem (e: (Loc.t, Loc.t) Flow_ast.Expression.Array.element) =
match e with
Expression exp -> exp
| _ -> raise (Invalid_argument "Improper args in variable declaration") in
let elems = List.map get_elem exp.elements in
let process id elem = proc_var_declaration_actual id (Some elem) kind builder in
List.map2 process id_elems elems |> List.flatten
| _, _ -> raise (Invalid_argument "Improper args in variable declaration") in
foo
and proc_var_dec_declarators (decs : (Loc.t, Loc.t) Flow_ast.Statement.VariableDeclaration.Declarator.t list) (kind: Flow_ast.Statement.VariableDeclaration.kind) (builder : builder) =
match decs with
[] -> []
| (_, declarator) :: tl ->
proc_handle_single_var_declaration declarator kind builder @ (proc_var_dec_declarators tl kind builder)
and proc_var_decl_statement (var_decl: (Loc.t, Loc.t) Flow_ast.Statement.VariableDeclaration.t) (builder: builder) =
let decs = var_decl.declarations in
let kind = var_decl.kind in
proc_var_dec_declarators decs kind builder
and proc_if_statement (if_statement: (Loc.t, Loc.t) Flow_ast.Statement.If.t) (builder: builder) =
let test = if_statement.test in
let (test_temp_val, test_inst) = proc_expression test builder in
let begin_if_inst = build_begin_if test_temp_val builder in
push_local_scope builder;
let consequent_statements = proc_single_statement if_statement.consequent builder in
pop_local_scope builder;
Fuzzilli requires an else for each if , due to how AbstractInterpreter works
let begin_else_inst = build_begin_else builder in
push_local_scope builder;
let fin_statement = match if_statement.alternate with
None -> []
| Some (_, alt) ->
let alt_inst = proc_single_statement alt.body builder in
alt_inst in
pop_local_scope builder;
let end_if_inst = build_end_if builder in
test_inst @ begin_if_inst :: consequent_statements @ [begin_else_inst] @ fin_statement @ [end_if_inst]
and proc_while (while_statement: (Loc.t, Loc.t) Flow_ast.Statement.While.t) (builder: builder) =
let test_exp_reg, test_exp_inst = proc_expression while_statement.test builder in
let pre_loop_inst = test_exp_inst in
let zero_temp, zero_temp_inst = build_load_integer 0L builder in
let begin_while_inst = build_begin_while test_exp_reg zero_temp NotEqual builder in
let begin_loop_inst = zero_temp_inst :: [begin_while_inst] in
push_local_scope builder;
let body_statement = proc_single_statement while_statement.body builder in
pop_local_scope builder;
let test_exp_reg_internal, test_exp_inst_internal = proc_expression while_statement.test builder in
let reassign_inst = build_reassign_op test_exp_reg test_exp_reg_internal builder in
let re_exec_test_exp = test_exp_inst_internal @ [reassign_inst] in
let end_while_inst = build_end_while builder in
pre_loop_inst @ begin_loop_inst @ body_statement @ re_exec_test_exp @ [end_while_inst]
and proc_do_while (do_while_statement: (Loc.t, Loc.t) Flow_ast.Statement.DoWhile.t) (builder: builder) =
let zero_temp, zero_temp_inst = build_load_integer 0L builder in
let intermed, dup_inst = build_dup_op zero_temp builder in
let begin_while_inst = build_begin_do_while intermed zero_temp NotEqual builder in
push_local_scope builder;
let body_statement = proc_single_statement do_while_statement.body builder in
pop_local_scope builder;
let test_exp_reg_internal, test_exp_inst_internal = proc_expression do_while_statement.test builder in
let reassign_inst = build_reassign_op intermed test_exp_reg_internal builder in
let re_exec_test_exp = test_exp_inst_internal @ [reassign_inst] in
let end_while_inst = build_end_do_while builder in
[zero_temp_inst; dup_inst; begin_while_inst] @ body_statement @ re_exec_test_exp @ [end_while_inst]
and proc_try (try_statement: (Loc.t, Loc.t) Flow_ast.Statement.Try.t) (builder: builder) =
let try_inst = build_begin_try_op builder in
push_local_scope builder;
let (_, try_block) = try_statement.block in
let block_inst = proc_statements try_block.body builder in
let catch_inst, catch_body_inst = match try_statement.handler with
None -> raise (Invalid_argument "Empty catch")
| Some (_, catch_clause) ->
let temp_name = match catch_clause.param with
| Some (_, (Flow_ast.Pattern.Identifier var_identifier)) ->
let (_, act_name) = var_identifier.name in
act_name.name
| _ -> raise (Invalid_argument "Unsupported catch type")
in
let (_, catch_cause_block) = catch_clause.body in
let catch_body_inst = proc_statements catch_cause_block.body builder in
let catch_inst = build_begin_catch_op temp_name builder in
(catch_inst, catch_body_inst)
in
let finalizer_inst = match try_statement.finalizer with
None -> []
| Some (_, fin_block) -> proc_statements fin_block.body builder in
pop_local_scope builder;
let end_try_catch_inst = build_end_try_catch_op builder in
[try_inst] @ block_inst @ [catch_inst] @ catch_body_inst @ [end_try_catch_inst] @ finalizer_inst
and proc_func (func: (Loc.t, Loc.t) Flow_ast.Function.t) (builder : builder) (is_arrow: bool) =
let func_name_opt = match func.id with
None -> None
| Some (_, id) ->
Some id.name
in
let param_to_id (input: ('M, 'T) Flow_ast.Function.Param.t) =
let (_, unwrapped_input) = input in
let pattern = unwrapped_input.argument in
let (_, act_name) = match pattern with
(_, (Flow_ast.Pattern.Identifier x)) -> x.name
| _ -> raise (Invalid_argument "Didn't get an Identifier when expected in function declaration") in
act_name.name in
let (_, unwrapped_param) = func.params in
let param_ids = List.map param_to_id unwrapped_param.params in
let rest_arg_name_opt = match unwrapped_param.rest with
None -> None
| Some (_, rest_id) ->
let act_id = rest_id.argument in
let (_, id_string) = match act_id with
(_, (Flow_ast.Pattern.Identifier x)) -> x.name
| _ -> raise (Invalid_argument "Unhandled rest temp") in
Some id_string.name
in
let func_temp = get_new_intermed_temp builder in
(match func_name_opt with
Some name ->
if is_hoisted_var name builder then
()
else
add_new_var_identifier name func_temp builder;
| _ -> ());
push_local_scope builder;
let func_temp, begin_func_inst, end_func_inst = build_func_ops func_temp param_ids rest_arg_name_opt is_arrow func.async func.generator builder in
let func_inst = match func.body with
BodyBlock body_block ->
let _, state_block = body_block in
let hoisted_statements = handle_varHoist state_block.body builder in
hoisted_statements @ proc_statements state_block.body builder
| BodyExpression body_exp ->
let _, inst = proc_expression body_exp builder in
inst
in
pop_local_scope builder;
let reassign_inst = (match func_name_opt with
Some name ->
if is_hoisted_var name builder then
match (lookup_var_name builder name) with
NotFound -> raise (Invalid_argument "Hoisted func not found")
| InScope x -> [build_reassign_op x func_temp builder]
else
[]
| _ -> []) in
func_temp, [begin_func_inst] @ func_inst @ [end_func_inst] @ reassign_inst
and proc_return (ret_state: (Loc.t, Loc.t) Flow_ast.Statement.Return.t) (builder: builder) =
let return_var, return_insts = match ret_state.argument with
None ->
let temp, inst = build_load_undefined builder in
temp, [inst]
| Some exp ->
let temp_num, insts = proc_expression exp builder in
temp_num, insts
in
let return_inst = build_return_op return_var builder in
return_insts @ [return_inst]
and proc_with (with_state: (Loc.t, Loc.t) Flow_ast.Statement.With.t) (builder: builder) =
let result_var, with_insts = proc_expression with_state._object builder in
let begin_with_inst = build_begin_with_op result_var builder in
let body_insts = proc_single_statement with_state.body builder in
let end_with_inst = build_end_with_op builder in
with_insts @ [begin_with_inst] @ body_insts @ [end_with_inst]
and proc_throw (throw_state: (Loc.t, Loc.t) Flow_ast.Statement.Throw.t) (builder: builder) =
let temp, inst = proc_expression throw_state.argument builder in
let throw_inst = build_throw_op temp builder in
inst @ [throw_inst]
and proc_break builder =
TODO switch_break_op
and proc_for_in (for_in_state: (Loc.t, Loc.t) Flow_ast.Statement.ForIn.t) (builder: builder) =
let right_temp, right_inst = proc_expression for_in_state.right builder in
push_local_scope builder;
let var_temp, end_of_loop_cleanup_inst = match for_in_state.left with
LeftDeclaration (_, d) ->
let decs = d.declarations in
(match decs with
[(_, declarator)] -> ( match declarator.id with
(_, (Flow_ast.Pattern.Identifier id)) ->
let (_, id_type) = id.name in
let left_temp = get_new_intermed_temp builder in
add_new_var_identifier id_type.name left_temp builder;
left_temp, []
| _ -> raise (Invalid_argument ("Improper declaration in for-in loop")))
| _ -> raise (Invalid_argument "Improper declaration in for-in loop"))
| LeftPattern p -> (match p with
(_, (Flow_ast.Pattern.Identifier id)) ->
let (_, id_type) = id.name in
let lookup = lookup_var_name builder id_type.name in
(match lookup with
InScope x ->
let left_temp = get_new_intermed_temp builder in
add_new_var_identifier id_type.name left_temp builder;
let reassign_inst = build_reassign_op x left_temp builder in
left_temp, [reassign_inst]
| NotFound ->
let left_temp = get_new_intermed_temp builder in
add_new_var_identifier id_type.name left_temp builder;
left_temp, [] )
| _ -> raise (Invalid_argument ("Inproper left pattern in for-in loop"))) in
let _, start_for_in_inst = build_begin_for_in_op var_temp right_temp builder in
let body_inst = proc_single_statement for_in_state.body builder in
let end_for_in = build_end_for_in_op builder in
pop_local_scope builder;
right_inst @ [start_for_in_inst] @ body_inst @ end_of_loop_cleanup_inst @ [end_for_in];
and proc_for_of (for_of_state: (Loc.t, Loc.t) Flow_ast.Statement.ForOf.t) (builder: builder) =
let right_temp, right_inst = proc_expression for_of_state.right builder in
push_local_scope builder;
let var_id = match for_of_state.left with
LeftDeclaration (_, d) ->
let decs = d.declarations in
(match decs with
[(_, declarator)] -> ( match declarator.id with
(_, (Flow_ast.Pattern.Identifier x)) -> x
| _ -> raise (Invalid_argument ("Improper declaration in for-of loop")))
| _ -> raise (Invalid_argument "Improper declaration in for-of loop"))
| LeftPattern p -> (match p with
(_, (Flow_ast.Pattern.Identifier id)) -> id
| _ -> raise (Invalid_argument ("Inproper left pattern in for-of loop"))) in
let (_, act_name) = var_id.name in
let left_temp, start_for_of_inst = build_begin_for_of_op right_temp builder in
add_new_var_identifier act_name.name left_temp builder;
let body_inst = proc_single_statement for_of_state.body builder in
let end_for_of_inst = build_end_for_of_op builder in
right_inst @ [start_for_of_inst] @ body_inst @ [end_for_of_inst];
Fuzzilli For loops in only
and proc_for (for_state: (Loc.t, Loc.t) Flow_ast.Statement.For.t) (builder: builder) =
let init_inst = match for_state.init with
None -> []
| Some (InitDeclaration (_, decl)) -> proc_var_decl_statement decl builder
| Some (InitExpression exp) ->
let (_, exp_insts) = proc_expression exp builder in
exp_insts
in
let test_exp_reg, test_exp_inst = match for_state.test with
Some exp -> proc_expression exp builder
| None -> raise (Invalid_argument "Unhandled empty for-loop test") in
let pre_loop_inst = test_exp_inst in
push_local_scope builder;
let zero_temp, zero_temp_inst = build_load_integer 0L builder in
let begin_while_inst = build_begin_while test_exp_reg zero_temp NotEqual builder in
let begin_loop_inst = zero_temp_inst :: [begin_while_inst] in
let body_insts = proc_single_statement for_state.body builder in
let update_insts = match for_state.update with
None -> []
| Some exp ->
let (_, exp_insts) = proc_expression exp builder
in exp_insts in
Redo the check
let test_exp_reg_internal, test_exp_inst_internal = match for_state.test with
Some exp -> proc_expression exp builder
| None -> raise (Invalid_argument "Unhandled empty for-loop test") in
let reassign_inst = build_reassign_op test_exp_reg test_exp_reg_internal builder in
let re_exec_test_exp = test_exp_inst_internal @ [reassign_inst] in
let end_while_inst = build_end_while builder in
pop_local_scope builder;
init_inst @ pre_loop_inst @ begin_loop_inst @ body_insts @ update_insts @ re_exec_test_exp @ [end_while_inst]
and proc_continue builder =
[build_continue builder]
and proc_single_statement (statement: (Loc.t, Loc.t) Flow_ast.Statement.t) builder =
match statement with
(_, Flow_ast.Statement.Block state_block) -> proc_statements state_block.body builder
| (_, Flow_ast.Statement.Break _) -> proc_break builder
| (_, Flow_ast.Statement.Continue state_continue) -> proc_continue builder
| (_, Flow_ast.Statement.DoWhile state_do_while) -> proc_do_while state_do_while builder
| (_, Flow_ast.Statement.Empty _) -> []
| (_, Flow_ast.Statement.Expression state_exp) ->
let (_, inst) = proc_expression state_exp.expression builder in
inst
| (_, Flow_ast.Statement.For state_for) -> proc_for state_for builder
| (_, Flow_ast.Statement.ForIn state_foin) -> proc_for_in state_foin builder
| (_, Flow_ast.Statement.ForOf state_forof) -> proc_for_of state_forof builder
| (_, Flow_ast.Statement.FunctionDeclaration func_def) ->
let (_, res) = proc_func func_def builder false in
res
| (_, Flow_ast.Statement.If state_if) -> proc_if_statement state_if builder
| (_, Flow_ast.Statement.ImportDeclaration _) -> []
| (_, Flow_ast.Statement.Return state_return) -> proc_return state_return builder
| (_, Flow_ast.Statement.Throw state_throw) -> proc_throw state_throw builder
| (_, Flow_ast.Statement.Try state_try) -> proc_try state_try builder
| (_ , VariableDeclaration decl) -> proc_var_decl_statement decl builder
| (_, Flow_ast.Statement.While state_while) -> proc_while state_while builder
| (_, Flow_ast.Statement.With state_with) -> proc_with state_with builder
| _ as s -> raise (Invalid_argument (Printf.sprintf "Unhandled statement type %s" (Util.trim_flow_ast_string (Util.print_statement s))))
and proc_statements (statements: (Loc.t, Loc.t) Flow_ast.Statement.t list) (var_builder: builder) =
match statements with
[] -> []
| hd :: tl ->
let new_statement = proc_single_statement hd var_builder in
new_statement @ proc_statements tl var_builder
let flow_ast_to_inst_list (prog: (Loc.t, Loc.t) Flow_ast.Program.t) emit_builtins include_v8_natives use_placeholder =
let init_var_builder = init_builder emit_builtins include_v8_natives use_placeholder in
let (_, prog_t) = prog in
let hoisted_funcs = handle_varHoist prog_t.statements init_var_builder in
let proced_statements = hoisted_funcs @ proc_statements prog_t.statements init_var_builder in
let proced_statements_converted = List.map inst_to_prog_inst proced_statements in
proced_statements_converted
|
372b62aab38fb8337a71b50c4005a2c9d2fbc81df9eaa13eb68007d009e58715 | tolysz/ghcjs-stack | Simple.hs | module Simple where
-- | For hiding needles.
data Haystack = Haystack
| null | https://raw.githubusercontent.com/tolysz/ghcjs-stack/83d5be83e87286d984e89635d5926702c55b9f29/special/cabal/Cabal/tests/PackageTests/Haddock/Simple.hs | haskell | | For hiding needles. | module Simple where
data Haystack = Haystack
|
76ed91da52ef4d7ae9d5b1bfa558fd78ecf777103642cd16b8660ada64c1d201 | vseloved/rutils | packages.lisp | ;;;;; RUTILSX package definitions
;;;;; see LICENSE file for permissions
(cl:in-package :cl-user)
(defpackage #:rutilsx.generators
(:documentation "Python-like generators (yield) support.")
(:use :common-lisp #:rtl)
(:export #:doing
#:force
#:generated
#:generated-item
#:yield
#:yield-to))
(defpackage #:rutilsx.readtable
(:documentation "Additional reader syntax support.")
(:use :common-lisp #:rtl)
(:export #:rutilsx-readtable))
(defpackage #:rutilsx
(:documentation "The whole set of utilities in one package.")
(:use :common-lisp))
| null | https://raw.githubusercontent.com/vseloved/rutils/db3c3f4ae897025b5f0cd81042ca147da60ca0c5/contrib/packages.lisp | lisp | RUTILSX package definitions
see LICENSE file for permissions |
(cl:in-package :cl-user)
(defpackage #:rutilsx.generators
(:documentation "Python-like generators (yield) support.")
(:use :common-lisp #:rtl)
(:export #:doing
#:force
#:generated
#:generated-item
#:yield
#:yield-to))
(defpackage #:rutilsx.readtable
(:documentation "Additional reader syntax support.")
(:use :common-lisp #:rtl)
(:export #:rutilsx-readtable))
(defpackage #:rutilsx
(:documentation "The whole set of utilities in one package.")
(:use :common-lisp))
|
9b53710c3cf5a5aadc393cc2dbbe7a9aa945f4e3c3ab56fcc3671c473433d268 | carl-eastlund/dracula | module.rkt | #lang racket/base
(require
mzlib/etc
racket/require
(path-up "self/require.rkt")
(cce-in require-provide)
"keywords.rkt"
"dynamic-rep.rkt"
"../lang/defun.rkt"
"../lang/do-check.rkt"
"../lang/theorems.rkt"
(for-syntax
racket/base
racket/list
racket/match
racket/block
syntax/parse
syntax/boundmap
racket/require-transform
(cce-in syntax)
(cce-in values)
(cce-in text)
(path-up "self/module-path.rkt")
"static-rep.rkt"
"syntax-meta.rkt"
"../proof/proof.rkt"
"../proof/syntax.rkt"))
(provide module-macro)
(define-for-syntax (matcher . ids)
(let* ([table (make-free-identifier-mapping)])
(for ([id ids])
(free-identifier-mapping-put! table id #t))
(lambda (stx)
(syntax-case stx ()
[(name . _)
(identifier? #'name)
(free-identifier-mapping-get table #'name (lambda () #f))]
[_ #f]))))
(define-for-syntax (expand-module-export port id)
(let* ([source (port/static-source port)]
[concrete (export/static-concrete port)]
[internals (port/static-sig-names/internal port)]
[externals (port/static-sig-names/external port)]
[arguments (port/static-sig-args port)])
(with-syntax ([exp/dynamic id]
[(put ...) (reloc* #:src source externals)]
[(get ...) (reloc* #:src source internals)])
(values
concrete
(syntax/loc source
(define-values ()
(begin
(for ([sym (in-list '(put ...))]
[fun (in-list (unchecked-arity (list get ...)))])
(interface/dynamic-put-function! exp/dynamic sym fun))
(values))))
#'(begin)))))
(define-for-syntax (expand-module-import port id)
(let* ([source (port/static-source port)]
[abstract (import/static-abstract port)]
[internals (port/static-sig-names/internal port)]
[externals (port/static-sig-names/external port)]
[arguments (port/static-sig-args port)]
[axioms (port/static-con-names/internal port)])
(with-syntax ([imp/dynamic id]
[(get ...) (reloc* #:src source externals)]
[(put ...) (reloc* #:src source internals)]
[(tmp ...) (reloc* #:src source
(fresh-ids externals))]
[(args ...) (map (lambda (arg) (reloc* #:src source arg))
arguments)]
[axs axioms])
(values
abstract
(syntax/loc source
(begin
(define-values [tmp ...]
(apply values
(for/list ([sym (in-list '(get ...))])
(interface/dynamic-get-function imp/dynamic sym))))
combining multiple imported functions into one definition
(mutual-recursion (defun put args (tmp . args)) ...)
combining multiple imported axioms / theorems into one definition
(define-theorems "axiom" . axs)))
#'(begin)))))
(define-for-syntax (expand-definition stx)
(syntax-case* stx (include-book :dir :system :teachpacks) text=?
[(include-book file :dir :teachpacks)
(string-literal? #'file)
(let*-values ([(module-path)
(dracula-teachpack-syntax #:stx stx
(string-append (syntax-e #'file) ".rkt"))]
[(imports sources) (expand-import module-path)]
[(names) (map import-local-id imports)])
(with-syntax ([spec module-path]
[(name ...) names]
[(temp ...) (fresh-ids names)])
(values stx
(syntax/loc stx (rename-below [temp name] ...))
(syntax/loc stx (require (rename-in spec [name temp] ...))))))]
[(include-book file :dir :system)
(string-literal? #'file)
(values stx (syntax/loc stx (begin)) (syntax/loc stx (begin)))]
[(include-book file)
(string-literal? #'file)
(syntax-error
stx
"modules cannot include local books; convert the book to a module")]
[(include-book . _)
(syntax-error
stx
"expected a book name with :dir :system or :dir :teachpacks")]
[_ (values stx stx (syntax/loc stx (begin)))]))
(define-for-syntax (expand-module-body imp exp body)
(cond
[(import/static? body) (expand-module-import body imp)]
[(export/static? body) (expand-module-export body exp)]
[else (expand-definition body)]))
(define-syntax (define-dynamic stx)
(syntax-case stx ()
[(_ static-name dynamic-name)
(let* ([import-name #'imp/dynamic]
[export-name #'exp/dynamic]
[mod (syntax->meta #:message "not a module" #'static-name)]
[source (module/static-source mod)])
(let*-values ([(defs runs reqs)
(for/lists [defs runs reqs]
([stx (in-list (module/static-body mod))])
(expand-module-body import-name export-name stx))])
(with-syntax ([(run ...) runs]
[(req ...) reqs])
(annotate-part
(make-part
(syntax-e #'static-name)
(syntax->loc stx)
(map syntax->term defs))
(syntax/loc source
(begin
req ...
(define dynamic-name
(make-module/dynamic
(lambda (imp/dynamic)
(define exp/dynamic (empty-interface/dynamic))
(begin-below run ...)
(interface/dynamic-join
exp/dynamic
imp/dynamic))))))))))]))
(define-for-syntax (parse-port make-port/static rev-ports stx)
(syntax-case stx ()
[(_ ifc [ext int] ...)
(let* ([ifc (syntax->meta #:message "not an interface" #'ifc)])
(make-port/static
stx
ifc
(map cons
(syntax->list #'(ext ...))
(syntax->list #'(int ...)))
(map (lambda (inc)
(or
(findf (lambda (port)
(interface/static-external=?
inc (port/static-interface port)))
rev-ports)
(syntax-error stx
"no im/export of ~a (required by ~a)"
(syntax-e (interface/static-name inc))
(syntax-e (interface/static-name ifc)))))
(interface/static-includes ifc))))]))
(define-for-syntax (parse-body prior stxs)
(match stxs
[(list) (list)]
[(list* stx stxs)
(syntax-case stx (import export)
[(import . _)
(block
(define port
(parse-port
make-import/static
(filter import/static? prior)
stx))
(cons port
(parse-body (cons port prior) stxs)))]
[(export . _)
(block
(define port
(parse-port
make-export/static
prior
stx))
(cons port
(parse-body (cons port prior) stxs)))]
[_ (cons stx (parse-body prior stxs))])]))
(define-syntax (define-static stx)
(syntax-case stx ()
[(_ static-name dynamic-name original def ...)
(syntax/loc #'original
(define-syntax static-name
(make-syntax-meta
(make-module/static
#'static-name
#'dynamic-name
#'original
(parse-body null (list (quote-syntax def) ...)))
(expand-keyword "cannot be used as an expression"))))]))
(define-for-syntax (expand-module stx)
(parameterize ([current-syntax stx])
(syntax-case stx ()
[(_ static-name . body)
(parameterize ([current-syntax stx])
(with-syntax ([original stx])
(syntax/loc stx
(begin
(define-static static-name dynamic-name original . body)
(define-dynamic static-name dynamic-name)))))])))
(define-syntax module-macro expand-module)
| null | https://raw.githubusercontent.com/carl-eastlund/dracula/a937f4b40463779246e3544e4021c53744a33847/modular/module.rkt | racket | #lang racket/base
(require
mzlib/etc
racket/require
(path-up "self/require.rkt")
(cce-in require-provide)
"keywords.rkt"
"dynamic-rep.rkt"
"../lang/defun.rkt"
"../lang/do-check.rkt"
"../lang/theorems.rkt"
(for-syntax
racket/base
racket/list
racket/match
racket/block
syntax/parse
syntax/boundmap
racket/require-transform
(cce-in syntax)
(cce-in values)
(cce-in text)
(path-up "self/module-path.rkt")
"static-rep.rkt"
"syntax-meta.rkt"
"../proof/proof.rkt"
"../proof/syntax.rkt"))
(provide module-macro)
(define-for-syntax (matcher . ids)
(let* ([table (make-free-identifier-mapping)])
(for ([id ids])
(free-identifier-mapping-put! table id #t))
(lambda (stx)
(syntax-case stx ()
[(name . _)
(identifier? #'name)
(free-identifier-mapping-get table #'name (lambda () #f))]
[_ #f]))))
(define-for-syntax (expand-module-export port id)
(let* ([source (port/static-source port)]
[concrete (export/static-concrete port)]
[internals (port/static-sig-names/internal port)]
[externals (port/static-sig-names/external port)]
[arguments (port/static-sig-args port)])
(with-syntax ([exp/dynamic id]
[(put ...) (reloc* #:src source externals)]
[(get ...) (reloc* #:src source internals)])
(values
concrete
(syntax/loc source
(define-values ()
(begin
(for ([sym (in-list '(put ...))]
[fun (in-list (unchecked-arity (list get ...)))])
(interface/dynamic-put-function! exp/dynamic sym fun))
(values))))
#'(begin)))))
(define-for-syntax (expand-module-import port id)
(let* ([source (port/static-source port)]
[abstract (import/static-abstract port)]
[internals (port/static-sig-names/internal port)]
[externals (port/static-sig-names/external port)]
[arguments (port/static-sig-args port)]
[axioms (port/static-con-names/internal port)])
(with-syntax ([imp/dynamic id]
[(get ...) (reloc* #:src source externals)]
[(put ...) (reloc* #:src source internals)]
[(tmp ...) (reloc* #:src source
(fresh-ids externals))]
[(args ...) (map (lambda (arg) (reloc* #:src source arg))
arguments)]
[axs axioms])
(values
abstract
(syntax/loc source
(begin
(define-values [tmp ...]
(apply values
(for/list ([sym (in-list '(get ...))])
(interface/dynamic-get-function imp/dynamic sym))))
combining multiple imported functions into one definition
(mutual-recursion (defun put args (tmp . args)) ...)
combining multiple imported axioms / theorems into one definition
(define-theorems "axiom" . axs)))
#'(begin)))))
(define-for-syntax (expand-definition stx)
(syntax-case* stx (include-book :dir :system :teachpacks) text=?
[(include-book file :dir :teachpacks)
(string-literal? #'file)
(let*-values ([(module-path)
(dracula-teachpack-syntax #:stx stx
(string-append (syntax-e #'file) ".rkt"))]
[(imports sources) (expand-import module-path)]
[(names) (map import-local-id imports)])
(with-syntax ([spec module-path]
[(name ...) names]
[(temp ...) (fresh-ids names)])
(values stx
(syntax/loc stx (rename-below [temp name] ...))
(syntax/loc stx (require (rename-in spec [name temp] ...))))))]
[(include-book file :dir :system)
(string-literal? #'file)
(values stx (syntax/loc stx (begin)) (syntax/loc stx (begin)))]
[(include-book file)
(string-literal? #'file)
(syntax-error
stx
"modules cannot include local books; convert the book to a module")]
[(include-book . _)
(syntax-error
stx
"expected a book name with :dir :system or :dir :teachpacks")]
[_ (values stx stx (syntax/loc stx (begin)))]))
(define-for-syntax (expand-module-body imp exp body)
(cond
[(import/static? body) (expand-module-import body imp)]
[(export/static? body) (expand-module-export body exp)]
[else (expand-definition body)]))
(define-syntax (define-dynamic stx)
(syntax-case stx ()
[(_ static-name dynamic-name)
(let* ([import-name #'imp/dynamic]
[export-name #'exp/dynamic]
[mod (syntax->meta #:message "not a module" #'static-name)]
[source (module/static-source mod)])
(let*-values ([(defs runs reqs)
(for/lists [defs runs reqs]
([stx (in-list (module/static-body mod))])
(expand-module-body import-name export-name stx))])
(with-syntax ([(run ...) runs]
[(req ...) reqs])
(annotate-part
(make-part
(syntax-e #'static-name)
(syntax->loc stx)
(map syntax->term defs))
(syntax/loc source
(begin
req ...
(define dynamic-name
(make-module/dynamic
(lambda (imp/dynamic)
(define exp/dynamic (empty-interface/dynamic))
(begin-below run ...)
(interface/dynamic-join
exp/dynamic
imp/dynamic))))))))))]))
(define-for-syntax (parse-port make-port/static rev-ports stx)
(syntax-case stx ()
[(_ ifc [ext int] ...)
(let* ([ifc (syntax->meta #:message "not an interface" #'ifc)])
(make-port/static
stx
ifc
(map cons
(syntax->list #'(ext ...))
(syntax->list #'(int ...)))
(map (lambda (inc)
(or
(findf (lambda (port)
(interface/static-external=?
inc (port/static-interface port)))
rev-ports)
(syntax-error stx
"no im/export of ~a (required by ~a)"
(syntax-e (interface/static-name inc))
(syntax-e (interface/static-name ifc)))))
(interface/static-includes ifc))))]))
(define-for-syntax (parse-body prior stxs)
(match stxs
[(list) (list)]
[(list* stx stxs)
(syntax-case stx (import export)
[(import . _)
(block
(define port
(parse-port
make-import/static
(filter import/static? prior)
stx))
(cons port
(parse-body (cons port prior) stxs)))]
[(export . _)
(block
(define port
(parse-port
make-export/static
prior
stx))
(cons port
(parse-body (cons port prior) stxs)))]
[_ (cons stx (parse-body prior stxs))])]))
(define-syntax (define-static stx)
(syntax-case stx ()
[(_ static-name dynamic-name original def ...)
(syntax/loc #'original
(define-syntax static-name
(make-syntax-meta
(make-module/static
#'static-name
#'dynamic-name
#'original
(parse-body null (list (quote-syntax def) ...)))
(expand-keyword "cannot be used as an expression"))))]))
(define-for-syntax (expand-module stx)
(parameterize ([current-syntax stx])
(syntax-case stx ()
[(_ static-name . body)
(parameterize ([current-syntax stx])
(with-syntax ([original stx])
(syntax/loc stx
(begin
(define-static static-name dynamic-name original . body)
(define-dynamic static-name dynamic-name)))))])))
(define-syntax module-macro expand-module)
| |
bf2b3c989e898d5f2c755dea6378d449672bdfb7136449777bf356106d18e583 | haskell/xhtml | Internals.hs | {-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.XHtml.internals
Copyright : ( c ) , and the Oregon Graduate Institute of
Science and Technology , 1999 - 2001 ,
( c ) , 2004 - 2006
-- License : BSD-style (see the file LICENSE)
Maintainer : < >
-- Stability : Stable
Portability : Portable
--
-- Internals of the XHTML combinator library.
-----------------------------------------------------------------------------
module Text.XHtml.Internals where
import Data.Char
import qualified Data.Semigroup as Sem
import qualified Data.Monoid as Mon
infixr 2 +++ -- combining Html
infixr 7 << -- nesting Html
infixl 8 ! -- adding optional arguments
--
-- * Data types
--
-- | A important property of Html is that all strings inside the
-- structure are already in Html friendly format.
data HtmlElement
= HtmlString String
-- ^ ..just..plain..normal..text... but using © and &amb;, etc.
| HtmlTag {
markupTag :: String,
markupAttrs :: [HtmlAttr],
markupContent :: Html
}
-- ^ tag with internal markup
-- | Attributes with name and value.
data HtmlAttr = HtmlAttr String String
htmlAttrPair :: HtmlAttr -> (String,String)
htmlAttrPair (HtmlAttr n v) = (n,v)
newtype Html = Html { getHtmlElements :: [HtmlElement] }
--
-- * Classes
--
instance Show Html where
showsPrec _ html = showString (renderHtmlFragment html)
showList htmls = foldr (.) id (map shows htmls)
instance Show HtmlAttr where
showsPrec _ (HtmlAttr str val) =
showString str .
showString "=" .
shows val
| @since 3000.2.2
instance Sem.Semigroup Html where
(<>) = (+++)
instance Mon.Monoid Html where
mempty = noHtml
mappend = (Sem.<>)
-- | HTML is the class of things that can be validly put
inside an HTML tag . So this can be one or more ' Html ' elements ,
-- or a 'String', for example.
class HTML a where
toHtml :: a -> Html
toHtmlFromList :: [a] -> Html
toHtmlFromList xs = Html (concat [ x | (Html x) <- map toHtml xs])
instance HTML Html where
toHtml a = a
instance HTML Char where
toHtml a = toHtml [a]
toHtmlFromList [] = Html []
toHtmlFromList str = Html [HtmlString (stringToHtmlString str)]
instance (HTML a) => HTML [a] where
toHtml xs = toHtmlFromList xs
instance HTML a => HTML (Maybe a) where
toHtml = maybe noHtml toHtml
class ADDATTRS a where
(!) :: a -> [HtmlAttr] -> a
-- | CHANGEATTRS is a more expressive alternative to ADDATTRS
class CHANGEATTRS a where
changeAttrs :: a -> ([HtmlAttr]->[HtmlAttr]) -> a
instance (ADDATTRS b) => ADDATTRS (a -> b) where
fn ! attr = \ arg -> fn arg ! attr
instance (CHANGEATTRS b) => CHANGEATTRS (a -> b) where
changeAttrs fn f = \ arg -> changeAttrs (fn arg) f
instance ADDATTRS Html where
(Html htmls) ! attr = Html (map addAttrs htmls)
where
addAttrs (html@(HtmlTag { markupAttrs = attrs }) )
= html { markupAttrs = attrs ++ attr }
addAttrs html = html
instance CHANGEATTRS Html where
changeAttrs (Html htmls) f = Html (map addAttrs htmls)
where
addAttrs (html@(HtmlTag { markupAttrs = attrs }) )
= html { markupAttrs = f attrs }
addAttrs html = html
--
-- * Html primitives and basic combinators
--
-- | Put something inside an HTML element.
(<<) :: (HTML a) =>
(Html -> b) -- ^ Parent
-> a -- ^ Child
-> b
fn << arg = fn (toHtml arg)
concatHtml :: (HTML a) => [a] -> Html
concatHtml as = Html (concat (map (getHtmlElements.toHtml) as))
-- | Create a piece of HTML which is the concatenation
of two things which can be made into HTML .
(+++) :: (HTML a,HTML b) => a -> b -> Html
a +++ b = Html (getHtmlElements (toHtml a) ++ getHtmlElements (toHtml b))
-- | An empty piece of HTML.
noHtml :: Html
noHtml = Html []
-- | Checks whether the given piece of HTML is empty.
isNoHtml :: Html -> Bool
isNoHtml (Html xs) = null xs
-- | Constructs an element with a custom name.
tag :: String -- ^ Element name
-> Html -- ^ Element contents
-> Html
tag str htmls = Html [
HtmlTag {
markupTag = str,
markupAttrs = [],
markupContent = htmls }]
-- | Constructs an element with a custom name, and
-- without any children.
itag :: String -> Html
itag str = tag str noHtml
emptyAttr :: String -> HtmlAttr
emptyAttr s = HtmlAttr s s
intAttr :: String -> Int -> HtmlAttr
intAttr s i = HtmlAttr s (show i)
strAttr :: String -> String -> HtmlAttr
strAttr s t = HtmlAttr s (stringToHtmlString t)
htmlAttr :: String -> Html -> HtmlAttr
htmlAttr s t = HtmlAttr s (show t)
foldHtml : : ( String - > [ HtmlAttr ] - > [ a ] - > a )
- > ( String - > a )
- > Html
- > a
foldHtml f g ( HtmlTag str attr fmls )
= f str attr ( map ( foldHtml f g ) fmls )
foldHtml f g ( HtmlString str )
=
foldHtml :: (String -> [HtmlAttr] -> [a] -> a)
-> (String -> a)
-> Html
-> a
foldHtml f g (HtmlTag str attr fmls)
= f str attr (map (foldHtml f g) fmls)
foldHtml f g (HtmlString str)
= g str
-}
-- | Processing Strings into Html friendly things.
stringToHtmlString :: String -> String
stringToHtmlString = concatMap fixChar
where
fixChar '<' = "<"
fixChar '>' = ">"
fixChar '&' = "&"
fixChar '"' = """
fixChar c | ord c < 0x80 = [c]
fixChar c = "&#" ++ show (ord c) ++ ";"
-- | This is not processed for special chars.
-- use stringToHtml or lineToHtml instead, for user strings,
-- because they understand special chars, like @'<'@.
primHtml :: String -> Html
primHtml x | null x = Html []
| otherwise = Html [HtmlString x]
--
*
--
mkHtml :: HTML html => html -> Html
mkHtml = (tag "html" ! [strAttr "xmlns" ""] <<)
-- | Output the HTML without adding newlines or spaces within the markup.
-- This should be the most time and space efficient way to
-- render HTML, though the output is quite unreadable.
showHtmlInternal :: HTML html =>
^ DOCTYPE declaration
-> html -> String
showHtmlInternal docType theHtml =
docType ++ showHtmlFragment (mkHtml theHtml)
-- | Outputs indented HTML. Because space matters in
-- HTML, the output is quite messy.
renderHtmlInternal :: HTML html =>
^ DOCTYPE declaration
-> html -> String
renderHtmlInternal docType theHtml =
docType ++ "\n" ++ renderHtmlFragment (mkHtml theHtml) ++ "\n"
-- | Outputs indented HTML, with indentation inside elements.
-- This can change the meaning of the HTML document, and
-- is mostly useful for debugging the HTML output.
-- The implementation is inefficient, and you are normally
-- better off using 'showHtml' or 'renderHtml'.
prettyHtmlInternal :: HTML html =>
^ DOCTYPE declaration
-> html -> String
prettyHtmlInternal docType theHtml =
docType ++ "\n" ++ prettyHtmlFragment (mkHtml theHtml)
| Render a piece of HTML without adding a DOCTYPE declaration
-- or root element. Does not add any extra whitespace.
showHtmlFragment :: HTML html => html -> String
showHtmlFragment h =
(foldr (.) id $ map showHtml' $ getHtmlElements $ toHtml h) ""
| Render a piece of indented HTML without adding a DOCTYPE declaration
-- or root element. Only adds whitespace where it does not change
-- the meaning of the document.
renderHtmlFragment :: HTML html => html -> String
renderHtmlFragment h =
(foldr (.) id $ map (renderHtml' 0) $ getHtmlElements $ toHtml h) ""
| Render a piece of indented HTML without adding a DOCTYPE declaration
-- or a root element.
-- The indentation is done inside elements.
-- This can change the meaning of the HTML document, and
-- is mostly useful for debugging the HTML output.
-- The implementation is inefficient, and you are normally
-- better off using 'showHtmlFragment' or 'renderHtmlFragment'.
prettyHtmlFragment :: HTML html => html -> String
prettyHtmlFragment =
unlines . concat . map prettyHtml' . getHtmlElements . toHtml
-- | Show a single HTML element, without adding whitespace.
showHtml' :: HtmlElement -> ShowS
showHtml' (HtmlString str) = (++) str
showHtml'(HtmlTag { markupTag = name,
markupContent = html,
markupAttrs = attrs })
= if isNoHtml html && elem name validHtmlITags
then renderTag True name attrs ""
else (renderTag False name attrs ""
. foldr (.) id (map showHtml' (getHtmlElements html))
. renderEndTag name "")
renderHtml' :: Int -> HtmlElement -> ShowS
renderHtml' _ (HtmlString str) = (++) str
renderHtml' n (HtmlTag
{ markupTag = name,
markupContent = html,
markupAttrs = attrs })
= if isNoHtml html && elem name validHtmlITags
then renderTag True name attrs (nl n)
else (renderTag False name attrs (nl n)
. foldr (.) id (map (renderHtml' (n+2)) (getHtmlElements html))
. renderEndTag name (nl n))
where
nl n' = "\n" ++ replicate (n' `div` 8) '\t'
++ replicate (n' `mod` 8) ' '
prettyHtml' :: HtmlElement -> [String]
prettyHtml' (HtmlString str) = [str]
prettyHtml' (HtmlTag
{ markupTag = name,
markupContent = html,
markupAttrs = attrs })
= if isNoHtml html && elem name validHtmlITags
then
[rmNL (renderTag True name attrs "" "")]
else
[rmNL (renderTag False name attrs "" "")] ++
shift (concat (map prettyHtml' (getHtmlElements html))) ++
[rmNL (renderEndTag name "" "")]
where
shift = map (\x -> " " ++ x)
rmNL = filter (/= '\n')
-- | Show a start tag
renderTag :: Bool -- ^ 'True' if the empty tag shorthand should be used
-> String -- ^ Tag name
-> [HtmlAttr] -- ^ Attributes
^ Whitespace to add after attributes
-> ShowS
renderTag empty name attrs nl r
= "<" ++ name ++ shownAttrs ++ nl ++ close ++ r
where
close = if empty then " />" else ">"
shownAttrs = concat [' ':showPair attr | attr <- attrs ]
showPair :: HtmlAttr -> String
showPair (HtmlAttr key val)
= key ++ "=\"" ++ val ++ "\""
-- | Show an end tag
renderEndTag :: String -- ^ Tag name
^ Whitespace to add after tag name
-> ShowS
renderEndTag name nl r = "</" ++ name ++ nl ++ ">" ++ r
-- | The names of all elements which can represented using the empty tag
-- short-hand.
validHtmlITags :: [String]
validHtmlITags = [
"area",
"base",
"basefont",
"br",
"col",
"frame",
"hr",
"img",
"input",
"isindex",
"link",
"meta",
"param"
]
| null | https://raw.githubusercontent.com/haskell/xhtml/6a9816582020a4bfcbeb23027b6c95ef028d45ed/Text/XHtml/Internals.hs | haskell | # OPTIONS_HADDOCK hide #
---------------------------------------------------------------------------
|
Module : Text.XHtml.internals
License : BSD-style (see the file LICENSE)
Stability : Stable
Internals of the XHTML combinator library.
---------------------------------------------------------------------------
combining Html
nesting Html
adding optional arguments
* Data types
| A important property of Html is that all strings inside the
structure are already in Html friendly format.
^ ..just..plain..normal..text... but using © and &amb;, etc.
^ tag with internal markup
| Attributes with name and value.
* Classes
| HTML is the class of things that can be validly put
or a 'String', for example.
| CHANGEATTRS is a more expressive alternative to ADDATTRS
* Html primitives and basic combinators
| Put something inside an HTML element.
^ Parent
^ Child
| Create a piece of HTML which is the concatenation
| An empty piece of HTML.
| Checks whether the given piece of HTML is empty.
| Constructs an element with a custom name.
^ Element name
^ Element contents
| Constructs an element with a custom name, and
without any children.
| Processing Strings into Html friendly things.
| This is not processed for special chars.
use stringToHtml or lineToHtml instead, for user strings,
because they understand special chars, like @'<'@.
| Output the HTML without adding newlines or spaces within the markup.
This should be the most time and space efficient way to
render HTML, though the output is quite unreadable.
| Outputs indented HTML. Because space matters in
HTML, the output is quite messy.
| Outputs indented HTML, with indentation inside elements.
This can change the meaning of the HTML document, and
is mostly useful for debugging the HTML output.
The implementation is inefficient, and you are normally
better off using 'showHtml' or 'renderHtml'.
or root element. Does not add any extra whitespace.
or root element. Only adds whitespace where it does not change
the meaning of the document.
or a root element.
The indentation is done inside elements.
This can change the meaning of the HTML document, and
is mostly useful for debugging the HTML output.
The implementation is inefficient, and you are normally
better off using 'showHtmlFragment' or 'renderHtmlFragment'.
| Show a single HTML element, without adding whitespace.
| Show a start tag
^ 'True' if the empty tag shorthand should be used
^ Tag name
^ Attributes
| Show an end tag
^ Tag name
| The names of all elements which can represented using the empty tag
short-hand. |
Copyright : ( c ) , and the Oregon Graduate Institute of
Science and Technology , 1999 - 2001 ,
( c ) , 2004 - 2006
Maintainer : < >
Portability : Portable
module Text.XHtml.Internals where
import Data.Char
import qualified Data.Semigroup as Sem
import qualified Data.Monoid as Mon
data HtmlElement
= HtmlString String
| HtmlTag {
markupTag :: String,
markupAttrs :: [HtmlAttr],
markupContent :: Html
}
data HtmlAttr = HtmlAttr String String
htmlAttrPair :: HtmlAttr -> (String,String)
htmlAttrPair (HtmlAttr n v) = (n,v)
newtype Html = Html { getHtmlElements :: [HtmlElement] }
instance Show Html where
showsPrec _ html = showString (renderHtmlFragment html)
showList htmls = foldr (.) id (map shows htmls)
instance Show HtmlAttr where
showsPrec _ (HtmlAttr str val) =
showString str .
showString "=" .
shows val
| @since 3000.2.2
instance Sem.Semigroup Html where
(<>) = (+++)
instance Mon.Monoid Html where
mempty = noHtml
mappend = (Sem.<>)
inside an HTML tag . So this can be one or more ' Html ' elements ,
class HTML a where
toHtml :: a -> Html
toHtmlFromList :: [a] -> Html
toHtmlFromList xs = Html (concat [ x | (Html x) <- map toHtml xs])
instance HTML Html where
toHtml a = a
instance HTML Char where
toHtml a = toHtml [a]
toHtmlFromList [] = Html []
toHtmlFromList str = Html [HtmlString (stringToHtmlString str)]
instance (HTML a) => HTML [a] where
toHtml xs = toHtmlFromList xs
instance HTML a => HTML (Maybe a) where
toHtml = maybe noHtml toHtml
class ADDATTRS a where
(!) :: a -> [HtmlAttr] -> a
class CHANGEATTRS a where
changeAttrs :: a -> ([HtmlAttr]->[HtmlAttr]) -> a
instance (ADDATTRS b) => ADDATTRS (a -> b) where
fn ! attr = \ arg -> fn arg ! attr
instance (CHANGEATTRS b) => CHANGEATTRS (a -> b) where
changeAttrs fn f = \ arg -> changeAttrs (fn arg) f
instance ADDATTRS Html where
(Html htmls) ! attr = Html (map addAttrs htmls)
where
addAttrs (html@(HtmlTag { markupAttrs = attrs }) )
= html { markupAttrs = attrs ++ attr }
addAttrs html = html
instance CHANGEATTRS Html where
changeAttrs (Html htmls) f = Html (map addAttrs htmls)
where
addAttrs (html@(HtmlTag { markupAttrs = attrs }) )
= html { markupAttrs = f attrs }
addAttrs html = html
(<<) :: (HTML a) =>
-> b
fn << arg = fn (toHtml arg)
concatHtml :: (HTML a) => [a] -> Html
concatHtml as = Html (concat (map (getHtmlElements.toHtml) as))
of two things which can be made into HTML .
(+++) :: (HTML a,HTML b) => a -> b -> Html
a +++ b = Html (getHtmlElements (toHtml a) ++ getHtmlElements (toHtml b))
noHtml :: Html
noHtml = Html []
isNoHtml :: Html -> Bool
isNoHtml (Html xs) = null xs
-> Html
tag str htmls = Html [
HtmlTag {
markupTag = str,
markupAttrs = [],
markupContent = htmls }]
itag :: String -> Html
itag str = tag str noHtml
emptyAttr :: String -> HtmlAttr
emptyAttr s = HtmlAttr s s
intAttr :: String -> Int -> HtmlAttr
intAttr s i = HtmlAttr s (show i)
strAttr :: String -> String -> HtmlAttr
strAttr s t = HtmlAttr s (stringToHtmlString t)
htmlAttr :: String -> Html -> HtmlAttr
htmlAttr s t = HtmlAttr s (show t)
foldHtml : : ( String - > [ HtmlAttr ] - > [ a ] - > a )
- > ( String - > a )
- > Html
- > a
foldHtml f g ( HtmlTag str attr fmls )
= f str attr ( map ( foldHtml f g ) fmls )
foldHtml f g ( HtmlString str )
=
foldHtml :: (String -> [HtmlAttr] -> [a] -> a)
-> (String -> a)
-> Html
-> a
foldHtml f g (HtmlTag str attr fmls)
= f str attr (map (foldHtml f g) fmls)
foldHtml f g (HtmlString str)
= g str
-}
stringToHtmlString :: String -> String
stringToHtmlString = concatMap fixChar
where
fixChar '<' = "<"
fixChar '>' = ">"
fixChar '&' = "&"
fixChar '"' = """
fixChar c | ord c < 0x80 = [c]
fixChar c = "&#" ++ show (ord c) ++ ";"
primHtml :: String -> Html
primHtml x | null x = Html []
| otherwise = Html [HtmlString x]
*
mkHtml :: HTML html => html -> Html
mkHtml = (tag "html" ! [strAttr "xmlns" ""] <<)
showHtmlInternal :: HTML html =>
^ DOCTYPE declaration
-> html -> String
showHtmlInternal docType theHtml =
docType ++ showHtmlFragment (mkHtml theHtml)
renderHtmlInternal :: HTML html =>
^ DOCTYPE declaration
-> html -> String
renderHtmlInternal docType theHtml =
docType ++ "\n" ++ renderHtmlFragment (mkHtml theHtml) ++ "\n"
prettyHtmlInternal :: HTML html =>
^ DOCTYPE declaration
-> html -> String
prettyHtmlInternal docType theHtml =
docType ++ "\n" ++ prettyHtmlFragment (mkHtml theHtml)
| Render a piece of HTML without adding a DOCTYPE declaration
showHtmlFragment :: HTML html => html -> String
showHtmlFragment h =
(foldr (.) id $ map showHtml' $ getHtmlElements $ toHtml h) ""
| Render a piece of indented HTML without adding a DOCTYPE declaration
renderHtmlFragment :: HTML html => html -> String
renderHtmlFragment h =
(foldr (.) id $ map (renderHtml' 0) $ getHtmlElements $ toHtml h) ""
| Render a piece of indented HTML without adding a DOCTYPE declaration
prettyHtmlFragment :: HTML html => html -> String
prettyHtmlFragment =
unlines . concat . map prettyHtml' . getHtmlElements . toHtml
showHtml' :: HtmlElement -> ShowS
showHtml' (HtmlString str) = (++) str
showHtml'(HtmlTag { markupTag = name,
markupContent = html,
markupAttrs = attrs })
= if isNoHtml html && elem name validHtmlITags
then renderTag True name attrs ""
else (renderTag False name attrs ""
. foldr (.) id (map showHtml' (getHtmlElements html))
. renderEndTag name "")
renderHtml' :: Int -> HtmlElement -> ShowS
renderHtml' _ (HtmlString str) = (++) str
renderHtml' n (HtmlTag
{ markupTag = name,
markupContent = html,
markupAttrs = attrs })
= if isNoHtml html && elem name validHtmlITags
then renderTag True name attrs (nl n)
else (renderTag False name attrs (nl n)
. foldr (.) id (map (renderHtml' (n+2)) (getHtmlElements html))
. renderEndTag name (nl n))
where
nl n' = "\n" ++ replicate (n' `div` 8) '\t'
++ replicate (n' `mod` 8) ' '
prettyHtml' :: HtmlElement -> [String]
prettyHtml' (HtmlString str) = [str]
prettyHtml' (HtmlTag
{ markupTag = name,
markupContent = html,
markupAttrs = attrs })
= if isNoHtml html && elem name validHtmlITags
then
[rmNL (renderTag True name attrs "" "")]
else
[rmNL (renderTag False name attrs "" "")] ++
shift (concat (map prettyHtml' (getHtmlElements html))) ++
[rmNL (renderEndTag name "" "")]
where
shift = map (\x -> " " ++ x)
rmNL = filter (/= '\n')
^ Whitespace to add after attributes
-> ShowS
renderTag empty name attrs nl r
= "<" ++ name ++ shownAttrs ++ nl ++ close ++ r
where
close = if empty then " />" else ">"
shownAttrs = concat [' ':showPair attr | attr <- attrs ]
showPair :: HtmlAttr -> String
showPair (HtmlAttr key val)
= key ++ "=\"" ++ val ++ "\""
^ Whitespace to add after tag name
-> ShowS
renderEndTag name nl r = "</" ++ name ++ nl ++ ">" ++ r
validHtmlITags :: [String]
validHtmlITags = [
"area",
"base",
"basefont",
"br",
"col",
"frame",
"hr",
"img",
"input",
"isindex",
"link",
"meta",
"param"
]
|
348bdfe1b5a248c77d4e94827a5583245a85d82058dccae119c62fb1b84e463f | ankushdas/Nomos | Infer.ml | module A = Ast
module R = Arith
module N = Normalize
module S = Solver
module C = Core
module M = C.Map
module PP = Pprint
module F = NomosFlags
module ClpS = S.Clp (S.Clp_std_options);;
exception InferImpossible;;
(************************************************************)
(* Substituting potential variables for star in annotations *)
(************************************************************)
let vnum = ref 0;;
let fresh () =
let v = "_v" ^ string_of_int !vnum in
let () = vnum := !vnum + 1 in
v;;
let remove_star pot = match pot with
A.Star ->
let v = fresh () in
A.Arith(R.Var(v))
| A.Arith e -> A.Arith e;;
let rec remove_stars_tp tp = match tp with
A.Plus(choices) -> A.Plus(remove_stars_choices choices)
| A.With(choices) -> A.With(remove_stars_choices choices)
| A.Tensor(a,b,m) -> A.Tensor(remove_stars_tp a, remove_stars_tp b,m)
| A.Lolli(a,b,m) -> A.Lolli(remove_stars_tp a, remove_stars_tp b,m)
| A.One -> A.One
| A.PayPot(pot,a) -> A.PayPot(remove_star pot, remove_stars_tp a)
| A.GetPot(pot,a) -> A.GetPot(remove_star pot, remove_stars_tp a)
| A.TpName(v) -> A.TpName(v)
| A.Up(a) -> A.Up(remove_stars_tp a)
| A.Down(a) -> A.Down(remove_stars_tp a)
| A.FArrow(t,a) -> A.FArrow(t,remove_stars_tp a)
| A.FProduct(t,a) -> A.FProduct(t,remove_stars_tp a)
| A.FMap(kt,vt) -> A.FMap(kt, vt)
| A.STMap(kt,vt) -> A.STMap(kt, remove_stars_tp vt)
| A.Coin -> A.Coin
and remove_stars_choices choices = match choices with
(l,a)::choices' -> (l,remove_stars_tp a)::(remove_stars_choices choices')
| [] -> []
and remove_stars_ftp ftp = match ftp with
A.ListTP(t,pot) -> A.ListTP(t, remove_star pot)
| A.Integer | A.Boolean | A.String | A.Address | A.VarT _ -> ftp
| A.Arrow(t1,t2) -> A.Arrow(remove_stars_ftp t1, remove_stars_ftp t2);;
let rec remove_stars_exp exp = match exp with
A.Fwd(x,y) -> A.Fwd(x,y)
| A.Spawn(x,f,xs,q) -> A.Spawn(x,f,xs, remove_stars_aug q)
| A.ExpName(x,f,xs) -> A.ExpName(x,f,xs)
| A.Lab(x,k,p) -> A.Lab(x,k, remove_stars_aug p)
| A.Case(x,branches) -> A.Case(x, remove_stars_branches branches)
| A.Send(x,w,p) -> A.Send(x,w, remove_stars_aug p)
| A.Recv(x,y,p) -> A.Recv(x,y, remove_stars_aug p)
| A.Close(x) -> A.Close(x)
| A.Wait(x,q) -> A.Wait(x, remove_stars_aug q)
| A.Work(pot,p) ->
let pot' = remove_star pot in
A.Work(pot', remove_stars_aug p)
| A.Deposit(pot,p) ->
let pot' = remove_star pot in
A.Deposit(pot', remove_stars_aug p)
| A.Pay(x,pot,p) ->
let pot' = remove_star pot in
A.Pay(x, pot', remove_stars_aug p)
| A.Get(x,pot,p) ->
let pot' = remove_star pot in
A.Get(x, pot', remove_stars_aug p)
| A.Acquire(x,y,p) -> A.Acquire(x,y, remove_stars_aug p)
| A.Accept(x,y,p) -> A.Accept(x,y, remove_stars_aug p)
| A.Release(x,y,p) -> A.Release(x,y, remove_stars_aug p)
| A.Detach(x,y,p) -> A.Detach(x,y, remove_stars_aug p)
| A.SendF(x,e,p) -> A.SendF(x, remove_stars_faug e, remove_stars_aug p)
| A.RecvF(x,y,p) -> A.RecvF(x,y, remove_stars_aug p)
| A.Let(x,e,p) -> A.Let(x, remove_stars_faug e, remove_stars_aug p)
| A.IfS(e,p1,p2) -> A.IfS(remove_stars_faug e, remove_stars_aug p1, remove_stars_aug p2)
| A.FMapCreate(mp,kt,vt,p) -> A.FMapCreate(mp, kt, vt, remove_stars_aug p)
| A.STMapCreate(mp,kt,vt,p) -> A.STMapCreate(mp, kt, vt, remove_stars_aug p)
| A.FMapInsert(mp,k,v,p) -> A.FMapInsert(mp, k, v, remove_stars_aug p)
| A.STMapInsert(mp,k,v,p) -> A.STMapInsert(mp, k, v, remove_stars_aug p)
| A.FMapDelete(v,mp,k,p) -> A.FMapDelete(v,mp, k, remove_stars_aug p)
| A.STMapDelete(v,mp,k,p) -> A.STMapDelete(v,mp, k, remove_stars_aug p)
| A.MapClose(mp,p) -> A.MapClose(mp, remove_stars_aug p)
| A.Abort -> A.Abort
| A.Print(l,args,p) -> A.Print(l,args,remove_stars_aug p)
and remove_stars_branches bs = match bs with
[] -> []
| (l,p)::bs' ->
(l, remove_stars_aug p)::
(remove_stars_branches bs')
and remove_stars_aug {A.st_data = d; A.st_structure = p} = {A.st_data = d; A.st_structure = remove_stars_exp p}
and remove_stars_faug {A.func_data = d; A.func_structure = e} = {A.func_data = d; A.func_structure = remove_stars_fexp e}
and remove_stars_fexp fexp = match fexp with
A.If(e1,e2,e3) -> A.If(remove_stars_faug e1, remove_stars_faug e2, remove_stars_faug e3)
| A.LetIn(x,e1,e2) -> A.LetIn(x, remove_stars_faug e1, remove_stars_faug e2)
| A.Bool _ | A.Int _ | A.Str _ | A.Addr _ | A.Var _ -> fexp
| A.ListE(l) -> A.ListE(List.map remove_stars_faug l)
| A.App(es) -> A.App(List.map remove_stars_faug es)
| A.Cons(e1,e2) -> A.Cons(remove_stars_faug e1, remove_stars_faug e2)
| A.Match(e1,e2,x,xs,e3) -> A.Match(remove_stars_faug e1, remove_stars_faug e2, x, xs, remove_stars_faug e3)
| A.Lambda(xs,e) -> A.Lambda(xs, remove_stars_faug e)
| A.Op(e1,op,e2) -> A.Op(remove_stars_faug e1, op, remove_stars_faug e2)
| A.CompOp(e1,cop,e2) -> A.CompOp(remove_stars_faug e1, cop, remove_stars_faug e2)
| A.EqAddr(e1,e2) -> A.EqAddr(remove_stars_faug e1, remove_stars_faug e2)
| A.RelOp(e1,rop,e2) -> A.RelOp(remove_stars_faug e1, rop, remove_stars_faug e2)
| A.Tick(pot,e) -> A.Tick(remove_star pot, remove_stars_faug e)
| A.MapSize(mp) -> A.MapSize(mp)
| A.GetTxnNum -> A.GetTxnNum
| A.GetTxnSender -> A.GetTxnSender
| A.Command(p) -> A.Command(remove_stars_aug p);;
(********************************************)
(* Substituting actual values for potential *)
(* variables as well as mode variables *)
(********************************************)
let rec getpval v sols = match sols with
[] -> 0
| (v',n)::sols' ->
if v = v' then n
else getpval v sols';;
let rec subst_pot e sols = match e with
R.Add(e1,e2) -> R.Add(subst_pot e1 sols, subst_pot e2 sols)
| R.Sub(e1,e2) -> R.Sub(subst_pot e1 sols, subst_pot e2 sols)
| R.Mult(e1,e2) -> R.Mult(subst_pot e1 sols, subst_pot e2 sols)
| R.Int(n) -> R.Int(n)
| R.Var(v) -> R.Int(getpval v sols);;
let substitute_pot pot sols = match pot with
A.Star -> raise InferImpossible
| A.Arith e -> A.Arith (subst_pot e sols);;
let rec getmval v sols = match sols with
[] -> A.Pure
| (v',n)::sols' ->
if v = v' then n
else getmval v sols';;
let subst_mode m sols = match m with
A.MVar(v) -> getmval v sols
| _m -> raise InferImpossible;;
let substitute_mode (s,c,m) sols = (s, c, subst_mode m sols);;
let substitute_argmode arg sols = match arg with
A.FArg a -> A.FArg a
| A.STArg a -> A.STArg (substitute_mode a sols);;
let rec substitute_tp tp psols msols = match tp with
A.Plus(choices) -> A.Plus(substitute_choices choices psols msols)
| A.With(choices) -> A.With(substitute_choices choices psols msols)
| A.Tensor(a,b,m) -> A.Tensor(substitute_tp a psols msols, substitute_tp b psols msols, subst_mode m msols)
| A.Lolli(a,b,m) -> A.Lolli(substitute_tp a psols msols, substitute_tp b psols msols, subst_mode m msols)
| A.One -> A.One
| A.PayPot(pot,a) -> A.PayPot(substitute_pot pot psols, substitute_tp a psols msols)
| A.GetPot(pot,a) -> A.GetPot(substitute_pot pot psols, substitute_tp a psols msols)
| A.TpName(v) -> A.TpName(v)
| A.Up(a) -> A.Up(substitute_tp a psols msols)
| A.Down(a) -> A.Down(substitute_tp a psols msols)
| A.FArrow(t,a) -> A.FArrow(t, substitute_tp a psols msols)
| A.FProduct(t,a) -> A.FProduct(t, substitute_tp a psols msols)
| A.FMap(kt,vt) -> A.FMap(kt, vt)
| A.STMap(kt,vt) -> A.STMap(kt, substitute_tp vt psols msols)
| A.Coin -> A.Coin
and substitute_choices choices psols msols = match choices with
(l,a)::choices' -> (l,substitute_tp a psols msols)::(substitute_choices choices' psols msols)
| [] -> []
and substitute_ftp ftp psols msols = match ftp with
A.ListTP(t,pot) -> A.ListTP(t, substitute_pot pot psols)
| A.Integer | A.Boolean | A.String | A.Address | A.VarT _ -> ftp
| A.Arrow(t1,t2) -> A.Arrow(substitute_ftp t1 psols msols, substitute_ftp t2 psols msols);;
let substitute_mode_list xs sols = List.map (fun c -> substitute_argmode c sols) xs;;
let rec substitute_exp exp psols msols = match exp with
A.Fwd(x,y) -> A.Fwd(substitute_mode x msols, substitute_mode y msols)
| A.Spawn(x,f,xs,q) -> A.Spawn(substitute_mode x msols, f, substitute_mode_list xs msols, substitute_aug q psols msols)
| A.ExpName(x,f,xs) -> A.ExpName(substitute_mode x msols, f, substitute_mode_list xs msols)
| A.Lab(x,k,p) -> A.Lab(substitute_mode x msols, k, substitute_aug p psols msols)
| A.Case(x,branches) -> A.Case(substitute_mode x msols, substitute_branches branches psols msols)
| A.Send(x,w,p) -> A.Send(substitute_mode x msols, substitute_mode w msols, substitute_aug p psols msols)
| A.Recv(x,y,p) -> A.Recv(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.Close(x) -> A.Close(substitute_mode x msols)
| A.Wait(x,q) -> A.Wait(substitute_mode x msols, substitute_aug q psols msols)
| A.Work(pot,p) ->
let pot' = substitute_pot pot psols in
A.Work(pot', substitute_aug p psols msols)
| A.Deposit(pot,p) ->
let pot' = substitute_pot pot psols in
A.Deposit(pot', substitute_aug p psols msols)
| A.Pay(x,pot,p) ->
let pot' = substitute_pot pot psols in
A.Pay(substitute_mode x msols, pot', substitute_aug p psols msols)
| A.Get(x,pot,p) ->
let pot' = substitute_pot pot psols in
A.Get(substitute_mode x msols, pot', substitute_aug p psols msols)
| A.Acquire(x,y,p) -> A.Acquire(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.Accept(x,y,p) -> A.Accept(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.Release(x,y,p) -> A.Release(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.Detach(x,y,p) -> A.Detach(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.SendF(x,e,p) -> A.SendF(substitute_mode x msols, e, substitute_aug p psols msols)
| A.RecvF(x,y,p) -> A.RecvF(substitute_mode x msols, y, substitute_aug p psols msols)
| A.Let(x,e,p) -> A.Let(x,e, substitute_aug p psols msols)
| A.IfS(e,p1,p2) -> A.IfS(e, substitute_aug p1 psols msols, substitute_aug p2 psols msols)
| A.FMapCreate(mp,kt,vt,p) -> A.FMapCreate(substitute_mode mp msols, kt, vt, substitute_aug p psols msols)
| A.STMapCreate(mp,kt,vt,p) -> A.STMapCreate(substitute_mode mp msols, kt, vt, substitute_aug p psols msols)
| A.FMapInsert(mp,k,v,p) -> A.FMapInsert(substitute_mode mp msols, k, v, substitute_aug p psols msols)
| A.STMapInsert(mp,k,v,p) -> A.STMapInsert(substitute_mode mp msols, k, substitute_mode v msols, substitute_aug p psols msols)
| A.FMapDelete(v,mp,k,p) -> A.FMapDelete(v, substitute_mode mp msols, k, substitute_aug p psols msols)
| A.STMapDelete(v,mp,k,p) -> A.STMapDelete(substitute_mode v msols, substitute_mode mp msols, k, substitute_aug p psols msols)
| A.MapClose(mp,p) -> A.MapClose(substitute_mode mp msols, substitute_aug p psols msols)
| A.Abort -> A.Abort
| A.Print(l,args,p) -> A.Print(l,substitute_mode_list args msols,substitute_aug p psols msols)
and substitute_branches bs psols msols = match bs with
[] -> []
| (l,p)::bs' ->
(l, substitute_aug p psols msols)::
(substitute_branches bs' psols msols)
and substitute_aug {A.st_data = d; A.st_structure = p} psols msols = {A.st_data = d; A.st_structure = substitute_exp p psols msols}
and substitute_faug {A.func_data = d; A.func_structure = e} psols msols = {A.func_data = d; A.func_structure = substitute_fexp e psols msols}
and substitute_fexp fexp psols msols = match fexp with
A.If(e1,e2,e3) -> A.If(substitute_faug e1 psols msols, substitute_faug e2 psols msols, substitute_faug e3 psols msols)
| A.LetIn(x,e1,e2) -> A.LetIn(x, substitute_faug e1 psols msols, substitute_faug e2 psols msols)
| A.Bool _ | A.Int _ | A.Str _ | A.Addr _ | A.Var _ -> fexp
| A.ListE(l) -> A.ListE(List.map (fun e -> substitute_faug e psols msols) l)
| A.App(es) -> A.App(List.map (fun e -> substitute_faug e psols msols) es)
| A.Cons(e1,e2) -> A.Cons(substitute_faug e1 psols msols, substitute_faug e2 psols msols)
| A.Match(e1,e2,x,xs,e3) -> A.Match(substitute_faug e1 psols msols, substitute_faug e2 psols msols, x, xs, substitute_faug e3 psols msols)
| A.Lambda(xs,e) -> A.Lambda(xs, substitute_faug e psols msols)
| A.Op(e1,op,e2) -> A.Op(substitute_faug e1 psols msols, op, substitute_faug e2 psols msols)
| A.CompOp(e1,cop,e2) -> A.CompOp(substitute_faug e1 psols msols, cop, substitute_faug e2 psols msols)
| A.EqAddr(e1,e2) -> A.EqAddr(substitute_faug e1 psols msols, substitute_faug e2 psols msols)
| A.RelOp(e1,rop,e2) -> A.RelOp(substitute_faug e1 psols msols, rop, substitute_faug e2 psols msols)
| A.Tick(pot,e) -> A.Tick(substitute_pot pot psols, substitute_faug e psols msols)
| A.MapSize(mp) -> A.MapSize(mp)
| A.GetTxnNum -> A.GetTxnNum
| A.GetTxnSender -> A.GetTxnSender
| A.Command(p) -> A.Command(substitute_aug p psols msols);;
(***************************************************************)
Substituting mode variables for U in channel and type modes
(***************************************************************)
let mnum = ref 0;;
let mfresh () =
let m = "_m" ^ string_of_int !mnum in
let () = mnum := !mnum + 1 in
m;;
let unk m = match m with
A.Unknown -> true
| _m -> false;;
let removeU (s,c,m) = match m with
A.Unknown -> (s, c, A.MVar(mfresh ()))
| _m -> raise InferImpossible;;
let removeU_arg a = match a with
A.FArg a -> A.FArg a
| A.STArg c -> A.STArg (removeU c);;
let rec removeU_tp tp = match tp with
A.Plus(choices) -> A.Plus(removeU_choices choices)
| A.With(choices) -> A.With(removeU_choices choices)
| A.Tensor(a,b,m) -> if not (unk m) then raise InferImpossible else A.Tensor(removeU_tp a, removeU_tp b, A.MVar(mfresh ()))
| A.Lolli(a,b,m) -> if not (unk m) then raise InferImpossible else A.Lolli(removeU_tp a, removeU_tp b, A.MVar(mfresh ()))
| A.One -> A.One
| A.PayPot(pot,a) -> A.PayPot(pot, removeU_tp a)
| A.GetPot(pot,a) -> A.GetPot(pot, removeU_tp a)
| A.TpName(v) -> A.TpName(v)
| A.Up(a) -> A.Up(removeU_tp a)
| A.Down(a) -> A.Down(removeU_tp a)
| A.FArrow(t,a) -> A.FArrow(t,removeU_tp a)
| A.FProduct(t,a) -> A.FProduct(t,removeU_tp a)
| A.FMap(kt,vt) -> A.FMap(kt,vt)
| A.STMap(kt,vt) -> A.STMap(kt, removeU_tp vt)
| A.Coin -> A.Coin
and removeU_choices choices = match choices with
(l,a)::choices' -> (l,removeU_tp a)::(removeU_choices choices')
| [] -> [];;
let removeU_list xs = List.map (fun c -> removeU_arg c) xs;;
let rec removeU_exp exp = match exp with
A.Fwd(x,y) -> A.Fwd(removeU x, removeU y)
| A.Spawn(x,f,xs,q) -> A.Spawn(removeU x, f, removeU_list xs, removeU_aug q)
| A.ExpName(x,f,xs) -> A.ExpName(removeU x, f, removeU_list xs)
| A.Lab(x,k,p) -> A.Lab(removeU x, k, removeU_aug p)
| A.Case(x,branches) -> A.Case(removeU x, removeU_branches branches)
| A.Send(x,w,p) -> A.Send(removeU x, removeU w, removeU_aug p)
| A.Recv(x,y,p) -> A.Recv(removeU x, removeU y, removeU_aug p)
| A.Close(x) -> A.Close(removeU x)
| A.Wait(x,q) -> A.Wait(removeU x, removeU_aug q)
| A.Work(pot,p) -> A.Work(pot, removeU_aug p)
| A.Deposit(pot,p) -> A.Deposit(pot, removeU_aug p)
| A.Pay(x,pot,p) -> A.Pay(removeU x, pot, removeU_aug p)
| A.Get(x,pot,p) -> A.Get(removeU x, pot, removeU_aug p)
| A.Acquire(x,y,p) -> A.Acquire(removeU x, removeU y, removeU_aug p)
| A.Accept(x,y,p) -> A.Accept(removeU x, removeU y, removeU_aug p)
| A.Release(x,y,p) -> A.Release(removeU x, removeU y, removeU_aug p)
| A.Detach(x,y,p) -> A.Detach(removeU x, removeU y, removeU_aug p)
| A.SendF(x,e,p) -> A.SendF(removeU x, e, removeU_aug p)
| A.RecvF(x,y,p) -> A.RecvF(removeU x, y, removeU_aug p)
| A.Let(x,e,p) -> A.Let(x,e, removeU_aug p)
| A.IfS(e,p1,p2) -> A.IfS(e, removeU_aug p1, removeU_aug p2)
| A.FMapCreate(mp,kt,vt,p) -> A.FMapCreate(removeU mp, kt, vt, removeU_aug p)
| A.STMapCreate(mp,kt,vt,p) -> A.STMapCreate(removeU mp, kt, vt, removeU_aug p)
| A.FMapInsert(mp,k,v,p) -> A.FMapInsert(removeU mp, k, v, removeU_aug p)
| A.STMapInsert(mp,k,v,p) -> A.STMapInsert(removeU mp, k, removeU v, removeU_aug p)
| A.FMapDelete(v,mp,k,p) -> A.FMapDelete(v, removeU mp, k, removeU_aug p)
| A.STMapDelete(v,mp,k,p) -> A.STMapDelete(removeU v, removeU mp, k, removeU_aug p)
| A.MapClose(mp,p) -> A.MapClose(removeU mp, removeU_aug p)
| A.Abort -> A.Abort
| A.Print(l,args,p) -> A.Print(l, removeU_list args, removeU_aug p)
and removeU_branches bs = match bs with
[] -> []
| (l,p)::bs' ->
(l, removeU_aug p)::
(removeU_branches bs')
and removeU_aug {A.st_data = d; A.st_structure = p} = {A.st_data = d; A.st_structure = removeU_exp p}
and removeU_faug {A.func_data = d; A.func_structure = e} = {A.func_data = d; A.func_structure = removeU_fexp e}
and removeU_fexp fexp = match fexp with
A.If(e1,e2,e3) -> A.If(removeU_faug e1, removeU_faug e2, removeU_faug e3)
| A.LetIn(x,e1,e2) -> A.LetIn(x, removeU_faug e1, removeU_faug e2)
| A.Bool _ | A.Int _ | A.Str _ | A.Addr _ | A.Var _ -> fexp
| A.ListE(l) -> A.ListE(List.map removeU_faug l)
| A.App(es) -> A.App(List.map removeU_faug es)
| A.Cons(e1,e2) -> A.Cons(removeU_faug e1, removeU_faug e2)
| A.Match(e1,e2,x,xs,e3) -> A.Match(removeU_faug e1, removeU_faug e2, x, xs, removeU_faug e3)
| A.Lambda(xs,e) -> A.Lambda(xs, removeU_faug e)
| A.Op(e1,op,e2) -> A.Op(removeU_faug e1, op, removeU_faug e2)
| A.CompOp(e1,cop,e2) -> A.CompOp(removeU_faug e1, cop, removeU_faug e2)
| A.EqAddr(e1,e2) -> A.EqAddr(removeU_faug e1, removeU_faug e2)
| A.RelOp(e1,rop,e2) -> A.RelOp(removeU_faug e1, rop, removeU_faug e2)
| A.Tick(pot,e) -> A.Tick(pot, removeU_faug e)
| A.MapSize(mp) -> A.MapSize(removeU mp)
| A.GetTxnNum -> A.GetTxnNum
| A.GetTxnSender -> A.GetTxnSender
| A.Command(p) -> A.Command(removeU_aug p);;
(**************)
(* LP solving *)
(**************)
let potvar_map = ref (M.empty (module C.String));;
let modevar_map = ref (M.empty (module C.String));;
let num_vars = ref 0;;
let num_constraints = ref 0;;
let t_vars () = num_vars := !num_vars + 1;;
let t_cons () = num_constraints := !num_constraints + 1;;
let get_potvar v =
match M.find !potvar_map v with
None ->
let sv = ClpS.fresh_var () in
let () = t_vars () in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:0.0 [(sv, 1.0)] in
let () = potvar_map := M.add_exn !potvar_map ~key:v ~data:sv in
sv
| Some sv -> sv;;
let get_modevar v =
match M.find !modevar_map v with
None ->
let sv = ClpS.fresh_var () in
let () = t_vars () in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:0.0 ~upper:3.0 [(sv, 1.0)] in
let () = modevar_map := M.add_exn !modevar_map ~key:v ~data:sv in
sv
| Some sv -> sv;;
type entry =
Var of int * string
| Const of int;;
let get_entry p = match p with
R.Mult(R.Int(n), R.Var(v)) -> Var(n, v)
| R.Mult(R.Int(n), R.Int(1)) -> Const(n)
| _p -> raise InferImpossible;;
let rec get_expr_list e = match e with
R.Int(0) -> (0, [])
| R.Add(p,s) ->
begin
let e = get_entry p in
let (c, l) = get_expr_list s in
match e with
Var (n,v) -> (c, (n,v)::l)
| Const(n) -> (n+c, l)
end
| p ->
begin
let e = get_entry p in
match e with
Var(n,v) -> (0, [(n,v)])
| Const(n) -> (n, [])
end;;
let constr_list l = List.map (fun (n, v) -> (get_potvar v, float_of_int n)) l;;
let add_eq_constr n l =
if List.length l = 0 then ()
else
let cl = constr_list l in
let neg_n = float_of_int (-n) in
let () = t_cons () in
ClpS.add_constr_list ~lower:neg_n ~upper:neg_n cl;;
let add_ge_constr n l =
if List.length l = 0 then ()
else
let cl = constr_list l in
let neg_n = float_of_int (-n) in
let () = t_cons () in
ClpS.add_constr_list ~lower:neg_n cl;;
let eq e1 e2 =
try (R.evaluate e1) = (R.evaluate e2)
with R.NotClosed ->
let en = N.normalize (R.minus e1 e2) in
let () = if !F.verbosity >= 2 then print_string (R.pp_arith e1 ^ " = " ^ R.pp_arith e2 ^ "\n") in
let (n, l) = get_expr_list en in
let () = add_eq_constr n l in
true;;
let ge e1 e2 =
try (R.evaluate e1) >= (R.evaluate e2)
with R.NotClosed ->
let en = N.normalize (R.minus e1 e2) in
let () = if !F.verbosity >= 2 then print_string (R.pp_arith e1 ^ " >= " ^ R.pp_arith e2 ^ "\n") in
let (n, l) = get_expr_list en in
let () = add_ge_constr n l in
true;;
let m_eq v1 v2 =
if v1 = v2
then true
else
let sv1 = get_modevar v1 in
let sv2 = get_modevar v2 in
let () = if !F.verbosity >= 2 then print_string (v1 ^ " = " ^ v2 ^ "\n") in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:0.0 ~upper:0.0 [(sv1, 1.0); (sv2, -1.0)]
in true;;
let modeval m = match m with
A.Shared -> 0.0
| A.Pure -> 1.0
| A.Linear -> 2.0
| A.Transaction -> 3.0
| _m -> raise InferImpossible;;
let get_mode f = match f with
0.0 -> A.Shared
| 1.0 -> A.Pure
| 2.0 -> A.Linear
| 3.0 -> A.Transaction
| _f -> raise InferImpossible;;
let m_eq_const v m =
let c = modeval m in
let sv = get_modevar v in
let () = if !F.verbosity >= 2 then print_string (v ^ " = " ^ PP.pp_mode m ^ "\n") in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:c ~upper:c [(sv, 1.0)] in
true;;
let m_eq_pair v m1 m2 =
let c1 = modeval m1 in
let c2 = modeval m2 in
let min_val = min c1 c2 in
let max_val = max c1 c2 in
let sv = get_modevar v in
let () = if !F.verbosity >= 2 then print_string (v ^ " = " ^ PP.pp_mode A.Pure ^ " or " ^ v ^ " = " ^ PP.pp_mode A.Shared ^ "\n") in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:min_val ~upper:max_val [(sv, 1.0)] in
true;;
let min_max m1 m2 m3 =
let c1 = modeval m1 in
let c2 = modeval m2 in
let c3 = modeval m3 in
let min_val = min c1 (min c2 c3) in
let max_val = max c1 (max c2 c3) in
(min_val, max_val);;
let m_lin v =
let (min_val, max_val) = min_max A.Pure A.Linear A.Transaction in
let sv = get_modevar v in
let () = if !F.verbosity >= 2 then print_string (v ^ " = " ^ PP.pp_mode A.Pure ^ " or " ^ v ^ " = " ^ PP.pp_mode A.Linear ^ " or " ^ v ^ " = " ^ PP.pp_mode A.Transaction ^ "\n") in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:min_val ~upper:max_val [(sv, 1.0)] in
true;;
let get_potvarlist () =
M.fold_right !potvar_map ~init:[] ~f:(fun ~key:k ~data:_v l -> k::l);;
let get_modevarlist () =
M.fold_right !modevar_map ~init:[] ~f:(fun ~key:k ~data:_v l -> k::l);;
let get_solution () =
let vs = get_potvarlist () in
let ms = get_modevarlist () in
(List.map (fun v -> (v, int_of_float (ClpS.get_solution (get_potvar v)))) vs,
List.map (fun m -> (m, get_mode (ClpS.get_solution (get_modevar m)))) ms);;
let rec print_pot_solution sols =
match sols with
[] -> ()
| (v,n)::sols' ->
let () = print_string (v ^ " = " ^ string_of_int n ^ "\n") in
print_pot_solution sols';;
let rec print_mode_solution sols =
match sols with
[] -> ()
| (m,n)::sols' ->
let () = print_string (m ^ " = " ^ PP.pp_mode n ^ "\n") in
print_mode_solution sols';;
let reset () =
let () = potvar_map := M.empty (module C.String) in
let () = modevar_map := M.empty (module C.String) in
let () = mnum := 0 in
let () = vnum := 0 in
let () = ClpS.reset () in
();;
let print_stats () =
let () = print_string ("# Vars = " ^ string_of_int !num_vars ^ "\n") in
let () = print_string ("# Constraints = " ^ string_of_int !num_constraints ^ "\n") in
();;
let solve_and_print () =
let res = ClpS.first_solve () in
match res with
S.Feasible ->
let (psols, msols) = get_solution () in
let () = if !F.verbosity >= 2 then print_pot_solution psols in
let () = if !F.verbosity >= 2 then print_mode_solution msols in
(psols, msols)
| S.Infeasible ->
raise (ErrorMsg.TypeError "Infeasible LP!\n");;
| null | https://raw.githubusercontent.com/ankushdas/Nomos/db678f3981e75a1b3310bb55f66009bb23430cb1/nomos/nomos-lib/Infer.ml | ocaml | **********************************************************
Substituting potential variables for star in annotations
**********************************************************
******************************************
Substituting actual values for potential
variables as well as mode variables
******************************************
*************************************************************
*************************************************************
************
LP solving
************ | module A = Ast
module R = Arith
module N = Normalize
module S = Solver
module C = Core
module M = C.Map
module PP = Pprint
module F = NomosFlags
module ClpS = S.Clp (S.Clp_std_options);;
exception InferImpossible;;
let vnum = ref 0;;
let fresh () =
let v = "_v" ^ string_of_int !vnum in
let () = vnum := !vnum + 1 in
v;;
let remove_star pot = match pot with
A.Star ->
let v = fresh () in
A.Arith(R.Var(v))
| A.Arith e -> A.Arith e;;
let rec remove_stars_tp tp = match tp with
A.Plus(choices) -> A.Plus(remove_stars_choices choices)
| A.With(choices) -> A.With(remove_stars_choices choices)
| A.Tensor(a,b,m) -> A.Tensor(remove_stars_tp a, remove_stars_tp b,m)
| A.Lolli(a,b,m) -> A.Lolli(remove_stars_tp a, remove_stars_tp b,m)
| A.One -> A.One
| A.PayPot(pot,a) -> A.PayPot(remove_star pot, remove_stars_tp a)
| A.GetPot(pot,a) -> A.GetPot(remove_star pot, remove_stars_tp a)
| A.TpName(v) -> A.TpName(v)
| A.Up(a) -> A.Up(remove_stars_tp a)
| A.Down(a) -> A.Down(remove_stars_tp a)
| A.FArrow(t,a) -> A.FArrow(t,remove_stars_tp a)
| A.FProduct(t,a) -> A.FProduct(t,remove_stars_tp a)
| A.FMap(kt,vt) -> A.FMap(kt, vt)
| A.STMap(kt,vt) -> A.STMap(kt, remove_stars_tp vt)
| A.Coin -> A.Coin
and remove_stars_choices choices = match choices with
(l,a)::choices' -> (l,remove_stars_tp a)::(remove_stars_choices choices')
| [] -> []
and remove_stars_ftp ftp = match ftp with
A.ListTP(t,pot) -> A.ListTP(t, remove_star pot)
| A.Integer | A.Boolean | A.String | A.Address | A.VarT _ -> ftp
| A.Arrow(t1,t2) -> A.Arrow(remove_stars_ftp t1, remove_stars_ftp t2);;
let rec remove_stars_exp exp = match exp with
A.Fwd(x,y) -> A.Fwd(x,y)
| A.Spawn(x,f,xs,q) -> A.Spawn(x,f,xs, remove_stars_aug q)
| A.ExpName(x,f,xs) -> A.ExpName(x,f,xs)
| A.Lab(x,k,p) -> A.Lab(x,k, remove_stars_aug p)
| A.Case(x,branches) -> A.Case(x, remove_stars_branches branches)
| A.Send(x,w,p) -> A.Send(x,w, remove_stars_aug p)
| A.Recv(x,y,p) -> A.Recv(x,y, remove_stars_aug p)
| A.Close(x) -> A.Close(x)
| A.Wait(x,q) -> A.Wait(x, remove_stars_aug q)
| A.Work(pot,p) ->
let pot' = remove_star pot in
A.Work(pot', remove_stars_aug p)
| A.Deposit(pot,p) ->
let pot' = remove_star pot in
A.Deposit(pot', remove_stars_aug p)
| A.Pay(x,pot,p) ->
let pot' = remove_star pot in
A.Pay(x, pot', remove_stars_aug p)
| A.Get(x,pot,p) ->
let pot' = remove_star pot in
A.Get(x, pot', remove_stars_aug p)
| A.Acquire(x,y,p) -> A.Acquire(x,y, remove_stars_aug p)
| A.Accept(x,y,p) -> A.Accept(x,y, remove_stars_aug p)
| A.Release(x,y,p) -> A.Release(x,y, remove_stars_aug p)
| A.Detach(x,y,p) -> A.Detach(x,y, remove_stars_aug p)
| A.SendF(x,e,p) -> A.SendF(x, remove_stars_faug e, remove_stars_aug p)
| A.RecvF(x,y,p) -> A.RecvF(x,y, remove_stars_aug p)
| A.Let(x,e,p) -> A.Let(x, remove_stars_faug e, remove_stars_aug p)
| A.IfS(e,p1,p2) -> A.IfS(remove_stars_faug e, remove_stars_aug p1, remove_stars_aug p2)
| A.FMapCreate(mp,kt,vt,p) -> A.FMapCreate(mp, kt, vt, remove_stars_aug p)
| A.STMapCreate(mp,kt,vt,p) -> A.STMapCreate(mp, kt, vt, remove_stars_aug p)
| A.FMapInsert(mp,k,v,p) -> A.FMapInsert(mp, k, v, remove_stars_aug p)
| A.STMapInsert(mp,k,v,p) -> A.STMapInsert(mp, k, v, remove_stars_aug p)
| A.FMapDelete(v,mp,k,p) -> A.FMapDelete(v,mp, k, remove_stars_aug p)
| A.STMapDelete(v,mp,k,p) -> A.STMapDelete(v,mp, k, remove_stars_aug p)
| A.MapClose(mp,p) -> A.MapClose(mp, remove_stars_aug p)
| A.Abort -> A.Abort
| A.Print(l,args,p) -> A.Print(l,args,remove_stars_aug p)
and remove_stars_branches bs = match bs with
[] -> []
| (l,p)::bs' ->
(l, remove_stars_aug p)::
(remove_stars_branches bs')
and remove_stars_aug {A.st_data = d; A.st_structure = p} = {A.st_data = d; A.st_structure = remove_stars_exp p}
and remove_stars_faug {A.func_data = d; A.func_structure = e} = {A.func_data = d; A.func_structure = remove_stars_fexp e}
and remove_stars_fexp fexp = match fexp with
A.If(e1,e2,e3) -> A.If(remove_stars_faug e1, remove_stars_faug e2, remove_stars_faug e3)
| A.LetIn(x,e1,e2) -> A.LetIn(x, remove_stars_faug e1, remove_stars_faug e2)
| A.Bool _ | A.Int _ | A.Str _ | A.Addr _ | A.Var _ -> fexp
| A.ListE(l) -> A.ListE(List.map remove_stars_faug l)
| A.App(es) -> A.App(List.map remove_stars_faug es)
| A.Cons(e1,e2) -> A.Cons(remove_stars_faug e1, remove_stars_faug e2)
| A.Match(e1,e2,x,xs,e3) -> A.Match(remove_stars_faug e1, remove_stars_faug e2, x, xs, remove_stars_faug e3)
| A.Lambda(xs,e) -> A.Lambda(xs, remove_stars_faug e)
| A.Op(e1,op,e2) -> A.Op(remove_stars_faug e1, op, remove_stars_faug e2)
| A.CompOp(e1,cop,e2) -> A.CompOp(remove_stars_faug e1, cop, remove_stars_faug e2)
| A.EqAddr(e1,e2) -> A.EqAddr(remove_stars_faug e1, remove_stars_faug e2)
| A.RelOp(e1,rop,e2) -> A.RelOp(remove_stars_faug e1, rop, remove_stars_faug e2)
| A.Tick(pot,e) -> A.Tick(remove_star pot, remove_stars_faug e)
| A.MapSize(mp) -> A.MapSize(mp)
| A.GetTxnNum -> A.GetTxnNum
| A.GetTxnSender -> A.GetTxnSender
| A.Command(p) -> A.Command(remove_stars_aug p);;
let rec getpval v sols = match sols with
[] -> 0
| (v',n)::sols' ->
if v = v' then n
else getpval v sols';;
let rec subst_pot e sols = match e with
R.Add(e1,e2) -> R.Add(subst_pot e1 sols, subst_pot e2 sols)
| R.Sub(e1,e2) -> R.Sub(subst_pot e1 sols, subst_pot e2 sols)
| R.Mult(e1,e2) -> R.Mult(subst_pot e1 sols, subst_pot e2 sols)
| R.Int(n) -> R.Int(n)
| R.Var(v) -> R.Int(getpval v sols);;
let substitute_pot pot sols = match pot with
A.Star -> raise InferImpossible
| A.Arith e -> A.Arith (subst_pot e sols);;
let rec getmval v sols = match sols with
[] -> A.Pure
| (v',n)::sols' ->
if v = v' then n
else getmval v sols';;
let subst_mode m sols = match m with
A.MVar(v) -> getmval v sols
| _m -> raise InferImpossible;;
let substitute_mode (s,c,m) sols = (s, c, subst_mode m sols);;
let substitute_argmode arg sols = match arg with
A.FArg a -> A.FArg a
| A.STArg a -> A.STArg (substitute_mode a sols);;
let rec substitute_tp tp psols msols = match tp with
A.Plus(choices) -> A.Plus(substitute_choices choices psols msols)
| A.With(choices) -> A.With(substitute_choices choices psols msols)
| A.Tensor(a,b,m) -> A.Tensor(substitute_tp a psols msols, substitute_tp b psols msols, subst_mode m msols)
| A.Lolli(a,b,m) -> A.Lolli(substitute_tp a psols msols, substitute_tp b psols msols, subst_mode m msols)
| A.One -> A.One
| A.PayPot(pot,a) -> A.PayPot(substitute_pot pot psols, substitute_tp a psols msols)
| A.GetPot(pot,a) -> A.GetPot(substitute_pot pot psols, substitute_tp a psols msols)
| A.TpName(v) -> A.TpName(v)
| A.Up(a) -> A.Up(substitute_tp a psols msols)
| A.Down(a) -> A.Down(substitute_tp a psols msols)
| A.FArrow(t,a) -> A.FArrow(t, substitute_tp a psols msols)
| A.FProduct(t,a) -> A.FProduct(t, substitute_tp a psols msols)
| A.FMap(kt,vt) -> A.FMap(kt, vt)
| A.STMap(kt,vt) -> A.STMap(kt, substitute_tp vt psols msols)
| A.Coin -> A.Coin
and substitute_choices choices psols msols = match choices with
(l,a)::choices' -> (l,substitute_tp a psols msols)::(substitute_choices choices' psols msols)
| [] -> []
and substitute_ftp ftp psols msols = match ftp with
A.ListTP(t,pot) -> A.ListTP(t, substitute_pot pot psols)
| A.Integer | A.Boolean | A.String | A.Address | A.VarT _ -> ftp
| A.Arrow(t1,t2) -> A.Arrow(substitute_ftp t1 psols msols, substitute_ftp t2 psols msols);;
let substitute_mode_list xs sols = List.map (fun c -> substitute_argmode c sols) xs;;
let rec substitute_exp exp psols msols = match exp with
A.Fwd(x,y) -> A.Fwd(substitute_mode x msols, substitute_mode y msols)
| A.Spawn(x,f,xs,q) -> A.Spawn(substitute_mode x msols, f, substitute_mode_list xs msols, substitute_aug q psols msols)
| A.ExpName(x,f,xs) -> A.ExpName(substitute_mode x msols, f, substitute_mode_list xs msols)
| A.Lab(x,k,p) -> A.Lab(substitute_mode x msols, k, substitute_aug p psols msols)
| A.Case(x,branches) -> A.Case(substitute_mode x msols, substitute_branches branches psols msols)
| A.Send(x,w,p) -> A.Send(substitute_mode x msols, substitute_mode w msols, substitute_aug p psols msols)
| A.Recv(x,y,p) -> A.Recv(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.Close(x) -> A.Close(substitute_mode x msols)
| A.Wait(x,q) -> A.Wait(substitute_mode x msols, substitute_aug q psols msols)
| A.Work(pot,p) ->
let pot' = substitute_pot pot psols in
A.Work(pot', substitute_aug p psols msols)
| A.Deposit(pot,p) ->
let pot' = substitute_pot pot psols in
A.Deposit(pot', substitute_aug p psols msols)
| A.Pay(x,pot,p) ->
let pot' = substitute_pot pot psols in
A.Pay(substitute_mode x msols, pot', substitute_aug p psols msols)
| A.Get(x,pot,p) ->
let pot' = substitute_pot pot psols in
A.Get(substitute_mode x msols, pot', substitute_aug p psols msols)
| A.Acquire(x,y,p) -> A.Acquire(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.Accept(x,y,p) -> A.Accept(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.Release(x,y,p) -> A.Release(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.Detach(x,y,p) -> A.Detach(substitute_mode x msols, substitute_mode y msols, substitute_aug p psols msols)
| A.SendF(x,e,p) -> A.SendF(substitute_mode x msols, e, substitute_aug p psols msols)
| A.RecvF(x,y,p) -> A.RecvF(substitute_mode x msols, y, substitute_aug p psols msols)
| A.Let(x,e,p) -> A.Let(x,e, substitute_aug p psols msols)
| A.IfS(e,p1,p2) -> A.IfS(e, substitute_aug p1 psols msols, substitute_aug p2 psols msols)
| A.FMapCreate(mp,kt,vt,p) -> A.FMapCreate(substitute_mode mp msols, kt, vt, substitute_aug p psols msols)
| A.STMapCreate(mp,kt,vt,p) -> A.STMapCreate(substitute_mode mp msols, kt, vt, substitute_aug p psols msols)
| A.FMapInsert(mp,k,v,p) -> A.FMapInsert(substitute_mode mp msols, k, v, substitute_aug p psols msols)
| A.STMapInsert(mp,k,v,p) -> A.STMapInsert(substitute_mode mp msols, k, substitute_mode v msols, substitute_aug p psols msols)
| A.FMapDelete(v,mp,k,p) -> A.FMapDelete(v, substitute_mode mp msols, k, substitute_aug p psols msols)
| A.STMapDelete(v,mp,k,p) -> A.STMapDelete(substitute_mode v msols, substitute_mode mp msols, k, substitute_aug p psols msols)
| A.MapClose(mp,p) -> A.MapClose(substitute_mode mp msols, substitute_aug p psols msols)
| A.Abort -> A.Abort
| A.Print(l,args,p) -> A.Print(l,substitute_mode_list args msols,substitute_aug p psols msols)
and substitute_branches bs psols msols = match bs with
[] -> []
| (l,p)::bs' ->
(l, substitute_aug p psols msols)::
(substitute_branches bs' psols msols)
and substitute_aug {A.st_data = d; A.st_structure = p} psols msols = {A.st_data = d; A.st_structure = substitute_exp p psols msols}
and substitute_faug {A.func_data = d; A.func_structure = e} psols msols = {A.func_data = d; A.func_structure = substitute_fexp e psols msols}
and substitute_fexp fexp psols msols = match fexp with
A.If(e1,e2,e3) -> A.If(substitute_faug e1 psols msols, substitute_faug e2 psols msols, substitute_faug e3 psols msols)
| A.LetIn(x,e1,e2) -> A.LetIn(x, substitute_faug e1 psols msols, substitute_faug e2 psols msols)
| A.Bool _ | A.Int _ | A.Str _ | A.Addr _ | A.Var _ -> fexp
| A.ListE(l) -> A.ListE(List.map (fun e -> substitute_faug e psols msols) l)
| A.App(es) -> A.App(List.map (fun e -> substitute_faug e psols msols) es)
| A.Cons(e1,e2) -> A.Cons(substitute_faug e1 psols msols, substitute_faug e2 psols msols)
| A.Match(e1,e2,x,xs,e3) -> A.Match(substitute_faug e1 psols msols, substitute_faug e2 psols msols, x, xs, substitute_faug e3 psols msols)
| A.Lambda(xs,e) -> A.Lambda(xs, substitute_faug e psols msols)
| A.Op(e1,op,e2) -> A.Op(substitute_faug e1 psols msols, op, substitute_faug e2 psols msols)
| A.CompOp(e1,cop,e2) -> A.CompOp(substitute_faug e1 psols msols, cop, substitute_faug e2 psols msols)
| A.EqAddr(e1,e2) -> A.EqAddr(substitute_faug e1 psols msols, substitute_faug e2 psols msols)
| A.RelOp(e1,rop,e2) -> A.RelOp(substitute_faug e1 psols msols, rop, substitute_faug e2 psols msols)
| A.Tick(pot,e) -> A.Tick(substitute_pot pot psols, substitute_faug e psols msols)
| A.MapSize(mp) -> A.MapSize(mp)
| A.GetTxnNum -> A.GetTxnNum
| A.GetTxnSender -> A.GetTxnSender
| A.Command(p) -> A.Command(substitute_aug p psols msols);;
Substituting mode variables for U in channel and type modes
let mnum = ref 0;;
let mfresh () =
let m = "_m" ^ string_of_int !mnum in
let () = mnum := !mnum + 1 in
m;;
let unk m = match m with
A.Unknown -> true
| _m -> false;;
let removeU (s,c,m) = match m with
A.Unknown -> (s, c, A.MVar(mfresh ()))
| _m -> raise InferImpossible;;
let removeU_arg a = match a with
A.FArg a -> A.FArg a
| A.STArg c -> A.STArg (removeU c);;
let rec removeU_tp tp = match tp with
A.Plus(choices) -> A.Plus(removeU_choices choices)
| A.With(choices) -> A.With(removeU_choices choices)
| A.Tensor(a,b,m) -> if not (unk m) then raise InferImpossible else A.Tensor(removeU_tp a, removeU_tp b, A.MVar(mfresh ()))
| A.Lolli(a,b,m) -> if not (unk m) then raise InferImpossible else A.Lolli(removeU_tp a, removeU_tp b, A.MVar(mfresh ()))
| A.One -> A.One
| A.PayPot(pot,a) -> A.PayPot(pot, removeU_tp a)
| A.GetPot(pot,a) -> A.GetPot(pot, removeU_tp a)
| A.TpName(v) -> A.TpName(v)
| A.Up(a) -> A.Up(removeU_tp a)
| A.Down(a) -> A.Down(removeU_tp a)
| A.FArrow(t,a) -> A.FArrow(t,removeU_tp a)
| A.FProduct(t,a) -> A.FProduct(t,removeU_tp a)
| A.FMap(kt,vt) -> A.FMap(kt,vt)
| A.STMap(kt,vt) -> A.STMap(kt, removeU_tp vt)
| A.Coin -> A.Coin
and removeU_choices choices = match choices with
(l,a)::choices' -> (l,removeU_tp a)::(removeU_choices choices')
| [] -> [];;
let removeU_list xs = List.map (fun c -> removeU_arg c) xs;;
let rec removeU_exp exp = match exp with
A.Fwd(x,y) -> A.Fwd(removeU x, removeU y)
| A.Spawn(x,f,xs,q) -> A.Spawn(removeU x, f, removeU_list xs, removeU_aug q)
| A.ExpName(x,f,xs) -> A.ExpName(removeU x, f, removeU_list xs)
| A.Lab(x,k,p) -> A.Lab(removeU x, k, removeU_aug p)
| A.Case(x,branches) -> A.Case(removeU x, removeU_branches branches)
| A.Send(x,w,p) -> A.Send(removeU x, removeU w, removeU_aug p)
| A.Recv(x,y,p) -> A.Recv(removeU x, removeU y, removeU_aug p)
| A.Close(x) -> A.Close(removeU x)
| A.Wait(x,q) -> A.Wait(removeU x, removeU_aug q)
| A.Work(pot,p) -> A.Work(pot, removeU_aug p)
| A.Deposit(pot,p) -> A.Deposit(pot, removeU_aug p)
| A.Pay(x,pot,p) -> A.Pay(removeU x, pot, removeU_aug p)
| A.Get(x,pot,p) -> A.Get(removeU x, pot, removeU_aug p)
| A.Acquire(x,y,p) -> A.Acquire(removeU x, removeU y, removeU_aug p)
| A.Accept(x,y,p) -> A.Accept(removeU x, removeU y, removeU_aug p)
| A.Release(x,y,p) -> A.Release(removeU x, removeU y, removeU_aug p)
| A.Detach(x,y,p) -> A.Detach(removeU x, removeU y, removeU_aug p)
| A.SendF(x,e,p) -> A.SendF(removeU x, e, removeU_aug p)
| A.RecvF(x,y,p) -> A.RecvF(removeU x, y, removeU_aug p)
| A.Let(x,e,p) -> A.Let(x,e, removeU_aug p)
| A.IfS(e,p1,p2) -> A.IfS(e, removeU_aug p1, removeU_aug p2)
| A.FMapCreate(mp,kt,vt,p) -> A.FMapCreate(removeU mp, kt, vt, removeU_aug p)
| A.STMapCreate(mp,kt,vt,p) -> A.STMapCreate(removeU mp, kt, vt, removeU_aug p)
| A.FMapInsert(mp,k,v,p) -> A.FMapInsert(removeU mp, k, v, removeU_aug p)
| A.STMapInsert(mp,k,v,p) -> A.STMapInsert(removeU mp, k, removeU v, removeU_aug p)
| A.FMapDelete(v,mp,k,p) -> A.FMapDelete(v, removeU mp, k, removeU_aug p)
| A.STMapDelete(v,mp,k,p) -> A.STMapDelete(removeU v, removeU mp, k, removeU_aug p)
| A.MapClose(mp,p) -> A.MapClose(removeU mp, removeU_aug p)
| A.Abort -> A.Abort
| A.Print(l,args,p) -> A.Print(l, removeU_list args, removeU_aug p)
and removeU_branches bs = match bs with
[] -> []
| (l,p)::bs' ->
(l, removeU_aug p)::
(removeU_branches bs')
and removeU_aug {A.st_data = d; A.st_structure = p} = {A.st_data = d; A.st_structure = removeU_exp p}
and removeU_faug {A.func_data = d; A.func_structure = e} = {A.func_data = d; A.func_structure = removeU_fexp e}
and removeU_fexp fexp = match fexp with
A.If(e1,e2,e3) -> A.If(removeU_faug e1, removeU_faug e2, removeU_faug e3)
| A.LetIn(x,e1,e2) -> A.LetIn(x, removeU_faug e1, removeU_faug e2)
| A.Bool _ | A.Int _ | A.Str _ | A.Addr _ | A.Var _ -> fexp
| A.ListE(l) -> A.ListE(List.map removeU_faug l)
| A.App(es) -> A.App(List.map removeU_faug es)
| A.Cons(e1,e2) -> A.Cons(removeU_faug e1, removeU_faug e2)
| A.Match(e1,e2,x,xs,e3) -> A.Match(removeU_faug e1, removeU_faug e2, x, xs, removeU_faug e3)
| A.Lambda(xs,e) -> A.Lambda(xs, removeU_faug e)
| A.Op(e1,op,e2) -> A.Op(removeU_faug e1, op, removeU_faug e2)
| A.CompOp(e1,cop,e2) -> A.CompOp(removeU_faug e1, cop, removeU_faug e2)
| A.EqAddr(e1,e2) -> A.EqAddr(removeU_faug e1, removeU_faug e2)
| A.RelOp(e1,rop,e2) -> A.RelOp(removeU_faug e1, rop, removeU_faug e2)
| A.Tick(pot,e) -> A.Tick(pot, removeU_faug e)
| A.MapSize(mp) -> A.MapSize(removeU mp)
| A.GetTxnNum -> A.GetTxnNum
| A.GetTxnSender -> A.GetTxnSender
| A.Command(p) -> A.Command(removeU_aug p);;
let potvar_map = ref (M.empty (module C.String));;
let modevar_map = ref (M.empty (module C.String));;
let num_vars = ref 0;;
let num_constraints = ref 0;;
let t_vars () = num_vars := !num_vars + 1;;
let t_cons () = num_constraints := !num_constraints + 1;;
let get_potvar v =
match M.find !potvar_map v with
None ->
let sv = ClpS.fresh_var () in
let () = t_vars () in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:0.0 [(sv, 1.0)] in
let () = potvar_map := M.add_exn !potvar_map ~key:v ~data:sv in
sv
| Some sv -> sv;;
let get_modevar v =
match M.find !modevar_map v with
None ->
let sv = ClpS.fresh_var () in
let () = t_vars () in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:0.0 ~upper:3.0 [(sv, 1.0)] in
let () = modevar_map := M.add_exn !modevar_map ~key:v ~data:sv in
sv
| Some sv -> sv;;
type entry =
Var of int * string
| Const of int;;
let get_entry p = match p with
R.Mult(R.Int(n), R.Var(v)) -> Var(n, v)
| R.Mult(R.Int(n), R.Int(1)) -> Const(n)
| _p -> raise InferImpossible;;
let rec get_expr_list e = match e with
R.Int(0) -> (0, [])
| R.Add(p,s) ->
begin
let e = get_entry p in
let (c, l) = get_expr_list s in
match e with
Var (n,v) -> (c, (n,v)::l)
| Const(n) -> (n+c, l)
end
| p ->
begin
let e = get_entry p in
match e with
Var(n,v) -> (0, [(n,v)])
| Const(n) -> (n, [])
end;;
let constr_list l = List.map (fun (n, v) -> (get_potvar v, float_of_int n)) l;;
let add_eq_constr n l =
if List.length l = 0 then ()
else
let cl = constr_list l in
let neg_n = float_of_int (-n) in
let () = t_cons () in
ClpS.add_constr_list ~lower:neg_n ~upper:neg_n cl;;
let add_ge_constr n l =
if List.length l = 0 then ()
else
let cl = constr_list l in
let neg_n = float_of_int (-n) in
let () = t_cons () in
ClpS.add_constr_list ~lower:neg_n cl;;
let eq e1 e2 =
try (R.evaluate e1) = (R.evaluate e2)
with R.NotClosed ->
let en = N.normalize (R.minus e1 e2) in
let () = if !F.verbosity >= 2 then print_string (R.pp_arith e1 ^ " = " ^ R.pp_arith e2 ^ "\n") in
let (n, l) = get_expr_list en in
let () = add_eq_constr n l in
true;;
let ge e1 e2 =
try (R.evaluate e1) >= (R.evaluate e2)
with R.NotClosed ->
let en = N.normalize (R.minus e1 e2) in
let () = if !F.verbosity >= 2 then print_string (R.pp_arith e1 ^ " >= " ^ R.pp_arith e2 ^ "\n") in
let (n, l) = get_expr_list en in
let () = add_ge_constr n l in
true;;
let m_eq v1 v2 =
if v1 = v2
then true
else
let sv1 = get_modevar v1 in
let sv2 = get_modevar v2 in
let () = if !F.verbosity >= 2 then print_string (v1 ^ " = " ^ v2 ^ "\n") in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:0.0 ~upper:0.0 [(sv1, 1.0); (sv2, -1.0)]
in true;;
let modeval m = match m with
A.Shared -> 0.0
| A.Pure -> 1.0
| A.Linear -> 2.0
| A.Transaction -> 3.0
| _m -> raise InferImpossible;;
let get_mode f = match f with
0.0 -> A.Shared
| 1.0 -> A.Pure
| 2.0 -> A.Linear
| 3.0 -> A.Transaction
| _f -> raise InferImpossible;;
let m_eq_const v m =
let c = modeval m in
let sv = get_modevar v in
let () = if !F.verbosity >= 2 then print_string (v ^ " = " ^ PP.pp_mode m ^ "\n") in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:c ~upper:c [(sv, 1.0)] in
true;;
let m_eq_pair v m1 m2 =
let c1 = modeval m1 in
let c2 = modeval m2 in
let min_val = min c1 c2 in
let max_val = max c1 c2 in
let sv = get_modevar v in
let () = if !F.verbosity >= 2 then print_string (v ^ " = " ^ PP.pp_mode A.Pure ^ " or " ^ v ^ " = " ^ PP.pp_mode A.Shared ^ "\n") in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:min_val ~upper:max_val [(sv, 1.0)] in
true;;
let min_max m1 m2 m3 =
let c1 = modeval m1 in
let c2 = modeval m2 in
let c3 = modeval m3 in
let min_val = min c1 (min c2 c3) in
let max_val = max c1 (max c2 c3) in
(min_val, max_val);;
let m_lin v =
let (min_val, max_val) = min_max A.Pure A.Linear A.Transaction in
let sv = get_modevar v in
let () = if !F.verbosity >= 2 then print_string (v ^ " = " ^ PP.pp_mode A.Pure ^ " or " ^ v ^ " = " ^ PP.pp_mode A.Linear ^ " or " ^ v ^ " = " ^ PP.pp_mode A.Transaction ^ "\n") in
let () = t_cons () in
let () = ClpS.add_constr_list ~lower:min_val ~upper:max_val [(sv, 1.0)] in
true;;
let get_potvarlist () =
M.fold_right !potvar_map ~init:[] ~f:(fun ~key:k ~data:_v l -> k::l);;
let get_modevarlist () =
M.fold_right !modevar_map ~init:[] ~f:(fun ~key:k ~data:_v l -> k::l);;
let get_solution () =
let vs = get_potvarlist () in
let ms = get_modevarlist () in
(List.map (fun v -> (v, int_of_float (ClpS.get_solution (get_potvar v)))) vs,
List.map (fun m -> (m, get_mode (ClpS.get_solution (get_modevar m)))) ms);;
let rec print_pot_solution sols =
match sols with
[] -> ()
| (v,n)::sols' ->
let () = print_string (v ^ " = " ^ string_of_int n ^ "\n") in
print_pot_solution sols';;
let rec print_mode_solution sols =
match sols with
[] -> ()
| (m,n)::sols' ->
let () = print_string (m ^ " = " ^ PP.pp_mode n ^ "\n") in
print_mode_solution sols';;
let reset () =
let () = potvar_map := M.empty (module C.String) in
let () = modevar_map := M.empty (module C.String) in
let () = mnum := 0 in
let () = vnum := 0 in
let () = ClpS.reset () in
();;
let print_stats () =
let () = print_string ("# Vars = " ^ string_of_int !num_vars ^ "\n") in
let () = print_string ("# Constraints = " ^ string_of_int !num_constraints ^ "\n") in
();;
let solve_and_print () =
let res = ClpS.first_solve () in
match res with
S.Feasible ->
let (psols, msols) = get_solution () in
let () = if !F.verbosity >= 2 then print_pot_solution psols in
let () = if !F.verbosity >= 2 then print_mode_solution msols in
(psols, msols)
| S.Infeasible ->
raise (ErrorMsg.TypeError "Infeasible LP!\n");;
|
58488f949eaa00a8be1ad13df53bf7677407219b93c25f9bda9d83fa0970b180 | CSCfi/rems | category.cljs | (ns rems.administration.category
(:require [re-frame.core :as rf]
[rems.administration.administration :as administration]
[rems.administration.components :refer [inline-info-field localized-info-field]]
[rems.atoms :as atoms :refer [document-title]]
[rems.collapsible :as collapsible]
[rems.flash-message :as flash-message]
[rems.common.roles :as roles]
[rems.common.util :refer [parse-int]]
[rems.spinner :as spinner]
[rems.text :refer [text localized]]
[rems.util :refer [fetch navigate! post!]]))
(rf/reg-event-fx
::enter-page
(fn [{:keys [db]} [_ category-id]]
{:dispatch [::fetch-category category-id]}))
(rf/reg-event-fx
::fetch-category
(fn [{:keys [db]} [_ category-id]]
(fetch (str "/api/categories/" category-id)
{:handler #(rf/dispatch [::fetch-category-result %])
:error-handler (flash-message/default-error-handler :top "Fetch category")})
{:db (assoc db ::loading? true)}))
(rf/reg-event-fx
::fetch-category-result
(fn [{:keys [db]} [_ category]]
{:db (-> db
(assoc ::category category)
(dissoc ::loading?))}))
(rf/reg-event-fx
::delete-category
(fn [{:keys [db]} _]
(let [description [text :t.administration/delete]
category-id (parse-int (get-in db [::category :category/id]))]
(post! "/api/categories/delete"
{:params {:category/id category-id}
:handler (flash-message/status-update-handler
:top description #(navigate! "/administration/categories"))
:error-handler (flash-message/default-error-handler :top description)}))
{}))
(rf/reg-sub ::category (fn [db _] (::category db)))
(rf/reg-sub ::loading? (fn [db _] (::loading? db)))
(defn- category-link [category]
[atoms/link nil
(str "/administration/categories/" (:category/id category))
(localized (:category/title category))])
(defn- to-edit-category [category-id]
[atoms/link {:class "btn btn-primary" :id :edit}
(str "/administration/categories/edit/" category-id)
(text :t.administration/edit)])
(defn- delete-category-button []
[:button#delete.btn.btn-primary
{:type :button
:on-click #(when (js/confirm (text :t.administration/delete-confirmation))
(rf/dispatch [::delete-category]))}
(text :t.administration/delete)])
(defn category-view []
(let [category (rf/subscribe [::category])
language (rf/subscribe [:language])]
[:div.spaced-vertically-3
[collapsible/component
{:id "category"
:title [:span (get-in @category [:category/title @language])]
:always [:div
[localized-info-field (:category/title @category) {:label (text :t.administration/title)}]
[localized-info-field (:category/description @category) {:label (text :t.administration/description)}]
[inline-info-field (text :t.administration/display-order) (:category/display-order @category)]
[inline-info-field (text :t.administration/category-children)
(when-let [categories (:category/children @category)]
(doall (interpose ", " (for [cat categories]
^{:key {:category/id cat}}
[category-link cat]))))]]}]
[:div.col.commands
[administration/back-button "/administration/categories"]
[roles/show-when roles/+admin-write-roles+
[delete-category-button]
[to-edit-category (:category/id @category)]]]]))
(defn category-page []
(let [loading? (rf/subscribe [::loading?])]
[:div
[administration/navigator]
[document-title (text :t.administration/category)]
[flash-message/component :top]
(if @loading?
[spinner/big]
[category-view])]))
| null | https://raw.githubusercontent.com/CSCfi/rems/4d172447f68b16e47eca714b400dc04c21dd3d95/src/cljs/rems/administration/category.cljs | clojure | (ns rems.administration.category
(:require [re-frame.core :as rf]
[rems.administration.administration :as administration]
[rems.administration.components :refer [inline-info-field localized-info-field]]
[rems.atoms :as atoms :refer [document-title]]
[rems.collapsible :as collapsible]
[rems.flash-message :as flash-message]
[rems.common.roles :as roles]
[rems.common.util :refer [parse-int]]
[rems.spinner :as spinner]
[rems.text :refer [text localized]]
[rems.util :refer [fetch navigate! post!]]))
(rf/reg-event-fx
::enter-page
(fn [{:keys [db]} [_ category-id]]
{:dispatch [::fetch-category category-id]}))
(rf/reg-event-fx
::fetch-category
(fn [{:keys [db]} [_ category-id]]
(fetch (str "/api/categories/" category-id)
{:handler #(rf/dispatch [::fetch-category-result %])
:error-handler (flash-message/default-error-handler :top "Fetch category")})
{:db (assoc db ::loading? true)}))
(rf/reg-event-fx
::fetch-category-result
(fn [{:keys [db]} [_ category]]
{:db (-> db
(assoc ::category category)
(dissoc ::loading?))}))
(rf/reg-event-fx
::delete-category
(fn [{:keys [db]} _]
(let [description [text :t.administration/delete]
category-id (parse-int (get-in db [::category :category/id]))]
(post! "/api/categories/delete"
{:params {:category/id category-id}
:handler (flash-message/status-update-handler
:top description #(navigate! "/administration/categories"))
:error-handler (flash-message/default-error-handler :top description)}))
{}))
(rf/reg-sub ::category (fn [db _] (::category db)))
(rf/reg-sub ::loading? (fn [db _] (::loading? db)))
(defn- category-link [category]
[atoms/link nil
(str "/administration/categories/" (:category/id category))
(localized (:category/title category))])
(defn- to-edit-category [category-id]
[atoms/link {:class "btn btn-primary" :id :edit}
(str "/administration/categories/edit/" category-id)
(text :t.administration/edit)])
(defn- delete-category-button []
[:button#delete.btn.btn-primary
{:type :button
:on-click #(when (js/confirm (text :t.administration/delete-confirmation))
(rf/dispatch [::delete-category]))}
(text :t.administration/delete)])
(defn category-view []
(let [category (rf/subscribe [::category])
language (rf/subscribe [:language])]
[:div.spaced-vertically-3
[collapsible/component
{:id "category"
:title [:span (get-in @category [:category/title @language])]
:always [:div
[localized-info-field (:category/title @category) {:label (text :t.administration/title)}]
[localized-info-field (:category/description @category) {:label (text :t.administration/description)}]
[inline-info-field (text :t.administration/display-order) (:category/display-order @category)]
[inline-info-field (text :t.administration/category-children)
(when-let [categories (:category/children @category)]
(doall (interpose ", " (for [cat categories]
^{:key {:category/id cat}}
[category-link cat]))))]]}]
[:div.col.commands
[administration/back-button "/administration/categories"]
[roles/show-when roles/+admin-write-roles+
[delete-category-button]
[to-edit-category (:category/id @category)]]]]))
(defn category-page []
(let [loading? (rf/subscribe [::loading?])]
[:div
[administration/navigator]
[document-title (text :t.administration/category)]
[flash-message/component :top]
(if @loading?
[spinner/big]
[category-view])]))
| |
a339094fcd87b5f1f8ed2894f13ce5ff70a08320109741d917b214e0599e86ca | agentultra/adventure-engine | Keystroke.hs | |
Module : . Widgets . Containers . Keystroke
Copyright : ( c ) 2018
License : BSD-3 - Clause ( see the LICENSE file )
Maintainer :
Stability : experimental
Portability : non - portable
Container which generates user provided events when combinations of keys occur .
Using these event makes sense at the application or Composite level . If you are
implementing a widget from scratch , keyboard events are directly available .
The shortcut definitions are provided as a list of tuples of ' Text ' , containing
the key combination and associated event . The widget handles unordered
combinations of multiple keys at the same time , but does not support ordered
sequences ( pressing " a " , releasing , then " b " and " c " ) . The available keys are :
- Mod keys : A , Alt , C , Ctrl , Cmd , O , Option , S , Shift
- Action keys : Caps , Delete , Enter , Esc , Return , Space , Tab
- Arrows : Up , Down , Left , Right
- Function keys : F1 - F12
- Lowercase letters ( uppercase keys are reserved for mod and action keys )
- Numbers
These can be combined , for example :
- Copy : " Ctrl - c " or " C - c "
- App config : " Ctrl - Shift - p " or " C - S - p "
Module : Monomer.Widgets.Containers.Keystroke
Copyright : (c) 2018 Francisco Vallarino
License : BSD-3-Clause (see the LICENSE file)
Maintainer :
Stability : experimental
Portability : non-portable
Container which generates user provided events when combinations of keys occur.
Using these event makes sense at the application or Composite level. If you are
implementing a widget from scratch, keyboard events are directly available.
The shortcut definitions are provided as a list of tuples of 'Text', containing
the key combination and associated event. The widget handles unordered
combinations of multiple keys at the same time, but does not support ordered
sequences (pressing "a", releasing, then "b" and "c"). The available keys are:
- Mod keys: A, Alt, C, Ctrl, Cmd, O, Option, S, Shift
- Action keys: Caps, Delete, Enter, Esc, Return, Space, Tab
- Arrows: Up, Down, Left, Right
- Function keys: F1-F12
- Lowercase letters (uppercase keys are reserved for mod and action keys)
- Numbers
These can be combined, for example:
- Copy: "Ctrl-c" or "C-c"
- App config: "Ctrl-Shift-p" or "C-S-p"
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE TemplateHaskell #
{-# LANGUAGE Strict #-}
module Adventure.GUI.Widgets.Keystroke (
-- * Configuration
KeystrokeCfg,
-- * Constructors
keystroke,
keystroke_
) where
import Control.Applicative ((<|>))
import Control.Lens ((&), (^.), (.~), (%~), at)
import Control.Lens.TH (abbreviatedFields, makeLensesWith)
import Data.Bifunctor (first)
import Data.Char (chr, isAscii, isPrint, ord)
import Data.Default
import Data.List (foldl')
import Data.Maybe
import Data.Set (Set)
import Data.Text (Text)
import qualified Data.Map as M
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import qualified Data.Text as T
import Monomer.Widgets.Container
import Monomer.Widgets.Containers.Scroll
import qualified Monomer.Lens as L
import Debug.Trace
|
Configuration options for keystroke :
- ' ignoreChildrenEvts ' : If True , when a shortcut is detected , the KeyAction
event will not be passed down to children .
Configuration options for keystroke:
- 'ignoreChildrenEvts': If True, when a shortcut is detected, the KeyAction
event will not be passed down to children.
-}
newtype KeystrokeCfg = KeystrokeCfg {
_kscIgnoreChildren :: Maybe Bool
}
instance Default KeystrokeCfg where
def = KeystrokeCfg {
_kscIgnoreChildren = Nothing
}
instance Semigroup KeystrokeCfg where
(<>) t1 t2 = KeystrokeCfg {
_kscIgnoreChildren = _kscIgnoreChildren t2 <|> _kscIgnoreChildren t1
}
instance Monoid KeystrokeCfg where
mempty = def
instance CmbIgnoreChildrenEvts KeystrokeCfg where
ignoreChildrenEvts_ ignore = def {
_kscIgnoreChildren = Just ignore
}
data KeyStroke = KeyStroke {
_kstKsC :: Bool,
_kstKsCtrl :: Bool,
_kstKsCmd :: Bool,
_kstKsAlt :: Bool,
_kstKsShift :: Bool,
_kstKsKeys :: Set KeyCode
} deriving (Eq, Show)
instance Default KeyStroke where
def = KeyStroke {
_kstKsC = False,
_kstKsCtrl = False,
_kstKsCmd = False,
_kstKsAlt = False,
_kstKsShift = False,
_kstKsKeys = Set.empty
}
makeLensesWith abbreviatedFields ''KeyStroke
-- | Creates a keystroke container with a single node as child.
keystroke :: WidgetEvent e => [(Text, e)] -> WidgetNode s e -> WidgetNode s e
keystroke bindings managed = keystroke_ bindings def managed
-- | Creates a keystroke container with a single node as child. Accepts config,
keystroke_
:: WidgetEvent e
=> [(Text, e)]
-> [KeystrokeCfg]
-> WidgetNode s e
-> WidgetNode s e
keystroke_ bindings configs managed = makeNode widget managed where
config = mconcat configs
newBindings = fmap (first textToStroke) bindings
widget = makeKeystroke newBindings config
makeNode :: Widget s e -> WidgetNode s e -> WidgetNode s e
makeNode widget managedWidget = defaultWidgetNode "keystroke" widget
& L.info . L.focusable .~ False
& L.children .~ Seq.singleton managedWidget
makeKeystroke :: WidgetEvent e => [(KeyStroke, e)] -> KeystrokeCfg -> Widget s e
makeKeystroke bindings config = widget where
widget = createContainer () def {
containerHandleEvent = handleEvent
}
handleEvent wenv node target evt = case evt of
KeyAction mod code KeyPressed -> Just result where
ignoreChildren = Just True == _kscIgnoreChildren config
newWenv = wenv & L.inputStatus %~ removeMods
evts = snd <$> filter (keyStrokeActive newWenv code . fst) bindings
scrollToReqs = maybeToList ((\wid -> SendMessage wid (ScrollTo (Rect 20 20 (200000) (20000)))) <$> findWidgetIdFromPath wenv (Seq.fromList [0, 0, 0, 0]))
reqs
| ignoreChildren && not (null evts) = [IgnoreChildrenEvents]
| otherwise = []
result = resultReqsEvts node (if null evts then reqs else reqs ++ scrollToReqs) evts
_ -> Nothing
keyStrokeActive :: WidgetEnv s e -> KeyCode -> KeyStroke -> Bool
keyStrokeActive wenv code ks = currValid && allPressed && validMods where
status = wenv ^. L.inputStatus
keyMod = status ^. L.keyMod
pressedKeys = M.filter (== KeyPressed) (status ^. L.keys)
currValid = code `elem` (ks ^. ksKeys) || code `elem` modKeys
allPressed = M.keysSet pressedKeys == ks ^. ksKeys
ctrlPressed = isCtrlPressed keyMod
cmdPressed = isMacOS wenv && isGUIPressed keyMod
validC = not (ks ^. ksC) || ks ^. ksC == (ctrlPressed || cmdPressed)
validCtrl = ks ^. ksCtrl == ctrlPressed || ctrlPressed && validC
validCmd = ks ^. ksCmd == cmdPressed || cmdPressed && validC
validShift = ks ^. ksShift == isShiftPressed keyMod
validAlt = ks ^. ksAlt == isAltPressed keyMod
validMods = (validC && validCtrl && validCmd) && validShift && validAlt
textToStroke :: Text -> KeyStroke
textToStroke text = ks where
parts = T.split (=='-') text
ks = foldl' partToStroke def parts
partToStroke :: KeyStroke -> Text -> KeyStroke
partToStroke ks "A" = ks & ksAlt .~ True
partToStroke ks "Alt" = ks & ksAlt .~ True
partToStroke ks "C" = ks & ksC .~ True
partToStroke ks "Ctrl" = ks & ksCtrl .~ True
partToStroke ks "Cmd" = ks & ksCmd .~ True
partToStroke ks "O" = ks & ksAlt .~ True
partToStroke ks "Option" = ks & ksAlt .~ True
partToStroke ks "S" = ks & ksShift .~ True
partToStroke ks "Shift" = ks & ksShift .~ True
-- Main keys
partToStroke ks "Caps" = ks & ksKeys %~ Set.insert keyCapsLock
partToStroke ks "Delete" = ks & ksKeys %~ Set.insert keyDelete
partToStroke ks "Enter" = ks & ksKeys %~ Set.insert keyReturn
partToStroke ks "Esc" = ks & ksKeys %~ Set.insert keyEscape
partToStroke ks "Return" = ks & ksKeys %~ Set.insert keyReturn
partToStroke ks "Space" = ks & ksKeys %~ Set.insert keySpace
partToStroke ks "Tab" = ks & ksKeys %~ Set.insert keyTab
Arrows
partToStroke ks "Up" = ks & ksKeys %~ Set.insert keyUp
partToStroke ks "Down" = ks & ksKeys %~ Set.insert keyDown
partToStroke ks "Left" = ks & ksKeys %~ Set.insert keyLeft
partToStroke ks "Right" = ks & ksKeys %~ Set.insert keyRight
-- Function keys
partToStroke ks "F1" = ks & ksKeys %~ Set.insert keyF1
partToStroke ks "F2" = ks & ksKeys %~ Set.insert keyF2
partToStroke ks "F3" = ks & ksKeys %~ Set.insert keyF3
partToStroke ks "F4" = ks & ksKeys %~ Set.insert keyF4
partToStroke ks "F5" = ks & ksKeys %~ Set.insert keyF5
partToStroke ks "F6" = ks & ksKeys %~ Set.insert keyF6
partToStroke ks "F7" = ks & ksKeys %~ Set.insert keyF7
partToStroke ks "F8" = ks & ksKeys %~ Set.insert keyF8
partToStroke ks "F9" = ks & ksKeys %~ Set.insert keyF9
partToStroke ks "F10" = ks & ksKeys %~ Set.insert keyF10
partToStroke ks "F11" = ks & ksKeys %~ Set.insert keyF11
partToStroke ks "F12" = ks & ksKeys %~ Set.insert keyF12
-- Other keys (numbers, letters, points, etc)
partToStroke ks txt
| isValid = ks & ksKeys %~ Set.insert (KeyCode (ord txtHead))
| otherwise = ks
where
isValid = T.length txt == 1 && isAscii txtHead && isPrint txtHead
txtHead = T.index txt 0
removeMods :: InputStatus -> InputStatus
removeMods status = status
& L.keys %~ M.filterWithKey (\k v -> k `notElem` modKeys)
modKeys :: [KeyCode]
modKeys = [
keyLAlt, keyRAlt, keyLCtrl, keyRCtrl, keyLGUI, keyRGUI, keyLShift, keyRShift
]
| null | https://raw.githubusercontent.com/agentultra/adventure-engine/ad89279638acefa969f03a3ab973a66e62e20868/src/Adventure/GUI/Widgets/Keystroke.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE Strict #
* Configuration
* Constructors
| Creates a keystroke container with a single node as child.
| Creates a keystroke container with a single node as child. Accepts config,
Main keys
Function keys
Other keys (numbers, letters, points, etc) | |
Module : . Widgets . Containers . Keystroke
Copyright : ( c ) 2018
License : BSD-3 - Clause ( see the LICENSE file )
Maintainer :
Stability : experimental
Portability : non - portable
Container which generates user provided events when combinations of keys occur .
Using these event makes sense at the application or Composite level . If you are
implementing a widget from scratch , keyboard events are directly available .
The shortcut definitions are provided as a list of tuples of ' Text ' , containing
the key combination and associated event . The widget handles unordered
combinations of multiple keys at the same time , but does not support ordered
sequences ( pressing " a " , releasing , then " b " and " c " ) . The available keys are :
- Mod keys : A , Alt , C , Ctrl , Cmd , O , Option , S , Shift
- Action keys : Caps , Delete , Enter , Esc , Return , Space , Tab
- Arrows : Up , Down , Left , Right
- Function keys : F1 - F12
- Lowercase letters ( uppercase keys are reserved for mod and action keys )
- Numbers
These can be combined , for example :
- Copy : " Ctrl - c " or " C - c "
- App config : " Ctrl - Shift - p " or " C - S - p "
Module : Monomer.Widgets.Containers.Keystroke
Copyright : (c) 2018 Francisco Vallarino
License : BSD-3-Clause (see the LICENSE file)
Maintainer :
Stability : experimental
Portability : non-portable
Container which generates user provided events when combinations of keys occur.
Using these event makes sense at the application or Composite level. If you are
implementing a widget from scratch, keyboard events are directly available.
The shortcut definitions are provided as a list of tuples of 'Text', containing
the key combination and associated event. The widget handles unordered
combinations of multiple keys at the same time, but does not support ordered
sequences (pressing "a", releasing, then "b" and "c"). The available keys are:
- Mod keys: A, Alt, C, Ctrl, Cmd, O, Option, S, Shift
- Action keys: Caps, Delete, Enter, Esc, Return, Space, Tab
- Arrows: Up, Down, Left, Right
- Function keys: F1-F12
- Lowercase letters (uppercase keys are reserved for mod and action keys)
- Numbers
These can be combined, for example:
- Copy: "Ctrl-c" or "C-c"
- App config: "Ctrl-Shift-p" or "C-S-p"
-}
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE TemplateHaskell #
module Adventure.GUI.Widgets.Keystroke (
KeystrokeCfg,
keystroke,
keystroke_
) where
import Control.Applicative ((<|>))
import Control.Lens ((&), (^.), (.~), (%~), at)
import Control.Lens.TH (abbreviatedFields, makeLensesWith)
import Data.Bifunctor (first)
import Data.Char (chr, isAscii, isPrint, ord)
import Data.Default
import Data.List (foldl')
import Data.Maybe
import Data.Set (Set)
import Data.Text (Text)
import qualified Data.Map as M
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import qualified Data.Text as T
import Monomer.Widgets.Container
import Monomer.Widgets.Containers.Scroll
import qualified Monomer.Lens as L
import Debug.Trace
|
Configuration options for keystroke :
- ' ignoreChildrenEvts ' : If True , when a shortcut is detected , the KeyAction
event will not be passed down to children .
Configuration options for keystroke:
- 'ignoreChildrenEvts': If True, when a shortcut is detected, the KeyAction
event will not be passed down to children.
-}
newtype KeystrokeCfg = KeystrokeCfg {
_kscIgnoreChildren :: Maybe Bool
}
instance Default KeystrokeCfg where
def = KeystrokeCfg {
_kscIgnoreChildren = Nothing
}
instance Semigroup KeystrokeCfg where
(<>) t1 t2 = KeystrokeCfg {
_kscIgnoreChildren = _kscIgnoreChildren t2 <|> _kscIgnoreChildren t1
}
instance Monoid KeystrokeCfg where
mempty = def
instance CmbIgnoreChildrenEvts KeystrokeCfg where
ignoreChildrenEvts_ ignore = def {
_kscIgnoreChildren = Just ignore
}
data KeyStroke = KeyStroke {
_kstKsC :: Bool,
_kstKsCtrl :: Bool,
_kstKsCmd :: Bool,
_kstKsAlt :: Bool,
_kstKsShift :: Bool,
_kstKsKeys :: Set KeyCode
} deriving (Eq, Show)
instance Default KeyStroke where
def = KeyStroke {
_kstKsC = False,
_kstKsCtrl = False,
_kstKsCmd = False,
_kstKsAlt = False,
_kstKsShift = False,
_kstKsKeys = Set.empty
}
makeLensesWith abbreviatedFields ''KeyStroke
keystroke :: WidgetEvent e => [(Text, e)] -> WidgetNode s e -> WidgetNode s e
keystroke bindings managed = keystroke_ bindings def managed
keystroke_
:: WidgetEvent e
=> [(Text, e)]
-> [KeystrokeCfg]
-> WidgetNode s e
-> WidgetNode s e
keystroke_ bindings configs managed = makeNode widget managed where
config = mconcat configs
newBindings = fmap (first textToStroke) bindings
widget = makeKeystroke newBindings config
makeNode :: Widget s e -> WidgetNode s e -> WidgetNode s e
makeNode widget managedWidget = defaultWidgetNode "keystroke" widget
& L.info . L.focusable .~ False
& L.children .~ Seq.singleton managedWidget
makeKeystroke :: WidgetEvent e => [(KeyStroke, e)] -> KeystrokeCfg -> Widget s e
makeKeystroke bindings config = widget where
widget = createContainer () def {
containerHandleEvent = handleEvent
}
handleEvent wenv node target evt = case evt of
KeyAction mod code KeyPressed -> Just result where
ignoreChildren = Just True == _kscIgnoreChildren config
newWenv = wenv & L.inputStatus %~ removeMods
evts = snd <$> filter (keyStrokeActive newWenv code . fst) bindings
scrollToReqs = maybeToList ((\wid -> SendMessage wid (ScrollTo (Rect 20 20 (200000) (20000)))) <$> findWidgetIdFromPath wenv (Seq.fromList [0, 0, 0, 0]))
reqs
| ignoreChildren && not (null evts) = [IgnoreChildrenEvents]
| otherwise = []
result = resultReqsEvts node (if null evts then reqs else reqs ++ scrollToReqs) evts
_ -> Nothing
keyStrokeActive :: WidgetEnv s e -> KeyCode -> KeyStroke -> Bool
keyStrokeActive wenv code ks = currValid && allPressed && validMods where
status = wenv ^. L.inputStatus
keyMod = status ^. L.keyMod
pressedKeys = M.filter (== KeyPressed) (status ^. L.keys)
currValid = code `elem` (ks ^. ksKeys) || code `elem` modKeys
allPressed = M.keysSet pressedKeys == ks ^. ksKeys
ctrlPressed = isCtrlPressed keyMod
cmdPressed = isMacOS wenv && isGUIPressed keyMod
validC = not (ks ^. ksC) || ks ^. ksC == (ctrlPressed || cmdPressed)
validCtrl = ks ^. ksCtrl == ctrlPressed || ctrlPressed && validC
validCmd = ks ^. ksCmd == cmdPressed || cmdPressed && validC
validShift = ks ^. ksShift == isShiftPressed keyMod
validAlt = ks ^. ksAlt == isAltPressed keyMod
validMods = (validC && validCtrl && validCmd) && validShift && validAlt
textToStroke :: Text -> KeyStroke
textToStroke text = ks where
parts = T.split (=='-') text
ks = foldl' partToStroke def parts
partToStroke :: KeyStroke -> Text -> KeyStroke
partToStroke ks "A" = ks & ksAlt .~ True
partToStroke ks "Alt" = ks & ksAlt .~ True
partToStroke ks "C" = ks & ksC .~ True
partToStroke ks "Ctrl" = ks & ksCtrl .~ True
partToStroke ks "Cmd" = ks & ksCmd .~ True
partToStroke ks "O" = ks & ksAlt .~ True
partToStroke ks "Option" = ks & ksAlt .~ True
partToStroke ks "S" = ks & ksShift .~ True
partToStroke ks "Shift" = ks & ksShift .~ True
partToStroke ks "Caps" = ks & ksKeys %~ Set.insert keyCapsLock
partToStroke ks "Delete" = ks & ksKeys %~ Set.insert keyDelete
partToStroke ks "Enter" = ks & ksKeys %~ Set.insert keyReturn
partToStroke ks "Esc" = ks & ksKeys %~ Set.insert keyEscape
partToStroke ks "Return" = ks & ksKeys %~ Set.insert keyReturn
partToStroke ks "Space" = ks & ksKeys %~ Set.insert keySpace
partToStroke ks "Tab" = ks & ksKeys %~ Set.insert keyTab
Arrows
partToStroke ks "Up" = ks & ksKeys %~ Set.insert keyUp
partToStroke ks "Down" = ks & ksKeys %~ Set.insert keyDown
partToStroke ks "Left" = ks & ksKeys %~ Set.insert keyLeft
partToStroke ks "Right" = ks & ksKeys %~ Set.insert keyRight
partToStroke ks "F1" = ks & ksKeys %~ Set.insert keyF1
partToStroke ks "F2" = ks & ksKeys %~ Set.insert keyF2
partToStroke ks "F3" = ks & ksKeys %~ Set.insert keyF3
partToStroke ks "F4" = ks & ksKeys %~ Set.insert keyF4
partToStroke ks "F5" = ks & ksKeys %~ Set.insert keyF5
partToStroke ks "F6" = ks & ksKeys %~ Set.insert keyF6
partToStroke ks "F7" = ks & ksKeys %~ Set.insert keyF7
partToStroke ks "F8" = ks & ksKeys %~ Set.insert keyF8
partToStroke ks "F9" = ks & ksKeys %~ Set.insert keyF9
partToStroke ks "F10" = ks & ksKeys %~ Set.insert keyF10
partToStroke ks "F11" = ks & ksKeys %~ Set.insert keyF11
partToStroke ks "F12" = ks & ksKeys %~ Set.insert keyF12
partToStroke ks txt
| isValid = ks & ksKeys %~ Set.insert (KeyCode (ord txtHead))
| otherwise = ks
where
isValid = T.length txt == 1 && isAscii txtHead && isPrint txtHead
txtHead = T.index txt 0
removeMods :: InputStatus -> InputStatus
removeMods status = status
& L.keys %~ M.filterWithKey (\k v -> k `notElem` modKeys)
modKeys :: [KeyCode]
modKeys = [
keyLAlt, keyRAlt, keyLCtrl, keyRCtrl, keyLGUI, keyRGUI, keyLShift, keyRShift
]
|
e25887c7a92be3e1b84f9dc41516d597b5eb98df8a09bf629c6871fc25c5e0c7 | OctopiChalmers/haski | Util.hs | {-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuantifiedConstraints #
# LANGUAGE UndecidableInstances #
module Haski.Util where
import Control.Monad.State.Lazy (StateT, get, execState, modify)
import Control.Monad (replicateM)
import Haski.Type
---------
-- Named
---------
type Name = String
-- Name things, even dolphins do!
class Named a where
getName :: a -> Name
------
-- Ex
------
-- Consider types `Var a` and Exp a`,
where Var , Exp : : * - > *
-- The type `Ex` (exists) allows us to say `Ex Var` and `Ex Exp`
-- when we don't care about `a` (but only that there exists one)
data Ex f where
Ex :: LT a => f a -> Ex f
exMap :: (forall a . f a -> g a) -> Ex f -> Ex g
exMap f (Ex x) = Ex (f x)
exMapM :: Monad m => (forall a . f a -> m (g a)) -> Ex f -> m (Ex g)
exMapM f (Ex x) = Ex <$> (f x)
-- eliminate an existential quantification
extract :: (forall a . LT a => f a -> b) -> Ex f -> b
extract f (Ex x) = f x
instance (forall a . LT a => Eq (f a)) => Eq (Ex f) where
(Ex x) == (Ex y) = maybe False (==y) (gcast x)
instance (forall a . LT a => Ord (f a)) => Ord (Ex f) where
(Ex x) <= (Ex y) = maybe False (<=y) (gcast x)
---------
-- Plant
---------
-- Plant is a `put` specialized to fields in the state
class Plant s a where
plant :: (Monad m) => a -> StateT s m ()
-- cons a list element in state
consTo :: (Monad m, Plant s [a]) => (s -> [a]) -> a -> StateT s m ()
consTo r x = do
xs <- r <$> get
plant (x : xs)
type Seed = Int
nextSeed :: Int -> Int
nextSeed = (+1)
class (Plant s Seed) => Fresh s where
getSeed :: (Monad m) => StateT s m Seed
freshName :: (Fresh s, Monad m) => String -> StateT s m (String)
freshName pre = do
seed <- getSeed
plant (nextSeed seed)
return $ pre ++ (letters !! seed)
where
letters = [1..] >>= flip replicateM ['a'..'z']
| null | https://raw.githubusercontent.com/OctopiChalmers/haski/97835d6d90d0c82d29864db03955db0aaaf08c67/src/Haski/Util.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE Rank2Types #
-------
Named
-------
Name things, even dolphins do!
----
Ex
----
Consider types `Var a` and Exp a`,
The type `Ex` (exists) allows us to say `Ex Var` and `Ex Exp`
when we don't care about `a` (but only that there exists one)
eliminate an existential quantification
-------
Plant
-------
Plant is a `put` specialized to fields in the state
cons a list element in state | # LANGUAGE FlexibleContexts #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE QuantifiedConstraints #
# LANGUAGE UndecidableInstances #
module Haski.Util where
import Control.Monad.State.Lazy (StateT, get, execState, modify)
import Control.Monad (replicateM)
import Haski.Type
type Name = String
class Named a where
getName :: a -> Name
where Var , Exp : : * - > *
data Ex f where
Ex :: LT a => f a -> Ex f
exMap :: (forall a . f a -> g a) -> Ex f -> Ex g
exMap f (Ex x) = Ex (f x)
exMapM :: Monad m => (forall a . f a -> m (g a)) -> Ex f -> m (Ex g)
exMapM f (Ex x) = Ex <$> (f x)
extract :: (forall a . LT a => f a -> b) -> Ex f -> b
extract f (Ex x) = f x
instance (forall a . LT a => Eq (f a)) => Eq (Ex f) where
(Ex x) == (Ex y) = maybe False (==y) (gcast x)
instance (forall a . LT a => Ord (f a)) => Ord (Ex f) where
(Ex x) <= (Ex y) = maybe False (<=y) (gcast x)
class Plant s a where
plant :: (Monad m) => a -> StateT s m ()
consTo :: (Monad m, Plant s [a]) => (s -> [a]) -> a -> StateT s m ()
consTo r x = do
xs <- r <$> get
plant (x : xs)
type Seed = Int
nextSeed :: Int -> Int
nextSeed = (+1)
class (Plant s Seed) => Fresh s where
getSeed :: (Monad m) => StateT s m Seed
freshName :: (Fresh s, Monad m) => String -> StateT s m (String)
freshName pre = do
seed <- getSeed
plant (nextSeed seed)
return $ pre ++ (letters !! seed)
where
letters = [1..] >>= flip replicateM ['a'..'z']
|
770fb3142de942448e7513106d8648d62abaf5783053909f02f747ee9c60bb8d | sbcl/sbcl | sxhash.lisp | that part of SXHASH logic which runs not only in the target Lisp but
;;;; in the cross-compilation host Lisp
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
(in-package "SB-C")
;;; CAUTION: transforms are selected in the *reverse* order of definition,
so define the most general first , followed by more specific .
I once tried to fix that glitch by using instead of PUSH into
;;; FUN-INFO-TRANSFORMS, and of course it broke things because we depend on such
;;; stupidity. It would be remedied by reversing all definitions whenever
;;; it matters but I didn't feel like figuring out all places where it does.
(deftransform sxhash ((x) (t))
(let ((type (lvar-type x)))
;; It is common for structure slots to have a :TYPE resembling (OR STRING NULL),
;; and also common to create custom hash calculations on structures with such slots.
;; So it makes sense for the compiler to try to pick off cases where the slot type
has a specialized hash computation via sxhash after picking off NIL .
(or (dolist (case '((simple-string . %sxhash-simple-string)
(string . %sxhash-string)
(simple-bit-vector . %sxhash-simple-bit-vector)
(bit-vector . %sxhash-bit-vector)))
(cond ((csubtypep type (specifier-type (car case)))
(return `(,(cdr case) x)))
((csubtypep type (specifier-type `(or null ,(car case))))
(return `(if x (,(cdr case) x) ,(sb-xc:sxhash nil))))))
(give-up-ir1-transform))))
(deftransform sxhash ((x) (number)) `(sb-impl::number-sxhash x))
(deftransform sxhash ((x) (integer)) `(sb-impl::integer-sxhash x))
Note about signed zeros with respect to SXHASH ( but not PSXHASH ! ) -
;;; Change b0a51fec91 added some logic to discard the sign of floating-point zeros
before computing SXHASH . Its reasoning was based on the notion of " similarity " .
;;; But if +/-0 were truly "similar" as per the definition
;;; at
;;; then it causes a massive semantic problem: it essentially would mean that
when used as first class objects in code compiled not to memory ,
literal floating - point zeros might have their sign bit ignored .
;;;
;;; i.e. if you hang your hat on "similarity", then the literals externalized
;;; in (DEFUN F () (VALUES -0d0 0d0))
might cause F to return two pointers to the identical object , or not ,
;;; because, after all, they're similar values, aren't they?
;;;
;;; Well, we know it returns different values, thus they must be non-similar.
;;; Of course, you could also argue that similar values don't *have* to be
collapsed into one object - they simply _ may _ be one object ,
;;; but this completely misses the point.
;;;
;;; The crux of the question is: if they are similar, then would it be legal
to return the positive zero where you wrote the negative zero ? Yes , it would
;;; be. But that's ludicrous. Therefore they must be non-similar.
;;;
Taking it from the top , the reason cited in the prior change is that SXHASH
respects similarity . OK , then , what does the SXHASH writeup actually say ?
;;; The manner in which the hash code is computed is implementation-dependent,
;;; but subject to certain constraints:
1 . ( equal x y ) implies (= ( sxhash x ) ( sxhash y ) ) .
2 . For any two objects , x and y , both of which are [ ... ] numbers [ ... ]
which are similar , ( sxhash x ) and ( sxhash y ) yield the same mathematical
;;; value even if x and y exist in different Lisp images ...
;;;
You have to look at SXHASH bullet points as to intent , and the definition of
;;; similarity as to intent.
;;;
Point ( 1 ) says that SXHASH should make a distinction between objects when EQUAL
;;; does, and not more. It's like an "only-if" in that:
- SXHASH must not make distinctions that EQUAL does not make if EQUAL said T.
i.e. you must not hash to different things if EQUAL says they 're the same .
- it is always legal to make fewer distinctions than EQUAL makes ,
;;; which is why all structure instances may hash to a constant.
- SXHASH might make distinctions when EQUAL says NIL , but nobody should care
;;; about what exactly those distinctions are.
;;;
Point ( 2 ) is concerned with predictability of hash values for a certain domain
;;; of objects, such that if you exit an image, and either restart it, or start up
a completely different image , then _ if _ two objects would satisfy the
;;; similarity test, they will hash to the same value.
;;; The remaining few points say that the behavior is predictable within a session,
;;; it terminates in the presence of circularity, and is intended for hashing.
But the aforementioned change made two mistakes :
;;; - it assumed that the definition of "similarity" of floating-point zeroes
implies that is similar to -0f0 , respectively for double - float .
- it assumed that we care what SXHASH says when EQUAL says NIL for numbers
;;; when in fact it is overwhelmingly clear that the intent of similarity
regarding numbers is to capture the behavior of EQL , and not EQUALP or = .
A reductio ad absurdum argument shows that the first assumption is false .
The main defining aspect of SXHASH is that it agrees with EQUAL which is like
EQL , not EQUALP ( or =) for numbers . The text for " similar " bears some semblance to
;;; the footnote to '=' where it has an adjective "mathematical", but '=' says in its
;;; main body text that it performs "arithmetic" comparison. "Similar" does not say that.
The = footnote is clarifying why it is not the same as EQL with respect to signed
;;; zeroes. You can not infer from it that "similar" entails arithmetic equality
;;; in the exact sense of '='. Mention of "mathematical" value at "similar" is meant to
distinguish itself from EQ comparison . This is obvious because plenty of functions
use a " mathematical " value of a signed zero , and make distinctions between them ,
;;; which is to say, just because a definition inserts the adjective "mathematical"
you do n't get to drop the sign bit of a zero as we seem to have done .
Pretty much it should have said under " similar " to compare numbers as if by EQL .
Not to mention , externalizing a signaling NaN should not be allowed to compare
on anything except the bits , so EQL is legal to call but = is n't .
;;;
;;; You can't then leap from an already slightly wrong treatment of the similarity
;;; notion for numbers to conclude that +/-0.0 hash the same, when even if they did,
only an EQUALP table would have ( eq ( gethash +0.0 tbl ) ( gethash -0.0 ) ) .
;;; So unless someone is seriously going to argue that similarity of numbers implies
;;; that the distinction between +0 and -0 makes no difference *ANYWHERE* that uses
;;; floating-point literals, I think there is no argument here.
SXHASH of FLOAT values is defined directly in terms of DEFTRANSFORM in
;;; order to avoid boxing.
(deftransform sxhash ((x) (single-float)) '#.(sb-impl::sxhash-single-float-xform 'x))
SXHASH of FIXNUM values is defined as a DEFTRANSFORM because it 's so
;;; simple.
(deftransform sxhash ((x) (fixnum)) '#.(sb-impl::sxhash-fixnum-xform 'x))
(deftransform sxhash ((x) (double-float)) '#.(sb-impl::sxhash-double-float-xform 'x))
(deftransform sxhash ((x) (symbol))
;; All interned symbols have a precomputed hash.
;; The types for which interned-ness can be conveyed via type constraints
are KEYWORD and MEMBER . Despite the existence of UNINTERN , the optimization
;; here is admissible. If the user uninterns a symbol, the hash is still there.
;; TBH I think we should just precompute the hash of all symbols.
(cond ((or (csubtypep (lvar-type x) (specifier-type 'keyword))
(and (member-type-p (lvar-type x))
(progn
;; can't be a subtype of SYMBOL with fp-zeroes in it
(aver (null (sb-kernel::member-type-fp-zeroes (lvar-type x))))
(xset-every #'cl:symbol-package
(sb-kernel::member-type-xset (lvar-type x))))))
`(symbol-hash x)) ; Never need to lazily compute and memoize
((gethash 'ensure-symbol-hash *backend-parsed-vops*)
;; A vop might emit slightly better code than the expression below
`(ensure-symbol-hash x))
(t
;; Cache the value of the symbol's sxhash in the symbol-hash
;; slot.
'(let ((result (symbol-hash x)))
0 marks uninitialized slot . We ca n't use negative
values for the uninitialized slots since NIL might be
;; located so high in memory on some platforms that its
SYMBOL - HASH ( which contains NIL itself ) is a negative
;; fixnum.
(if (= 0 result)
(ensure-symbol-hash x)
result)))))
(deftransform symbol-hash* ((object predicate) (symbol null) * :important nil)
annotate that object satisfies
(deftransform symbol-hash* ((object predicate)
((and (not null) symbol)
(constant-arg (member nil symbolp)))
* :important nil)
`(symbol-hash* object 'non-null-symbol-p)) ; etc
| null | https://raw.githubusercontent.com/sbcl/sbcl/dae890e6f92d6732eee0c0931772a4f368a14928/src/compiler/sxhash.lisp | lisp | in the cross-compilation host Lisp
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
CAUTION: transforms are selected in the *reverse* order of definition,
FUN-INFO-TRANSFORMS, and of course it broke things because we depend on such
stupidity. It would be remedied by reversing all definitions whenever
it matters but I didn't feel like figuring out all places where it does.
It is common for structure slots to have a :TYPE resembling (OR STRING NULL),
and also common to create custom hash calculations on structures with such slots.
So it makes sense for the compiler to try to pick off cases where the slot type
Change b0a51fec91 added some logic to discard the sign of floating-point zeros
But if +/-0 were truly "similar" as per the definition
at
then it causes a massive semantic problem: it essentially would mean that
i.e. if you hang your hat on "similarity", then the literals externalized
in (DEFUN F () (VALUES -0d0 0d0))
because, after all, they're similar values, aren't they?
Well, we know it returns different values, thus they must be non-similar.
Of course, you could also argue that similar values don't *have* to be
but this completely misses the point.
The crux of the question is: if they are similar, then would it be legal
be. But that's ludicrous. Therefore they must be non-similar.
The manner in which the hash code is computed is implementation-dependent,
but subject to certain constraints:
value even if x and y exist in different Lisp images ...
similarity as to intent.
does, and not more. It's like an "only-if" in that:
which is why all structure instances may hash to a constant.
about what exactly those distinctions are.
of objects, such that if you exit an image, and either restart it, or start up
similarity test, they will hash to the same value.
The remaining few points say that the behavior is predictable within a session,
it terminates in the presence of circularity, and is intended for hashing.
- it assumed that the definition of "similarity" of floating-point zeroes
when in fact it is overwhelmingly clear that the intent of similarity
the footnote to '=' where it has an adjective "mathematical", but '=' says in its
main body text that it performs "arithmetic" comparison. "Similar" does not say that.
zeroes. You can not infer from it that "similar" entails arithmetic equality
in the exact sense of '='. Mention of "mathematical" value at "similar" is meant to
which is to say, just because a definition inserts the adjective "mathematical"
You can't then leap from an already slightly wrong treatment of the similarity
notion for numbers to conclude that +/-0.0 hash the same, when even if they did,
So unless someone is seriously going to argue that similarity of numbers implies
that the distinction between +0 and -0 makes no difference *ANYWHERE* that uses
floating-point literals, I think there is no argument here.
order to avoid boxing.
simple.
All interned symbols have a precomputed hash.
The types for which interned-ness can be conveyed via type constraints
here is admissible. If the user uninterns a symbol, the hash is still there.
TBH I think we should just precompute the hash of all symbols.
can't be a subtype of SYMBOL with fp-zeroes in it
Never need to lazily compute and memoize
A vop might emit slightly better code than the expression below
Cache the value of the symbol's sxhash in the symbol-hash
slot.
located so high in memory on some platforms that its
fixnum.
etc | that part of SXHASH logic which runs not only in the target Lisp but
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
(in-package "SB-C")
so define the most general first , followed by more specific .
I once tried to fix that glitch by using instead of PUSH into
(deftransform sxhash ((x) (t))
(let ((type (lvar-type x)))
has a specialized hash computation via sxhash after picking off NIL .
(or (dolist (case '((simple-string . %sxhash-simple-string)
(string . %sxhash-string)
(simple-bit-vector . %sxhash-simple-bit-vector)
(bit-vector . %sxhash-bit-vector)))
(cond ((csubtypep type (specifier-type (car case)))
(return `(,(cdr case) x)))
((csubtypep type (specifier-type `(or null ,(car case))))
(return `(if x (,(cdr case) x) ,(sb-xc:sxhash nil))))))
(give-up-ir1-transform))))
(deftransform sxhash ((x) (number)) `(sb-impl::number-sxhash x))
(deftransform sxhash ((x) (integer)) `(sb-impl::integer-sxhash x))
Note about signed zeros with respect to SXHASH ( but not PSXHASH ! ) -
before computing SXHASH . Its reasoning was based on the notion of " similarity " .
when used as first class objects in code compiled not to memory ,
literal floating - point zeros might have their sign bit ignored .
might cause F to return two pointers to the identical object , or not ,
collapsed into one object - they simply _ may _ be one object ,
to return the positive zero where you wrote the negative zero ? Yes , it would
Taking it from the top , the reason cited in the prior change is that SXHASH
respects similarity . OK , then , what does the SXHASH writeup actually say ?
1 . ( equal x y ) implies (= ( sxhash x ) ( sxhash y ) ) .
2 . For any two objects , x and y , both of which are [ ... ] numbers [ ... ]
which are similar , ( sxhash x ) and ( sxhash y ) yield the same mathematical
You have to look at SXHASH bullet points as to intent , and the definition of
Point ( 1 ) says that SXHASH should make a distinction between objects when EQUAL
- SXHASH must not make distinctions that EQUAL does not make if EQUAL said T.
i.e. you must not hash to different things if EQUAL says they 're the same .
- it is always legal to make fewer distinctions than EQUAL makes ,
- SXHASH might make distinctions when EQUAL says NIL , but nobody should care
Point ( 2 ) is concerned with predictability of hash values for a certain domain
a completely different image , then _ if _ two objects would satisfy the
But the aforementioned change made two mistakes :
implies that is similar to -0f0 , respectively for double - float .
- it assumed that we care what SXHASH says when EQUAL says NIL for numbers
regarding numbers is to capture the behavior of EQL , and not EQUALP or = .
A reductio ad absurdum argument shows that the first assumption is false .
The main defining aspect of SXHASH is that it agrees with EQUAL which is like
EQL , not EQUALP ( or =) for numbers . The text for " similar " bears some semblance to
The = footnote is clarifying why it is not the same as EQL with respect to signed
distinguish itself from EQ comparison . This is obvious because plenty of functions
use a " mathematical " value of a signed zero , and make distinctions between them ,
you do n't get to drop the sign bit of a zero as we seem to have done .
Pretty much it should have said under " similar " to compare numbers as if by EQL .
Not to mention , externalizing a signaling NaN should not be allowed to compare
on anything except the bits , so EQL is legal to call but = is n't .
only an EQUALP table would have ( eq ( gethash +0.0 tbl ) ( gethash -0.0 ) ) .
SXHASH of FLOAT values is defined directly in terms of DEFTRANSFORM in
(deftransform sxhash ((x) (single-float)) '#.(sb-impl::sxhash-single-float-xform 'x))
SXHASH of FIXNUM values is defined as a DEFTRANSFORM because it 's so
(deftransform sxhash ((x) (fixnum)) '#.(sb-impl::sxhash-fixnum-xform 'x))
(deftransform sxhash ((x) (double-float)) '#.(sb-impl::sxhash-double-float-xform 'x))
(deftransform sxhash ((x) (symbol))
are KEYWORD and MEMBER . Despite the existence of UNINTERN , the optimization
(cond ((or (csubtypep (lvar-type x) (specifier-type 'keyword))
(and (member-type-p (lvar-type x))
(progn
(aver (null (sb-kernel::member-type-fp-zeroes (lvar-type x))))
(xset-every #'cl:symbol-package
(sb-kernel::member-type-xset (lvar-type x))))))
((gethash 'ensure-symbol-hash *backend-parsed-vops*)
`(ensure-symbol-hash x))
(t
'(let ((result (symbol-hash x)))
0 marks uninitialized slot . We ca n't use negative
values for the uninitialized slots since NIL might be
SYMBOL - HASH ( which contains NIL itself ) is a negative
(if (= 0 result)
(ensure-symbol-hash x)
result)))))
(deftransform symbol-hash* ((object predicate) (symbol null) * :important nil)
annotate that object satisfies
(deftransform symbol-hash* ((object predicate)
((and (not null) symbol)
(constant-arg (member nil symbolp)))
* :important nil)
|
15033cd5884f03738ef64cf6a87ac98b0be5a56c017e4a41095ec34f6b48fe9f | jaredly/belt | belt_Option.ml | let getExn =
function
| Some x -> x
| None -> Js.Exn.raiseError "File \"\", line 28, characters 14-20"
let mapWithDefaultU opt default f =
match opt with | Some x -> f x | None -> default
let mapWithDefault opt default f =
mapWithDefaultU opt default (fun x -> f x)
let mapU opt f = match opt with | Some x -> Some (f x) | None -> None
let map opt f = mapU opt (fun x -> f x)
let flatMapU opt f = match opt with | Some x -> f x | None -> None
let flatMap opt f = flatMapU opt (fun x -> f x)
let getWithDefault opt default =
match opt with | Some x -> x | None -> default
let isSome = function | Some _ -> true | None -> false
let isNone = function | Some _ -> false | None -> true
let eqU a b f =
match (a, b) with
| (Some a,Some b) -> f a b
| (None ,Some _)|(Some _,None ) -> false
| (None ,None ) -> true
let eq a b f = eqU a b (fun x -> fun y -> f x y)
let cmpU a b f =
match (a, b) with
| (Some a,Some b) -> f a b
| (None ,Some _) -> (-1)
| (Some _,None ) -> 1
| (None ,None ) -> 0
let cmp a b f = cmpU a b (fun x -> fun y -> f x y) | null | https://raw.githubusercontent.com/jaredly/belt/4d07f859403fdbd3fbfc5a9547c6066d657a2131/belt/belt_Option.ml | ocaml | let getExn =
function
| Some x -> x
| None -> Js.Exn.raiseError "File \"\", line 28, characters 14-20"
let mapWithDefaultU opt default f =
match opt with | Some x -> f x | None -> default
let mapWithDefault opt default f =
mapWithDefaultU opt default (fun x -> f x)
let mapU opt f = match opt with | Some x -> Some (f x) | None -> None
let map opt f = mapU opt (fun x -> f x)
let flatMapU opt f = match opt with | Some x -> f x | None -> None
let flatMap opt f = flatMapU opt (fun x -> f x)
let getWithDefault opt default =
match opt with | Some x -> x | None -> default
let isSome = function | Some _ -> true | None -> false
let isNone = function | Some _ -> false | None -> true
let eqU a b f =
match (a, b) with
| (Some a,Some b) -> f a b
| (None ,Some _)|(Some _,None ) -> false
| (None ,None ) -> true
let eq a b f = eqU a b (fun x -> fun y -> f x y)
let cmpU a b f =
match (a, b) with
| (Some a,Some b) -> f a b
| (None ,Some _) -> (-1)
| (Some _,None ) -> 1
| (None ,None ) -> 0
let cmp a b f = cmpU a b (fun x -> fun y -> f x y) | |
06bb400d99c070209da2f0017ba70ca21fb9fa87aedfdd3eebfe9da85848b9a9 | discus-lang/ddc | Witness.hs | -- | Type checker for witness expressions.
module DDC.Core.Check.Judge.Witness
( checkWitness
, checkWitnessM
, typeOfWitness
, typeOfWiCon)
where
import DDC.Core.Exp.Annot.AnT
import DDC.Core.Check.Error
import DDC.Core.Check.Base
import DDC.Core.Check.Judge.Kind
import DDC.Type.Transform.SubstituteT
import qualified DDC.Core.Env.EnvT as EnvT
import qualified DDC.Core.Check.Context as Context
import qualified Data.Map.Strict as Map
import qualified System.IO.Unsafe as S
-- Wrappers --------------------------------------------------------------------
-- | Check a witness.
--
-- If it's good, you get a new version with types attached to all the bound
-- variables, as well as the type of the overall witness.
--
-- If it's bad, you get a description of the error.
--
-- The returned expression has types attached to all variable occurrences,
so you can call ` typeOfWitness ` on any open subterm .
--
-- The kinds and types of primitives are added to the environments
-- automatically, you don't need to supply these as part of the
-- starting environments.
--
checkWitness
:: (Ord n, Show n, Pretty n)
=> Config n -- ^ Type checker configuration.
-> EnvX n -- ^ Type checker environment.
-> Witness a n -- ^ Witness to check.
-> Either (Error a n)
( Witness (AnT a n) n
, Type n)
checkWitness config env xx
= S.unsafePerformIO
$ let ctx = contextOfEnvX env
in evalCheck (mempty, 0, 0)
$ checkWitnessM config ctx xx
| Like ` checkWitness ` , but check in an empty environment .
--
-- As this function is not given an environment, the types of free variables
-- must be attached directly to the bound occurrences.
This attachment is performed by ` checkWitness ` above .
--
typeOfWitness
:: (Ord n, Show n, Pretty n)
=> Config n -- ^ Type checker configuration.
-> EnvX n -- ^ Type checker environment.
-> Witness a n -- ^ Witness to check.
-> Either (Error a n) (Type n)
typeOfWitness config env ww
= S.unsafePerformIO
$ case checkWitness config env ww of
Left err -> return $ Left err
Right (_, t) -> return $ Right t
------------------------------------------------------------------------------
| Like ` checkWitness ` but using the ` CheckM ` monad to manage errors .
checkWitnessM
:: (Ord n, Show n, Pretty n)
=> Config n -- ^ Type checker configuration.
-> Context n -- ^ Type checker context.
-> Witness a n -- ^ Witness to check.
-> CheckM a n
( Witness (AnT a n) n
, Type n)
checkWitnessM !_config !ctx (WVar a u)
-- Witness is defined locally.
| Just t <- lookupType u ctx
= return ( WVar (AnT t a) u, t)
-- Witness is defined globally.
| UName n <- u
, Just t <- Map.lookup n (EnvT.envtCapabilities (Context.contextEnvT ctx))
= return ( WVar (AnT t a) u, t)
| otherwise
= throw $ ErrorUndefinedVar a u UniverseWitness
checkWitnessM !_config !_ctx (WCon a wc)
= let t' = typeOfWiCon wc
in return ( WCon (AnT t' a) wc
, t')
-- witness-type application
checkWitnessM !config !ctx ww@(WApp a1 w1 (WType a2 t2))
= do (w1', t1) <- checkWitnessM config ctx w1
(t2', k2, _) <- checkTypeM config ctx UniverseSpec t2 Recon
case t1 of
TForall b11 t12
| typeOfBind b11 == k2
-> let t' = substituteT b11 t2' t12
in return ( WApp (AnT t' a1) w1' (WType (AnT k2 a2) t2')
, t')
| otherwise -> throw $ ErrorWAppMismatch a1 ww (typeOfBind b11) k2
_ -> throw $ ErrorWAppNotCtor a1 ww t1 t2'
-- witness-witness application
checkWitnessM !config !ctx ww@(WApp a w1 w2)
= do (w1', t1) <- checkWitnessM config ctx w1
(w2', t2) <- checkWitnessM config ctx w2
case t1 of
TApp (TApp (TCon (TyConWitness TwConImpl)) t11) t12
| t11 == t2
-> return ( WApp (AnT t12 a) w1' w2'
, t12)
| otherwise -> throw $ ErrorWAppMismatch a ww t11 t2
_ -> throw $ ErrorWAppNotCtor a ww t1 t2
-- embedded types
checkWitnessM !config !ctx (WType a t)
= do (t', k, _) <- checkTypeM config ctx UniverseSpec t Recon
return ( WType (AnT k a) t'
, k)
-- | Take the type of a witness constructor.
typeOfWiCon :: WiCon n -> Type n
typeOfWiCon wc
= case wc of
WiConBound _ t -> t
| null | https://raw.githubusercontent.com/discus-lang/ddc/2baa1b4e2d43b6b02135257677671a83cb7384ac/src/s1/ddc-core/DDC/Core/Check/Judge/Witness.hs | haskell | | Type checker for witness expressions.
Wrappers --------------------------------------------------------------------
| Check a witness.
If it's good, you get a new version with types attached to all the bound
variables, as well as the type of the overall witness.
If it's bad, you get a description of the error.
The returned expression has types attached to all variable occurrences,
The kinds and types of primitives are added to the environments
automatically, you don't need to supply these as part of the
starting environments.
^ Type checker configuration.
^ Type checker environment.
^ Witness to check.
As this function is not given an environment, the types of free variables
must be attached directly to the bound occurrences.
^ Type checker configuration.
^ Type checker environment.
^ Witness to check.
----------------------------------------------------------------------------
^ Type checker configuration.
^ Type checker context.
^ Witness to check.
Witness is defined locally.
Witness is defined globally.
witness-type application
witness-witness application
embedded types
| Take the type of a witness constructor. | module DDC.Core.Check.Judge.Witness
( checkWitness
, checkWitnessM
, typeOfWitness
, typeOfWiCon)
where
import DDC.Core.Exp.Annot.AnT
import DDC.Core.Check.Error
import DDC.Core.Check.Base
import DDC.Core.Check.Judge.Kind
import DDC.Type.Transform.SubstituteT
import qualified DDC.Core.Env.EnvT as EnvT
import qualified DDC.Core.Check.Context as Context
import qualified Data.Map.Strict as Map
import qualified System.IO.Unsafe as S
so you can call ` typeOfWitness ` on any open subterm .
checkWitness
:: (Ord n, Show n, Pretty n)
-> Either (Error a n)
( Witness (AnT a n) n
, Type n)
checkWitness config env xx
= S.unsafePerformIO
$ let ctx = contextOfEnvX env
in evalCheck (mempty, 0, 0)
$ checkWitnessM config ctx xx
| Like ` checkWitness ` , but check in an empty environment .
This attachment is performed by ` checkWitness ` above .
typeOfWitness
:: (Ord n, Show n, Pretty n)
-> Either (Error a n) (Type n)
typeOfWitness config env ww
= S.unsafePerformIO
$ case checkWitness config env ww of
Left err -> return $ Left err
Right (_, t) -> return $ Right t
| Like ` checkWitness ` but using the ` CheckM ` monad to manage errors .
checkWitnessM
:: (Ord n, Show n, Pretty n)
-> CheckM a n
( Witness (AnT a n) n
, Type n)
checkWitnessM !_config !ctx (WVar a u)
| Just t <- lookupType u ctx
= return ( WVar (AnT t a) u, t)
| UName n <- u
, Just t <- Map.lookup n (EnvT.envtCapabilities (Context.contextEnvT ctx))
= return ( WVar (AnT t a) u, t)
| otherwise
= throw $ ErrorUndefinedVar a u UniverseWitness
checkWitnessM !_config !_ctx (WCon a wc)
= let t' = typeOfWiCon wc
in return ( WCon (AnT t' a) wc
, t')
checkWitnessM !config !ctx ww@(WApp a1 w1 (WType a2 t2))
= do (w1', t1) <- checkWitnessM config ctx w1
(t2', k2, _) <- checkTypeM config ctx UniverseSpec t2 Recon
case t1 of
TForall b11 t12
| typeOfBind b11 == k2
-> let t' = substituteT b11 t2' t12
in return ( WApp (AnT t' a1) w1' (WType (AnT k2 a2) t2')
, t')
| otherwise -> throw $ ErrorWAppMismatch a1 ww (typeOfBind b11) k2
_ -> throw $ ErrorWAppNotCtor a1 ww t1 t2'
checkWitnessM !config !ctx ww@(WApp a w1 w2)
= do (w1', t1) <- checkWitnessM config ctx w1
(w2', t2) <- checkWitnessM config ctx w2
case t1 of
TApp (TApp (TCon (TyConWitness TwConImpl)) t11) t12
| t11 == t2
-> return ( WApp (AnT t12 a) w1' w2'
, t12)
| otherwise -> throw $ ErrorWAppMismatch a ww t11 t2
_ -> throw $ ErrorWAppNotCtor a ww t1 t2
checkWitnessM !config !ctx (WType a t)
= do (t', k, _) <- checkTypeM config ctx UniverseSpec t Recon
return ( WType (AnT k a) t'
, k)
typeOfWiCon :: WiCon n -> Type n
typeOfWiCon wc
= case wc of
WiConBound _ t -> t
|
b16b828295aa63b9672a61f93a9b395dc2077415dc9982b44a72859ca22f6f5b | transient-haskell/transient-universe | MapReduce.hs | # LANGUAGE ExistentialQuantification , DeriveDataTypeable
, FlexibleInstances , MultiParamTypeClasses , OverloadedStrings , CPP #
, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, CPP #-}
module Transient.MapReduce
(
Distributable(..),distribute, getText,
getUrl, getFile,textUrl, textFile,
mapKeyB, mapKeyU, reduce,eval,
--v* internals
DDS(..),Partition(..),PartRef(..))
where
#ifdef ghcjs_HOST_OS
import Transient.Base
import Transient.Move hiding (pack)
import Transient.Logged
-- dummy Transient.MapReduce module,
reduce _ _ = local stop :: Loggable a => Cloud a
mapKeyB _ _= undefined
mapKeyU _ _= undefined
distribute _ = undefined
getText _ _ = undefined
textFile _ = undefined
getUrl _ _ = undefined
textUrl _ = undefined
getFile _ _ = undefined
eval _= local stop
data Partition
data DDS= DDS
class Distributable
data PartRef a=PartRef a
#else
import Transient.Internals hiding (Ref)
import Transient.Move.Internals hiding (pack)
import Transient.Indeterminism
import Control.Applicative
import System.Random
import Control.Monad.State
import Control.Monad
import Data.Monoid
import Data.Typeable
import Data.List hiding (delete, foldl')
import Control.Exception
import Control.Concurrent
--import Data.Time.Clock
import Network.HTTP
import Data.TCache hiding (onNothing)
import Data.TCache.Defs
import Data.ByteString.Lazy.Char8 (pack,unpack)
import qualified Data.Map.Strict as M
import Control.Arrow (second)
import qualified Data.Vector.Unboxed as DVU
import qualified Data.Vector as DV
import Data.Hashable
import System.IO.Unsafe
import qualified Data.Foldable as F
import qualified Data.Text as Text
import Data.IORef
data DDS a= Loggable a => DDS (Cloud (PartRef a))
data PartRef a= Ref Node Path Save deriving (Typeable, Read, Show)
data Partition a= Part Node Path Save a deriving (Typeable,Read,Show)
type Save= Bool
instance Indexable (Partition a) where
key (Part _ string b _)= keyp string b
keyp s True= "PartP@"++s :: String
keyp s False="PartT@"++s
instance Loggable a => IResource (Partition a) where
keyResource= key
readResourceByKey k= r
where
typePart :: IO (Maybe a) -> a
typePart = undefined
r = if k !! 4 /= 'P' then return Nothing else
defaultReadByKey (defPath (typePart r) ++ k) >>= return . fmap ( read . unpack)
writeResource (s@(Part _ _ save _))=
unless (not save) $ defaultWrite (defPath s ++ key s) (pack $ show s)
eval :: DDS a -> Cloud (PartRef a)
eval (DDS mx) = mx
type Path=String
instance F.Foldable DVU.Vector where
# INLINE foldr #
foldr = foldr
{-# INLINE foldl #-}
foldl = foldl
# INLINE foldr1 #
foldr1 = foldr1
# INLINE foldl1 #
foldl1 = foldl1
--foldlIt' :: V.Unbox a => (b -> a -> b) -> b -> V.Vector a -> b
--foldlIt' f z0 xs= V.foldr f' id xs z0
-- where f' x k z = k $! f z x
--
foldlIt1 : : V.Unbox a = > ( a - > a - > a ) - > V.Vector a - > a
foldlIt1 f xs = fromMaybe ( error " foldl1 : empty structure " )
-- (V.foldl mf Nothing xs)
-- where
-- mf m y = Just (case m of
-- Nothing -> y
-- Just x -> f x y)
class (F.Foldable c, Typeable c, Typeable a, Monoid (c a), Loggable (c a)) => Distributable c a where
singleton :: a -> c a
splitAt :: Int -> c a -> (c a, c a)
fromList :: [a] -> c a
instance (Loggable a) => Distributable DV.Vector a where
singleton = DV.singleton
splitAt= DV.splitAt
fromList = DV.fromList
instance (Loggable a,DVU.Unbox a) => Distributable DVU.Vector a where
singleton= DVU.singleton
splitAt= DVU.splitAt
fromList= DVU.fromList
-- | perform a map and partition the result with different keys using boxed vectors
-- The final result will be used by reduce.
mapKeyB :: (Loggable a, Loggable b, Loggable k,Ord k)
=> (a -> (k,b))
-> DDS (DV.Vector a)
-> DDS (M.Map k(DV.Vector b))
mapKeyB= mapKey
-- | perform a map and partition the result with different keys using unboxed vectors
-- The final result will be used by reduce.
mapKeyU :: (Loggable a, DVU.Unbox a, Loggable b, DVU.Unbox b, Loggable k,Ord k)
=> (a -> (k,b))
-> DDS (DVU.Vector a)
-> DDS (M.Map k(DVU.Vector b))
mapKeyU= mapKey
-- | perform a map and partition the result with different keys.
-- The final result will be used by reduce.
mapKey :: (Distributable vector a,Distributable vector b, Loggable k,Ord k)
=> (a -> (k,b))
-> DDS (vector a)
-> DDS (M.Map k (vector b))
mapKey f (DDS mx)= DDS $ loggedc $ do
refs <- mx
process refs -- !> ("process",refs)
where
-- process :: Partition a -> Cloud [Partition b]
process (ref@(Ref node path sav))= runAt node $ local $ do
xs <- getPartitionData ref -- !> ("CMAP", ref,node)
(generateRef $ map1 f xs)
map1 : : ( , F.Foldable vector ) = > ( a - > ( k , b ) ) - > vector a - > M.Map k(vector b )
map1 f v= F.foldl' f1 M.empty v
where
f1 map x=
let (k,r) = f x
in M.insertWith (<>) k (Transient.MapReduce.singleton r) map
data ReduceChunk a= EndReduce | Reduce a deriving (Typeable, Read, Show)
boxids= unsafePerformIO $ newIORef (0 :: Int)
reduce :: (Hashable k,Ord k, Distributable vector a, Loggable k,Loggable a)
=> (a -> a -> a) -> DDS (M.Map k (vector a)) ->Cloud (M.Map k a)
reduce red (dds@(DDS mx))= loggedc $ do
mboxid <- localIO $ atomicModifyIORef boxids $ \n -> let n'= n+1 in (n',n')
nodes <- local getEqualNodes
let lengthNodes = length nodes
shuffler nodes = do
localIO $ threadDelay 100000
ref@(Ref node path sav) <- mx -- return the resulting blocks of the map
runAt node $ foldAndSend node nodes ref
stop
-- groupByDestiny :: (Hashable k, Distributable vector a) => M.Map k (vector a) -> M.Map Int [(k ,vector a)]
groupByDestiny map = M.foldlWithKey' f M.empty map
where
-- f :: M.Map Int [(k ,vector a)] -> k -> vector a -> M.Map Int [(k ,vector a)]
f map k vs= M.insertWith (<>) (hash1 k) [(k,vs)] map
hash1 k= abs $ hash k `rem` length nodes
foldAndSend : : ( Hashable k , Distributable vector a)= > ( Int,[(k , vector a ) ] ) - > Cloud ( )
foldAndSend node nodes ref= do
pairs <- onAll $ getPartitionData1 ref
<|> return (error $ "DDS computed out of his node:"++ show ref )
let mpairs = groupByDestiny pairs
length <- local . return $ M.size mpairs
let port2= nodePort node
if length == 0 then sendEnd nodes else do
nsent <- onAll $ liftIO $ newMVar 0
(i,folded) <- local $ parallelize foldthem (M.assocs mpairs)
n <- localIO $ modifyMVar nsent $ \r -> return (r+1, r+1)
(runAt (nodes !! i) $ local $ putMailbox' mboxid (Reduce folded))
!> ("SENDDDDDDDDDDDDDDDDDDDDDDD",n,length,i,folded)
-- return () !> (port,n,length)
when (n == length) $ sendEnd nodes
empty
where
foldthem (i,kvs)= async . return
$ (i,map (\(k,vs) -> (k,foldl1 red vs)) kvs)
sendEnd nodes = onNodes nodes $ local $ do
node <- getMyNode
putMailbox' mboxid (EndReduce `asTypeOf` paramOf dds)
!> ("SEEEEEEEEEEEEEEEEEEEEEEEEND ENDREDUCE FROM", node)
onNodes nodes f = foldr (<|>) empty $ map (\n -> runAt n f) nodes
sumNodes nodes f= do foldr (<>) mempty $ map (\n -> runAt n f) nodes
a reduce1 process in each node , get the results and mappend them
-- reduce :: (Ord k) => Cloud (M.Map k v)
reduce1 = local $ do
reduceResults <- liftIO $ newMVar M.empty
numberSent <- liftIO $ newMVar 0
minput <- getMailbox' mboxid -- get the chunk once it arrives to the mailbox
case minput of
EndReduce -> do
n <- liftIO $ modifyMVar numberSent $ \r -> let r'= r+1 in return (r', r')
if n == lengthNodes
!> ("END REDUCE RECEIVEDDDDDDDDDDDDDDDDDDDDDDDDDD",n, lengthNodes)
then do
cleanMailbox' mboxid (EndReduce `asTypeOf` paramOf dds)
r <- liftIO $ readMVar reduceResults
rem <- getState <|> return NoRemote
return r !> ("RETURNING",r,rem)
else stop
Reduce kvs -> do
let addIt (k,inp) = do
let input= inp `asTypeOf` atype dds
liftIO $ modifyMVar_ reduceResults
$ \map -> do
let maccum = M.lookup k map
return $ M.insert k (case maccum of
Just accum -> red input accum
Nothing -> input) map
mapM addIt (kvs `asTypeOf` paramOf' dds)
!> ("RECEIVED REDUCEEEEEEEEEEEEE",kvs)
stop
reducer nodes <|> shuffler nodes
where
atype ::DDS(M.Map k (vector a)) -> a
atype = undefined -- type level
paramOf :: DDS (M.Map k (vector a)) -> ReduceChunk [( k, a)]
paramOf = undefined -- type level
paramOf' :: DDS (M.Map k (vector a)) -> [( k, a)]
paramOf' = undefined -- type level
-- parallelize :: Loggable b => (a -> Cloud b) -> [a] -> Cloud b
parallelize f xs = foldr (<|>) empty $ map f xs
mparallelize f xs = loggedc $ foldr (<>) mempty $ map f xs
getPartitionData :: Loggable a => PartRef a -> TransIO a
getPartitionData (Ref node path save) = Transient $ do
mp <- (liftIO $ atomically
$ readDBRef
$ getDBRef
$ keyp path save)
`onNothing` error ("not found DDS data: "++ keyp path save)
case mp of
(Part _ _ _ xs) -> return $ Just xs
getPartitionData1 :: Loggable a => PartRef a -> TransIO a
getPartitionData1 (Ref node path save) = Transient $ do
mp <- liftIO $ atomically
$ readDBRef
$ getDBRef
$ keyp path save
case mp of
Just (Part _ _ _ xs) -> return $ Just xs
Nothing -> return Nothing
getPartitionData2 :: Loggable a => PartRef a -> IO a
getPartitionData2 (Ref node path save) = do
mp <- ( atomically
$ readDBRef
$ getDBRef
$ keyp path save)
`onNothing` error ("not found DDS data: "++ keyp path save)
case mp of
(Part _ _ _ xs) -> return xs
en caso , se clustered en busca del path
si solo uno , se copia a otro
-- se pone ese nodo de referencia en Part
runAtP :: Loggable a => Node -> (Path -> IO a) -> Path -> Cloud a
runAtP node f uuid= do
r <- runAt node $ onAll . liftIO $ (SLast <$> f uuid) `catch` sendAnyError
case r of
SLast r -> return r
SError e -> do
nodes <- mclustered $ search uuid
when(length nodes < 1) $ asyncDuplicate node uuid
runAtP ( head nodes) f uuid
search uuid= error $ "chunk failover not yet defined. Lookin for: "++ uuid
asyncDuplicate node uuid= do
forkTo node
nodes <- onAll getEqualNodes
let node'= head $ nodes \\ [node]
content <- onAll . liftIO $ readFile uuid
runAt node' $ local $ liftIO $ writeFile uuid content
sendAnyError :: SomeException -> IO (StreamData a)
sendAnyError e= return $ SError e
-- | distribute a vector of values among many nodes.
-- If the vector is static and sharable, better use the get* primitives
-- since each node will load the data independently.
distribute :: (Loggable a, Distributable vector a ) => vector a -> DDS (vector a)
distribute = DDS . distribute'
distribute' xs= loggedc $ do
! > " DISTRIBUTE "
let lnodes = length nodes
let size= case F.length xs `div` (length nodes) of 0 ->1 ; n -> n
xss= split size lnodes 1 xs -- !> size
r <- distribute'' xss nodes
return r
where
split n s s' xs | s==s' = [xs]
split n s s' xs=
let (h,t)= Transient.MapReduce.splitAt n xs
in h : split n s (s'+1) t
distribute'' :: (Loggable a, Distributable vector a)
=> [vector a] -> [Node] -> Cloud (PartRef (vector a))
distribute'' xss nodes =
parallelize move $ zip nodes xss -- !> show xss
where
move (node, xs)= runAt node $ local $ do
par <- generateRef xs
return par
-- !> ("move", node,xs)
-- | input data from a text that must be static and shared by all the nodes.
-- The function parameter partition the text in words
getText :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a)
getText part str= DDS $ loggedc $ do
nodes <- local getEqualNodes -- !> "getText"
return () !> ("DISTRIBUTE TEXT IN NODES:",nodes)
let lnodes = length nodes
parallelize (process lnodes) $ zip nodes [0..lnodes-1]
where
process lnodes (node,i)=
runAt node $ local $ do
let xs = part str
size= case length xs `div` lnodes of 0 ->1 ; n -> n
xss= Transient.MapReduce.fromList $
if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs
generateRef xss
-- | get the worlds of an URL
textUrl :: String -> DDS (DV.Vector Text.Text)
textUrl= getUrl (map Text.pack . words)
| generate a DDS from the content of a URL .
The first parameter is a function that divide the text in words
getUrl :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a)
getUrl partitioner url= DDS $ do
! > " DISTRIBUTE "
let lnodes = length nodes
parallelize (process lnodes) $ zip nodes [0..lnodes-1] -- !> show xss
where
process lnodes (node,i)= runAt node $ local $ do
r <- liftIO . simpleHTTP $ getRequest url
body <- liftIO $ getResponseBody r
let xs = partitioner body
size= case length xs `div` lnodes of 0 ->1 ; n -> n
xss= Transient.MapReduce.fromList $
if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs
generateRef xss
-- | get the words of a file
textFile :: String -> DDS (DV.Vector Text.Text)
textFile= getFile (map Text.pack . words)
| generate a DDS from a file . All the nodes must access the file with the same path
the first parameter is the parser that generates elements from the content
getFile :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a)
getFile partitioner file= DDS $ do
! > " DISTRIBUTE "
let lnodes = length nodes
parallelize (process lnodes) $ zip nodes [0..lnodes-1] -- !> show xss
where
process lnodes (node, i)= runAt node $ local $ do
content <- do
c <- liftIO $ readFile file
length c `seq` return c
let xs = partitioner content
size= case length xs `div` lnodes of 0 ->1 ; n -> n
xss= Transient.MapReduce.fromList $
if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs
generateRef xss
generateRef :: Loggable a => a -> TransIO (PartRef a)
generateRef x= do
node <- getMyNode
liftIO $ do
temp <- getTempName
let reg= Part node temp False x
atomically $ newDBRef reg
-- syncCache
(return $ getRef reg) -- !> ("generateRef",reg,node)
getRef (Part n t s x)= Ref n t s
getTempName :: IO String
getTempName= ("DDS" ++) <$> replicateM 5 (randomRIO ('a','z'))
-------------- Distributed Datasource Streams ---------
| produce a stream of DDS 's that can be map - reduced . Similar to spark streams .
each interval of time , a new DDS is produced.(to be tested )
streamDDS
:: (Loggable a, Distributable vector a) =>
Int -> IO (StreamData a) -> DDS (vector a)
streamDDS time io= DDS $ do
xs <- local . groupByTime time $ do
r <- parallel io
case r of
SDone -> empty
SLast x -> return [x]
SMore x -> return [x]
SError e -> error $ show e
distribute' $ Transient.MapReduce.fromList xs
#endif | null | https://raw.githubusercontent.com/transient-haskell/transient-universe/7cfbbdfa8eefbea79f48ccb69bc1823ba9abc7ea/src/Transient/MapReduce.hs | haskell | v* internals
dummy Transient.MapReduce module,
import Data.Time.Clock
# INLINE foldl #
foldlIt' :: V.Unbox a => (b -> a -> b) -> b -> V.Vector a -> b
foldlIt' f z0 xs= V.foldr f' id xs z0
where f' x k z = k $! f z x
(V.foldl mf Nothing xs)
where
mf m y = Just (case m of
Nothing -> y
Just x -> f x y)
| perform a map and partition the result with different keys using boxed vectors
The final result will be used by reduce.
| perform a map and partition the result with different keys using unboxed vectors
The final result will be used by reduce.
| perform a map and partition the result with different keys.
The final result will be used by reduce.
!> ("process",refs)
process :: Partition a -> Cloud [Partition b]
!> ("CMAP", ref,node)
return the resulting blocks of the map
groupByDestiny :: (Hashable k, Distributable vector a) => M.Map k (vector a) -> M.Map Int [(k ,vector a)]
f :: M.Map Int [(k ,vector a)] -> k -> vector a -> M.Map Int [(k ,vector a)]
return () !> (port,n,length)
reduce :: (Ord k) => Cloud (M.Map k v)
get the chunk once it arrives to the mailbox
type level
type level
type level
parallelize :: Loggable b => (a -> Cloud b) -> [a] -> Cloud b
se pone ese nodo de referencia en Part
| distribute a vector of values among many nodes.
If the vector is static and sharable, better use the get* primitives
since each node will load the data independently.
!> size
!> show xss
!> ("move", node,xs)
| input data from a text that must be static and shared by all the nodes.
The function parameter partition the text in words
!> "getText"
| get the worlds of an URL
!> show xss
| get the words of a file
!> show xss
syncCache
!> ("generateRef",reg,node)
------------ Distributed Datasource Streams --------- | # LANGUAGE ExistentialQuantification , DeriveDataTypeable
, FlexibleInstances , MultiParamTypeClasses , OverloadedStrings , CPP #
, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, CPP #-}
module Transient.MapReduce
(
Distributable(..),distribute, getText,
getUrl, getFile,textUrl, textFile,
mapKeyB, mapKeyU, reduce,eval,
DDS(..),Partition(..),PartRef(..))
where
#ifdef ghcjs_HOST_OS
import Transient.Base
import Transient.Move hiding (pack)
import Transient.Logged
reduce _ _ = local stop :: Loggable a => Cloud a
mapKeyB _ _= undefined
mapKeyU _ _= undefined
distribute _ = undefined
getText _ _ = undefined
textFile _ = undefined
getUrl _ _ = undefined
textUrl _ = undefined
getFile _ _ = undefined
eval _= local stop
data Partition
data DDS= DDS
class Distributable
data PartRef a=PartRef a
#else
import Transient.Internals hiding (Ref)
import Transient.Move.Internals hiding (pack)
import Transient.Indeterminism
import Control.Applicative
import System.Random
import Control.Monad.State
import Control.Monad
import Data.Monoid
import Data.Typeable
import Data.List hiding (delete, foldl')
import Control.Exception
import Control.Concurrent
import Network.HTTP
import Data.TCache hiding (onNothing)
import Data.TCache.Defs
import Data.ByteString.Lazy.Char8 (pack,unpack)
import qualified Data.Map.Strict as M
import Control.Arrow (second)
import qualified Data.Vector.Unboxed as DVU
import qualified Data.Vector as DV
import Data.Hashable
import System.IO.Unsafe
import qualified Data.Foldable as F
import qualified Data.Text as Text
import Data.IORef
data DDS a= Loggable a => DDS (Cloud (PartRef a))
data PartRef a= Ref Node Path Save deriving (Typeable, Read, Show)
data Partition a= Part Node Path Save a deriving (Typeable,Read,Show)
type Save= Bool
instance Indexable (Partition a) where
key (Part _ string b _)= keyp string b
keyp s True= "PartP@"++s :: String
keyp s False="PartT@"++s
instance Loggable a => IResource (Partition a) where
keyResource= key
readResourceByKey k= r
where
typePart :: IO (Maybe a) -> a
typePart = undefined
r = if k !! 4 /= 'P' then return Nothing else
defaultReadByKey (defPath (typePart r) ++ k) >>= return . fmap ( read . unpack)
writeResource (s@(Part _ _ save _))=
unless (not save) $ defaultWrite (defPath s ++ key s) (pack $ show s)
eval :: DDS a -> Cloud (PartRef a)
eval (DDS mx) = mx
type Path=String
instance F.Foldable DVU.Vector where
# INLINE foldr #
foldr = foldr
foldl = foldl
# INLINE foldr1 #
foldr1 = foldr1
# INLINE foldl1 #
foldl1 = foldl1
foldlIt1 : : V.Unbox a = > ( a - > a - > a ) - > V.Vector a - > a
foldlIt1 f xs = fromMaybe ( error " foldl1 : empty structure " )
class (F.Foldable c, Typeable c, Typeable a, Monoid (c a), Loggable (c a)) => Distributable c a where
singleton :: a -> c a
splitAt :: Int -> c a -> (c a, c a)
fromList :: [a] -> c a
instance (Loggable a) => Distributable DV.Vector a where
singleton = DV.singleton
splitAt= DV.splitAt
fromList = DV.fromList
instance (Loggable a,DVU.Unbox a) => Distributable DVU.Vector a where
singleton= DVU.singleton
splitAt= DVU.splitAt
fromList= DVU.fromList
mapKeyB :: (Loggable a, Loggable b, Loggable k,Ord k)
=> (a -> (k,b))
-> DDS (DV.Vector a)
-> DDS (M.Map k(DV.Vector b))
mapKeyB= mapKey
mapKeyU :: (Loggable a, DVU.Unbox a, Loggable b, DVU.Unbox b, Loggable k,Ord k)
=> (a -> (k,b))
-> DDS (DVU.Vector a)
-> DDS (M.Map k(DVU.Vector b))
mapKeyU= mapKey
mapKey :: (Distributable vector a,Distributable vector b, Loggable k,Ord k)
=> (a -> (k,b))
-> DDS (vector a)
-> DDS (M.Map k (vector b))
mapKey f (DDS mx)= DDS $ loggedc $ do
refs <- mx
where
process (ref@(Ref node path sav))= runAt node $ local $ do
(generateRef $ map1 f xs)
map1 : : ( , F.Foldable vector ) = > ( a - > ( k , b ) ) - > vector a - > M.Map k(vector b )
map1 f v= F.foldl' f1 M.empty v
where
f1 map x=
let (k,r) = f x
in M.insertWith (<>) k (Transient.MapReduce.singleton r) map
data ReduceChunk a= EndReduce | Reduce a deriving (Typeable, Read, Show)
boxids= unsafePerformIO $ newIORef (0 :: Int)
reduce :: (Hashable k,Ord k, Distributable vector a, Loggable k,Loggable a)
=> (a -> a -> a) -> DDS (M.Map k (vector a)) ->Cloud (M.Map k a)
reduce red (dds@(DDS mx))= loggedc $ do
mboxid <- localIO $ atomicModifyIORef boxids $ \n -> let n'= n+1 in (n',n')
nodes <- local getEqualNodes
let lengthNodes = length nodes
shuffler nodes = do
localIO $ threadDelay 100000
runAt node $ foldAndSend node nodes ref
stop
groupByDestiny map = M.foldlWithKey' f M.empty map
where
f map k vs= M.insertWith (<>) (hash1 k) [(k,vs)] map
hash1 k= abs $ hash k `rem` length nodes
foldAndSend : : ( Hashable k , Distributable vector a)= > ( Int,[(k , vector a ) ] ) - > Cloud ( )
foldAndSend node nodes ref= do
pairs <- onAll $ getPartitionData1 ref
<|> return (error $ "DDS computed out of his node:"++ show ref )
let mpairs = groupByDestiny pairs
length <- local . return $ M.size mpairs
let port2= nodePort node
if length == 0 then sendEnd nodes else do
nsent <- onAll $ liftIO $ newMVar 0
(i,folded) <- local $ parallelize foldthem (M.assocs mpairs)
n <- localIO $ modifyMVar nsent $ \r -> return (r+1, r+1)
(runAt (nodes !! i) $ local $ putMailbox' mboxid (Reduce folded))
!> ("SENDDDDDDDDDDDDDDDDDDDDDDD",n,length,i,folded)
when (n == length) $ sendEnd nodes
empty
where
foldthem (i,kvs)= async . return
$ (i,map (\(k,vs) -> (k,foldl1 red vs)) kvs)
sendEnd nodes = onNodes nodes $ local $ do
node <- getMyNode
putMailbox' mboxid (EndReduce `asTypeOf` paramOf dds)
!> ("SEEEEEEEEEEEEEEEEEEEEEEEEND ENDREDUCE FROM", node)
onNodes nodes f = foldr (<|>) empty $ map (\n -> runAt n f) nodes
sumNodes nodes f= do foldr (<>) mempty $ map (\n -> runAt n f) nodes
a reduce1 process in each node , get the results and mappend them
reduce1 = local $ do
reduceResults <- liftIO $ newMVar M.empty
numberSent <- liftIO $ newMVar 0
case minput of
EndReduce -> do
n <- liftIO $ modifyMVar numberSent $ \r -> let r'= r+1 in return (r', r')
if n == lengthNodes
!> ("END REDUCE RECEIVEDDDDDDDDDDDDDDDDDDDDDDDDDD",n, lengthNodes)
then do
cleanMailbox' mboxid (EndReduce `asTypeOf` paramOf dds)
r <- liftIO $ readMVar reduceResults
rem <- getState <|> return NoRemote
return r !> ("RETURNING",r,rem)
else stop
Reduce kvs -> do
let addIt (k,inp) = do
let input= inp `asTypeOf` atype dds
liftIO $ modifyMVar_ reduceResults
$ \map -> do
let maccum = M.lookup k map
return $ M.insert k (case maccum of
Just accum -> red input accum
Nothing -> input) map
mapM addIt (kvs `asTypeOf` paramOf' dds)
!> ("RECEIVED REDUCEEEEEEEEEEEEE",kvs)
stop
reducer nodes <|> shuffler nodes
where
atype ::DDS(M.Map k (vector a)) -> a
paramOf :: DDS (M.Map k (vector a)) -> ReduceChunk [( k, a)]
paramOf' :: DDS (M.Map k (vector a)) -> [( k, a)]
parallelize f xs = foldr (<|>) empty $ map f xs
mparallelize f xs = loggedc $ foldr (<>) mempty $ map f xs
getPartitionData :: Loggable a => PartRef a -> TransIO a
getPartitionData (Ref node path save) = Transient $ do
mp <- (liftIO $ atomically
$ readDBRef
$ getDBRef
$ keyp path save)
`onNothing` error ("not found DDS data: "++ keyp path save)
case mp of
(Part _ _ _ xs) -> return $ Just xs
getPartitionData1 :: Loggable a => PartRef a -> TransIO a
getPartitionData1 (Ref node path save) = Transient $ do
mp <- liftIO $ atomically
$ readDBRef
$ getDBRef
$ keyp path save
case mp of
Just (Part _ _ _ xs) -> return $ Just xs
Nothing -> return Nothing
getPartitionData2 :: Loggable a => PartRef a -> IO a
getPartitionData2 (Ref node path save) = do
mp <- ( atomically
$ readDBRef
$ getDBRef
$ keyp path save)
`onNothing` error ("not found DDS data: "++ keyp path save)
case mp of
(Part _ _ _ xs) -> return xs
en caso , se clustered en busca del path
si solo uno , se copia a otro
runAtP :: Loggable a => Node -> (Path -> IO a) -> Path -> Cloud a
runAtP node f uuid= do
r <- runAt node $ onAll . liftIO $ (SLast <$> f uuid) `catch` sendAnyError
case r of
SLast r -> return r
SError e -> do
nodes <- mclustered $ search uuid
when(length nodes < 1) $ asyncDuplicate node uuid
runAtP ( head nodes) f uuid
search uuid= error $ "chunk failover not yet defined. Lookin for: "++ uuid
asyncDuplicate node uuid= do
forkTo node
nodes <- onAll getEqualNodes
let node'= head $ nodes \\ [node]
content <- onAll . liftIO $ readFile uuid
runAt node' $ local $ liftIO $ writeFile uuid content
sendAnyError :: SomeException -> IO (StreamData a)
sendAnyError e= return $ SError e
distribute :: (Loggable a, Distributable vector a ) => vector a -> DDS (vector a)
distribute = DDS . distribute'
distribute' xs= loggedc $ do
! > " DISTRIBUTE "
let lnodes = length nodes
let size= case F.length xs `div` (length nodes) of 0 ->1 ; n -> n
r <- distribute'' xss nodes
return r
where
split n s s' xs | s==s' = [xs]
split n s s' xs=
let (h,t)= Transient.MapReduce.splitAt n xs
in h : split n s (s'+1) t
distribute'' :: (Loggable a, Distributable vector a)
=> [vector a] -> [Node] -> Cloud (PartRef (vector a))
distribute'' xss nodes =
where
move (node, xs)= runAt node $ local $ do
par <- generateRef xs
return par
getText :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a)
getText part str= DDS $ loggedc $ do
return () !> ("DISTRIBUTE TEXT IN NODES:",nodes)
let lnodes = length nodes
parallelize (process lnodes) $ zip nodes [0..lnodes-1]
where
process lnodes (node,i)=
runAt node $ local $ do
let xs = part str
size= case length xs `div` lnodes of 0 ->1 ; n -> n
xss= Transient.MapReduce.fromList $
if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs
generateRef xss
textUrl :: String -> DDS (DV.Vector Text.Text)
textUrl= getUrl (map Text.pack . words)
| generate a DDS from the content of a URL .
The first parameter is a function that divide the text in words
getUrl :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a)
getUrl partitioner url= DDS $ do
! > " DISTRIBUTE "
let lnodes = length nodes
where
process lnodes (node,i)= runAt node $ local $ do
r <- liftIO . simpleHTTP $ getRequest url
body <- liftIO $ getResponseBody r
let xs = partitioner body
size= case length xs `div` lnodes of 0 ->1 ; n -> n
xss= Transient.MapReduce.fromList $
if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs
generateRef xss
textFile :: String -> DDS (DV.Vector Text.Text)
textFile= getFile (map Text.pack . words)
| generate a DDS from a file . All the nodes must access the file with the same path
the first parameter is the parser that generates elements from the content
getFile :: (Loggable a, Distributable vector a) => (String -> [a]) -> String -> DDS (vector a)
getFile partitioner file= DDS $ do
! > " DISTRIBUTE "
let lnodes = length nodes
where
process lnodes (node, i)= runAt node $ local $ do
content <- do
c <- liftIO $ readFile file
length c `seq` return c
let xs = partitioner content
size= case length xs `div` lnodes of 0 ->1 ; n -> n
xss= Transient.MapReduce.fromList $
if i== lnodes-1 then drop (i* size) xs else take size $ drop (i * size) xs
generateRef xss
generateRef :: Loggable a => a -> TransIO (PartRef a)
generateRef x= do
node <- getMyNode
liftIO $ do
temp <- getTempName
let reg= Part node temp False x
atomically $ newDBRef reg
getRef (Part n t s x)= Ref n t s
getTempName :: IO String
getTempName= ("DDS" ++) <$> replicateM 5 (randomRIO ('a','z'))
| produce a stream of DDS 's that can be map - reduced . Similar to spark streams .
each interval of time , a new DDS is produced.(to be tested )
streamDDS
:: (Loggable a, Distributable vector a) =>
Int -> IO (StreamData a) -> DDS (vector a)
streamDDS time io= DDS $ do
xs <- local . groupByTime time $ do
r <- parallel io
case r of
SDone -> empty
SLast x -> return [x]
SMore x -> return [x]
SError e -> error $ show e
distribute' $ Transient.MapReduce.fromList xs
#endif |
d8202941d18047a0cf95805a147ee93271442f6f8a5144c8bba6cd3f21b1d9e5 | techascent/tvm-clj | random.clj | (ns tvm-clj.impl.fns.tvm.contrib.random
(:require [tvm-clj.impl.tvm-ns-fns :as tvm-ns-fns]))
(tvm-ns-fns/export-tvm-functions "tvm.contrib.random") | null | https://raw.githubusercontent.com/techascent/tvm-clj/1088845bd613b4ba14b00381ffe3cdbd3d8b639e/src/tvm_clj/impl/fns/tvm/contrib/random.clj | clojure | (ns tvm-clj.impl.fns.tvm.contrib.random
(:require [tvm-clj.impl.tvm-ns-fns :as tvm-ns-fns]))
(tvm-ns-fns/export-tvm-functions "tvm.contrib.random") | |
d1227315e2edc891a7a6d8c9c98df377344d04b1574ac4558022884997365c64 | IBM/probzelus | mat.ml |
* Copyright 2018 - 2020 IBM Corporation
*
* 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 .
* Copyright 2018-2020 IBM Corporation
*
* 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.
*)
include Owl.Mat
let uniform a b x y = uniform ~a ~b x y
let create_ out = create_ ~out
let uniform_ a b out = uniform_ ~a ~b ~out
let bernoulli_ out = bernoulli_ ~out
let zeros_ out = zeros_ ~out
let ones_ out = ones_ ~out
let one_hot_ out = one_hot_ ~out
let copy_ out = copy_ ~out
let reshape_ out = reshape_ ~out
let transpose_ out = transpose_ ~out
let sum_ out = sum_ ~out
let min_ out = min_ ~out
let max_ out = max_ ~out
let dot_ ~c = dot_ ~c
| null | https://raw.githubusercontent.com/IBM/probzelus/424b53146885cbe1502edb09f39cda8ec89fed08/zelus-libs/owl/mat.ml | ocaml |
* Copyright 2018 - 2020 IBM Corporation
*
* 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 .
* Copyright 2018-2020 IBM Corporation
*
* 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.
*)
include Owl.Mat
let uniform a b x y = uniform ~a ~b x y
let create_ out = create_ ~out
let uniform_ a b out = uniform_ ~a ~b ~out
let bernoulli_ out = bernoulli_ ~out
let zeros_ out = zeros_ ~out
let ones_ out = ones_ ~out
let one_hot_ out = one_hot_ ~out
let copy_ out = copy_ ~out
let reshape_ out = reshape_ ~out
let transpose_ out = transpose_ ~out
let sum_ out = sum_ ~out
let min_ out = min_ ~out
let max_ out = max_ ~out
let dot_ ~c = dot_ ~c
| |
cf817320fd01178f2a18e89ae286e255ad683821c0f9819ef1bc0009beaa40ed | vim-erlang/vim-erlang | my_lib.erl | -module(my_lib).
| null | https://raw.githubusercontent.com/vim-erlang/vim-erlang/84d245af205302406c764980aecc9638069769c8/test/fixture/errors/rebar_config_error/src/my_lib.erl | erlang | -module(my_lib).
| |
dca2fd67f8f8e524b2b762a1e64f8c24241d07b5ae98f9bf4a82943fcf8239e5 | klutometis/clrs | radix-sort.scm | (define (cardinality integer base)
(loop ((for power (up-from 0))
(until (> (expt base power) integer))) => power))
(define (integer->digits integer base)
(let ((cardinality (cardinality integer base)))
(list-tabulate
cardinality
(lambda (i)
(let* ((modulizer (expt base (- cardinality i)))
(integrizer (/ modulizer base)))
(exact-floor (/ (modulo integer modulizer) integrizer)))))))
(define (number->integer number cardinality base)
(apply + (map (lambda (d) (* (expt base (- cardinality d 1))
(number d)))
(iota cardinality))))
(define (number integer)
(let ((digits (integer->digits integer 10)))
(lambda (d) (list-ref digits d))))
(define (word->string word cardinality)
(list->string (map (cut (compose integer->char word) <>)
(iota cardinality))))
(define (word letters)
(let ((letters (string->list letters)))
(lambda (d) (char->integer (list-ref letters d)))))
(define (key-numbers fortuita d)
(loop ((for number (in-vector-reverse fortuita))
(for fortuita (listing (cons (number d) number))))
=> fortuita))
(define (counting-sort-d fortuita d)
(let* ((fortuita (key-numbers fortuita d))
(digits (map car fortuita)))
(let ((sortita (make-vector (length fortuita)))
(numerata (make-vector
(+ (apply max digits) 1)
0)))
(loop ((for key-number (in-list fortuita)))
(let ((key (car key-number)))
(vector-set! numerata key (+ (vector-ref numerata key) 1))))
(loop ((for x i (in-vector numerata 1)))
(vector-set! numerata i (+ x (vector-ref numerata (- i 1)))))
(loop ((for key-number (in-list fortuita)))
(let ((key (car key-number))
(number (cdr key-number)))
(let ((count-index (- (vector-ref numerata key) 1)))
(vector-set! sortita count-index number)
(vector-set! numerata key count-index))))
sortita)))
(define (radix-sort numbers cardinality)
(loop ((for d (down-from cardinality (to 0)))
(with sorted numbers (counting-sort-d sorted d)))
=> sorted))
| null | https://raw.githubusercontent.com/klutometis/clrs/f85a8f0036f0946c9e64dde3259a19acc62b74a1/8.3/radix-sort.scm | scheme | (define (cardinality integer base)
(loop ((for power (up-from 0))
(until (> (expt base power) integer))) => power))
(define (integer->digits integer base)
(let ((cardinality (cardinality integer base)))
(list-tabulate
cardinality
(lambda (i)
(let* ((modulizer (expt base (- cardinality i)))
(integrizer (/ modulizer base)))
(exact-floor (/ (modulo integer modulizer) integrizer)))))))
(define (number->integer number cardinality base)
(apply + (map (lambda (d) (* (expt base (- cardinality d 1))
(number d)))
(iota cardinality))))
(define (number integer)
(let ((digits (integer->digits integer 10)))
(lambda (d) (list-ref digits d))))
(define (word->string word cardinality)
(list->string (map (cut (compose integer->char word) <>)
(iota cardinality))))
(define (word letters)
(let ((letters (string->list letters)))
(lambda (d) (char->integer (list-ref letters d)))))
(define (key-numbers fortuita d)
(loop ((for number (in-vector-reverse fortuita))
(for fortuita (listing (cons (number d) number))))
=> fortuita))
(define (counting-sort-d fortuita d)
(let* ((fortuita (key-numbers fortuita d))
(digits (map car fortuita)))
(let ((sortita (make-vector (length fortuita)))
(numerata (make-vector
(+ (apply max digits) 1)
0)))
(loop ((for key-number (in-list fortuita)))
(let ((key (car key-number)))
(vector-set! numerata key (+ (vector-ref numerata key) 1))))
(loop ((for x i (in-vector numerata 1)))
(vector-set! numerata i (+ x (vector-ref numerata (- i 1)))))
(loop ((for key-number (in-list fortuita)))
(let ((key (car key-number))
(number (cdr key-number)))
(let ((count-index (- (vector-ref numerata key) 1)))
(vector-set! sortita count-index number)
(vector-set! numerata key count-index))))
sortita)))
(define (radix-sort numbers cardinality)
(loop ((for d (down-from cardinality (to 0)))
(with sorted numbers (counting-sort-d sorted d)))
=> sorted))
| |
e5a56109f931f874b178aa0fe0909972066bb6de6ba442c2fc1afaa9955009b0 | ndmitchell/rattle | UI.hs | {-# LANGUAGE Rank2Types #-}
module Development.Rattle.UI(
UI, withUI, addUI, isControlledUI,
RattleUI(..),
) where
import System.Time.Extra
import Control.Exception
import Data.List.Extra
import qualified System.Console.Terminal.Size as Terminal
import Numeric.Extra
import General.EscCodes
import qualified Data.ByteString.Char8 as BS
import Data.IORef.Extra
import Control.Concurrent.Async
import Control.Monad.Extra
-- | What UI should rattle show the user.
data RattleUI
= -- | Show a series of lines for each command run
RattleSerial
| -- | Show a few lines that change as commands run
RattleFancy
| -- | Don't show commands
RattleQuiet
deriving Show
data S = S
{sTraces :: [Maybe (String, String, Seconds)] -- ^ the traced items, in the order we display them, and relative start time
,sUnwind :: Int -- ^ Number of lines we used last time around
}
emptyS :: S
emptyS = S [] 0
addTrace :: String -> String -> Seconds -> S -> S
addTrace msg1 msg2 time s = s{sTraces = f (msg1,msg2,time) $ sTraces s}
where
f v (Nothing:xs) = Just v:xs
f v (x:xs) = x : f v xs
f v [] = [Just v]
delTrace :: String -> String -> Seconds -> S -> S
delTrace msg1 msg2 time s = s{sTraces = f (msg1,msg2,time) $ sTraces s}
where
f v (Just x:xs) | x == v = Nothing:xs
f v (x:xs) = x : f v xs
f v [] = []
display :: Int -> String -> Seconds -> S -> (S, String)
display width header time s = (s{sUnwind=length post}, escCursorUp (sUnwind s) ++ unlines (map pad post))
where
post = "" : (escForeground Green ++ "Status: " ++ header ++ escNormal) : map f (sTraces s)
pad x = x ++ escClearLine
f Nothing = " *"
f (Just (s1,s2,t))
| width - endN1 > 20 = " * " ++ take (width - endN1 - 4) s1 ++ end1
| width - endN2 > 20 = " * " ++ take (width - endN2 - 4) s1 ++ end2
| otherwise = take width $ " * " ++ s1
where
end1 = g (time - t) s2
endN1 = length $ removeEscCodes end1
end2 = g (time - t) ""
endN2 = length $ removeEscCodes end2
g i m | showDurationSecs i == "0s" = if null m then "" else "(" ++ m ++ ")"
| i < 10 = " (" ++ s ++ ")"
| otherwise = " (" ++ escForeground (if i > 20 then Red else Yellow) ++ s ++ escNormal ++ ")"
where s = m ++ [' ' | m /= ""] ++ showDurationSecs i
data UI = UI Bool (forall a . String -> String -> IO a -> IO a)
addUI :: UI -> String -> String -> IO a -> IO a
addUI (UI _ x) = x
isControlledUI :: UI -> Bool
isControlledUI (UI x _) = x
showDurationSecs :: Seconds -> String
showDurationSecs = replace ".00s" "s" . showDuration . intToDouble . round
| Run a compact UI , with the ShakeOptions modifier , combined with
withUI :: Maybe RattleUI -> IO String -> (UI -> IO a) -> IO a
withUI fancy header act = case fancy of
Nothing ->
{-
b <- checkEscCodes
if b then withUICompact header act else withUISerial act
-}
-- for now, let's default to serial
withUISerial act
Just RattleFancy -> do
-- checking the escape codes may also enable them
checkEscCodes
withUICompact header act
Just RattleSerial ->
withUISerial act
Just RattleQuiet ->
withUIQuiet act
withUICompact :: IO String -> (UI -> IO a) -> IO a
withUICompact header act = do
ref <- newIORef emptyS
let tweak = atomicModifyIORef_ ref
time <- offsetTime
let tick = do
h <- header
t <- time
w <- maybe 80 Terminal.width <$> Terminal.size
mask_ $ putStr =<< atomicModifyIORef ref (display w h t)
withAsync (forever (tick >> sleep 0.4) `finally` tick) $ \_ ->
act $ UI True $ \s1 s2 act -> do
t <- time
bracket_
(tweak $ addTrace s1 s2 t)
(tweak $ delTrace s1 s2 t)
act
withUISerial :: (UI -> IO a) -> IO a
withUISerial act =
act $ UI False $ \msg1 msg2 act -> do
BS.putStrLn $ BS.pack $ msg1 ++ if null msg2 then "" else " (" ++ msg2 ++ ")"
act
withUIQuiet :: (UI -> IO a) -> IO a
withUIQuiet act =
act $ UI False $ \_ _ act -> act
| null | https://raw.githubusercontent.com/ndmitchell/rattle/ea9af0923bb8146c83ae54676f175d72ed737fc6/src/Development/Rattle/UI.hs | haskell | # LANGUAGE Rank2Types #
| What UI should rattle show the user.
| Show a series of lines for each command run
| Show a few lines that change as commands run
| Don't show commands
^ the traced items, in the order we display them, and relative start time
^ Number of lines we used last time around
b <- checkEscCodes
if b then withUICompact header act else withUISerial act
for now, let's default to serial
checking the escape codes may also enable them |
module Development.Rattle.UI(
UI, withUI, addUI, isControlledUI,
RattleUI(..),
) where
import System.Time.Extra
import Control.Exception
import Data.List.Extra
import qualified System.Console.Terminal.Size as Terminal
import Numeric.Extra
import General.EscCodes
import qualified Data.ByteString.Char8 as BS
import Data.IORef.Extra
import Control.Concurrent.Async
import Control.Monad.Extra
data RattleUI
RattleSerial
RattleFancy
RattleQuiet
deriving Show
data S = S
}
emptyS :: S
emptyS = S [] 0
addTrace :: String -> String -> Seconds -> S -> S
addTrace msg1 msg2 time s = s{sTraces = f (msg1,msg2,time) $ sTraces s}
where
f v (Nothing:xs) = Just v:xs
f v (x:xs) = x : f v xs
f v [] = [Just v]
delTrace :: String -> String -> Seconds -> S -> S
delTrace msg1 msg2 time s = s{sTraces = f (msg1,msg2,time) $ sTraces s}
where
f v (Just x:xs) | x == v = Nothing:xs
f v (x:xs) = x : f v xs
f v [] = []
display :: Int -> String -> Seconds -> S -> (S, String)
display width header time s = (s{sUnwind=length post}, escCursorUp (sUnwind s) ++ unlines (map pad post))
where
post = "" : (escForeground Green ++ "Status: " ++ header ++ escNormal) : map f (sTraces s)
pad x = x ++ escClearLine
f Nothing = " *"
f (Just (s1,s2,t))
| width - endN1 > 20 = " * " ++ take (width - endN1 - 4) s1 ++ end1
| width - endN2 > 20 = " * " ++ take (width - endN2 - 4) s1 ++ end2
| otherwise = take width $ " * " ++ s1
where
end1 = g (time - t) s2
endN1 = length $ removeEscCodes end1
end2 = g (time - t) ""
endN2 = length $ removeEscCodes end2
g i m | showDurationSecs i == "0s" = if null m then "" else "(" ++ m ++ ")"
| i < 10 = " (" ++ s ++ ")"
| otherwise = " (" ++ escForeground (if i > 20 then Red else Yellow) ++ s ++ escNormal ++ ")"
where s = m ++ [' ' | m /= ""] ++ showDurationSecs i
data UI = UI Bool (forall a . String -> String -> IO a -> IO a)
addUI :: UI -> String -> String -> IO a -> IO a
addUI (UI _ x) = x
isControlledUI :: UI -> Bool
isControlledUI (UI x _) = x
showDurationSecs :: Seconds -> String
showDurationSecs = replace ".00s" "s" . showDuration . intToDouble . round
| Run a compact UI , with the ShakeOptions modifier , combined with
withUI :: Maybe RattleUI -> IO String -> (UI -> IO a) -> IO a
withUI fancy header act = case fancy of
Nothing ->
withUISerial act
Just RattleFancy -> do
checkEscCodes
withUICompact header act
Just RattleSerial ->
withUISerial act
Just RattleQuiet ->
withUIQuiet act
withUICompact :: IO String -> (UI -> IO a) -> IO a
withUICompact header act = do
ref <- newIORef emptyS
let tweak = atomicModifyIORef_ ref
time <- offsetTime
let tick = do
h <- header
t <- time
w <- maybe 80 Terminal.width <$> Terminal.size
mask_ $ putStr =<< atomicModifyIORef ref (display w h t)
withAsync (forever (tick >> sleep 0.4) `finally` tick) $ \_ ->
act $ UI True $ \s1 s2 act -> do
t <- time
bracket_
(tweak $ addTrace s1 s2 t)
(tweak $ delTrace s1 s2 t)
act
withUISerial :: (UI -> IO a) -> IO a
withUISerial act =
act $ UI False $ \msg1 msg2 act -> do
BS.putStrLn $ BS.pack $ msg1 ++ if null msg2 then "" else " (" ++ msg2 ++ ")"
act
withUIQuiet :: (UI -> IO a) -> IO a
withUIQuiet act =
act $ UI False $ \_ _ act -> act
|
a1978945432936be003ebc0cbe8da9121dfa70db5dd8b325fed3e6379725d5cf | deg/re-frame-firebase | specs.cljc | Author : ( )
Copyright ( c ) 2017 ,
(ns com.degel.re-frame-firebase.specs
(:require
[clojure.spec.alpha :as s]))
Database
(s/def ::path (s/coll-of (s/or :string string? :keyword keyword?) :into []))
;; Firestore
(s/def ::path-collection (s/and ::path #(odd? (count %))))
(s/def ::path-document (s/and ::path #(even? (count %))))
| null | https://raw.githubusercontent.com/deg/re-frame-firebase/ed5eabb6caa404af3395e3c97cb59a7c4d302c6b/src/com/degel/re_frame_firebase/specs.cljc | clojure | Firestore | Author : ( )
Copyright ( c ) 2017 ,
(ns com.degel.re-frame-firebase.specs
(:require
[clojure.spec.alpha :as s]))
Database
(s/def ::path (s/coll-of (s/or :string string? :keyword keyword?) :into []))
(s/def ::path-collection (s/and ::path #(odd? (count %))))
(s/def ::path-document (s/and ::path #(even? (count %))))
|
55463a838c8f3f2f732706cce29b3764240ad5467eeed2c6ba33eb10e3c80fd1 | cyverse-archive/DiscoveryEnvironmentBackend | callbacks.clj | (ns metadactyl.service.callbacks
(:require [clojure.tools.logging :as log]
[metadactyl.persistence.jobs :as jp]
[metadactyl.service.apps :as apps]
[metadactyl.util.service :as service]))
(defn update-de-job-status
[{{end-date :completion_date :keys [status uuid]} :state}]
(service/assert-valid uuid "no job UUID provided")
(service/assert-valid status "no status provided")
(log/info (str "received a status update for DE job " uuid ": status = " status))
(when-not (= status jp/submitted-status)
(apps/update-job-status uuid status end-date)))
(defn update-agave-job-status
[job-id {:keys [status external-id end-time]}]
(service/assert-valid job-id "no job UUID provided")
(service/assert-valid status "no status provided")
(service/assert-valid external-id "no external job ID provided")
(log/info (str "received a status update for Agave job " external-id ": status = " status))
(apps/update-job-status job-id external-id status end-time))
| null | https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/services/metadactyl-clj/src/metadactyl/service/callbacks.clj | clojure | (ns metadactyl.service.callbacks
(:require [clojure.tools.logging :as log]
[metadactyl.persistence.jobs :as jp]
[metadactyl.service.apps :as apps]
[metadactyl.util.service :as service]))
(defn update-de-job-status
[{{end-date :completion_date :keys [status uuid]} :state}]
(service/assert-valid uuid "no job UUID provided")
(service/assert-valid status "no status provided")
(log/info (str "received a status update for DE job " uuid ": status = " status))
(when-not (= status jp/submitted-status)
(apps/update-job-status uuid status end-date)))
(defn update-agave-job-status
[job-id {:keys [status external-id end-time]}]
(service/assert-valid job-id "no job UUID provided")
(service/assert-valid status "no status provided")
(service/assert-valid external-id "no external job ID provided")
(log/info (str "received a status update for Agave job " external-id ": status = " status))
(apps/update-job-status job-id external-id status end-time))
| |
d96e586a026d2620c57aac54f5e84987f445f897667232932997c40ba6b0f61d | threatgrid/ctia | store_service.clj | (ns ctia.store-service
(:require [ctia.store-service-core :as core]
[puppetlabs.trapperkeeper.core :as tk]
[puppetlabs.trapperkeeper.services :refer [service-context]]))
(defprotocol StoreService
(all-stores [this]
"Returns a map of current stores.
See also: ctia.store-service.schemas/AllStoresFn")
(get-store [this store-id]
"Returns the identified store.
See also: ctia.store-service.schemas/GetStoreFn"))
(tk/defservice store-service
"A service to manage the central storage area for all stores."
StoreService
[[:ConfigService get-in-config]
[:FeaturesService flag-value]]
(init [this context]
(core/init context))
(start [this context]
(core/start
{:ConfigService {:get-in-config get-in-config}
:FeaturesService {:flag-value flag-value}}
context))
(stop [this context]
(core/stop context))
(all-stores [this]
(core/all-stores (service-context this)))
(get-store [this store-id]
(core/get-store (service-context this)
store-id)))
| null | https://raw.githubusercontent.com/threatgrid/ctia/1c84e16a639abc242329dce8a87e415c6b166706/src/ctia/store_service.clj | clojure | (ns ctia.store-service
(:require [ctia.store-service-core :as core]
[puppetlabs.trapperkeeper.core :as tk]
[puppetlabs.trapperkeeper.services :refer [service-context]]))
(defprotocol StoreService
(all-stores [this]
"Returns a map of current stores.
See also: ctia.store-service.schemas/AllStoresFn")
(get-store [this store-id]
"Returns the identified store.
See also: ctia.store-service.schemas/GetStoreFn"))
(tk/defservice store-service
"A service to manage the central storage area for all stores."
StoreService
[[:ConfigService get-in-config]
[:FeaturesService flag-value]]
(init [this context]
(core/init context))
(start [this context]
(core/start
{:ConfigService {:get-in-config get-in-config}
:FeaturesService {:flag-value flag-value}}
context))
(stop [this context]
(core/stop context))
(all-stores [this]
(core/all-stores (service-context this)))
(get-store [this store-id]
(core/get-store (service-context this)
store-id)))
| |
2aed664291dba70cd059cfb3a394cf2bbdf20bee28cdaa778b45ea66e8a52d89 | erszcz/learning | exprecs_example.erl | -module(exprecs_example).
%-compile(export_all).
-compile({parse_transform, exprecs}).
-record(r, {a = 0 :: integer(),
b = 0 :: integer(),
c = 0 :: integer()}).
-record(s,{a}).
%-export_records([r,s]).
-export_records([r]).
-exprecs_prefix([operation]).
-exprecs_fname([prefix, "_", record]).
-exprecs_vfname([fname, "__", version]).
f() ->
{new, new_r([])}.
| null | https://raw.githubusercontent.com/erszcz/learning/b21c58a09598e2aa5fa8a6909a80c81dc6be1601/erlang-uwiger-exprecs/src/exprecs_example.erl | erlang | -compile(export_all).
-export_records([r,s]). | -module(exprecs_example).
-compile({parse_transform, exprecs}).
-record(r, {a = 0 :: integer(),
b = 0 :: integer(),
c = 0 :: integer()}).
-record(s,{a}).
-export_records([r]).
-exprecs_prefix([operation]).
-exprecs_fname([prefix, "_", record]).
-exprecs_vfname([fname, "__", version]).
f() ->
{new, new_r([])}.
|
ab9fd90deff2ec6d9c2819c82c5eb1d2e4e743ce213ffd651e29688ddeee1dcc | janestreet/core | make_substring_intf.ml | open! Import
module type Base = sig
type t [@@deriving quickcheck]
val create : int -> t
val length : t -> int
val blit : (t, t) Blit.blito
val blit_to_bytes : (t, bytes) Blit.blito
val blit_to_bigstring : (t, bigstring) Blit.blito
val blit_from_string : (string, t) Blit.blito
val blit_from_bigstring : (bigstring, t) Blit.blito
val blit_to_string : (t, bytes) Blit.blito
[@@deprecated "[since 2017-10] use [blit_to_bytes] instead"]
val get : t -> int -> char
end
module type S = Substring_intf.S
module type Make_substring = sig
module type Base = Base
module type S = S
type bigstring = Bigstring.t
module Blit : sig
type ('src, 'dst) t = ('src, 'dst) Blit.blito
val string_string : (string, bytes) t
[@@deprecated "[since 2017-10] use [string_bytes] instead"]
val bigstring_string : (bigstring, bytes) t
[@@deprecated "[since 2017-10] use [bigstring_bytes] instead"]
val string_bytes : (string, bytes) t
val bytes_bytes : (bytes, bytes) t
val bigstring_bytes : (bigstring, bytes) t
val string_bigstring : (string, bigstring) t
val bytes_bigstring : (bytes, bigstring) t
val bigstring_bigstring : (bigstring, bigstring) t
end
module F (Base : Base) : S with type base = Base.t
end
| null | https://raw.githubusercontent.com/janestreet/core/b0be1daa71b662bd38ef2bb406f7b3e70d63d05f/core/src/make_substring_intf.ml | ocaml | open! Import
module type Base = sig
type t [@@deriving quickcheck]
val create : int -> t
val length : t -> int
val blit : (t, t) Blit.blito
val blit_to_bytes : (t, bytes) Blit.blito
val blit_to_bigstring : (t, bigstring) Blit.blito
val blit_from_string : (string, t) Blit.blito
val blit_from_bigstring : (bigstring, t) Blit.blito
val blit_to_string : (t, bytes) Blit.blito
[@@deprecated "[since 2017-10] use [blit_to_bytes] instead"]
val get : t -> int -> char
end
module type S = Substring_intf.S
module type Make_substring = sig
module type Base = Base
module type S = S
type bigstring = Bigstring.t
module Blit : sig
type ('src, 'dst) t = ('src, 'dst) Blit.blito
val string_string : (string, bytes) t
[@@deprecated "[since 2017-10] use [string_bytes] instead"]
val bigstring_string : (bigstring, bytes) t
[@@deprecated "[since 2017-10] use [bigstring_bytes] instead"]
val string_bytes : (string, bytes) t
val bytes_bytes : (bytes, bytes) t
val bigstring_bytes : (bigstring, bytes) t
val string_bigstring : (string, bigstring) t
val bytes_bigstring : (bytes, bigstring) t
val bigstring_bigstring : (bigstring, bigstring) t
end
module F (Base : Base) : S with type base = Base.t
end
| |
7ee96beb60d79fa6056ad0084403d96135564d229f104eebfdc651b891618da9 | mfikes/fifth-postulate | ns133.cljs | (ns fifth-postulate.ns133)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| null | https://raw.githubusercontent.com/mfikes/fifth-postulate/22cfd5f8c2b4a2dead1c15a96295bfeb4dba235e/src/fifth_postulate/ns133.cljs | clojure | (ns fifth-postulate.ns133)
(defn solve-for01 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for02 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for03 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for04 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for05 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for06 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for07 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for08 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for09 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for10 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for11 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for12 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for13 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for14 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for15 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for16 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for17 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for18 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
(defn solve-for19 [xs v]
(for [ndx0 (range 0 (- (count xs) 3))
ndx1 (range (inc ndx0) (- (count xs) 2))
ndx2 (range (inc ndx1) (- (count xs) 1))
ndx3 (range (inc ndx2) (count xs))
:when (= v (+ (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3)))]
(list (xs ndx0) (xs ndx1) (xs ndx2) (xs ndx3))))
| |
cc27f83c07ec7ede08c2f29e7a20a972a4058761a1f099b3e47fe3caba99ec4e | nervous-systems/kvlt | params.cljc | (ns kvlt.test.middleware.params
(:require [kvlt.test.middleware.util :refer [mw-req]]
[kvlt.middleware.params :as params]
#? (:clj [clojure.test :refer [deftest is]]
:cljs [cljs.test :refer-macros [deftest is]])
[kvlt.test.util #?(:clj :refer :cljs :refer-macros) [is=]]))
(deftest query-params
(is (nil? (-> (mw-req params/query) :query-string)))
(let [qp (comp
:query-string
(partial mw-req params/query :query-params))]
(is= "qux=quux" (qp {:qux "quux"}))
(is= "qux=quux" (qp {"qux" "quux"}))
(is= "a=b&c=d" (qp (into (sorted-map) {"a" "b" "c" "d"})))
(is= "a=b&c=%3C" (qp {:c "<"} :query-string "a=b"))
(is= "x=%E3%82%AB" (qp {:x "カ"}))
#? (:clj
(is= "x=%3F"
(qp {:x "カ"} :content-type "text/plain;charset=US-ASCII")))))
(deftest form-params
(is (nil? (:body (mw-req params/form))))
(let [fp (comp
#(select-keys % #{:body :content-type})
(partial mw-req params/form
:request-method :post
:form-params))]
(is (nil? (:body (fp {:x 1} :request-method :get))))
(doseq [method [:post :put :patch]]
(is (:body (fp {:x 1} :request-method method))))
(is= {:body "qux=quux"
:content-type "application/x-www-form-urlencoded"}
(fp {:qux "quux"}))
(is= {:body "{:x 1}"
:content-type "application/edn"}
(fp {:x 1} :content-type :edn))
(is= "x=%E3%82%AB" (:body (fp {:x "カ"})))
#? (:clj
(is= "x=%3F" (:body (fp {:x "カ"}
:form-param-encoding "US-ASCII"))))))
| null | https://raw.githubusercontent.com/nervous-systems/kvlt/26fe43eb9de6d7cc7ad8a466953fa0ffe09889ca/test/kvlt/test/middleware/params.cljc | clojure | (ns kvlt.test.middleware.params
(:require [kvlt.test.middleware.util :refer [mw-req]]
[kvlt.middleware.params :as params]
#? (:clj [clojure.test :refer [deftest is]]
:cljs [cljs.test :refer-macros [deftest is]])
[kvlt.test.util #?(:clj :refer :cljs :refer-macros) [is=]]))
(deftest query-params
(is (nil? (-> (mw-req params/query) :query-string)))
(let [qp (comp
:query-string
(partial mw-req params/query :query-params))]
(is= "qux=quux" (qp {:qux "quux"}))
(is= "qux=quux" (qp {"qux" "quux"}))
(is= "a=b&c=d" (qp (into (sorted-map) {"a" "b" "c" "d"})))
(is= "a=b&c=%3C" (qp {:c "<"} :query-string "a=b"))
(is= "x=%E3%82%AB" (qp {:x "カ"}))
#? (:clj
(is= "x=%3F"
(qp {:x "カ"} :content-type "text/plain;charset=US-ASCII")))))
(deftest form-params
(is (nil? (:body (mw-req params/form))))
(let [fp (comp
#(select-keys % #{:body :content-type})
(partial mw-req params/form
:request-method :post
:form-params))]
(is (nil? (:body (fp {:x 1} :request-method :get))))
(doseq [method [:post :put :patch]]
(is (:body (fp {:x 1} :request-method method))))
(is= {:body "qux=quux"
:content-type "application/x-www-form-urlencoded"}
(fp {:qux "quux"}))
(is= {:body "{:x 1}"
:content-type "application/edn"}
(fp {:x 1} :content-type :edn))
(is= "x=%E3%82%AB" (:body (fp {:x "カ"})))
#? (:clj
(is= "x=%3F" (:body (fp {:x "カ"}
:form-param-encoding "US-ASCII"))))))
| |
97642c087970e4b982856bf36c51f00c026489af10c880e97a15fd726549fca7 | lispnik/cl-http | xml-attribute.lisp | ;;; -*- Package: ("XML-PARSER") -*-
;;;
this version ( C ) mecom gmbh 24.11.97
;;; available only from the cl-http repository and NOT to be REdistributed
;;; in ANY form. see cl-xml.html.
(in-package :xml-parser)
(defMethod node-class
((node (eql 'attribute)) (name t) (value t))
*attribute-class*)
(defClass xml-attribute (xml-named-node)
((name
:accessor xml-attribute.name)
(content
:accessor xml-attribute.value
:type string)))
(defMethod initialize-instance
((self xml-attribute) &key value)
(setf (xml-attribute.value self) value)
(call-next-method))
(defMethod print-object
((datum xml-attribute) (stream t))
(if *xml-print-readably*
(if *parent-node*
(format stream "~s=~s" (xml-attribute.name datum)
(xml-attribute.value datum))
(format stream "#i(~s :name ~s :content ~s)"
(type-of datum)
(xml-attribute.name datum)
(xml-attribute.value datum)))
(print-unreadable-object (datum stream :type t :identity t)
(format stream "~s=~s" (xml-attribute.name datum)
(xml-attribute.value datum)))))
#|
(let ((*xml-print-readably* t))
(print (make-instance 'xml-attribute :name 'test :content "ASDF")))
|#
:EOF
| null | https://raw.githubusercontent.com/lispnik/cl-http/84391892d88c505aed705762a153eb65befb6409/contrib/janderson/xml-1998-02-27/xml-attribute.lisp | lisp | -*- Package: ("XML-PARSER") -*-
available only from the cl-http repository and NOT to be REdistributed
in ANY form. see cl-xml.html.
(let ((*xml-print-readably* t))
(print (make-instance 'xml-attribute :name 'test :content "ASDF")))
| this version ( C ) mecom gmbh 24.11.97
(in-package :xml-parser)
(defMethod node-class
((node (eql 'attribute)) (name t) (value t))
*attribute-class*)
(defClass xml-attribute (xml-named-node)
((name
:accessor xml-attribute.name)
(content
:accessor xml-attribute.value
:type string)))
(defMethod initialize-instance
((self xml-attribute) &key value)
(setf (xml-attribute.value self) value)
(call-next-method))
(defMethod print-object
((datum xml-attribute) (stream t))
(if *xml-print-readably*
(if *parent-node*
(format stream "~s=~s" (xml-attribute.name datum)
(xml-attribute.value datum))
(format stream "#i(~s :name ~s :content ~s)"
(type-of datum)
(xml-attribute.name datum)
(xml-attribute.value datum)))
(print-unreadable-object (datum stream :type t :identity t)
(format stream "~s=~s" (xml-attribute.name datum)
(xml-attribute.value datum)))))
:EOF
|
5e6528af8bbab9e0836adc637cea01c8adc99c86568fff20447ed8df839e5b0d | mwotton/roboservant | Server.hs | {-# LANGUAGE RankNTypes #-}
# LANGUAGE TypeApplications #
# LANGUAGE PolyKinds #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Roboservant.Server (fuzz, module Roboservant.Types ) where
import Roboservant.Direct(fuzz',Report)
import Roboservant.Types
( FlattenServer (..),
ReifiedApi,
)
import Roboservant.Types.ReifiedApi.Server(ToReifiedApi (..))
import Servant (Endpoints, Proxy (Proxy), Server)
import Roboservant.Types.Config
fuzz :: forall api.
(FlattenServer api, ToReifiedApi (Endpoints api)) =>
Server api ->
Config ->
IO (Maybe Report)
fuzz s = fuzz' (reifyServer s)
-- todo: how do we pull reifyServer out?
where reifyServer :: (FlattenServer api, ToReifiedApi (Endpoints api))
=> Server api -> ReifiedApi
reifyServer server = toReifiedApi (flattenServer @api server) (Proxy @(Endpoints api))
-- reifyServer server = toReifiedApi server (Proxy @(Endpoints api))
| null | https://raw.githubusercontent.com/mwotton/roboservant/c61d4868cc1a7a0bb5d8f1c3996305c82da13879/src/Roboservant/Server.hs | haskell | # LANGUAGE RankNTypes #
# LANGUAGE GADTs #
todo: how do we pull reifyServer out?
reifyServer server = toReifiedApi server (Proxy @(Endpoints api)) | # LANGUAGE TypeApplications #
# LANGUAGE PolyKinds #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE FlexibleContexts #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeApplications #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Roboservant.Server (fuzz, module Roboservant.Types ) where
import Roboservant.Direct(fuzz',Report)
import Roboservant.Types
( FlattenServer (..),
ReifiedApi,
)
import Roboservant.Types.ReifiedApi.Server(ToReifiedApi (..))
import Servant (Endpoints, Proxy (Proxy), Server)
import Roboservant.Types.Config
fuzz :: forall api.
(FlattenServer api, ToReifiedApi (Endpoints api)) =>
Server api ->
Config ->
IO (Maybe Report)
fuzz s = fuzz' (reifyServer s)
where reifyServer :: (FlattenServer api, ToReifiedApi (Endpoints api))
=> Server api -> ReifiedApi
reifyServer server = toReifiedApi (flattenServer @api server) (Proxy @(Endpoints api))
|
e4d8a1685b1f185634d1937be28d04b09bd061c2f713b13f629631c14c4ece0c | Gbury/archsat | closure_test.ml | This file is free software , part of Archsat . See file " LICENSE " for more details .
let section = Section.make "closure_test"
(* Problem generation *)
(* ************************************************************************ *)
let chain =
let config = Expr_test.Term.{ var = 0; meta = 0; } in
let aux ty self n =
QCheck.Gen.(
if n <= 0 then return [] else
Misc_test.split_int n >>= fun (a, b) ->
map2 CCList.cons (Expr_test.Term.typed ~config ty a) (self b)
) in
QCheck.Gen.(
Expr_test.Ty.gen >>= fun ty ->
sized (fix (aux ty))
)
let pairify l =
let rec aux acc = function
| [_] | [] -> acc
| a :: ((b :: _) as r) ->
aux ((a, b) :: acc) r
in
aux [] l
let pb =
let g =
QCheck.Gen.(
list chain >>= fun eqs ->
Misc_test.sublist (List.concat eqs) >>= fun neqs ->
let l = List.map (fun x -> (true, x))
(CCList.flat_map pairify eqs) in
let l' = List.map (fun x -> (false, x)) (pairify neqs) in
shuffle_l (l @ l')
) in
QCheck.(set_gen g
(list (pair bool (pair Expr_test.Term.t Expr_test.Term.t))))
(* Naive solving *)
(* ************************************************************************ *)
module S = Set.Make(Expr.Term)
module H = Hashtbl.Make(Expr.Term)
type t = { mutable eq : S.t }
let find h t =
match H.find h t with
| eq -> eq
| exception Not_found ->
let ht = { eq = S.singleton t } in
H.add h t ht;
ht
let make l =
let h = H.create 42 in
let aux (a, b) =
let ha = find h a in
ha.eq <- S.add b ha.eq;
let hb = find h b in
hb.eq <- S.add a hb.eq;
()
in
List.iter aux l;
h
let compile l =
let eq, neq = CCList.partition_map (function
| (true, p) -> `Left p
| (false, p) -> `Right p) l in
let t = make eq in
t, neq
let all_eq h t =
let rec aux curr todo =
if S.is_empty todo then curr
else begin
let a = S.choose todo in
let s = find h a in
let s' = S.diff s.eq curr in
aux (S.union curr s') (S.union s' (S.remove a todo))
end
in
aux S.empty (S.singleton t)
let sat l =
let t, neq = compile l in
List.for_all (fun (a, b) -> not (S.mem a (all_eq t b))) neq
let check_proof l (a, b, chain) =
let t, neq = compile l in
List.exists (fun (c, d) ->
Expr.Term.((equal a c && equal b d) ||
(equal a d && equal b c))) neq &&
List.for_all (fun (c, d) -> S.mem d (find t c).eq) (pairify chain) &&
CCOpt.map_or ~default:false (Expr.Term.equal a) (CCList.head_opt chain) &&
CCOpt.map_or ~default:false (Expr.Term.equal b) (CCList.last_opt chain)
(* Checking Closure *)
(* ************************************************************************ *)
module C = Closure.Eq(Expr.Term)
let mk_closure l =
let gen _ = () and merge () () = () in
let t = C.create ~gen ~merge ~section
(Backtrack.Stack.create section) in
List.iter (function
| (true, (a, b)) -> C.add_eq t a b
| (false, (a, b)) -> C.add_neq t a b) l
let closure_sat =
QCheck.Test.make ~count:1 ~long_factor:100
~name:"closure_sat" pb
(fun l ->
QCheck.assume (sat l);
try mk_closure l; true
with C.Unsat _ -> false
)
let closure_unsat =
QCheck.Test.make ~count:10 ~long_factor:10
~name:"closure_unsat" pb
(fun l ->
QCheck.assume (not (sat l));
try mk_closure l; false
with C.Unsat (a, b, chain) -> check_proof l (a, b, chain)
)
let closure_check =
QCheck.Test.make ~count:10 ~long_factor:100
~name:"closure_check" pb
(fun l ->
try
mk_closure l;
sat l
with C.Unsat (a, b, chain) ->
check_proof l (a, b, chain))
let closure_qtests = [
closure_sat;
closure_unsat;
closure_check;
]
| null | https://raw.githubusercontent.com/Gbury/archsat/322fbefa4a58023ddafb3fa1a51f8199c25cde3d/src/test/closure_test.ml | ocaml | Problem generation
************************************************************************
Naive solving
************************************************************************
Checking Closure
************************************************************************ | This file is free software , part of Archsat . See file " LICENSE " for more details .
let section = Section.make "closure_test"
let chain =
let config = Expr_test.Term.{ var = 0; meta = 0; } in
let aux ty self n =
QCheck.Gen.(
if n <= 0 then return [] else
Misc_test.split_int n >>= fun (a, b) ->
map2 CCList.cons (Expr_test.Term.typed ~config ty a) (self b)
) in
QCheck.Gen.(
Expr_test.Ty.gen >>= fun ty ->
sized (fix (aux ty))
)
let pairify l =
let rec aux acc = function
| [_] | [] -> acc
| a :: ((b :: _) as r) ->
aux ((a, b) :: acc) r
in
aux [] l
let pb =
let g =
QCheck.Gen.(
list chain >>= fun eqs ->
Misc_test.sublist (List.concat eqs) >>= fun neqs ->
let l = List.map (fun x -> (true, x))
(CCList.flat_map pairify eqs) in
let l' = List.map (fun x -> (false, x)) (pairify neqs) in
shuffle_l (l @ l')
) in
QCheck.(set_gen g
(list (pair bool (pair Expr_test.Term.t Expr_test.Term.t))))
module S = Set.Make(Expr.Term)
module H = Hashtbl.Make(Expr.Term)
type t = { mutable eq : S.t }
let find h t =
match H.find h t with
| eq -> eq
| exception Not_found ->
let ht = { eq = S.singleton t } in
H.add h t ht;
ht
let make l =
let h = H.create 42 in
let aux (a, b) =
let ha = find h a in
ha.eq <- S.add b ha.eq;
let hb = find h b in
hb.eq <- S.add a hb.eq;
()
in
List.iter aux l;
h
let compile l =
let eq, neq = CCList.partition_map (function
| (true, p) -> `Left p
| (false, p) -> `Right p) l in
let t = make eq in
t, neq
let all_eq h t =
let rec aux curr todo =
if S.is_empty todo then curr
else begin
let a = S.choose todo in
let s = find h a in
let s' = S.diff s.eq curr in
aux (S.union curr s') (S.union s' (S.remove a todo))
end
in
aux S.empty (S.singleton t)
let sat l =
let t, neq = compile l in
List.for_all (fun (a, b) -> not (S.mem a (all_eq t b))) neq
let check_proof l (a, b, chain) =
let t, neq = compile l in
List.exists (fun (c, d) ->
Expr.Term.((equal a c && equal b d) ||
(equal a d && equal b c))) neq &&
List.for_all (fun (c, d) -> S.mem d (find t c).eq) (pairify chain) &&
CCOpt.map_or ~default:false (Expr.Term.equal a) (CCList.head_opt chain) &&
CCOpt.map_or ~default:false (Expr.Term.equal b) (CCList.last_opt chain)
module C = Closure.Eq(Expr.Term)
let mk_closure l =
let gen _ = () and merge () () = () in
let t = C.create ~gen ~merge ~section
(Backtrack.Stack.create section) in
List.iter (function
| (true, (a, b)) -> C.add_eq t a b
| (false, (a, b)) -> C.add_neq t a b) l
let closure_sat =
QCheck.Test.make ~count:1 ~long_factor:100
~name:"closure_sat" pb
(fun l ->
QCheck.assume (sat l);
try mk_closure l; true
with C.Unsat _ -> false
)
let closure_unsat =
QCheck.Test.make ~count:10 ~long_factor:10
~name:"closure_unsat" pb
(fun l ->
QCheck.assume (not (sat l));
try mk_closure l; false
with C.Unsat (a, b, chain) -> check_proof l (a, b, chain)
)
let closure_check =
QCheck.Test.make ~count:10 ~long_factor:100
~name:"closure_check" pb
(fun l ->
try
mk_closure l;
sat l
with C.Unsat (a, b, chain) ->
check_proof l (a, b, chain))
let closure_qtests = [
closure_sat;
closure_unsat;
closure_check;
]
|
3e597955a165610bf77e7c16e7576d5d6c583d1a06a4bc0d8f969159adf075c2 | bobzhang/fan | state.ml | open Sigs_util
let current_filters: (plugin_name* plugin) list ref = ref []
let reset_current_filters = function | () -> current_filters := []
let keep = ref true
let id = ref 0
let reset = function | () -> (keep := true; current_filters := [])
let gensym ?(pkg= "") =
function
| prefix ->
let res =
"fan_" ^ (prefix ^ ("_" ^ (pkg ^ ("_" ^ (string_of_int (!id)))))) in
(incr id; res)
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/cold/state.ml | ocaml | open Sigs_util
let current_filters: (plugin_name* plugin) list ref = ref []
let reset_current_filters = function | () -> current_filters := []
let keep = ref true
let id = ref 0
let reset = function | () -> (keep := true; current_filters := [])
let gensym ?(pkg= "") =
function
| prefix ->
let res =
"fan_" ^ (prefix ^ ("_" ^ (pkg ^ ("_" ^ (string_of_int (!id)))))) in
(incr id; res)
| |
637c8a5f838c9cfd3c4485e2eb141f842be28d87ae6dfab1c614fdfe09270d73 | geneweb/geneweb | birthDeath.mli | val select_person :
Config.config ->
Gwdb.base ->
(Gwdb.person -> Def.date option) ->
bool ->
(Gwdb.person * Def.dmy * Def.calendar) list * int
* [ select_person conf base get_date find_oldest ] select 20 persons
from the base according to the one of their date ( birth , death ,
marriage , specific event , etc . ) that could be get with [ get_date ] .
Returns sorted by date persons that have the latest ( if [ find_oldest ]
is false ) or oldest ( otherwise ) date . Selection could be different depending
on environement [ conf.env ] . These variables affect the selection :
k - allows to modify default value ( 20 ) of selected persons
by , bm , bd - allows to set reference date ( all dates after the reference
one are n't selected )
Returns also the number of selected persons
from the base according to the one of their date (birth, death,
marriage, specific event, etc.) that could be get with [get_date].
Returns sorted by date persons that have the latest (if [find_oldest]
is false) or oldest (otherwise) date. Selection could be different depending
on environement [conf.env]. These variables affect the selection:
k - allows to modify default value (20) of selected persons
by,bm,bd - allows to set reference date (all dates after the reference
one aren't selected)
Returns also the number of selected persons *)
val select_family :
Config.config ->
Gwdb.base ->
(Gwdb.family -> Def.date option) ->
bool ->
(Gwdb.family * Def.dmy * Def.calendar) list * int
(** Same as [select_person] but dealing with families *)
val death_date : Gwdb.person -> Adef.date option
(** Returns person's death date (if exists) *)
val make_population_pyramid :
nb_intervals:int ->
interval:int ->
limit:int ->
at_date:Def.dmy ->
Config.config ->
Gwdb.base ->
int array * int array
* [ make_population_pyramid nb_intervals interval interval at_date conf base ]
Calculates population pyramid of all perons in the base . Population pyramid
consists of two separated arrays that regroups number of men 's and women 's born
in each time interval . One array has a size [ nb_intervals + 1 ] and every element
is a number of persons born in the giving time interval that represents [ interval ] years .
Calculation starts at the date [ at_date ] and persons that are considered
in pyramid should be alive at this date . [ limit ] allows to limit persons
by age ( those that has age greater then limit are n't taken into the account )
Calculates population pyramid of all perons in the base. Population pyramid
consists of two separated arrays that regroups number of men's and women's born
in each time interval. One array has a size [nb_intervals + 1] and every element
is a number of persons born in the giving time interval that represents [interval] years.
Calculation starts at the date [at_date] and persons that are considered
in pyramid should be alive at this date. [limit] allows to limit persons
by age (those that has age greater then limit aren't taken into the account) *)
| null | https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/lib/birthDeath.mli | ocaml | * Same as [select_person] but dealing with families
* Returns person's death date (if exists) | val select_person :
Config.config ->
Gwdb.base ->
(Gwdb.person -> Def.date option) ->
bool ->
(Gwdb.person * Def.dmy * Def.calendar) list * int
* [ select_person conf base get_date find_oldest ] select 20 persons
from the base according to the one of their date ( birth , death ,
marriage , specific event , etc . ) that could be get with [ get_date ] .
Returns sorted by date persons that have the latest ( if [ find_oldest ]
is false ) or oldest ( otherwise ) date . Selection could be different depending
on environement [ conf.env ] . These variables affect the selection :
k - allows to modify default value ( 20 ) of selected persons
by , bm , bd - allows to set reference date ( all dates after the reference
one are n't selected )
Returns also the number of selected persons
from the base according to the one of their date (birth, death,
marriage, specific event, etc.) that could be get with [get_date].
Returns sorted by date persons that have the latest (if [find_oldest]
is false) or oldest (otherwise) date. Selection could be different depending
on environement [conf.env]. These variables affect the selection:
k - allows to modify default value (20) of selected persons
by,bm,bd - allows to set reference date (all dates after the reference
one aren't selected)
Returns also the number of selected persons *)
val select_family :
Config.config ->
Gwdb.base ->
(Gwdb.family -> Def.date option) ->
bool ->
(Gwdb.family * Def.dmy * Def.calendar) list * int
val death_date : Gwdb.person -> Adef.date option
val make_population_pyramid :
nb_intervals:int ->
interval:int ->
limit:int ->
at_date:Def.dmy ->
Config.config ->
Gwdb.base ->
int array * int array
* [ make_population_pyramid nb_intervals interval interval at_date conf base ]
Calculates population pyramid of all perons in the base . Population pyramid
consists of two separated arrays that regroups number of men 's and women 's born
in each time interval . One array has a size [ nb_intervals + 1 ] and every element
is a number of persons born in the giving time interval that represents [ interval ] years .
Calculation starts at the date [ at_date ] and persons that are considered
in pyramid should be alive at this date . [ limit ] allows to limit persons
by age ( those that has age greater then limit are n't taken into the account )
Calculates population pyramid of all perons in the base. Population pyramid
consists of two separated arrays that regroups number of men's and women's born
in each time interval. One array has a size [nb_intervals + 1] and every element
is a number of persons born in the giving time interval that represents [interval] years.
Calculation starts at the date [at_date] and persons that are considered
in pyramid should be alive at this date. [limit] allows to limit persons
by age (those that has age greater then limit aren't taken into the account) *)
|
b6cb1db83db4ffd94f22c72fb2557ea8fb3806e0723c447c1fef8411485de675 | fredrikt/yxa | mk_yxa_ssl_pkix_oid.erl | -module(mk_yxa_ssl_pkix_oid).
-export([make/0]).
-include("config.hrl").
-ifdef( HAS_OTP_PUB_KEY_HRL ).
-define(PKIX_MODULES, ['OTP-PUB-KEY']).
-else.
-define(PKIX_MODULES, ['OTP-PKIX']).
-endif.
make() ->
{ok, Fd} = file:open("yxa_ssl_pkix_oid.erl", [write]),
io:fwrite(Fd, "%%% File: yxa_ssl_pkix_oid.erl\n"
"%%% NB This file has been automatically generated by "
"mk_yxa_ssl_pkix_oid.\n"
"%%% Do not edit it.\n\n", []),
io:fwrite(Fd, "-module(yxa_ssl_pkix_oid).\n", []),
io:fwrite(Fd, "-export([id2atom/1, atom2id/1"
"]).\n\n", []),
AIds0 = get_atom_ids(?PKIX_MODULES),
AIds1 = modify_atoms(AIds0),
gen_id2atom(Fd, AIds1),
gen_atom2id(Fd, AIds1),
gen_all(Fd , AIds1 ) ,
file:close(Fd).
get_atom_ids(Ms) ->
get_atom_ids(Ms, []).
get_atom_ids([], AIdss) ->
lists:flatten(AIdss);
get_atom_ids([M| Ms], AIdss) ->
{value, {exports, Exports}} =
lists:keysearch(exports, 1, M:module_info()),
As = lists:zf(
fun ({info, 0}) -> false;
({module_info, 0}) -> false;
({encoding_rule, 0}) -> false;
({F, 0}) ->
case atom_to_list(F) of
%% Remove upper-bound (ub-) functions
"ub-" ++ _Rest ->
false;
_ ->
{true, F}
end;
(_) -> false
end, Exports),
AIds = lists:map(fun(F) -> {F, M:F()} end, As),
get_atom_ids(Ms, [AIds| AIdss]).
modify_atoms(AIds) ->
F = fun({A, I}) ->
NAS = case atom_to_list(A) of
"id-" ++ Rest ->
Rest;
Any ->
Any
end,
{list_to_atom(NAS), I} end,
lists:map(F, AIds).
gen_id2atom(Fd, AIds0) ->
AIds1 = lists:keysort(2, AIds0),
Txt = join(";\n",
lists:map(
fun({Atom, Id}) ->
io_lib:fwrite("id2atom(~p) ->\n ~p", [Id, Atom])
end, AIds1)),
io:fwrite(Fd, "~s;\nid2atom(Any)->\n Any.\n\n", [Txt]).
gen_atom2id(Fd, AIds0) ->
AIds1 = lists:keysort(1, AIds0),
Txt = join(";\n",
lists:map(
fun({Atom, Id}) ->
io_lib:fwrite("atom2id(~p) ->\n ~p", [Atom, Id])
end, AIds1)),
io:fwrite(Fd, "~s;\natom2id(Any)->\n Any.\n\n", [Txt]).
%% gen_all(Fd, AIds) ->
%% Atoms = lists:sort([A || {A, _} <- AIds]),
%% Ids = lists:sort([I || {_, I} <- AIds]),
F = fun(X ) - > io_lib : ( " ~w " , [ X ] ) end ,
ATxt = " all_atoms ( ) ->\n " + + join(",\n " , lists : map(F , Atoms ) ) ,
io : fwrite(Fd , " ~s.\n\n " , [ ATxt ] ) ,
ITxt = " all_ids ( ) ->\n " + + join(",\n " , lists : map(F , Ids ) ) ,
%% io:fwrite(Fd, "~s.\n\n", [ITxt]).
join(Sep, [H1, H2| T]) ->
[H1, Sep| join(Sep, [H2| T])];
join(_Sep, [H1]) ->
H1;
join(_, []) ->
[].
| null | https://raw.githubusercontent.com/fredrikt/yxa/85da46a999d083e6f00b5f156a634ca9be65645b/src/transportlayer/mk_yxa_ssl_pkix_oid.erl | erlang | Remove upper-bound (ub-) functions
gen_all(Fd, AIds) ->
Atoms = lists:sort([A || {A, _} <- AIds]),
Ids = lists:sort([I || {_, I} <- AIds]),
io:fwrite(Fd, "~s.\n\n", [ITxt]). | -module(mk_yxa_ssl_pkix_oid).
-export([make/0]).
-include("config.hrl").
-ifdef( HAS_OTP_PUB_KEY_HRL ).
-define(PKIX_MODULES, ['OTP-PUB-KEY']).
-else.
-define(PKIX_MODULES, ['OTP-PKIX']).
-endif.
make() ->
{ok, Fd} = file:open("yxa_ssl_pkix_oid.erl", [write]),
io:fwrite(Fd, "%%% File: yxa_ssl_pkix_oid.erl\n"
"%%% NB This file has been automatically generated by "
"mk_yxa_ssl_pkix_oid.\n"
"%%% Do not edit it.\n\n", []),
io:fwrite(Fd, "-module(yxa_ssl_pkix_oid).\n", []),
io:fwrite(Fd, "-export([id2atom/1, atom2id/1"
"]).\n\n", []),
AIds0 = get_atom_ids(?PKIX_MODULES),
AIds1 = modify_atoms(AIds0),
gen_id2atom(Fd, AIds1),
gen_atom2id(Fd, AIds1),
gen_all(Fd , AIds1 ) ,
file:close(Fd).
get_atom_ids(Ms) ->
get_atom_ids(Ms, []).
get_atom_ids([], AIdss) ->
lists:flatten(AIdss);
get_atom_ids([M| Ms], AIdss) ->
{value, {exports, Exports}} =
lists:keysearch(exports, 1, M:module_info()),
As = lists:zf(
fun ({info, 0}) -> false;
({module_info, 0}) -> false;
({encoding_rule, 0}) -> false;
({F, 0}) ->
case atom_to_list(F) of
"ub-" ++ _Rest ->
false;
_ ->
{true, F}
end;
(_) -> false
end, Exports),
AIds = lists:map(fun(F) -> {F, M:F()} end, As),
get_atom_ids(Ms, [AIds| AIdss]).
modify_atoms(AIds) ->
F = fun({A, I}) ->
NAS = case atom_to_list(A) of
"id-" ++ Rest ->
Rest;
Any ->
Any
end,
{list_to_atom(NAS), I} end,
lists:map(F, AIds).
gen_id2atom(Fd, AIds0) ->
AIds1 = lists:keysort(2, AIds0),
Txt = join(";\n",
lists:map(
fun({Atom, Id}) ->
io_lib:fwrite("id2atom(~p) ->\n ~p", [Id, Atom])
end, AIds1)),
io:fwrite(Fd, "~s;\nid2atom(Any)->\n Any.\n\n", [Txt]).
gen_atom2id(Fd, AIds0) ->
AIds1 = lists:keysort(1, AIds0),
Txt = join(";\n",
lists:map(
fun({Atom, Id}) ->
io_lib:fwrite("atom2id(~p) ->\n ~p", [Atom, Id])
end, AIds1)),
io:fwrite(Fd, "~s;\natom2id(Any)->\n Any.\n\n", [Txt]).
F = fun(X ) - > io_lib : ( " ~w " , [ X ] ) end ,
ATxt = " all_atoms ( ) ->\n " + + join(",\n " , lists : map(F , Atoms ) ) ,
io : fwrite(Fd , " ~s.\n\n " , [ ATxt ] ) ,
ITxt = " all_ids ( ) ->\n " + + join(",\n " , lists : map(F , Ids ) ) ,
join(Sep, [H1, H2| T]) ->
[H1, Sep| join(Sep, [H2| T])];
join(_Sep, [H1]) ->
H1;
join(_, []) ->
[].
|
99fbe5e3304e7f1aa4090a835800d48daf5e955c8cf4bef21f457ef868a237dd | stephenpascoe/hs-arrow | InputStream.hs |
|
Copyright : , and
License : LGPL-2.1
Maintainer : ( )
/No description available in the introspection data./
Copyright : Will Thompson, Iñaki García Etxebarria and Jonas Platte
License : LGPL-2.1
Maintainer : Iñaki García Etxebarria ()
/No description available in the introspection data./
-}
#define ENABLE_OVERLOADING (MIN_VERSION_haskell_gi_overloading(1,0,0) \
&& !defined(__HADDOCK_VERSION__))
module GI.Arrow.Objects.InputStream
(
-- * Exported types
InputStream(..) ,
IsInputStream ,
toInputStream ,
noInputStream ,
-- * Properties
-- ** inputStream #attr:inputStream#
{- | /No description available in the introspection data./
-}
#if ENABLE_OVERLOADING
InputStreamInputStreamPropertyInfo ,
#endif
constructInputStreamInputStream ,
#if ENABLE_OVERLOADING
inputStreamInputStream ,
#endif
) where
import Data.GI.Base.ShortPrelude
import qualified Data.GI.Base.ShortPrelude as SP
import qualified Data.GI.Base.Overloading as O
import qualified Prelude as P
import qualified Data.GI.Base.Attributes as GI.Attributes
import qualified Data.GI.Base.ManagedPtr as B.ManagedPtr
import qualified Data.GI.Base.GError as B.GError
import qualified Data.GI.Base.GVariant as B.GVariant
import qualified Data.GI.Base.GValue as B.GValue
import qualified Data.GI.Base.GParamSpec as B.GParamSpec
import qualified Data.GI.Base.CallStack as B.CallStack
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as Map
import qualified Foreign.Ptr as FP
import {-# SOURCE #-} qualified GI.Arrow.Interfaces.File as Arrow.File
import {-# SOURCE #-} qualified GI.Arrow.Interfaces.Readable as Arrow.Readable
import qualified GI.GObject.Objects.Object as GObject.Object
-- | Memory-managed wrapper type.
newtype InputStream = InputStream (ManagedPtr InputStream)
foreign import ccall "garrow_input_stream_get_type"
c_garrow_input_stream_get_type :: IO GType
instance GObject InputStream where
gobjectType _ = c_garrow_input_stream_get_type
| Type class for types which can be safely cast to ` InputStream ` , for instance with ` toInputStream ` .
class GObject o => IsInputStream o
#if MIN_VERSION_base(4,9,0)
instance {-# OVERLAPPABLE #-} (GObject a, O.UnknownAncestorError InputStream a) =>
IsInputStream a
#endif
instance IsInputStream InputStream
instance GObject.Object.IsObject InputStream
instance Arrow.File.IsFile InputStream
instance Arrow.Readable.IsReadable InputStream
| Cast to ` InputStream ` , for types for which this is known to be safe . For general casts , use ` Data . . ManagedPtr.castTo ` .
toInputStream :: (MonadIO m, IsInputStream o) => o -> m InputStream
toInputStream = liftIO . unsafeCastTo InputStream
-- | A convenience alias for `Nothing` :: `Maybe` `InputStream`.
noInputStream :: Maybe InputStream
noInputStream = Nothing
#if ENABLE_OVERLOADING
type family ResolveInputStreamMethod (t :: Symbol) (o :: *) :: * where
ResolveInputStreamMethod "bindProperty" o = GObject.Object.ObjectBindPropertyMethodInfo
ResolveInputStreamMethod "bindPropertyFull" o = GObject.Object.ObjectBindPropertyFullMethodInfo
ResolveInputStreamMethod "close" o = Arrow.File.FileCloseMethodInfo
ResolveInputStreamMethod "forceFloating" o = GObject.Object.ObjectForceFloatingMethodInfo
ResolveInputStreamMethod "freezeNotify" o = GObject.Object.ObjectFreezeNotifyMethodInfo
ResolveInputStreamMethod "getv" o = GObject.Object.ObjectGetvMethodInfo
ResolveInputStreamMethod "isFloating" o = GObject.Object.ObjectIsFloatingMethodInfo
ResolveInputStreamMethod "notify" o = GObject.Object.ObjectNotifyMethodInfo
ResolveInputStreamMethod "notifyByPspec" o = GObject.Object.ObjectNotifyByPspecMethodInfo
ResolveInputStreamMethod "read" o = Arrow.Readable.ReadableReadMethodInfo
ResolveInputStreamMethod "ref" o = GObject.Object.ObjectRefMethodInfo
ResolveInputStreamMethod "refSink" o = GObject.Object.ObjectRefSinkMethodInfo
ResolveInputStreamMethod "runDispose" o = GObject.Object.ObjectRunDisposeMethodInfo
ResolveInputStreamMethod "stealData" o = GObject.Object.ObjectStealDataMethodInfo
ResolveInputStreamMethod "stealQdata" o = GObject.Object.ObjectStealQdataMethodInfo
ResolveInputStreamMethod "tell" o = Arrow.File.FileTellMethodInfo
ResolveInputStreamMethod "thawNotify" o = GObject.Object.ObjectThawNotifyMethodInfo
ResolveInputStreamMethod "unref" o = GObject.Object.ObjectUnrefMethodInfo
ResolveInputStreamMethod "watchClosure" o = GObject.Object.ObjectWatchClosureMethodInfo
ResolveInputStreamMethod "getData" o = GObject.Object.ObjectGetDataMethodInfo
ResolveInputStreamMethod "getMode" o = Arrow.File.FileGetModeMethodInfo
ResolveInputStreamMethod "getProperty" o = GObject.Object.ObjectGetPropertyMethodInfo
ResolveInputStreamMethod "getQdata" o = GObject.Object.ObjectGetQdataMethodInfo
ResolveInputStreamMethod "setData" o = GObject.Object.ObjectSetDataMethodInfo
ResolveInputStreamMethod "setProperty" o = GObject.Object.ObjectSetPropertyMethodInfo
ResolveInputStreamMethod l o = O.MethodResolutionFailed l o
instance (info ~ ResolveInputStreamMethod t InputStream, O.MethodInfo info InputStream p) => O.IsLabelProxy t (InputStream -> p) where
fromLabelProxy _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#if MIN_VERSION_base(4,9,0)
instance (info ~ ResolveInputStreamMethod t InputStream, O.MethodInfo info InputStream p) => O.IsLabel t (InputStream -> p) where
#if MIN_VERSION_base(4,10,0)
fromLabel = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#else
fromLabel _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#endif
#endif
#endif
-- VVV Prop "input-stream"
Type : TBasicType TPtr
Flags : [ PropertyWritable , PropertyConstructOnly ]
-- Nullable: (Nothing,Nothing)
|
Construct a ` GValueConstruct ` with valid value for the “ @input - stream@ ” property . This is rarely needed directly , but it is used by ` Data.GI.Base.Constructible.new ` .
Construct a `GValueConstruct` with valid value for the “@input-stream@” property. This is rarely needed directly, but it is used by `Data.GI.Base.Constructible.new`.
-}
constructInputStreamInputStream :: (IsInputStream o) => Ptr () -> IO (GValueConstruct o)
constructInputStreamInputStream val = constructObjectPropertyPtr "input-stream" val
#if ENABLE_OVERLOADING
data InputStreamInputStreamPropertyInfo
instance AttrInfo InputStreamInputStreamPropertyInfo where
type AttrAllowedOps InputStreamInputStreamPropertyInfo = '[ 'AttrConstruct]
type AttrSetTypeConstraint InputStreamInputStreamPropertyInfo = (~) (Ptr ())
type AttrBaseTypeConstraint InputStreamInputStreamPropertyInfo = IsInputStream
type AttrGetType InputStreamInputStreamPropertyInfo = ()
type AttrLabel InputStreamInputStreamPropertyInfo = "input-stream"
type AttrOrigin InputStreamInputStreamPropertyInfo = InputStream
attrGet _ = undefined
attrSet _ = undefined
attrConstruct _ = constructInputStreamInputStream
attrClear _ = undefined
#endif
#if ENABLE_OVERLOADING
instance O.HasAttributeList InputStream
type instance O.AttributeList InputStream = InputStreamAttributeList
type InputStreamAttributeList = ('[ '("inputStream", InputStreamInputStreamPropertyInfo)] :: [(Symbol, *)])
#endif
#if ENABLE_OVERLOADING
inputStreamInputStream :: AttrLabelProxy "inputStream"
inputStreamInputStream = AttrLabelProxy
#endif
#if ENABLE_OVERLOADING
type instance O.SignalList InputStream = InputStreamSignalList
type InputStreamSignalList = ('[ '("notify", GObject.Object.ObjectNotifySignalInfo)] :: [(Symbol, *)])
#endif
| null | https://raw.githubusercontent.com/stephenpascoe/hs-arrow/86c7c452a8626b1d69a3cffd277078d455823271/gi-arrow/GI/Arrow/Objects/InputStream.hs | haskell | * Exported types
* Properties
** inputStream #attr:inputStream#
| /No description available in the introspection data./
# SOURCE #
# SOURCE #
| Memory-managed wrapper type.
# OVERLAPPABLE #
| A convenience alias for `Nothing` :: `Maybe` `InputStream`.
VVV Prop "input-stream"
Nullable: (Nothing,Nothing) |
|
Copyright : , and
License : LGPL-2.1
Maintainer : ( )
/No description available in the introspection data./
Copyright : Will Thompson, Iñaki García Etxebarria and Jonas Platte
License : LGPL-2.1
Maintainer : Iñaki García Etxebarria ()
/No description available in the introspection data./
-}
#define ENABLE_OVERLOADING (MIN_VERSION_haskell_gi_overloading(1,0,0) \
&& !defined(__HADDOCK_VERSION__))
module GI.Arrow.Objects.InputStream
(
InputStream(..) ,
IsInputStream ,
toInputStream ,
noInputStream ,
#if ENABLE_OVERLOADING
InputStreamInputStreamPropertyInfo ,
#endif
constructInputStreamInputStream ,
#if ENABLE_OVERLOADING
inputStreamInputStream ,
#endif
) where
import Data.GI.Base.ShortPrelude
import qualified Data.GI.Base.ShortPrelude as SP
import qualified Data.GI.Base.Overloading as O
import qualified Prelude as P
import qualified Data.GI.Base.Attributes as GI.Attributes
import qualified Data.GI.Base.ManagedPtr as B.ManagedPtr
import qualified Data.GI.Base.GError as B.GError
import qualified Data.GI.Base.GVariant as B.GVariant
import qualified Data.GI.Base.GValue as B.GValue
import qualified Data.GI.Base.GParamSpec as B.GParamSpec
import qualified Data.GI.Base.CallStack as B.CallStack
import qualified Data.Text as T
import qualified Data.ByteString.Char8 as B
import qualified Data.Map as Map
import qualified Foreign.Ptr as FP
import qualified GI.GObject.Objects.Object as GObject.Object
newtype InputStream = InputStream (ManagedPtr InputStream)
foreign import ccall "garrow_input_stream_get_type"
c_garrow_input_stream_get_type :: IO GType
instance GObject InputStream where
gobjectType _ = c_garrow_input_stream_get_type
| Type class for types which can be safely cast to ` InputStream ` , for instance with ` toInputStream ` .
class GObject o => IsInputStream o
#if MIN_VERSION_base(4,9,0)
IsInputStream a
#endif
instance IsInputStream InputStream
instance GObject.Object.IsObject InputStream
instance Arrow.File.IsFile InputStream
instance Arrow.Readable.IsReadable InputStream
| Cast to ` InputStream ` , for types for which this is known to be safe . For general casts , use ` Data . . ManagedPtr.castTo ` .
toInputStream :: (MonadIO m, IsInputStream o) => o -> m InputStream
toInputStream = liftIO . unsafeCastTo InputStream
noInputStream :: Maybe InputStream
noInputStream = Nothing
#if ENABLE_OVERLOADING
type family ResolveInputStreamMethod (t :: Symbol) (o :: *) :: * where
ResolveInputStreamMethod "bindProperty" o = GObject.Object.ObjectBindPropertyMethodInfo
ResolveInputStreamMethod "bindPropertyFull" o = GObject.Object.ObjectBindPropertyFullMethodInfo
ResolveInputStreamMethod "close" o = Arrow.File.FileCloseMethodInfo
ResolveInputStreamMethod "forceFloating" o = GObject.Object.ObjectForceFloatingMethodInfo
ResolveInputStreamMethod "freezeNotify" o = GObject.Object.ObjectFreezeNotifyMethodInfo
ResolveInputStreamMethod "getv" o = GObject.Object.ObjectGetvMethodInfo
ResolveInputStreamMethod "isFloating" o = GObject.Object.ObjectIsFloatingMethodInfo
ResolveInputStreamMethod "notify" o = GObject.Object.ObjectNotifyMethodInfo
ResolveInputStreamMethod "notifyByPspec" o = GObject.Object.ObjectNotifyByPspecMethodInfo
ResolveInputStreamMethod "read" o = Arrow.Readable.ReadableReadMethodInfo
ResolveInputStreamMethod "ref" o = GObject.Object.ObjectRefMethodInfo
ResolveInputStreamMethod "refSink" o = GObject.Object.ObjectRefSinkMethodInfo
ResolveInputStreamMethod "runDispose" o = GObject.Object.ObjectRunDisposeMethodInfo
ResolveInputStreamMethod "stealData" o = GObject.Object.ObjectStealDataMethodInfo
ResolveInputStreamMethod "stealQdata" o = GObject.Object.ObjectStealQdataMethodInfo
ResolveInputStreamMethod "tell" o = Arrow.File.FileTellMethodInfo
ResolveInputStreamMethod "thawNotify" o = GObject.Object.ObjectThawNotifyMethodInfo
ResolveInputStreamMethod "unref" o = GObject.Object.ObjectUnrefMethodInfo
ResolveInputStreamMethod "watchClosure" o = GObject.Object.ObjectWatchClosureMethodInfo
ResolveInputStreamMethod "getData" o = GObject.Object.ObjectGetDataMethodInfo
ResolveInputStreamMethod "getMode" o = Arrow.File.FileGetModeMethodInfo
ResolveInputStreamMethod "getProperty" o = GObject.Object.ObjectGetPropertyMethodInfo
ResolveInputStreamMethod "getQdata" o = GObject.Object.ObjectGetQdataMethodInfo
ResolveInputStreamMethod "setData" o = GObject.Object.ObjectSetDataMethodInfo
ResolveInputStreamMethod "setProperty" o = GObject.Object.ObjectSetPropertyMethodInfo
ResolveInputStreamMethod l o = O.MethodResolutionFailed l o
instance (info ~ ResolveInputStreamMethod t InputStream, O.MethodInfo info InputStream p) => O.IsLabelProxy t (InputStream -> p) where
fromLabelProxy _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#if MIN_VERSION_base(4,9,0)
instance (info ~ ResolveInputStreamMethod t InputStream, O.MethodInfo info InputStream p) => O.IsLabel t (InputStream -> p) where
#if MIN_VERSION_base(4,10,0)
fromLabel = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#else
fromLabel _ = O.overloadedMethod (O.MethodProxy :: O.MethodProxy info)
#endif
#endif
#endif
Type : TBasicType TPtr
Flags : [ PropertyWritable , PropertyConstructOnly ]
|
Construct a ` GValueConstruct ` with valid value for the “ @input - stream@ ” property . This is rarely needed directly , but it is used by ` Data.GI.Base.Constructible.new ` .
Construct a `GValueConstruct` with valid value for the “@input-stream@” property. This is rarely needed directly, but it is used by `Data.GI.Base.Constructible.new`.
-}
constructInputStreamInputStream :: (IsInputStream o) => Ptr () -> IO (GValueConstruct o)
constructInputStreamInputStream val = constructObjectPropertyPtr "input-stream" val
#if ENABLE_OVERLOADING
data InputStreamInputStreamPropertyInfo
instance AttrInfo InputStreamInputStreamPropertyInfo where
type AttrAllowedOps InputStreamInputStreamPropertyInfo = '[ 'AttrConstruct]
type AttrSetTypeConstraint InputStreamInputStreamPropertyInfo = (~) (Ptr ())
type AttrBaseTypeConstraint InputStreamInputStreamPropertyInfo = IsInputStream
type AttrGetType InputStreamInputStreamPropertyInfo = ()
type AttrLabel InputStreamInputStreamPropertyInfo = "input-stream"
type AttrOrigin InputStreamInputStreamPropertyInfo = InputStream
attrGet _ = undefined
attrSet _ = undefined
attrConstruct _ = constructInputStreamInputStream
attrClear _ = undefined
#endif
#if ENABLE_OVERLOADING
instance O.HasAttributeList InputStream
type instance O.AttributeList InputStream = InputStreamAttributeList
type InputStreamAttributeList = ('[ '("inputStream", InputStreamInputStreamPropertyInfo)] :: [(Symbol, *)])
#endif
#if ENABLE_OVERLOADING
inputStreamInputStream :: AttrLabelProxy "inputStream"
inputStreamInputStream = AttrLabelProxy
#endif
#if ENABLE_OVERLOADING
type instance O.SignalList InputStream = InputStreamSignalList
type InputStreamSignalList = ('[ '("notify", GObject.Object.ObjectNotifySignalInfo)] :: [(Symbol, *)])
#endif
|
75a72c6fb2d189abff19ded84f384f79d926bef6ea72a4eaa83f7ce003e24fa8 | kelamg/HtDP2e-workthrough | ex495.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-intermediate-lambda-reader.ss" "lang")((modname ex495) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; [List-of N] -> N
sums all the numbers in alon0
(check-expect (sum.v2 '()) 0)
(check-expect (sum.v2 '(10 4 6)) 20)
(define (sum.v2 alon0)
(sum/a alon0 0))
; [List-of Number] ??? -> Number
; computes the sum of the numbers on alon
; accumulator a is the sum of the numbers
that alon lacks from alon0
(define (sum/a alon a)
(cond
[(empty? alon) a]
[else (sum/a (rest alon)
(+ (first alon) a))]))
(sum/a '(10 4 6) 0)
(sum/a (rest '(10 4 6)) (+ (first '(10 4 6)) 0))
(sum/a '(4 6) (+ (first '(10 4 6)) 0))
(sum/a '(4 6) (+ 10 0))
(sum/a '(4 6) 10)
(sum/a (rest '(4 6)) (+ (first '(4 6)) 10))
(sum/a '(6) (+ (first '(4 6)) 10))
(sum/a '(6) (+ 4 10))
(sum/a '(6) 14)
(sum/a (rest '(6)) (+ (first '(6)) 14))
(sum/a '() (+ (first '(6)) 14))
(sum/a '() (+ 6 14))
(sum/a '() 20)
20
| null | https://raw.githubusercontent.com/kelamg/HtDP2e-workthrough/ec05818d8b667a3c119bea8d1d22e31e72e0a958/HtDP/Accumulators/ex495.rkt | racket | about the language level of this file in a form that our tools can easily process.
[List-of N] -> N
[List-of Number] ??? -> Number
computes the sum of the numbers on alon
accumulator a is the sum of the numbers | The first three lines of this file were inserted by . They record metadata
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname ex495) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
sums all the numbers in alon0
(check-expect (sum.v2 '()) 0)
(check-expect (sum.v2 '(10 4 6)) 20)
(define (sum.v2 alon0)
(sum/a alon0 0))
that alon lacks from alon0
(define (sum/a alon a)
(cond
[(empty? alon) a]
[else (sum/a (rest alon)
(+ (first alon) a))]))
(sum/a '(10 4 6) 0)
(sum/a (rest '(10 4 6)) (+ (first '(10 4 6)) 0))
(sum/a '(4 6) (+ (first '(10 4 6)) 0))
(sum/a '(4 6) (+ 10 0))
(sum/a '(4 6) 10)
(sum/a (rest '(4 6)) (+ (first '(4 6)) 10))
(sum/a '(6) (+ (first '(4 6)) 10))
(sum/a '(6) (+ 4 10))
(sum/a '(6) 14)
(sum/a (rest '(6)) (+ (first '(6)) 14))
(sum/a '() (+ (first '(6)) 14))
(sum/a '() (+ 6 14))
(sum/a '() 20)
20
|
3bd1c1bf9a0c3ec88c397cdfedc663c281e64621a1e83fae1fd6af0752b9dba3 | input-output-hk/cardano-wallet | Tx.hs | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE EmptyCase #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
{-# LANGUAGE GADTs #-}
# LANGUAGE LambdaCase #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
-- |
Copyright : © 2022 IOHK
-- License: Apache-2.0
--
-- Module containing primitive types and functionality appropriate for
-- constructing transactions.
--
Indented as a replacement to closer
to the ledger types , and only caring about the two latest eras ( Cf .
-- 'RecentEra'). Intended to be used by things like balanceTx, constructTx and
-- wallet migration.
module Cardano.Wallet.Write.Tx
(
-- * Eras
-- ** RecentEra
RecentEra (..)
, IsRecentEra (..)
, toRecentEra
, fromRecentEra
, LatestLedgerEra
, LatestEra
-- ** Helpers for cardano-api compatibility
, cardanoEra
, shelleyBasedEra
, ShelleyLedgerEra
, cardanoEraFromRecentEra
, shelleyBasedEraFromRecentEra
-- ** Existential wrapper
, AnyRecentEra (..)
, InAnyRecentEra (..)
, asAnyRecentEra
, fromAnyRecentEra
, withInAnyRecentEra
, withRecentEra
-- ** Misc
, StandardCrypto
, StandardBabbage
, StandardAlonzo
-- * PParams
, Core.PParams
-- * Tx
, Core.Tx
, Core.TxBody
, txBody
, outputs
, modifyTxOutputs
, modifyLedgerBody
-- * TxOut
, Core.TxOut
, TxOutInBabbage
, TxOutInRecentEra (..)
, unwrapTxOutInRecentEra
, ErrInvalidTxOutInEra (..)
, modifyTxOutValue
, modifyTxOutCoin
, txOutValue
, computeMinimumCoinForTxOut
, isBelowMinimumCoinForTxOut
-- ** Address
, Address
, unsafeAddressFromBytes
-- ** Value
, Value
, modifyCoin
, coin
, Coin (..)
* * Datum
, Datum (..)
, datumFromCardanoScriptData
, datumToCardanoScriptData
-- *** Binary Data
, BinaryData
, binaryDataFromBytes
, binaryDataToBytes
-- *** Datum Hash
, DatumHash
, datumHashFromBytes
, datumHashToBytes
-- ** Script
, Script (..)
, scriptFromCardanoScriptInAnyLang
, scriptToCardanoScriptInAnyLang
, scriptToCardanoEnvelopeJSON
, scriptFromCardanoEnvelopeJSON
, Alonzo.isPlutusScript
*
, TxIn
, unsafeMkTxIn
*
, Shelley.UTxO (..)
, utxoFromTxOutsInRecentEra
, utxoFromTxOutsInLatestEra
, utxoFromTxOuts
, fromCardanoTx
, toCardanoUTxO
, fromCardanoUTxO
, toCardanoValue
-- * Balancing
, evaluateTransactionBalance
)
where
import Prelude
import Cardano.Api
( AlonzoEra, BabbageEra )
import Cardano.Api.Shelley
( ShelleyLedgerEra )
import Cardano.Crypto.Hash
( Hash (UnsafeHash) )
import Cardano.Ledger.Alonzo.Data
( BinaryData, Datum (..) )
import Cardano.Ledger.Alonzo.Scripts
( Script (..) )
import Cardano.Ledger.Coin
( Coin (..) )
import Cardano.Ledger.Crypto
( StandardCrypto )
import Cardano.Ledger.Era
( Crypto )
import Cardano.Ledger.Mary
( Value )
import Cardano.Ledger.SafeHash
( SafeHash, extractHash, unsafeMakeSafeHash )
import Cardano.Ledger.Serialization
( Sized (..), mkSized )
import Cardano.Ledger.Shelley.API
( CLI (evaluateMinLovelaceOutput) )
import Cardano.Ledger.Val
( coin, modifyCoin )
import Cardano.Wallet.Primitive.Types.Tx.Constraints
( txOutMaxCoin )
import Cardano.Wallet.Shelley.Compatibility.Ledger
( toLedger )
import Control.Arrow
( second )
import Data.ByteString
( ByteString )
import Data.ByteString.Short
( toShort )
import Data.Foldable
( toList )
import Data.Maybe
( fromMaybe )
import Data.Maybe.Strict
( StrictMaybe (..) )
import Ouroboros.Consensus.Shelley.Eras
( StandardBabbage )
import Test.Cardano.Ledger.Alonzo.Examples.Consensus
( StandardAlonzo )
import qualified Cardano.Api as Cardano
import qualified Cardano.Api.Byron as Cardano
import qualified Cardano.Api.Extra as Cardano
import qualified Cardano.Api.Shelley as Cardano
import qualified Cardano.Binary as CBOR
import qualified Cardano.Crypto.Hash.Class as Crypto
import qualified Cardano.Ledger.Address as Ledger
import qualified Cardano.Ledger.Alonzo.Data as Alonzo
import qualified Cardano.Ledger.Alonzo.Scripts as Alonzo
import qualified Cardano.Ledger.Alonzo.Tx as Alonzo
import qualified Cardano.Ledger.Alonzo.TxBody as Alonzo
import qualified Cardano.Ledger.Babbage as Babbage
import qualified Cardano.Ledger.Babbage.TxBody as Babbage
import qualified Cardano.Ledger.Core as Core
import qualified Cardano.Ledger.Shelley.API.Wallet as Shelley
import qualified Cardano.Ledger.Shelley.UTxO as Shelley
import qualified Cardano.Ledger.TxIn as Ledger
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
import qualified Data.Map as Map
--------------------------------------------------------------------------------
-- Eras
--------------------------------------------------------------------------------
type LatestEra = BabbageEra
type LatestLedgerEra = StandardBabbage
--------------------------------------------------------------------------------
RecentEra
--------------------------------------------------------------------------------
-- | 'RecentEra' respresents the eras we care about constructing transactions
-- for.
--
-- To have the same software constructing transactions just before and just
after a hard - fork , we need to , at that time , support the two latest eras . We
-- could get away with just supporting one era at other times, but for
simplicity we stick with always supporting the two latest eras for now .
--
-- NOTE: We /could/ let 'era' refer to eras from the ledger rather than from
-- cardano-api.
data RecentEra era where
RecentEraBabbage :: RecentEra BabbageEra
RecentEraAlonzo :: RecentEra AlonzoEra
deriving instance Eq (RecentEra era)
deriving instance Show (RecentEra era)
class Cardano.IsShelleyBasedEra era => IsRecentEra era where
recentEra :: RecentEra era
| Return a proof that the wallet can create txs in this era , or @Nothing@.
toRecentEra :: Cardano.CardanoEra era -> Maybe (RecentEra era)
toRecentEra = \case
Cardano.BabbageEra -> Just RecentEraBabbage
Cardano.AlonzoEra -> Just RecentEraAlonzo
Cardano.MaryEra -> Nothing
Cardano.AllegraEra -> Nothing
Cardano.ShelleyEra -> Nothing
Cardano.ByronEra -> Nothing
fromRecentEra :: RecentEra era -> Cardano.CardanoEra era
fromRecentEra = \case
RecentEraBabbage -> Cardano.BabbageEra
RecentEraAlonzo -> Cardano.AlonzoEra
instance IsRecentEra BabbageEra where
recentEra = RecentEraBabbage
instance IsRecentEra AlonzoEra where
recentEra = RecentEraAlonzo
cardanoEraFromRecentEra :: RecentEra era -> Cardano.CardanoEra era
cardanoEraFromRecentEra =
Cardano.shelleyBasedToCardanoEra
. shelleyBasedEraFromRecentEra
shelleyBasedEraFromRecentEra :: RecentEra era -> Cardano.ShelleyBasedEra era
shelleyBasedEraFromRecentEra = \case
RecentEraBabbage -> Cardano.ShelleyBasedEraBabbage
RecentEraAlonzo -> Cardano.ShelleyBasedEraAlonzo
| For convenience working with ' IsRecentEra ' . Similar to ' Cardano.cardanoEra ,
but with a ' IsRecentEra era ' constraint instead of ' Cardano . IsCardanoEra .
cardanoEra :: forall era. IsRecentEra era => Cardano.CardanoEra era
cardanoEra = cardanoEraFromRecentEra $ recentEra @era
-- | For convenience working with 'IsRecentEra'. Similar to
' Cardano.shelleyBasedEra , but with a ' IsRecentEra era ' constraint instead of
' Cardano . IsShelleyBasedEra ' .
shelleyBasedEra :: forall era. IsRecentEra era => Cardano.ShelleyBasedEra era
shelleyBasedEra = shelleyBasedEraFromRecentEra $ recentEra @era
data InAnyRecentEra thing where
InAnyRecentEra
:: IsRecentEra era -- Provide class constraint
=> RecentEra era -- and explicit value.
-> thing era
-> InAnyRecentEra thing
withInAnyRecentEra
:: InAnyRecentEra thing
-> (forall era. IsRecentEra era => thing era -> a)
-> a
withInAnyRecentEra (InAnyRecentEra _era tx) f = f tx
-- | "Downcast" something existentially wrapped in 'Cardano.InAnyCardanoEra'.
asAnyRecentEra
:: Cardano.InAnyCardanoEra a
-> Maybe (InAnyRecentEra a)
asAnyRecentEra = \case
Cardano.InAnyCardanoEra Cardano.BabbageEra a ->
Just $ InAnyRecentEra RecentEraBabbage a
Cardano.InAnyCardanoEra Cardano.AlonzoEra a ->
Just $ InAnyRecentEra RecentEraAlonzo a
_ -> Nothing
| An existential type like ' ' , but for ' RecentEra ' .
data AnyRecentEra where
AnyRecentEra :: IsRecentEra era -- Provide class constraint
=> RecentEra era -- and explicit value.
-> AnyRecentEra -- and that's it.
instance Show AnyRecentEra where
show (AnyRecentEra era) = "AnyRecentEra " <> show era
fromAnyRecentEra :: AnyRecentEra -> Cardano.AnyCardanoEra
fromAnyRecentEra (AnyRecentEra era) = Cardano.AnyCardanoEra (fromRecentEra era)
withRecentEra ::
AnyRecentEra -> (forall era. IsRecentEra era => RecentEra era -> a) -> a
withRecentEra (AnyRecentEra era) f = f era
--------------------------------------------------------------------------------
-- TxIn
--------------------------------------------------------------------------------
type TxIn = Ledger.TxIn StandardCrypto
-- | Useful for testing
unsafeMkTxIn :: ByteString -> Word -> TxIn
unsafeMkTxIn hash ix = Ledger.mkTxInPartial
(toTxId hash)
(fromIntegral ix)
where
toTxId :: ByteString -> Ledger.TxId StandardCrypto
toTxId h =
(Ledger.TxId (unsafeMakeSafeHash $ UnsafeHash $ toShort h))
--------------------------------------------------------------------------------
-- TxOut
--------------------------------------------------------------------------------
type TxOut era = Core.TxOut era
modifyTxOutValue
:: RecentEra era
-> (Value (ShelleyLedgerEra era) -> Value (ShelleyLedgerEra era))
-> TxOut (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
modifyTxOutValue RecentEraBabbage f (Babbage.TxOut addr val dat script) =
withStandardCryptoConstraint RecentEraBabbage $
Babbage.TxOut addr (f val) dat script
modifyTxOutValue RecentEraAlonzo f (Alonzo.TxOut addr val dat) =
withStandardCryptoConstraint RecentEraAlonzo $
Alonzo.TxOut addr (f val) dat
modifyTxOutCoin
:: RecentEra era
-> (Coin -> Coin)
-> TxOut (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
modifyTxOutCoin era f = withStandardCryptoConstraint era $
modifyTxOutValue era (modifyCoin f)
txOutValue
:: RecentEra era
-> TxOut (ShelleyLedgerEra era)
-> Value (ShelleyLedgerEra era)
txOutValue RecentEraBabbage (Babbage.TxOut _ val _ _) = val
txOutValue RecentEraAlonzo (Alonzo.TxOut _ val _) = val
type TxOutInBabbage = Babbage.TxOut (Babbage.BabbageEra StandardCrypto)
type Address = Ledger.Addr StandardCrypto
unsafeAddressFromBytes :: ByteString -> Address
unsafeAddressFromBytes bytes = case Ledger.deserialiseAddr bytes of
Just addr -> addr
Nothing -> error "unsafeAddressFromBytes: failed to deserialise"
scriptFromCardanoScriptInAnyLang
:: Cardano.ScriptInAnyLang
-> Script LatestLedgerEra
scriptFromCardanoScriptInAnyLang
= Cardano.toShelleyScript
. fromMaybe (error "all valid scripts should be valid in latest era")
. Cardano.toScriptInEra latestEra
where
latestEra = Cardano.BabbageEra
-- | NOTE: The roundtrip
-- @
-- scriptToCardanoScriptInAnyLang . scriptFromCardanoScriptInAnyLang
-- @
-- will convert 'SimpleScriptV1' to 'SimpleScriptV2'. Because 'SimpleScriptV1'
is ' ShelleyEra'-specific , and ' ShelleyEra ' is not a ' RecentEra ' , this should
-- not be a problem.
scriptToCardanoScriptInAnyLang
:: Script LatestLedgerEra
-> Cardano.ScriptInAnyLang
scriptToCardanoScriptInAnyLang =
rewrap
. Cardano.fromShelleyBasedScript latestEra
where
rewrap (Cardano.ScriptInEra _ s) = Cardano.toScriptInAnyLang s
latestEra = Cardano.ShelleyBasedEraBabbage
-- | NOTE: The roundtrip
-- @
scriptToCardanoEnvelopeJSON . scriptFromCardanoEnvelopeJSON
-- @
-- will convert 'SimpleScriptV1' to 'SimpleScriptV2'. Because 'SimpleScriptV1'
is ' ShelleyEra'-specific , and ' ShelleyEra ' is not a ' RecentEra ' , this should
-- not be a problem.
scriptToCardanoEnvelopeJSON :: Script LatestLedgerEra -> Aeson.Value
scriptToCardanoEnvelopeJSON = scriptToJSON . scriptToCardanoScriptInAnyLang
where
scriptToJSON
:: Cardano.ScriptInAnyLang
-> Aeson.Value
scriptToJSON (Cardano.ScriptInAnyLang l s) = Aeson.toJSON
$ obtainScriptLangConstraint l
$ Cardano.serialiseToTextEnvelope Nothing s
where
obtainScriptLangConstraint
:: Cardano.ScriptLanguage lang
-> (Cardano.IsScriptLanguage lang => a)
-> a
obtainScriptLangConstraint lang f = case lang of
Cardano.SimpleScriptLanguage Cardano.SimpleScriptV1 -> f
Cardano.SimpleScriptLanguage Cardano.SimpleScriptV2 -> f
Cardano.PlutusScriptLanguage Cardano.PlutusScriptV1 -> f
Cardano.PlutusScriptLanguage Cardano.PlutusScriptV2 -> f
scriptFromCardanoEnvelopeJSON
:: Aeson.Value
-> Aeson.Parser (Script LatestLedgerEra)
scriptFromCardanoEnvelopeJSON v = fmap scriptFromCardanoScriptInAnyLang $ do
envelope <- Aeson.parseJSON v
case textEnvelopeToScript envelope of
Left textEnvErr
-> fail $ Cardano.displayError textEnvErr
Right (Cardano.ScriptInAnyLang l s)
-> pure $ Cardano.ScriptInAnyLang l s
where
textEnvelopeToScript
:: Cardano.TextEnvelope
-> Either Cardano.TextEnvelopeError Cardano.ScriptInAnyLang
textEnvelopeToScript =
Cardano.deserialiseFromTextEnvelopeAnyOf textEnvTypes
textEnvTypes
:: [Cardano.FromSomeType Cardano.HasTextEnvelope Cardano.ScriptInAnyLang]
textEnvTypes =
[ Cardano.FromSomeType
(Cardano.AsScript Cardano.AsSimpleScriptV1)
(Cardano.ScriptInAnyLang
(Cardano.SimpleScriptLanguage Cardano.SimpleScriptV1))
, Cardano.FromSomeType
(Cardano.AsScript Cardano.AsSimpleScriptV2)
(Cardano.ScriptInAnyLang
(Cardano.SimpleScriptLanguage Cardano.SimpleScriptV2))
, Cardano.FromSomeType
(Cardano.AsScript Cardano.AsPlutusScriptV1)
(Cardano.ScriptInAnyLang
(Cardano.PlutusScriptLanguage Cardano.PlutusScriptV1))
, Cardano.FromSomeType
(Cardano.AsScript Cardano.AsPlutusScriptV2)
(Cardano.ScriptInAnyLang
(Cardano.PlutusScriptLanguage Cardano.PlutusScriptV2))
]
-- NOTE on binary format: There are a couple of related types in the ledger each
with their own binary encoding . ' . Data ' seems to be the type with the
-- least amount of wrapping tags in the encoding.
--
- ' . Data ' - the simplest encoding of the following options
- ' Alonzo . BinaryData ' - adds a preceding @24@ tag
-- - 'Alonzo.Data' - n/a; doesn't have a ToCBOR
- ' . Datum ' - adds tags to differentiate between e.g. inline datums and
-- datum hashes. We could add helpers for this roundtrip, but they would be
-- separate from the existing 'datum{From,To}Bytes' pair.
binaryDataFromBytes
:: ByteString
-> Either String (BinaryData LatestLedgerEra)
binaryDataFromBytes =
Alonzo.makeBinaryData . toShort
binaryDataToBytes :: BinaryData LatestLedgerEra -> ByteString
binaryDataToBytes =
CBOR.serialize'
. Alonzo.getPlutusData
. Alonzo.binaryDataToData
datumFromCardanoScriptData
:: Cardano.ScriptData
-> BinaryData LatestLedgerEra
datumFromCardanoScriptData =
Alonzo.dataToBinaryData
. Cardano.toAlonzoData
datumToCardanoScriptData
:: BinaryData LatestLedgerEra
-> Cardano.ScriptData
datumToCardanoScriptData =
Cardano.fromAlonzoData
. Alonzo.binaryDataToData
type DatumHash = Alonzo.DataHash StandardCrypto
datumHashFromBytes :: ByteString -> Maybe DatumHash
datumHashFromBytes =
fmap unsafeMakeSafeHash <$> Crypto.hashFromBytes
datumHashToBytes :: SafeHash crypto a -> ByteString
datumHashToBytes = Crypto.hashToBytes . extractHash
| Type representing a TxOut in the latest or previous era .
--
-- The underlying respresentation is isomorphic to 'TxOut LatestLedgerEra'.
--
-- Can be unwrapped using 'unwrapTxOutInRecentEra' or
-- 'utxoFromTxOutsInRecentEra'.
--
-- Implementation assumes @TxOut latestEra ⊇ TxOut prevEra@ in the sense that
the latest era has not removed information from the @TxOut@. This is allows
e.g. @ToJSON@ / @FromJSON@ instances to be written for two eras using only
one implementation .
data TxOutInRecentEra
= TxOutInRecentEra
Address
(Value LatestLedgerEra)
(Datum LatestLedgerEra)
(Maybe (Script LatestLedgerEra))
-- Same contents as 'TxOut LatestLedgerEra'.
data ErrInvalidTxOutInEra
= ErrInlineDatumNotSupportedInAlonzo
| ErrInlineScriptNotSupportedInAlonzo
unwrapTxOutInRecentEra
:: RecentEra era
-> TxOutInRecentEra
-> Either ErrInvalidTxOutInEra (TxOut (ShelleyLedgerEra era))
unwrapTxOutInRecentEra era recentEraTxOut = case era of
RecentEraBabbage -> pure $ castTxOut recentEraTxOut
RecentEraAlonzo -> downcastTxOut recentEraTxOut
castTxOut
:: TxOutInRecentEra
-> TxOut (ShelleyLedgerEra BabbageEra)
castTxOut (TxOutInRecentEra addr val datum mscript) =
(Babbage.TxOut addr val datum (toStrict mscript))
where
toStrict (Just a) = SJust a
toStrict Nothing = SNothing
downcastTxOut
:: TxOutInRecentEra
-> Either
ErrInvalidTxOutInEra
(Core.TxOut (ShelleyLedgerEra AlonzoEra))
downcastTxOut (TxOutInRecentEra _addr _val _datum (Just _script))
= Left ErrInlineScriptNotSupportedInAlonzo
downcastTxOut (TxOutInRecentEra _addr _val (Alonzo.Datum _) _script)
= Left ErrInlineDatumNotSupportedInAlonzo
downcastTxOut (TxOutInRecentEra addr val Alonzo.NoDatum Nothing)
= Right $ Alonzo.TxOut addr val SNothing
downcastTxOut (TxOutInRecentEra addr val (Alonzo.DatumHash dh) Nothing)
= Right $ Alonzo.TxOut addr val (SJust dh)
--
-- MinimumUTxO
--
| Compute the minimum ada quantity required for a given ' TxOut ' .
--
-- Unlike @Ledger.evaluateMinLovelaceOutput@, this function may return an
-- overestimation for the sake of satisfying the property:
--
-- @
-- forall out.
-- let
-- c = computeMinimumCoinForUTxO out
-- in
-- forall c' >= c.
not $ isBelowMinimumCoinForTxOut modifyTxOutCoin ( const c ' ) out
-- @
--
This makes it easy for callers to create outputs with near - minimum ada
quantities regardless of the fact that modifying the ada ' Coin ' value may
itself change the size and requirement .
computeMinimumCoinForTxOut
:: forall era. RecentEra era
FIXME [ ADP-2353 ] Replace ' RecentEra ' with ' IsRecentEra '
-> Core.PParams (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
-> Coin
computeMinimumCoinForTxOut era pp out = withCLIConstraint era $
evaluateMinLovelaceOutput pp (withMaxLengthSerializedCoin out)
where
withMaxLengthSerializedCoin
:: TxOut (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
withMaxLengthSerializedCoin =
withStandardCryptoConstraint era $
modifyTxOutCoin era (const $ toLedger txOutMaxCoin)
isBelowMinimumCoinForTxOut
:: forall era. RecentEra era
FIXME [ ADP-2353 ] Replace ' RecentEra ' with ' IsRecentEra '
-> Core.PParams (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
-> Bool
isBelowMinimumCoinForTxOut era pp out =
actualCoin < requiredMin
where
-- IMPORTANT to use the exact minimum from the ledger function, and not our
-- overestimating 'computeMinimumCoinForTxOut'.
requiredMin = withCLIConstraint era $ evaluateMinLovelaceOutput pp out
actualCoin = getCoin era out
getCoin :: RecentEra era -> TxOut (ShelleyLedgerEra era) -> Coin
getCoin RecentEraBabbage (Babbage.TxOut _ val _ _) = coin val
getCoin RecentEraAlonzo (Alonzo.TxOut _ val _) = coin val
--------------------------------------------------------------------------------
-- UTxO
--------------------------------------------------------------------------------
| Construct a ' UTxO era ' using ' 's and ' TxOut 's in said era .
utxoFromTxOuts
:: RecentEra era
-> [(TxIn, Core.TxOut (ShelleyLedgerEra era))]
-> (Shelley.UTxO (ShelleyLedgerEra era))
utxoFromTxOuts era = withStandardCryptoConstraint era $
Shelley.UTxO . Map.fromList
-- | Construct a 'UTxO era' using 'TxOutInRecentEra'. Fails if any output is
-- invalid in the targeted 'era'.
utxoFromTxOutsInRecentEra
:: forall era. RecentEra era
-> [(TxIn, TxOutInRecentEra)]
-> Either ErrInvalidTxOutInEra (Shelley.UTxO (ShelleyLedgerEra era))
utxoFromTxOutsInRecentEra era = withStandardCryptoConstraint era $
fmap (Shelley.UTxO . Map.fromList) . mapM downcast
where
downcast
:: (TxIn, TxOutInRecentEra)
-> Either
ErrInvalidTxOutInEra
(TxIn, TxOut (ShelleyLedgerEra era))
downcast (i, o) = do
o' <- unwrapTxOutInRecentEra era o
pure (i, o')
-- | Useful for testing.
utxoFromTxOutsInLatestEra
:: [(TxIn, TxOutInRecentEra)]
-> Shelley.UTxO LatestLedgerEra
utxoFromTxOutsInLatestEra = withStandardCryptoConstraint RecentEraBabbage $
Shelley.UTxO . Map.fromList . map (second castTxOut)
--------------------------------------------------------------------------------
Tx
--------------------------------------------------------------------------------
modifyTxOutputs
:: RecentEra era
-> (TxOut (ShelleyLedgerEra era) -> TxOut (ShelleyLedgerEra era))
-> Core.TxBody (ShelleyLedgerEra era)
-> Core.TxBody (ShelleyLedgerEra era)
modifyTxOutputs era f body = case era of
RecentEraBabbage -> body
{ Babbage.outputs = mapSized f <$> Babbage.outputs body
}
RecentEraAlonzo -> body
{ Alonzo.outputs = f <$> Alonzo.outputs body
}
where
mapSized f' = mkSized . f' . sizedValue
txBody
:: RecentEra era
-> Core.Tx (ShelleyLedgerEra era)
-> Core.TxBody (ShelleyLedgerEra era)
txBody RecentEraBabbage = Alonzo.body -- same type for babbage
txBody RecentEraAlonzo = Alonzo.body
-- Until we have convenient lenses to use
outputs
:: RecentEra era
-> Core.TxBody (ShelleyLedgerEra era)
-> [TxOut (ShelleyLedgerEra era)]
outputs RecentEraBabbage = map sizedValue . toList . Babbage.outputs
outputs RecentEraAlonzo = toList . Alonzo.outputs
-- NOTE: To reduce the need for the caller to deal with @CardanoApiEra
( ShelleyLedgerEra era ) ~ era@ , we quantify this function over @cardanoEra@
-- instead of @era@.
--
-- TODO [ADP-2353] Move to @cardano-api@ related module
modifyLedgerBody
:: (Core.TxBody (ShelleyLedgerEra cardanoEra)
-> Core.TxBody (ShelleyLedgerEra cardanoEra))
-> Cardano.Tx cardanoEra
-> Cardano.Tx cardanoEra
modifyLedgerBody f (Cardano.Tx body keyWits) = Cardano.Tx body' keyWits
where
body' =
case body of
Cardano.ByronTxBody {} ->
error "Impossible: ByronTxBody in ShelleyLedgerEra"
Cardano.ShelleyTxBody
shelleyEra
ledgerBody
scripts
scriptData
auxData
validity ->
Cardano.ShelleyTxBody
shelleyEra
(f ledgerBody)
scripts
scriptData
auxData
validity
--------------------------------------------------------------------------------
-- Compatibility
--------------------------------------------------------------------------------
fromCardanoTx
:: forall era. IsRecentEra era
=> Cardano.Tx era
-> Core.Tx (Cardano.ShelleyLedgerEra era)
fromCardanoTx = \case
Cardano.ShelleyTx _era tx ->
tx
Cardano.ByronTx {} ->
case (recentEra @era) of
{}
-- | NOTE: The roundtrip
-- @
-- toCardanoUTxO . fromCardanoUTxO
-- @
-- will mark any 'SimpleScriptV1' reference scripts as 'SimpleScriptV2'. Because
' SimpleScriptV1 ' is ' ShelleyEra'-specific , and ' ShelleyEra ' is not a
-- 'RecentEra', this should not be a problem.
toCardanoUTxO
:: forall era. IsRecentEra era
=> Shelley.UTxO (ShelleyLedgerEra era)
-> Cardano.UTxO era
toCardanoUTxO = withConstraints $
Cardano.UTxO
. Map.mapKeys Cardano.fromShelleyTxIn
. Map.map (Cardano.fromShelleyTxOut (shelleyBasedEra @era))
. unUTxO
where
unUTxO (Shelley.UTxO m) = m
withConstraints
:: ((Crypto (Cardano.ShelleyLedgerEra era) ~ StandardCrypto) => a)
-> a
withConstraints a = case recentEra @era of
RecentEraBabbage -> a
RecentEraAlonzo -> a
fromCardanoUTxO
:: forall era. IsRecentEra era
=> Cardano.UTxO era
-> Shelley.UTxO (Cardano.ShelleyLedgerEra era)
fromCardanoUTxO = withStandardCryptoConstraint (recentEra @era) $
Shelley.UTxO
. Map.mapKeys Cardano.toShelleyTxIn
. Map.map (Cardano.toShelleyTxOut (shelleyBasedEra @era))
. unCardanoUTxO
where
unCardanoUTxO (Cardano.UTxO m) = m
toCardanoValue
:: forall era. IsRecentEra era
=> Core.Value (ShelleyLedgerEra era)
-> Cardano.Value
toCardanoValue = case recentEra @era of
RecentEraBabbage -> Cardano.fromMaryValue
RecentEraAlonzo -> Cardano.fromMaryValue
--------------------------------------------------------------------------------
-- Balancing
--------------------------------------------------------------------------------
-- | Evaluate the /balance/ of a transaction using the ledger.
--
-- The balance is defined as:
-- @
-- (value consumed by transaction) - (value produced by transaction)
-- @
--
For a transaction to be valid , it must have a balance of _ _ zero _ _ .
--
-- Note that the fee field of the transaction affects the balance, and
-- is not automatically the minimum fee.
--
evaluateTransactionBalance
:: RecentEra era
-> Core.PParams (Cardano.ShelleyLedgerEra era)
-> Shelley.UTxO (Cardano.ShelleyLedgerEra era)
-> Core.TxBody (Cardano.ShelleyLedgerEra era)
-> Core.Value (Cardano.ShelleyLedgerEra era)
evaluateTransactionBalance era pp utxo txBody' =
withCLIConstraint era $
Shelley.evaluateTransactionBalance pp utxo isNewPool txBody'
where
isNewPool =
-- TODO: ADP-2651
-- Pass this parameter in as a function instead of hard-coding the
-- value here:
const True
--------------------------------------------------------------------------------
-- Module-internal helpers
--------------------------------------------------------------------------------
withStandardCryptoConstraint
:: RecentEra era
-> ((Crypto (Cardano.ShelleyLedgerEra era) ~ StandardCrypto) => a)
-> a
withStandardCryptoConstraint era a = case era of
RecentEraBabbage -> a
RecentEraAlonzo -> a
withCLIConstraint
:: RecentEra era
-> (CLI (ShelleyLedgerEra era) => a)
-> a
withCLIConstraint era a = case era of
RecentEraBabbage -> a
RecentEraAlonzo -> a
| null | https://raw.githubusercontent.com/input-output-hk/cardano-wallet/b058cffeee4979ee3ae30ea6539246ddca73f762/lib/wallet/src/Cardano/Wallet/Write/Tx.hs | haskell | # LANGUAGE GADTs #
# LANGUAGE RankNTypes #
|
License: Apache-2.0
Module containing primitive types and functionality appropriate for
constructing transactions.
'RecentEra'). Intended to be used by things like balanceTx, constructTx and
wallet migration.
* Eras
** RecentEra
** Helpers for cardano-api compatibility
** Existential wrapper
** Misc
* PParams
* Tx
* TxOut
** Address
** Value
*** Binary Data
*** Datum Hash
** Script
* Balancing
------------------------------------------------------------------------------
Eras
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
| 'RecentEra' respresents the eras we care about constructing transactions
for.
To have the same software constructing transactions just before and just
could get away with just supporting one era at other times, but for
NOTE: We /could/ let 'era' refer to eras from the ledger rather than from
cardano-api.
| For convenience working with 'IsRecentEra'. Similar to
Provide class constraint
and explicit value.
| "Downcast" something existentially wrapped in 'Cardano.InAnyCardanoEra'.
Provide class constraint
and explicit value.
and that's it.
------------------------------------------------------------------------------
TxIn
------------------------------------------------------------------------------
| Useful for testing
------------------------------------------------------------------------------
TxOut
------------------------------------------------------------------------------
| NOTE: The roundtrip
@
scriptToCardanoScriptInAnyLang . scriptFromCardanoScriptInAnyLang
@
will convert 'SimpleScriptV1' to 'SimpleScriptV2'. Because 'SimpleScriptV1'
not be a problem.
| NOTE: The roundtrip
@
@
will convert 'SimpleScriptV1' to 'SimpleScriptV2'. Because 'SimpleScriptV1'
not be a problem.
NOTE on binary format: There are a couple of related types in the ledger each
least amount of wrapping tags in the encoding.
- 'Alonzo.Data' - n/a; doesn't have a ToCBOR
datum hashes. We could add helpers for this roundtrip, but they would be
separate from the existing 'datum{From,To}Bytes' pair.
The underlying respresentation is isomorphic to 'TxOut LatestLedgerEra'.
Can be unwrapped using 'unwrapTxOutInRecentEra' or
'utxoFromTxOutsInRecentEra'.
Implementation assumes @TxOut latestEra ⊇ TxOut prevEra@ in the sense that
Same contents as 'TxOut LatestLedgerEra'.
MinimumUTxO
Unlike @Ledger.evaluateMinLovelaceOutput@, this function may return an
overestimation for the sake of satisfying the property:
@
forall out.
let
c = computeMinimumCoinForUTxO out
in
forall c' >= c.
@
IMPORTANT to use the exact minimum from the ledger function, and not our
overestimating 'computeMinimumCoinForTxOut'.
------------------------------------------------------------------------------
UTxO
------------------------------------------------------------------------------
| Construct a 'UTxO era' using 'TxOutInRecentEra'. Fails if any output is
invalid in the targeted 'era'.
| Useful for testing.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
same type for babbage
Until we have convenient lenses to use
NOTE: To reduce the need for the caller to deal with @CardanoApiEra
instead of @era@.
TODO [ADP-2353] Move to @cardano-api@ related module
------------------------------------------------------------------------------
Compatibility
------------------------------------------------------------------------------
| NOTE: The roundtrip
@
toCardanoUTxO . fromCardanoUTxO
@
will mark any 'SimpleScriptV1' reference scripts as 'SimpleScriptV2'. Because
'RecentEra', this should not be a problem.
------------------------------------------------------------------------------
Balancing
------------------------------------------------------------------------------
| Evaluate the /balance/ of a transaction using the ledger.
The balance is defined as:
@
(value consumed by transaction) - (value produced by transaction)
@
Note that the fee field of the transaction affects the balance, and
is not automatically the minimum fee.
TODO: ADP-2651
Pass this parameter in as a function instead of hard-coding the
value here:
------------------------------------------------------------------------------
Module-internal helpers
------------------------------------------------------------------------------ | # LANGUAGE AllowAmbiguousTypes #
# LANGUAGE EmptyCase #
# LANGUAGE FlexibleContexts #
# LANGUAGE FlexibleInstances #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeApplications #
Copyright : © 2022 IOHK
Indented as a replacement to closer
to the ledger types , and only caring about the two latest eras ( Cf .
module Cardano.Wallet.Write.Tx
(
RecentEra (..)
, IsRecentEra (..)
, toRecentEra
, fromRecentEra
, LatestLedgerEra
, LatestEra
, cardanoEra
, shelleyBasedEra
, ShelleyLedgerEra
, cardanoEraFromRecentEra
, shelleyBasedEraFromRecentEra
, AnyRecentEra (..)
, InAnyRecentEra (..)
, asAnyRecentEra
, fromAnyRecentEra
, withInAnyRecentEra
, withRecentEra
, StandardCrypto
, StandardBabbage
, StandardAlonzo
, Core.PParams
, Core.Tx
, Core.TxBody
, txBody
, outputs
, modifyTxOutputs
, modifyLedgerBody
, Core.TxOut
, TxOutInBabbage
, TxOutInRecentEra (..)
, unwrapTxOutInRecentEra
, ErrInvalidTxOutInEra (..)
, modifyTxOutValue
, modifyTxOutCoin
, txOutValue
, computeMinimumCoinForTxOut
, isBelowMinimumCoinForTxOut
, Address
, unsafeAddressFromBytes
, Value
, modifyCoin
, coin
, Coin (..)
* * Datum
, Datum (..)
, datumFromCardanoScriptData
, datumToCardanoScriptData
, BinaryData
, binaryDataFromBytes
, binaryDataToBytes
, DatumHash
, datumHashFromBytes
, datumHashToBytes
, Script (..)
, scriptFromCardanoScriptInAnyLang
, scriptToCardanoScriptInAnyLang
, scriptToCardanoEnvelopeJSON
, scriptFromCardanoEnvelopeJSON
, Alonzo.isPlutusScript
*
, TxIn
, unsafeMkTxIn
*
, Shelley.UTxO (..)
, utxoFromTxOutsInRecentEra
, utxoFromTxOutsInLatestEra
, utxoFromTxOuts
, fromCardanoTx
, toCardanoUTxO
, fromCardanoUTxO
, toCardanoValue
, evaluateTransactionBalance
)
where
import Prelude
import Cardano.Api
( AlonzoEra, BabbageEra )
import Cardano.Api.Shelley
( ShelleyLedgerEra )
import Cardano.Crypto.Hash
( Hash (UnsafeHash) )
import Cardano.Ledger.Alonzo.Data
( BinaryData, Datum (..) )
import Cardano.Ledger.Alonzo.Scripts
( Script (..) )
import Cardano.Ledger.Coin
( Coin (..) )
import Cardano.Ledger.Crypto
( StandardCrypto )
import Cardano.Ledger.Era
( Crypto )
import Cardano.Ledger.Mary
( Value )
import Cardano.Ledger.SafeHash
( SafeHash, extractHash, unsafeMakeSafeHash )
import Cardano.Ledger.Serialization
( Sized (..), mkSized )
import Cardano.Ledger.Shelley.API
( CLI (evaluateMinLovelaceOutput) )
import Cardano.Ledger.Val
( coin, modifyCoin )
import Cardano.Wallet.Primitive.Types.Tx.Constraints
( txOutMaxCoin )
import Cardano.Wallet.Shelley.Compatibility.Ledger
( toLedger )
import Control.Arrow
( second )
import Data.ByteString
( ByteString )
import Data.ByteString.Short
( toShort )
import Data.Foldable
( toList )
import Data.Maybe
( fromMaybe )
import Data.Maybe.Strict
( StrictMaybe (..) )
import Ouroboros.Consensus.Shelley.Eras
( StandardBabbage )
import Test.Cardano.Ledger.Alonzo.Examples.Consensus
( StandardAlonzo )
import qualified Cardano.Api as Cardano
import qualified Cardano.Api.Byron as Cardano
import qualified Cardano.Api.Extra as Cardano
import qualified Cardano.Api.Shelley as Cardano
import qualified Cardano.Binary as CBOR
import qualified Cardano.Crypto.Hash.Class as Crypto
import qualified Cardano.Ledger.Address as Ledger
import qualified Cardano.Ledger.Alonzo.Data as Alonzo
import qualified Cardano.Ledger.Alonzo.Scripts as Alonzo
import qualified Cardano.Ledger.Alonzo.Tx as Alonzo
import qualified Cardano.Ledger.Alonzo.TxBody as Alonzo
import qualified Cardano.Ledger.Babbage as Babbage
import qualified Cardano.Ledger.Babbage.TxBody as Babbage
import qualified Cardano.Ledger.Core as Core
import qualified Cardano.Ledger.Shelley.API.Wallet as Shelley
import qualified Cardano.Ledger.Shelley.UTxO as Shelley
import qualified Cardano.Ledger.TxIn as Ledger
import qualified Data.Aeson as Aeson
import qualified Data.Aeson.Types as Aeson
import qualified Data.Map as Map
type LatestEra = BabbageEra
type LatestLedgerEra = StandardBabbage
RecentEra
after a hard - fork , we need to , at that time , support the two latest eras . We
simplicity we stick with always supporting the two latest eras for now .
data RecentEra era where
RecentEraBabbage :: RecentEra BabbageEra
RecentEraAlonzo :: RecentEra AlonzoEra
deriving instance Eq (RecentEra era)
deriving instance Show (RecentEra era)
class Cardano.IsShelleyBasedEra era => IsRecentEra era where
recentEra :: RecentEra era
| Return a proof that the wallet can create txs in this era , or @Nothing@.
toRecentEra :: Cardano.CardanoEra era -> Maybe (RecentEra era)
toRecentEra = \case
Cardano.BabbageEra -> Just RecentEraBabbage
Cardano.AlonzoEra -> Just RecentEraAlonzo
Cardano.MaryEra -> Nothing
Cardano.AllegraEra -> Nothing
Cardano.ShelleyEra -> Nothing
Cardano.ByronEra -> Nothing
fromRecentEra :: RecentEra era -> Cardano.CardanoEra era
fromRecentEra = \case
RecentEraBabbage -> Cardano.BabbageEra
RecentEraAlonzo -> Cardano.AlonzoEra
instance IsRecentEra BabbageEra where
recentEra = RecentEraBabbage
instance IsRecentEra AlonzoEra where
recentEra = RecentEraAlonzo
cardanoEraFromRecentEra :: RecentEra era -> Cardano.CardanoEra era
cardanoEraFromRecentEra =
Cardano.shelleyBasedToCardanoEra
. shelleyBasedEraFromRecentEra
shelleyBasedEraFromRecentEra :: RecentEra era -> Cardano.ShelleyBasedEra era
shelleyBasedEraFromRecentEra = \case
RecentEraBabbage -> Cardano.ShelleyBasedEraBabbage
RecentEraAlonzo -> Cardano.ShelleyBasedEraAlonzo
| For convenience working with ' IsRecentEra ' . Similar to ' Cardano.cardanoEra ,
but with a ' IsRecentEra era ' constraint instead of ' Cardano . IsCardanoEra .
cardanoEra :: forall era. IsRecentEra era => Cardano.CardanoEra era
cardanoEra = cardanoEraFromRecentEra $ recentEra @era
' Cardano.shelleyBasedEra , but with a ' IsRecentEra era ' constraint instead of
' Cardano . IsShelleyBasedEra ' .
shelleyBasedEra :: forall era. IsRecentEra era => Cardano.ShelleyBasedEra era
shelleyBasedEra = shelleyBasedEraFromRecentEra $ recentEra @era
data InAnyRecentEra thing where
InAnyRecentEra
-> thing era
-> InAnyRecentEra thing
withInAnyRecentEra
:: InAnyRecentEra thing
-> (forall era. IsRecentEra era => thing era -> a)
-> a
withInAnyRecentEra (InAnyRecentEra _era tx) f = f tx
asAnyRecentEra
:: Cardano.InAnyCardanoEra a
-> Maybe (InAnyRecentEra a)
asAnyRecentEra = \case
Cardano.InAnyCardanoEra Cardano.BabbageEra a ->
Just $ InAnyRecentEra RecentEraBabbage a
Cardano.InAnyCardanoEra Cardano.AlonzoEra a ->
Just $ InAnyRecentEra RecentEraAlonzo a
_ -> Nothing
| An existential type like ' ' , but for ' RecentEra ' .
data AnyRecentEra where
instance Show AnyRecentEra where
show (AnyRecentEra era) = "AnyRecentEra " <> show era
fromAnyRecentEra :: AnyRecentEra -> Cardano.AnyCardanoEra
fromAnyRecentEra (AnyRecentEra era) = Cardano.AnyCardanoEra (fromRecentEra era)
withRecentEra ::
AnyRecentEra -> (forall era. IsRecentEra era => RecentEra era -> a) -> a
withRecentEra (AnyRecentEra era) f = f era
type TxIn = Ledger.TxIn StandardCrypto
unsafeMkTxIn :: ByteString -> Word -> TxIn
unsafeMkTxIn hash ix = Ledger.mkTxInPartial
(toTxId hash)
(fromIntegral ix)
where
toTxId :: ByteString -> Ledger.TxId StandardCrypto
toTxId h =
(Ledger.TxId (unsafeMakeSafeHash $ UnsafeHash $ toShort h))
type TxOut era = Core.TxOut era
modifyTxOutValue
:: RecentEra era
-> (Value (ShelleyLedgerEra era) -> Value (ShelleyLedgerEra era))
-> TxOut (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
modifyTxOutValue RecentEraBabbage f (Babbage.TxOut addr val dat script) =
withStandardCryptoConstraint RecentEraBabbage $
Babbage.TxOut addr (f val) dat script
modifyTxOutValue RecentEraAlonzo f (Alonzo.TxOut addr val dat) =
withStandardCryptoConstraint RecentEraAlonzo $
Alonzo.TxOut addr (f val) dat
modifyTxOutCoin
:: RecentEra era
-> (Coin -> Coin)
-> TxOut (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
modifyTxOutCoin era f = withStandardCryptoConstraint era $
modifyTxOutValue era (modifyCoin f)
txOutValue
:: RecentEra era
-> TxOut (ShelleyLedgerEra era)
-> Value (ShelleyLedgerEra era)
txOutValue RecentEraBabbage (Babbage.TxOut _ val _ _) = val
txOutValue RecentEraAlonzo (Alonzo.TxOut _ val _) = val
type TxOutInBabbage = Babbage.TxOut (Babbage.BabbageEra StandardCrypto)
type Address = Ledger.Addr StandardCrypto
unsafeAddressFromBytes :: ByteString -> Address
unsafeAddressFromBytes bytes = case Ledger.deserialiseAddr bytes of
Just addr -> addr
Nothing -> error "unsafeAddressFromBytes: failed to deserialise"
scriptFromCardanoScriptInAnyLang
:: Cardano.ScriptInAnyLang
-> Script LatestLedgerEra
scriptFromCardanoScriptInAnyLang
= Cardano.toShelleyScript
. fromMaybe (error "all valid scripts should be valid in latest era")
. Cardano.toScriptInEra latestEra
where
latestEra = Cardano.BabbageEra
is ' ShelleyEra'-specific , and ' ShelleyEra ' is not a ' RecentEra ' , this should
scriptToCardanoScriptInAnyLang
:: Script LatestLedgerEra
-> Cardano.ScriptInAnyLang
scriptToCardanoScriptInAnyLang =
rewrap
. Cardano.fromShelleyBasedScript latestEra
where
rewrap (Cardano.ScriptInEra _ s) = Cardano.toScriptInAnyLang s
latestEra = Cardano.ShelleyBasedEraBabbage
scriptToCardanoEnvelopeJSON . scriptFromCardanoEnvelopeJSON
is ' ShelleyEra'-specific , and ' ShelleyEra ' is not a ' RecentEra ' , this should
scriptToCardanoEnvelopeJSON :: Script LatestLedgerEra -> Aeson.Value
scriptToCardanoEnvelopeJSON = scriptToJSON . scriptToCardanoScriptInAnyLang
where
scriptToJSON
:: Cardano.ScriptInAnyLang
-> Aeson.Value
scriptToJSON (Cardano.ScriptInAnyLang l s) = Aeson.toJSON
$ obtainScriptLangConstraint l
$ Cardano.serialiseToTextEnvelope Nothing s
where
obtainScriptLangConstraint
:: Cardano.ScriptLanguage lang
-> (Cardano.IsScriptLanguage lang => a)
-> a
obtainScriptLangConstraint lang f = case lang of
Cardano.SimpleScriptLanguage Cardano.SimpleScriptV1 -> f
Cardano.SimpleScriptLanguage Cardano.SimpleScriptV2 -> f
Cardano.PlutusScriptLanguage Cardano.PlutusScriptV1 -> f
Cardano.PlutusScriptLanguage Cardano.PlutusScriptV2 -> f
scriptFromCardanoEnvelopeJSON
:: Aeson.Value
-> Aeson.Parser (Script LatestLedgerEra)
scriptFromCardanoEnvelopeJSON v = fmap scriptFromCardanoScriptInAnyLang $ do
envelope <- Aeson.parseJSON v
case textEnvelopeToScript envelope of
Left textEnvErr
-> fail $ Cardano.displayError textEnvErr
Right (Cardano.ScriptInAnyLang l s)
-> pure $ Cardano.ScriptInAnyLang l s
where
textEnvelopeToScript
:: Cardano.TextEnvelope
-> Either Cardano.TextEnvelopeError Cardano.ScriptInAnyLang
textEnvelopeToScript =
Cardano.deserialiseFromTextEnvelopeAnyOf textEnvTypes
textEnvTypes
:: [Cardano.FromSomeType Cardano.HasTextEnvelope Cardano.ScriptInAnyLang]
textEnvTypes =
[ Cardano.FromSomeType
(Cardano.AsScript Cardano.AsSimpleScriptV1)
(Cardano.ScriptInAnyLang
(Cardano.SimpleScriptLanguage Cardano.SimpleScriptV1))
, Cardano.FromSomeType
(Cardano.AsScript Cardano.AsSimpleScriptV2)
(Cardano.ScriptInAnyLang
(Cardano.SimpleScriptLanguage Cardano.SimpleScriptV2))
, Cardano.FromSomeType
(Cardano.AsScript Cardano.AsPlutusScriptV1)
(Cardano.ScriptInAnyLang
(Cardano.PlutusScriptLanguage Cardano.PlutusScriptV1))
, Cardano.FromSomeType
(Cardano.AsScript Cardano.AsPlutusScriptV2)
(Cardano.ScriptInAnyLang
(Cardano.PlutusScriptLanguage Cardano.PlutusScriptV2))
]
with their own binary encoding . ' . Data ' seems to be the type with the
- ' . Data ' - the simplest encoding of the following options
- ' Alonzo . BinaryData ' - adds a preceding @24@ tag
- ' . Datum ' - adds tags to differentiate between e.g. inline datums and
binaryDataFromBytes
:: ByteString
-> Either String (BinaryData LatestLedgerEra)
binaryDataFromBytes =
Alonzo.makeBinaryData . toShort
binaryDataToBytes :: BinaryData LatestLedgerEra -> ByteString
binaryDataToBytes =
CBOR.serialize'
. Alonzo.getPlutusData
. Alonzo.binaryDataToData
datumFromCardanoScriptData
:: Cardano.ScriptData
-> BinaryData LatestLedgerEra
datumFromCardanoScriptData =
Alonzo.dataToBinaryData
. Cardano.toAlonzoData
datumToCardanoScriptData
:: BinaryData LatestLedgerEra
-> Cardano.ScriptData
datumToCardanoScriptData =
Cardano.fromAlonzoData
. Alonzo.binaryDataToData
type DatumHash = Alonzo.DataHash StandardCrypto
datumHashFromBytes :: ByteString -> Maybe DatumHash
datumHashFromBytes =
fmap unsafeMakeSafeHash <$> Crypto.hashFromBytes
datumHashToBytes :: SafeHash crypto a -> ByteString
datumHashToBytes = Crypto.hashToBytes . extractHash
| Type representing a TxOut in the latest or previous era .
the latest era has not removed information from the @TxOut@. This is allows
e.g. @ToJSON@ / @FromJSON@ instances to be written for two eras using only
one implementation .
data TxOutInRecentEra
= TxOutInRecentEra
Address
(Value LatestLedgerEra)
(Datum LatestLedgerEra)
(Maybe (Script LatestLedgerEra))
data ErrInvalidTxOutInEra
= ErrInlineDatumNotSupportedInAlonzo
| ErrInlineScriptNotSupportedInAlonzo
unwrapTxOutInRecentEra
:: RecentEra era
-> TxOutInRecentEra
-> Either ErrInvalidTxOutInEra (TxOut (ShelleyLedgerEra era))
unwrapTxOutInRecentEra era recentEraTxOut = case era of
RecentEraBabbage -> pure $ castTxOut recentEraTxOut
RecentEraAlonzo -> downcastTxOut recentEraTxOut
castTxOut
:: TxOutInRecentEra
-> TxOut (ShelleyLedgerEra BabbageEra)
castTxOut (TxOutInRecentEra addr val datum mscript) =
(Babbage.TxOut addr val datum (toStrict mscript))
where
toStrict (Just a) = SJust a
toStrict Nothing = SNothing
downcastTxOut
:: TxOutInRecentEra
-> Either
ErrInvalidTxOutInEra
(Core.TxOut (ShelleyLedgerEra AlonzoEra))
downcastTxOut (TxOutInRecentEra _addr _val _datum (Just _script))
= Left ErrInlineScriptNotSupportedInAlonzo
downcastTxOut (TxOutInRecentEra _addr _val (Alonzo.Datum _) _script)
= Left ErrInlineDatumNotSupportedInAlonzo
downcastTxOut (TxOutInRecentEra addr val Alonzo.NoDatum Nothing)
= Right $ Alonzo.TxOut addr val SNothing
downcastTxOut (TxOutInRecentEra addr val (Alonzo.DatumHash dh) Nothing)
= Right $ Alonzo.TxOut addr val (SJust dh)
| Compute the minimum ada quantity required for a given ' TxOut ' .
not $ isBelowMinimumCoinForTxOut modifyTxOutCoin ( const c ' ) out
This makes it easy for callers to create outputs with near - minimum ada
quantities regardless of the fact that modifying the ada ' Coin ' value may
itself change the size and requirement .
computeMinimumCoinForTxOut
:: forall era. RecentEra era
FIXME [ ADP-2353 ] Replace ' RecentEra ' with ' IsRecentEra '
-> Core.PParams (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
-> Coin
computeMinimumCoinForTxOut era pp out = withCLIConstraint era $
evaluateMinLovelaceOutput pp (withMaxLengthSerializedCoin out)
where
withMaxLengthSerializedCoin
:: TxOut (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
withMaxLengthSerializedCoin =
withStandardCryptoConstraint era $
modifyTxOutCoin era (const $ toLedger txOutMaxCoin)
isBelowMinimumCoinForTxOut
:: forall era. RecentEra era
FIXME [ ADP-2353 ] Replace ' RecentEra ' with ' IsRecentEra '
-> Core.PParams (ShelleyLedgerEra era)
-> TxOut (ShelleyLedgerEra era)
-> Bool
isBelowMinimumCoinForTxOut era pp out =
actualCoin < requiredMin
where
requiredMin = withCLIConstraint era $ evaluateMinLovelaceOutput pp out
actualCoin = getCoin era out
getCoin :: RecentEra era -> TxOut (ShelleyLedgerEra era) -> Coin
getCoin RecentEraBabbage (Babbage.TxOut _ val _ _) = coin val
getCoin RecentEraAlonzo (Alonzo.TxOut _ val _) = coin val
| Construct a ' UTxO era ' using ' 's and ' TxOut 's in said era .
utxoFromTxOuts
:: RecentEra era
-> [(TxIn, Core.TxOut (ShelleyLedgerEra era))]
-> (Shelley.UTxO (ShelleyLedgerEra era))
utxoFromTxOuts era = withStandardCryptoConstraint era $
Shelley.UTxO . Map.fromList
utxoFromTxOutsInRecentEra
:: forall era. RecentEra era
-> [(TxIn, TxOutInRecentEra)]
-> Either ErrInvalidTxOutInEra (Shelley.UTxO (ShelleyLedgerEra era))
utxoFromTxOutsInRecentEra era = withStandardCryptoConstraint era $
fmap (Shelley.UTxO . Map.fromList) . mapM downcast
where
downcast
:: (TxIn, TxOutInRecentEra)
-> Either
ErrInvalidTxOutInEra
(TxIn, TxOut (ShelleyLedgerEra era))
downcast (i, o) = do
o' <- unwrapTxOutInRecentEra era o
pure (i, o')
utxoFromTxOutsInLatestEra
:: [(TxIn, TxOutInRecentEra)]
-> Shelley.UTxO LatestLedgerEra
utxoFromTxOutsInLatestEra = withStandardCryptoConstraint RecentEraBabbage $
Shelley.UTxO . Map.fromList . map (second castTxOut)
Tx
modifyTxOutputs
:: RecentEra era
-> (TxOut (ShelleyLedgerEra era) -> TxOut (ShelleyLedgerEra era))
-> Core.TxBody (ShelleyLedgerEra era)
-> Core.TxBody (ShelleyLedgerEra era)
modifyTxOutputs era f body = case era of
RecentEraBabbage -> body
{ Babbage.outputs = mapSized f <$> Babbage.outputs body
}
RecentEraAlonzo -> body
{ Alonzo.outputs = f <$> Alonzo.outputs body
}
where
mapSized f' = mkSized . f' . sizedValue
txBody
:: RecentEra era
-> Core.Tx (ShelleyLedgerEra era)
-> Core.TxBody (ShelleyLedgerEra era)
txBody RecentEraAlonzo = Alonzo.body
outputs
:: RecentEra era
-> Core.TxBody (ShelleyLedgerEra era)
-> [TxOut (ShelleyLedgerEra era)]
outputs RecentEraBabbage = map sizedValue . toList . Babbage.outputs
outputs RecentEraAlonzo = toList . Alonzo.outputs
( ShelleyLedgerEra era ) ~ era@ , we quantify this function over @cardanoEra@
modifyLedgerBody
:: (Core.TxBody (ShelleyLedgerEra cardanoEra)
-> Core.TxBody (ShelleyLedgerEra cardanoEra))
-> Cardano.Tx cardanoEra
-> Cardano.Tx cardanoEra
modifyLedgerBody f (Cardano.Tx body keyWits) = Cardano.Tx body' keyWits
where
body' =
case body of
Cardano.ByronTxBody {} ->
error "Impossible: ByronTxBody in ShelleyLedgerEra"
Cardano.ShelleyTxBody
shelleyEra
ledgerBody
scripts
scriptData
auxData
validity ->
Cardano.ShelleyTxBody
shelleyEra
(f ledgerBody)
scripts
scriptData
auxData
validity
fromCardanoTx
:: forall era. IsRecentEra era
=> Cardano.Tx era
-> Core.Tx (Cardano.ShelleyLedgerEra era)
fromCardanoTx = \case
Cardano.ShelleyTx _era tx ->
tx
Cardano.ByronTx {} ->
case (recentEra @era) of
{}
' SimpleScriptV1 ' is ' ShelleyEra'-specific , and ' ShelleyEra ' is not a
toCardanoUTxO
:: forall era. IsRecentEra era
=> Shelley.UTxO (ShelleyLedgerEra era)
-> Cardano.UTxO era
toCardanoUTxO = withConstraints $
Cardano.UTxO
. Map.mapKeys Cardano.fromShelleyTxIn
. Map.map (Cardano.fromShelleyTxOut (shelleyBasedEra @era))
. unUTxO
where
unUTxO (Shelley.UTxO m) = m
withConstraints
:: ((Crypto (Cardano.ShelleyLedgerEra era) ~ StandardCrypto) => a)
-> a
withConstraints a = case recentEra @era of
RecentEraBabbage -> a
RecentEraAlonzo -> a
fromCardanoUTxO
:: forall era. IsRecentEra era
=> Cardano.UTxO era
-> Shelley.UTxO (Cardano.ShelleyLedgerEra era)
fromCardanoUTxO = withStandardCryptoConstraint (recentEra @era) $
Shelley.UTxO
. Map.mapKeys Cardano.toShelleyTxIn
. Map.map (Cardano.toShelleyTxOut (shelleyBasedEra @era))
. unCardanoUTxO
where
unCardanoUTxO (Cardano.UTxO m) = m
toCardanoValue
:: forall era. IsRecentEra era
=> Core.Value (ShelleyLedgerEra era)
-> Cardano.Value
toCardanoValue = case recentEra @era of
RecentEraBabbage -> Cardano.fromMaryValue
RecentEraAlonzo -> Cardano.fromMaryValue
For a transaction to be valid , it must have a balance of _ _ zero _ _ .
evaluateTransactionBalance
:: RecentEra era
-> Core.PParams (Cardano.ShelleyLedgerEra era)
-> Shelley.UTxO (Cardano.ShelleyLedgerEra era)
-> Core.TxBody (Cardano.ShelleyLedgerEra era)
-> Core.Value (Cardano.ShelleyLedgerEra era)
evaluateTransactionBalance era pp utxo txBody' =
withCLIConstraint era $
Shelley.evaluateTransactionBalance pp utxo isNewPool txBody'
where
isNewPool =
const True
withStandardCryptoConstraint
:: RecentEra era
-> ((Crypto (Cardano.ShelleyLedgerEra era) ~ StandardCrypto) => a)
-> a
withStandardCryptoConstraint era a = case era of
RecentEraBabbage -> a
RecentEraAlonzo -> a
withCLIConstraint
:: RecentEra era
-> (CLI (ShelleyLedgerEra era) => a)
-> a
withCLIConstraint era a = case era of
RecentEraBabbage -> a
RecentEraAlonzo -> a
|
4df08dacba5eb75a0d2adca7412be2927eb1cf3ae1fc15b57a74a5d64ab48732 | soegaard/racket-stories | validation.rkt | #lang racket/base
(provide (all-defined-out))
;;;
;;; Validation
;;;
; This file contains functions that can be used to validate data submitted
; via forms, as well as functions that use the validation results.
; The validators all return `validation` structs:
; (struct validation (value validated? invalid? feedback) #:transparent)
; Here validated? is true, if the struct is the result of a validator,
; invalid? is true, if value wasn't valid,
; feedback is the text shown to the user for an invalid value.
;;; Imports
(require racket/match
"def.rkt" "structs.rkt")
Validators for the input fields in the " Submit new entry page " :
(define (validate-url url)
(define feedback "Enter an url that starts with http:// or https://")
(match (regexp-match #rx"^http[s]?://.+" url) ; too permissive?
[#f (validation url #t #t feedback)]
[_ (validation url #t #f "")]))
(define (validate-title title)
(cond
[(< (string-length title) 4) (validation title #t #t "Enter a longer title")]
[else (validation title #t #f "")]))
;;; Combinator
; The form data as a whole is only valid of all field were valid.
(define (all-valid? . validations)
(for/and ([v validations])
(not (validation-invalid? v))))
;;; Styling
; Bootstrap needs the `input` form to have a class indication
; whether it has been validated and if it has, whether it was valid or invalid.
(define (input-class-validity v) ; validation -> css-class (a string)
(and v (let ()
(defm (validation _ validated? invalid? _) v)
(if validated? (if invalid? "is-invalid" "is-valid") ""))))
| null | https://raw.githubusercontent.com/soegaard/racket-stories/78f66867f213acecd646b0b757819391cee9c261/app-racket-stories/validation.rkt | racket |
Validation
This file contains functions that can be used to validate data submitted
via forms, as well as functions that use the validation results.
The validators all return `validation` structs:
(struct validation (value validated? invalid? feedback) #:transparent)
Here validated? is true, if the struct is the result of a validator,
invalid? is true, if value wasn't valid,
feedback is the text shown to the user for an invalid value.
Imports
too permissive?
Combinator
The form data as a whole is only valid of all field were valid.
Styling
Bootstrap needs the `input` form to have a class indication
whether it has been validated and if it has, whether it was valid or invalid.
validation -> css-class (a string) | #lang racket/base
(provide (all-defined-out))
(require racket/match
"def.rkt" "structs.rkt")
Validators for the input fields in the " Submit new entry page " :
(define (validate-url url)
(define feedback "Enter an url that starts with http:// or https://")
[#f (validation url #t #t feedback)]
[_ (validation url #t #f "")]))
(define (validate-title title)
(cond
[(< (string-length title) 4) (validation title #t #t "Enter a longer title")]
[else (validation title #t #f "")]))
(define (all-valid? . validations)
(for/and ([v validations])
(not (validation-invalid? v))))
(and v (let ()
(defm (validation _ validated? invalid? _) v)
(if validated? (if invalid? "is-invalid" "is-valid") ""))))
|
12abcd2836a3372c70337aa4a05dc87b976195620fbd3a59e752e89a5d8b1257 | vbrankov/hdf5-ocaml | h5tb.mli | open Bigarray
module Field_info : sig
type t = {
field_names : string array;
field_sizes : int array;
field_offsets : int array;
type_size : int;
}
end
(** A pointer to the data. *)
module Data : sig
type t
val of_genarray : _ Genarray.t -> t
val of_array1 : _ Array1.t -> t
val of_array2 : _ Array2.t -> t
val of_array3 : _ Array3.t -> t
end
external make_table : string -> Hid.t -> string -> nrecords:int -> type_size:int
-> field_names:string array -> field_offset:int array -> field_types:Hid.t array
-> chunk_size:int -> ?fill_data:Data.t -> compress:bool -> Data.t -> unit
= "hdf5_h5tb_make_table_bytecode" "hdf5_h5tb_make_table"
external append_records : Hid.t -> string -> nrecords:int -> type_size:int
-> field_offset:int array -> field_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_append_records_bytecode" "hdf5_h5tb_append_records"
external write_records : Hid.t -> string -> start:int -> nrecords:int -> type_size:int
-> field_offset:int array -> field_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_write_records_bytecode" "hdf5_h5tb_write_records"
external read_fields_name : Hid.t -> string -> string -> start:int -> nrecords:int
-> type_size:int -> field_offset:int array -> dst_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_read_fields_name_bytecode" "hdf5_h5tb_read_fields_name"
external read_table : Hid.t -> string -> dst_size:int -> dst_offset:int array
-> dst_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_read_table_bytecode" "hdf5_h5tb_read_table"
external read_records : Hid.t -> string -> start:int -> nrecords:int -> type_size:int
-> field_offset:int array -> dst_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_read_records_bytecode" "hdf5_h5tb_read_records"
external get_table_info : Hid.t -> string -> int = "hdf5_h5tb_get_table_info"
external get_field_info : Hid.t -> string -> Field_info.t = "hdf5_h5tb_get_field_info"
| null | https://raw.githubusercontent.com/vbrankov/hdf5-ocaml/7abc763189767cd6c92620f29ce98f6ee23ba88f/src/raw/h5tb.mli | ocaml | * A pointer to the data. | open Bigarray
module Field_info : sig
type t = {
field_names : string array;
field_sizes : int array;
field_offsets : int array;
type_size : int;
}
end
module Data : sig
type t
val of_genarray : _ Genarray.t -> t
val of_array1 : _ Array1.t -> t
val of_array2 : _ Array2.t -> t
val of_array3 : _ Array3.t -> t
end
external make_table : string -> Hid.t -> string -> nrecords:int -> type_size:int
-> field_names:string array -> field_offset:int array -> field_types:Hid.t array
-> chunk_size:int -> ?fill_data:Data.t -> compress:bool -> Data.t -> unit
= "hdf5_h5tb_make_table_bytecode" "hdf5_h5tb_make_table"
external append_records : Hid.t -> string -> nrecords:int -> type_size:int
-> field_offset:int array -> field_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_append_records_bytecode" "hdf5_h5tb_append_records"
external write_records : Hid.t -> string -> start:int -> nrecords:int -> type_size:int
-> field_offset:int array -> field_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_write_records_bytecode" "hdf5_h5tb_write_records"
external read_fields_name : Hid.t -> string -> string -> start:int -> nrecords:int
-> type_size:int -> field_offset:int array -> dst_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_read_fields_name_bytecode" "hdf5_h5tb_read_fields_name"
external read_table : Hid.t -> string -> dst_size:int -> dst_offset:int array
-> dst_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_read_table_bytecode" "hdf5_h5tb_read_table"
external read_records : Hid.t -> string -> start:int -> nrecords:int -> type_size:int
-> field_offset:int array -> dst_sizes:int array -> Data.t -> unit
= "hdf5_h5tb_read_records_bytecode" "hdf5_h5tb_read_records"
external get_table_info : Hid.t -> string -> int = "hdf5_h5tb_get_table_info"
external get_field_info : Hid.t -> string -> Field_info.t = "hdf5_h5tb_get_field_info"
|
79988d282d7dcae5dd38eafd55563ebe0af282835b996d454986df082a8c26df | webyrd/relational-parsing-with-derivatives | mk-lexer.scm | miniKanren version of ( a subset ) of code for
; a Scheme lexer, based on derivative parsing of regexp.
's original code can be found at
; -lexing-toolkit-based-on-regex-derivatives/
This file requires the miniKanren version of code for derivative
; parsing of regexp.
! shown in maino-3b : matching is n't necessarily greedy
In other words , Kleene star and Kleene plus do n't have ' maximum munch ' semantics :
;;;
Indeed , this is a problem pointed out by when not using committed choice .
;;; What is the right way to solve this problem? I smell constraints for the character
classes -- maybe constraints would help with maximum munch as well . seems skeptical
;;; that constraints will help. This is an interesting problem!
(load "mk-rd.scm")
;;; Regular language convenience operators
; Exactly n repetitions
n must be a numeral : z , ( s z ) , ( s ( s z ) ) , etc .
(define (n-repso n pat out)
(fresh ()
(conde
[(== 'z n) (== regex-BLANK out)]
[(fresh (n-1 res)
(== `(s ,n-1) n)
(n-repso n-1 pat res)
(seqo pat res out))])))
Kleene plus : one or more repetitions
( not to be mistaken with the relational arithmetic ! )
(define (pluso pat out)
(fresh (res)
(repo pat res)
(seqo pat res out)))
Option : zero or one instances
(define (optiono pat out)
(fresh ()
(alto regex-BLANK pat out)))
;;; letters: a-d (to make the branching factor tolerable)
(define alphas '(alt
(alt a b)
(alt c d)))
;;; special characters: _, ?, #, and \ (to make the branching factor tolerable)
(define specials '(alt
(alt _ ?)
(alt hash slash)))
;;; whitespace: ' ' and '\n' (to make the branching factor tolerable)
(define white-space '(alt space newline))
(define parens '(alt left-paren right-paren))
; Match any character
; Here we represent characters as symbols.
;;; WEB: I don't think I can just use a fresh logic variable
to represent AnyChar , for the same reason that _ is tricky in miniKanren .
;;; Basically, the question is how should this program behave:
;;;
;;; (run* (q)
;;; (fresh (x out)
;;; (any-charo x)
;;; (repo x out)
;;; (== `(,x ,out) q)))
;;;
;;; I assume the correct interpretation is [a-zA-Z0-0]*
In other words , this regex should match ' abc ' , not just ' aaa ' .
;;; Yet, the definition of any-charo below would only match 'aaa'.
;;;
;;; This feels like a scoping issue. Could nominal logic resolve this problem?
;;;
( define ( any - charo x ) ( symbolo x ) )
(define any-char `(alt (alt ,alphas ,specials) (alt ,white-space ,parens)))
;;; Scheme lexer
; abbreviations
Scheme literal character : # \\ ~ AnyChar
(define ch `(seq (seq hash slash) (seq slash ,alphas)))
;;; (simplified) Scheme identifier:
;;; (('a' thru 'd') ||
;;; oneOf("_?%"))+
;;;
The resulting regex is quite large . Tempting to use a
;;; higher-order representation using a conde. Not sure if this will
;;; run into the _-style problem described above.
(define id
(let ((pat `(alt ,alphas ,specials)))
`(seq ,pat (rep ,pat))))
;;; ** all of these character classes smell like constraints **
(define (appendo l s out)
(conde
[(== '() l) (== s out)]
[(fresh (a d res)
(== `(,a . ,d) l)
(== `(,a . ,res) out)
(appendo d s res))]))
;;; the main lexer loop
(define (maino chars tokens)
(conde
[(== '() chars) (== '() tokens)]
[(fresh (a d pat prefix suffix tok res)
(== `(,a . ,d) chars)
(emito pat chars prefix suffix tok)
(appendo tok res tokens)
(maino suffix res))]))
* * * fascinating ! This appears , at first glance , to be a counter
;;; example to Will's Law: that simpler goals that have finitely many
answers should come first in a conde . However , 's Law stil
;;; holds, since the paren cases can actually diverge. Still, the
;;; useful ordering seems counter intuitive!
(define (emito pat chars prefix suffix tok)
(fresh ()
(conde
;;; I don't think I need the END pattern.
[(== id pat) (== `((SymbolToken ,prefix)) tok)]
[(== ch pat) (== `((CharToken ,prefix)) tok)]
[(== white-space pat) (== '() tok)]
[(== 'left-paren pat) (== '((PuncToken left-paren)) tok)]
[(== 'right-paren pat) (== '((PuncToken right-paren)) tok)])
(regex-matcho pat prefix #t)
(appendo prefix suffix chars)))
;;; tests
(check-expect "n-repso-1"
(run 10 (q)
(fresh (n pat out)
(n-repso n pat out)
(== `(,n ,pat ,out) q)))
'((z _.0 #t) ; is this true, even if _.0 is #f?
((s z) #f #f)
((s z) #t #t)
(((s z) _.0 _.0) (=/= ((_.0 . #f)) ((_.0 . #t))))
((s (s z)) #f #f)
((s (s z)) #t #t)
(((s (s z)) _.0 (seq _.0 _.0)) (=/= ((_.0 . #f)) ((_.0 . #t))))
((s (s (s z))) #f #f)
((s (s (s z))) #t #t)
(((s (s (s z))) _.0 (seq _.0 (seq _.0 _.0))) (=/= ((_.0 . #f)) ((_.0 . #t))))))
(check-expect "pluso-1"
(run* (q)
(fresh (pat out)
(pluso pat out)
(== `(,pat ,out) q)))
'((#f #f)
((_.0 (seq _.0 (rep _.0))) (sym _.0))
(#t #t)
((rep _.0) (seq (rep _.0) (rep _.0)))
((seq _.0 _.1) (seq (seq _.0 _.1) (rep (seq _.0 _.1))))
((alt _.0 _.1) (seq (alt _.0 _.1) (rep (alt _.0 _.1))))))
(check-expect "optiono-1"
(run* (q)
(fresh (pat out)
(optiono pat out)
(== `(,pat ,out) q)))
'((#t #t)
(#f #t)
((_.0 (alt #t _.0)) (=/= ((_.0 . #f)) ((_.0 . #t))))))
run 5 appears to diverge
(check-expect "alphas-1"
(run 4 (q)
(regex-matcho alphas q regex-BLANK))
'((a) (b) (c) (d)))
(check-expect "specials-1"
(run 4 (q)
(regex-matcho specials q regex-BLANK))
'((_) (?) (hash) (slash)))
(check-expect "white-space-1"
(run 2 (q)
(regex-matcho white-space q regex-BLANK))
'((space) (newline)))
(check-expect "parens-1"
(run 2 (q)
(regex-matcho parens q regex-BLANK))
'((left-paren) (right-paren)))
(check-expect "any-char-1"
(run 5 (q)
(regex-matcho any-char q regex-BLANK))
'((a) (b) (c) (d) (_)))
(check-expect "ch-1"
(run 4 (q)
(regex-matcho ch q regex-BLANK))
'((hash slash slash a)
(hash slash slash b)
(hash slash slash c)
(hash slash slash d)))
(check-expect "id-1"
(run 20 (q)
(regex-matcho id q regex-BLANK))
'((a)
(b)
(a a)
(a b)
(c)
(b a)
(a a a)
(a c)
(b b)
(a a b)
(d)
(a d)
(c a)
(b a a)
(a a a a)
(b c)
(a a c)
(a _)
(a b a)
(c b)))
(check-expect "rep-any-char-1"
(run 10 (q)
(regex-matcho `(rep ,any-char) q regex-BLANK))
'(() (a) (b) (a a) (c) (a b) (b a) (d) (a a a) (a c)))
(check-expect "pluso-any-char-1"
(run 10 (q)
(fresh (pat)
(pluso any-char pat)
(regex-matcho pat q regex-BLANK)))
'((a) (b) (a a) (a b) (c) (b a) (a a a) (a c) (b b) (a a b)))
(check-expect "appemdo-1"
(run* (q)
(appendo '(a b c) '(d e) q))
'((a b c d e)))
(check-expect "emito-1"
(run 10 (q)
(fresh (pat chars prefix suffix tok)
(emito pat chars prefix suffix tok)
(== `(,pat ,chars ,prefix ,suffix ,tok) q)))
'((left-paren
(left-paren . _.0)
(left-paren)
_.0
((PuncToken left-paren)))
(right-paren
(right-paren . _.0)
(right-paren)
_.0
((PuncToken right-paren)))
((alt space newline) (space . _.0) (space) _.0 ())
((alt space newline) (newline . _.0) (newline) _.0 ())
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(a . _.0)
(a)
_.0
((SymbolToken (a))))
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(b . _.0)
(b)
_.0
((SymbolToken (b))))
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(a a . _.0)
(a a)
_.0
((SymbolToken (a a))))
((seq (seq hash slash)
(seq slash (alt (alt a b) (alt c d))))
(hash slash slash a . _.0) ; !!!!!! WTF!? sweet
(hash slash slash a)
_.0
((CharToken (hash slash slash a))))
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(a b . _.0)
(a b)
_.0
((SymbolToken (a b))))
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(c . _.0)
(c)
_.0
((SymbolToken (c))))))
(check-expect "maino-1"
(run 50 (q)
(fresh (chars tokens)
(maino chars tokens)
(== `(,chars ,tokens) q)))
'((() ())
((left-paren) ((PuncToken left-paren)))
((right-paren) ((PuncToken right-paren)))
((space) ())
((left-paren left-paren)
((PuncToken left-paren) (PuncToken left-paren)))
((left-paren right-paren)
((PuncToken left-paren) (PuncToken right-paren)))
((right-paren left-paren)
((PuncToken right-paren) (PuncToken left-paren)))
((right-paren right-paren)
((PuncToken right-paren) (PuncToken right-paren)))
((left-paren space) ((PuncToken left-paren)))
((left-paren left-paren left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((newline) ())
((left-paren left-paren right-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((space left-paren) ((PuncToken left-paren)))
((left-paren right-paren left-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((space right-paren) ((PuncToken right-paren)))
((left-paren right-paren right-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken right-paren)))
((right-paren space) ((PuncToken right-paren)))
((right-paren left-paren left-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((right-paren left-paren right-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((left-paren left-paren space)
((PuncToken left-paren) (PuncToken left-paren)))
((left-paren left-paren left-paren left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((left-paren newline) ((PuncToken left-paren)))
((left-paren left-paren left-paren right-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((right-paren right-paren left-paren)
((PuncToken right-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((left-paren space left-paren)
((PuncToken left-paren) (PuncToken left-paren)))
((newline left-paren) ((PuncToken left-paren)))
((right-paren right-paren right-paren)
((PuncToken right-paren)
(PuncToken right-paren)
(PuncToken right-paren)))
((left-paren left-paren right-paren left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((left-paren space right-paren)
((PuncToken left-paren) (PuncToken right-paren)))
((newline right-paren) ((PuncToken right-paren)))
((left-paren left-paren right-paren right-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)
(PuncToken right-paren)))
((space space) ())
((left-paren right-paren space)
((PuncToken left-paren) (PuncToken right-paren)))
((space left-paren left-paren)
((PuncToken left-paren) (PuncToken left-paren)))
((left-paren right-paren left-paren left-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((right-paren left-paren space)
((PuncToken right-paren) (PuncToken left-paren)))
((space left-paren right-paren)
((PuncToken left-paren) (PuncToken right-paren)))
((left-paren right-paren left-paren right-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((right-paren left-paren left-paren left-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((left-paren left-paren left-paren space)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((right-paren newline) ((PuncToken right-paren)))
((right-paren left-paren left-paren right-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((left-paren left-paren left-paren left-paren left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((left-paren left-paren newline)
((PuncToken left-paren) (PuncToken left-paren)))
((left-paren left-paren left-paren left-paren right-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((space right-paren left-paren)
((PuncToken right-paren) (PuncToken left-paren)))
((left-paren right-paren right-paren left-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((right-paren space left-paren)
((PuncToken right-paren) (PuncToken left-paren)))
((right-paren left-paren right-paren left-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((left-paren left-paren space left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))))
(check-expect "maino-2"
(run 9 (q)
(fresh (chars tokens x y z* rest)
(maino chars tokens)
(== `((SymbolToken (,x ,y . ,z*)) . ,rest) tokens)
(== `(,chars ,tokens) q)))
'(((a a) ((SymbolToken (a a))))
((a a left-paren)
((SymbolToken (a a)) (PuncToken left-paren)))
((a a right-paren)
((SymbolToken (a a)) (PuncToken right-paren)))
((a a space) ((SymbolToken (a a))))
((a a left-paren left-paren)
((SymbolToken (a a))
(PuncToken left-paren)
(PuncToken left-paren)))
((a a left-paren right-paren)
((SymbolToken (a a))
(PuncToken left-paren)
(PuncToken right-paren)))
((a a right-paren left-paren)
((SymbolToken (a a))
(PuncToken right-paren)
(PuncToken left-paren)))
((a a right-paren right-paren)
((SymbolToken (a a))
(PuncToken right-paren)
(PuncToken right-paren)))
((a a left-paren space)
((SymbolToken (a a)) (PuncToken left-paren)))))
(check-expect "maino-3"
(run 1 (q)
(maino '(left-paren a b right-paren) q))
'(((PuncToken left-paren)
(SymbolToken (a))
(SymbolToken (b))
(PuncToken right-paren))))
;;; Bug! The matching isn't always greedy.
(check-expect "maino-3b"
(run 2 (q)
(maino '(a a) q))
'(((SymbolToken (a)) (SymbolToken (a)))
((SymbolToken (a a)))))
;; this takes too long to run
;(check-expect "maino-4"
( run 1 ( q )
; (maino '(left-paren a b c c a space c a space right-paren) q))
; '???)
(check-expect "maino-5"
(run 1 (q)
(maino q '((PuncToken left-paren))))
'((left-paren)))
(check-expect "maino-6"
(run 1 (q)
(maino q '((PuncToken left-paren)
(SymbolToken (a)))))
'((left-paren a)))
;;; too slow to run
;(check-expect "maino-9"
( run 1 ( q )
( maino q ' ( ( PuncToken left - paren )
( SymbolToken ( a ) )
( SymbolToken ( b ) ) ) ) )
; '???)
;;; too slow
( check - expect " maino-10 "
( run 1 ( q )
( maino q ' ( ( PuncToken left - paren )
( SymbolToken ( a ) )
( SymbolToken ( b ) )
( PuncToken right - paren ) ) ) )
; '???)
| null | https://raw.githubusercontent.com/webyrd/relational-parsing-with-derivatives/2b5fea523ed2b35fb1687954449ee75dc67e94dd/miniKanren-version/mk-lexer.scm | scheme | a Scheme lexer, based on derivative parsing of regexp.
-lexing-toolkit-based-on-regex-derivatives/
parsing of regexp.
What is the right way to solve this problem? I smell constraints for the character
that constraints will help. This is an interesting problem!
Regular language convenience operators
Exactly n repetitions
letters: a-d (to make the branching factor tolerable)
special characters: _, ?, #, and \ (to make the branching factor tolerable)
whitespace: ' ' and '\n' (to make the branching factor tolerable)
Match any character
Here we represent characters as symbols.
WEB: I don't think I can just use a fresh logic variable
Basically, the question is how should this program behave:
(run* (q)
(fresh (x out)
(any-charo x)
(repo x out)
(== `(,x ,out) q)))
I assume the correct interpretation is [a-zA-Z0-0]*
Yet, the definition of any-charo below would only match 'aaa'.
This feels like a scoping issue. Could nominal logic resolve this problem?
Scheme lexer
abbreviations
(simplified) Scheme identifier:
(('a' thru 'd') ||
oneOf("_?%"))+
higher-order representation using a conde. Not sure if this will
run into the _-style problem described above.
** all of these character classes smell like constraints **
the main lexer loop
example to Will's Law: that simpler goals that have finitely many
holds, since the paren cases can actually diverge. Still, the
useful ordering seems counter intuitive!
I don't think I need the END pattern.
tests
is this true, even if _.0 is #f?
!!!!!! WTF!? sweet
Bug! The matching isn't always greedy.
this takes too long to run
(check-expect "maino-4"
(maino '(left-paren a b c c a space c a space right-paren) q))
'???)
too slow to run
(check-expect "maino-9"
'???)
too slow
'???) | miniKanren version of ( a subset ) of code for
's original code can be found at
This file requires the miniKanren version of code for derivative
! shown in maino-3b : matching is n't necessarily greedy
In other words , Kleene star and Kleene plus do n't have ' maximum munch ' semantics :
Indeed , this is a problem pointed out by when not using committed choice .
classes -- maybe constraints would help with maximum munch as well . seems skeptical
(load "mk-rd.scm")
n must be a numeral : z , ( s z ) , ( s ( s z ) ) , etc .
(define (n-repso n pat out)
(fresh ()
(conde
[(== 'z n) (== regex-BLANK out)]
[(fresh (n-1 res)
(== `(s ,n-1) n)
(n-repso n-1 pat res)
(seqo pat res out))])))
Kleene plus : one or more repetitions
( not to be mistaken with the relational arithmetic ! )
(define (pluso pat out)
(fresh (res)
(repo pat res)
(seqo pat res out)))
Option : zero or one instances
(define (optiono pat out)
(fresh ()
(alto regex-BLANK pat out)))
(define alphas '(alt
(alt a b)
(alt c d)))
(define specials '(alt
(alt _ ?)
(alt hash slash)))
(define white-space '(alt space newline))
(define parens '(alt left-paren right-paren))
to represent AnyChar , for the same reason that _ is tricky in miniKanren .
In other words , this regex should match ' abc ' , not just ' aaa ' .
( define ( any - charo x ) ( symbolo x ) )
(define any-char `(alt (alt ,alphas ,specials) (alt ,white-space ,parens)))
Scheme literal character : # \\ ~ AnyChar
(define ch `(seq (seq hash slash) (seq slash ,alphas)))
The resulting regex is quite large . Tempting to use a
(define id
(let ((pat `(alt ,alphas ,specials)))
`(seq ,pat (rep ,pat))))
(define (appendo l s out)
(conde
[(== '() l) (== s out)]
[(fresh (a d res)
(== `(,a . ,d) l)
(== `(,a . ,res) out)
(appendo d s res))]))
(define (maino chars tokens)
(conde
[(== '() chars) (== '() tokens)]
[(fresh (a d pat prefix suffix tok res)
(== `(,a . ,d) chars)
(emito pat chars prefix suffix tok)
(appendo tok res tokens)
(maino suffix res))]))
* * * fascinating ! This appears , at first glance , to be a counter
answers should come first in a conde . However , 's Law stil
(define (emito pat chars prefix suffix tok)
(fresh ()
(conde
[(== id pat) (== `((SymbolToken ,prefix)) tok)]
[(== ch pat) (== `((CharToken ,prefix)) tok)]
[(== white-space pat) (== '() tok)]
[(== 'left-paren pat) (== '((PuncToken left-paren)) tok)]
[(== 'right-paren pat) (== '((PuncToken right-paren)) tok)])
(regex-matcho pat prefix #t)
(appendo prefix suffix chars)))
(check-expect "n-repso-1"
(run 10 (q)
(fresh (n pat out)
(n-repso n pat out)
(== `(,n ,pat ,out) q)))
((s z) #f #f)
((s z) #t #t)
(((s z) _.0 _.0) (=/= ((_.0 . #f)) ((_.0 . #t))))
((s (s z)) #f #f)
((s (s z)) #t #t)
(((s (s z)) _.0 (seq _.0 _.0)) (=/= ((_.0 . #f)) ((_.0 . #t))))
((s (s (s z))) #f #f)
((s (s (s z))) #t #t)
(((s (s (s z))) _.0 (seq _.0 (seq _.0 _.0))) (=/= ((_.0 . #f)) ((_.0 . #t))))))
(check-expect "pluso-1"
(run* (q)
(fresh (pat out)
(pluso pat out)
(== `(,pat ,out) q)))
'((#f #f)
((_.0 (seq _.0 (rep _.0))) (sym _.0))
(#t #t)
((rep _.0) (seq (rep _.0) (rep _.0)))
((seq _.0 _.1) (seq (seq _.0 _.1) (rep (seq _.0 _.1))))
((alt _.0 _.1) (seq (alt _.0 _.1) (rep (alt _.0 _.1))))))
(check-expect "optiono-1"
(run* (q)
(fresh (pat out)
(optiono pat out)
(== `(,pat ,out) q)))
'((#t #t)
(#f #t)
((_.0 (alt #t _.0)) (=/= ((_.0 . #f)) ((_.0 . #t))))))
run 5 appears to diverge
(check-expect "alphas-1"
(run 4 (q)
(regex-matcho alphas q regex-BLANK))
'((a) (b) (c) (d)))
(check-expect "specials-1"
(run 4 (q)
(regex-matcho specials q regex-BLANK))
'((_) (?) (hash) (slash)))
(check-expect "white-space-1"
(run 2 (q)
(regex-matcho white-space q regex-BLANK))
'((space) (newline)))
(check-expect "parens-1"
(run 2 (q)
(regex-matcho parens q regex-BLANK))
'((left-paren) (right-paren)))
(check-expect "any-char-1"
(run 5 (q)
(regex-matcho any-char q regex-BLANK))
'((a) (b) (c) (d) (_)))
(check-expect "ch-1"
(run 4 (q)
(regex-matcho ch q regex-BLANK))
'((hash slash slash a)
(hash slash slash b)
(hash slash slash c)
(hash slash slash d)))
(check-expect "id-1"
(run 20 (q)
(regex-matcho id q regex-BLANK))
'((a)
(b)
(a a)
(a b)
(c)
(b a)
(a a a)
(a c)
(b b)
(a a b)
(d)
(a d)
(c a)
(b a a)
(a a a a)
(b c)
(a a c)
(a _)
(a b a)
(c b)))
(check-expect "rep-any-char-1"
(run 10 (q)
(regex-matcho `(rep ,any-char) q regex-BLANK))
'(() (a) (b) (a a) (c) (a b) (b a) (d) (a a a) (a c)))
(check-expect "pluso-any-char-1"
(run 10 (q)
(fresh (pat)
(pluso any-char pat)
(regex-matcho pat q regex-BLANK)))
'((a) (b) (a a) (a b) (c) (b a) (a a a) (a c) (b b) (a a b)))
(check-expect "appemdo-1"
(run* (q)
(appendo '(a b c) '(d e) q))
'((a b c d e)))
(check-expect "emito-1"
(run 10 (q)
(fresh (pat chars prefix suffix tok)
(emito pat chars prefix suffix tok)
(== `(,pat ,chars ,prefix ,suffix ,tok) q)))
'((left-paren
(left-paren . _.0)
(left-paren)
_.0
((PuncToken left-paren)))
(right-paren
(right-paren . _.0)
(right-paren)
_.0
((PuncToken right-paren)))
((alt space newline) (space . _.0) (space) _.0 ())
((alt space newline) (newline . _.0) (newline) _.0 ())
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(a . _.0)
(a)
_.0
((SymbolToken (a))))
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(b . _.0)
(b)
_.0
((SymbolToken (b))))
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(a a . _.0)
(a a)
_.0
((SymbolToken (a a))))
((seq (seq hash slash)
(seq slash (alt (alt a b) (alt c d))))
(hash slash slash a)
_.0
((CharToken (hash slash slash a))))
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(a b . _.0)
(a b)
_.0
((SymbolToken (a b))))
((seq (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))
(rep (alt (alt (alt a b) (alt c d))
(alt (alt _ ?) (alt hash slash)))))
(c . _.0)
(c)
_.0
((SymbolToken (c))))))
(check-expect "maino-1"
(run 50 (q)
(fresh (chars tokens)
(maino chars tokens)
(== `(,chars ,tokens) q)))
'((() ())
((left-paren) ((PuncToken left-paren)))
((right-paren) ((PuncToken right-paren)))
((space) ())
((left-paren left-paren)
((PuncToken left-paren) (PuncToken left-paren)))
((left-paren right-paren)
((PuncToken left-paren) (PuncToken right-paren)))
((right-paren left-paren)
((PuncToken right-paren) (PuncToken left-paren)))
((right-paren right-paren)
((PuncToken right-paren) (PuncToken right-paren)))
((left-paren space) ((PuncToken left-paren)))
((left-paren left-paren left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((newline) ())
((left-paren left-paren right-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((space left-paren) ((PuncToken left-paren)))
((left-paren right-paren left-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((space right-paren) ((PuncToken right-paren)))
((left-paren right-paren right-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken right-paren)))
((right-paren space) ((PuncToken right-paren)))
((right-paren left-paren left-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((right-paren left-paren right-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((left-paren left-paren space)
((PuncToken left-paren) (PuncToken left-paren)))
((left-paren left-paren left-paren left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((left-paren newline) ((PuncToken left-paren)))
((left-paren left-paren left-paren right-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((right-paren right-paren left-paren)
((PuncToken right-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((left-paren space left-paren)
((PuncToken left-paren) (PuncToken left-paren)))
((newline left-paren) ((PuncToken left-paren)))
((right-paren right-paren right-paren)
((PuncToken right-paren)
(PuncToken right-paren)
(PuncToken right-paren)))
((left-paren left-paren right-paren left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((left-paren space right-paren)
((PuncToken left-paren) (PuncToken right-paren)))
((newline right-paren) ((PuncToken right-paren)))
((left-paren left-paren right-paren right-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)
(PuncToken right-paren)))
((space space) ())
((left-paren right-paren space)
((PuncToken left-paren) (PuncToken right-paren)))
((space left-paren left-paren)
((PuncToken left-paren) (PuncToken left-paren)))
((left-paren right-paren left-paren left-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((right-paren left-paren space)
((PuncToken right-paren) (PuncToken left-paren)))
((space left-paren right-paren)
((PuncToken left-paren) (PuncToken right-paren)))
((left-paren right-paren left-paren right-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((right-paren left-paren left-paren left-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((left-paren left-paren left-paren space)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((right-paren newline) ((PuncToken right-paren)))
((right-paren left-paren left-paren right-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((left-paren left-paren left-paren left-paren left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))
((left-paren left-paren newline)
((PuncToken left-paren) (PuncToken left-paren)))
((left-paren left-paren left-paren left-paren right-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)
(PuncToken right-paren)))
((space right-paren left-paren)
((PuncToken right-paren) (PuncToken left-paren)))
((left-paren right-paren right-paren left-paren)
((PuncToken left-paren)
(PuncToken right-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((right-paren space left-paren)
((PuncToken right-paren) (PuncToken left-paren)))
((right-paren left-paren right-paren left-paren)
((PuncToken right-paren)
(PuncToken left-paren)
(PuncToken right-paren)
(PuncToken left-paren)))
((left-paren left-paren space left-paren)
((PuncToken left-paren)
(PuncToken left-paren)
(PuncToken left-paren)))))
(check-expect "maino-2"
(run 9 (q)
(fresh (chars tokens x y z* rest)
(maino chars tokens)
(== `((SymbolToken (,x ,y . ,z*)) . ,rest) tokens)
(== `(,chars ,tokens) q)))
'(((a a) ((SymbolToken (a a))))
((a a left-paren)
((SymbolToken (a a)) (PuncToken left-paren)))
((a a right-paren)
((SymbolToken (a a)) (PuncToken right-paren)))
((a a space) ((SymbolToken (a a))))
((a a left-paren left-paren)
((SymbolToken (a a))
(PuncToken left-paren)
(PuncToken left-paren)))
((a a left-paren right-paren)
((SymbolToken (a a))
(PuncToken left-paren)
(PuncToken right-paren)))
((a a right-paren left-paren)
((SymbolToken (a a))
(PuncToken right-paren)
(PuncToken left-paren)))
((a a right-paren right-paren)
((SymbolToken (a a))
(PuncToken right-paren)
(PuncToken right-paren)))
((a a left-paren space)
((SymbolToken (a a)) (PuncToken left-paren)))))
(check-expect "maino-3"
(run 1 (q)
(maino '(left-paren a b right-paren) q))
'(((PuncToken left-paren)
(SymbolToken (a))
(SymbolToken (b))
(PuncToken right-paren))))
(check-expect "maino-3b"
(run 2 (q)
(maino '(a a) q))
'(((SymbolToken (a)) (SymbolToken (a)))
((SymbolToken (a a)))))
( run 1 ( q )
(check-expect "maino-5"
(run 1 (q)
(maino q '((PuncToken left-paren))))
'((left-paren)))
(check-expect "maino-6"
(run 1 (q)
(maino q '((PuncToken left-paren)
(SymbolToken (a)))))
'((left-paren a)))
( run 1 ( q )
( maino q ' ( ( PuncToken left - paren )
( SymbolToken ( a ) )
( SymbolToken ( b ) ) ) ) )
( check - expect " maino-10 "
( run 1 ( q )
( maino q ' ( ( PuncToken left - paren )
( SymbolToken ( a ) )
( SymbolToken ( b ) )
( PuncToken right - paren ) ) ) )
|
a039ec862178037554fd574c9385ecc5ca72b876b98ebef1377a1fda30eb00d3 | screenshotbot/screenshotbot-oss | remote-file.lisp | (defpackage :build-utils/remote-file
(:use #:cl
#:asdf)
(:local-nicknames (#:a #:alexandria))
(:export
#:remote-file))
(in-package :build-utils/remote-file)
(defclass remote-file (asdf:system)
((url :initarg :url
:reader url)
(version :initarg :version
:reader version)
(remote-file-type :initarg :remote-file-type
:initform nil
:reader remote-file-type)))
(defmethod perform ((o compile-op) (s remote-file))
(unless (version s)
(error "Provide a version for remote-jar-file for caching purposes"))
(let ((output (output-file o s)))
(unless (uiop:file-exists-p output)
(uiop:with-staging-pathname (output)
(format t "Downloading asset: ~a~%" (url s))
(uiop:run-program
(list "curl" "-L" (url s)
"-o"
(namestring output)))))))
(defmethod output-files ((o compile-op) (s remote-file))
(list
(format nil "~a-~a.~a" (component-name s)
(version s)
(remote-file-type s))))
| null | https://raw.githubusercontent.com/screenshotbot/screenshotbot-oss/35f32a86e58221a371b1d38f58a67460a70521b4/src/build-utils/remote-file.lisp | lisp | (defpackage :build-utils/remote-file
(:use #:cl
#:asdf)
(:local-nicknames (#:a #:alexandria))
(:export
#:remote-file))
(in-package :build-utils/remote-file)
(defclass remote-file (asdf:system)
((url :initarg :url
:reader url)
(version :initarg :version
:reader version)
(remote-file-type :initarg :remote-file-type
:initform nil
:reader remote-file-type)))
(defmethod perform ((o compile-op) (s remote-file))
(unless (version s)
(error "Provide a version for remote-jar-file for caching purposes"))
(let ((output (output-file o s)))
(unless (uiop:file-exists-p output)
(uiop:with-staging-pathname (output)
(format t "Downloading asset: ~a~%" (url s))
(uiop:run-program
(list "curl" "-L" (url s)
"-o"
(namestring output)))))))
(defmethod output-files ((o compile-op) (s remote-file))
(list
(format nil "~a-~a.~a" (component-name s)
(version s)
(remote-file-type s))))
| |
a909deb75cb49850630a905b473e31b2cdfbb34f66e05223f944e55223a0e3f6 | amnh/poy5 | mlModel.ml | POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2014 , , , Ward Wheeler ,
and the American Museum of Natural History .
(* *)
(* This program is free software; you can redistribute it and/or modify *)
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
(* (at your option) any later version. *)
(* *)
(* This program is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *)
(* GNU General Public License for more details. *)
(* *)
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston ,
USA
let () = SadmanOutput.register "MlModel" "$Revision: 3672 $"
open Numerical.FPInfix
let (-->) b a = a b
let failwithf format = Printf.ksprintf failwith format
let debug = false
exception LikelihoodModelError of string
let likelihood_not_enabled =
"Likelihood not enabled: download different binary or contact mailing list"
let lfailwith () =
raise (LikelihoodModelError likelihood_not_enabled)
let dyno_likelihood_warning =
"Gap as an additional character is required for the dynamic "^
"likelihood criteria. Please add argument gap:coupled, or gap:character."
let dyno_gamma_warning =
"Gamma classes for dynamic MPL are un-necessary, and are being removed."
let debug_printf msg format =
Printf.ksprintf (fun x -> if debug then print_string x; flush stdout) msg format
let ba_of_array1 x = Bigarray.Array1.of_array Bigarray.float64 Bigarray.c_layout x
and ba_of_array2 x = Bigarray.Array2.of_array Bigarray.float64 Bigarray.c_layout x
let create_ba1 x = Bigarray.Array1.create Bigarray.float64 Bigarray.c_layout x
and create_ba2 x y = Bigarray.Array2.create Bigarray.float64 Bigarray.c_layout x y
let barray_to_array2 bray =
let a = Bigarray.Array2.dim1 bray and b = Bigarray.Array2.dim2 bray in
let r = Array.make_matrix a b 0.0 in
for i = 0 to a-1 do for j = 0 to b-1 do
r.(i).(j) <- bray.{i,j};
done; done; r
let print_barray1 a =
for i = 0 to (Bigarray.Array1.dim a)-1 do
Printf.printf "%2.10f\t" a.{i};
done; Printf.printf "\n%!"; ()
and print_barray2 a =
for i = 0 to (Bigarray.Array2.dim1 a)-1 do
for j = 0 to (Bigarray.Array2.dim2 a)-1 do
Printf.printf "%2.10f\t" a.{i,j};
done; Printf.printf "\n";
done; Printf.printf "\n%!"; ()
(* type to help the parsing of specification data *)
type string_spec = string * (string * string * string * string) * float list
* [ `Given of (string * float) list | `Estimate of float array option
| `Consistent of float array option | `Equal ]
* (string * float option) * string * string option
let empty_str_spec : string_spec = ("",("","","",""),[],`Consistent None,("",None),"",None)
(* the default when commands are left off from the interactive console / scripts *)
let default_command = (`Max, `MAL,`GTR [],None,`Consistent,`Missing)
(** [default_tstv] default ratio for models wth tstv rates; same as phyml *)
let default_tstv = 4.0
* [ default_gtr ] the default parameter rates for GTR ; all 1 's . False for
coupled . otherwise , true
coupled. otherwise, true *)
let default_gtr a =
function | false -> Array.make (((a-2)*(a+1))/2) 1.0
| true -> Array.make (((a)*(a-3))/2) 1.0 (* Coupled *)
(** [default_alpha] default value for alpha parameter; these are the same as
phyml. p is if theta is being used (as in is a percentage) *)
let default_alpha p = if p then 0.2 else 1.0
(** [default_invar] default percent for invariant sites *)
let default_invar = 0.2
(** [default_gap_r] default gap rate, for coupled gap parameters *)
let default_gap_r = 0.15
(** Define how characters can be sent to the classification function *)
type chars = [ `List of int list | `Packed of int ]
(** Define a distribution that branch lengths can be part of *)
type site_var =
| Gamma of int * float
| Theta of int * float * float
(* | Given of (float * float) array *)
| Constant
(** Define the substitution rate model, between characters *)
type subst_model =
| JC69
| F81
| K2P of float
| F84 of float
| HKY85 of float
| TN93 of (float * float)
| GTR of float array
| File of float array array * string
| Custom of (int All_sets.IntegerMap.t * float array * string)
(** Define how base frequencies are calculated and used *)
type priors =
| Estimated of float array
| Given of float array
| Equal
* This is a specification of a model ; and provides a one - to - one mapping to a
full model defined below *
full model defined below **)
type spec = {
substitution : subst_model;
site_variation : site_var;
base_priors : priors;
cost_fn : Methods.ml_costfn;
use_gap : Methods.ml_gap;
alphabet : Alphabet.a * int;
}
(** Define the Model; here we store a diagonalized matrix, priors in C-format
big-array, along with some other minor details *)
type model = {
spec : spec;
pi_0 : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array1.t;
invar : float option;
rate : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array1.t;
prob : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array1.t;
s : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t;
u : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t;
d : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t;
ui : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t option;
}
(** This is a mapping to the codes on the C-side for determining median
calculation functions from the cost-style *)
let get_costfn_code a = match a.spec.cost_fn with
| `MPL -> 1
| `MAL -> 0
(** Return the alphabet for the characters *)
let get_alphabet m = fst m.spec.alphabet
(** Return the size of the alphabet for this model; includes gaps if necessary *)
let get_alphabet_size m = snd m.spec.alphabet
* Compare two models ; not to be used for a total ordering ( ret neg or zero )
let compare a b =
let compare_array x y =
let results = ref true in
for i = 0 to (snd a.spec.alphabet) - 1 do
results := !results && (x.(i) =. y.(i));
done;
!results
in
let compare_priors a b = match a.spec.base_priors ,a.spec.base_priors with
| _ when (snd a.spec.alphabet) != (snd b.spec.alphabet) -> false
| Equal , Equal -> true
| Estimated x, Estimated y
| Given x, Given y -> compare_array x y
| (Equal | Estimated _ | Given _), _ -> false
in
let m_compare = match a.spec.substitution,b.spec.substitution with
| JC69 , JC69 | F81 , F81 -> 0
| K2P x, K2P y | F84 x, F84 y | HKY85 x, HKY85 y when x = y -> 0
| Custom _, Custom _ -> 0
| TN93 (x1,x2), TN93 (y1,y2) when x1 = y1 && x2 = y2 -> 0
| GTR xs, GTR ys when compare_array xs ys -> 0
| File (_,x), File (_,y) when x = y -> 0
| _,_ -> ~-1
and c_compare = if a.spec.cost_fn = b.spec.cost_fn then 0 else ~-1
and v_compare = match a.spec.site_variation,b.spec.site_variation with
| Gamma (ix,ax), Gamma (iy,ay) ->
if ix=iy && ax=ay then 0 else ~-1
| Theta (ix,ax,bx), Theta (iy,ay,by) ->
if ix=iy && ax=ay && bx=by then 0 else ~-1
| Constant, Constant -> 0
| (Gamma _|Theta _|Constant), _ -> ~-1
and g_compare = match a.spec.use_gap,b.spec.use_gap with
| `Missing, `Missing
| `Independent, `Independent -> 0
| `Coupled x, `Coupled y when x=y-> 0
| (`Missing | `Independent | `Coupled _), _ -> ~-1
and p_compare = if compare_priors a b then 0 else ~-1 in
(* just knowing that they are different is enough *)
if debug then begin
Printf.printf "Models : %b\n%!" (m_compare = 0);
Printf.printf "Rate : %b\n%!" (v_compare = 0);
Printf.printf "Use Gap: %b\n%!" (g_compare = 0);
Printf.printf "Priors : %b\n%!" (p_compare = 0);
Printf.printf "Cost : %b\n%!" (c_compare = 0);
end;
m_compare + v_compare + g_compare + p_compare + c_compare
module OrderedML = struct
we could choose model or spec , but spec can use Pervasives.compare
type t = spec
let compare a b = Pervasives.compare a b
end
module MlModelMap = Map.Make (OrderedML)
(** Categorize a list of codes by model *)
let categorize_by_model get_fn codes =
let set_codes,non_lk_codes =
List.fold_left
(fun (acc,oth) code ->
try let spec = get_fn code in
try let old = MlModelMap.find spec acc in
(MlModelMap.add spec (code::old) acc,oth)
with | Not_found ->
(MlModelMap.add spec ([code]) acc,oth)
with | _ -> (acc,code::oth))
(MlModelMap.empty,[])
codes
in
let init = match non_lk_codes with | [] -> [] | xs -> [xs] in
MlModelMap.fold (fun _ e a -> e :: a) set_codes init
(** Count the number of parameters in the model; used for xIC functions **)
let count_parameters model : int =
let num_subst = match model.spec.substitution with
| Custom (_,x,_) -> (Array.length x) - 1
| JC69 | F81 | File _ -> 0
| K2P _ | F84 _ | HKY85 _ -> 1
| TN93 _ -> 2
| GTR _ ->
let a = snd model.spec.alphabet in
((a*(a-1))/2)-1
and num_rates = match model.spec.site_variation with
| Constant -> 0
| Gamma _ -> 1
| Theta (x,_,_) when x = 1 -> 1
| Theta _ -> 2
and num_priors = match model.spec.base_priors with
| Estimated f -> (Array.length f) - 1
| Given _ -> 0
| Equal -> 0
in
num_subst + num_priors + num_rates
* Return a list of all the models with default parameters ; requires alphabet
to determine if tstv models are valid and length of GTR parameters
to determine if tstv models are valid and length of GTR parameters *)
let get_all_models alph gap est_prior =
[ (JC69,Equal);
(F81,est_prior);
(K2P default_tstv,Equal);
(F84 default_tstv,est_prior);
(HKY85 default_tstv,est_prior);
(TN93 (default_tstv,default_tstv),est_prior);
(GTR [||],est_prior)]
IFDEF USE_LIKELIHOOD THEN
(* ------------------------------------------------ *)
EXTERNAL FUNCTIONS -- maintained in likelihood.c
diagonalize a symmetric or gtr matrix , WARNING : modifies passed matrices
U D Ui
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
unit = "likelihood_CAML_diagonalize_gtr"
U D
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
unit = "likelihood_CAML_diagonalize_sym"
compose matrices -- for testing purposes , as this composition is
* usually done on the C side exclusively . If the time is less then zero , the
* instantaneious rate matrix will be returned instead ( which is just UDUi ) .
* usually done on the C side exclusively. If the time is less then zero, the
* instantaneious rate matrix will be returned instead (which is just UDUi). *)
U D Ui t
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t -> float
-> (float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t =
"likelihood_CAML_compose_gtr"
U D
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t -> float
-> (float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t =
"likelihood_CAML_compose_sym"
(* ------------------------------------------------ *)
(* MODEL CALCULATION FUNCTIONS *)
divide a matrix by the mean rate so it will equal 1
let m_meanrate srm pi_ =
let mr = ref 0.0 and a_size = Bigarray.Array2.dim1 srm in
for i = 0 to (a_size-1) do
mr := !mr +. (~-.(srm.{i,i}) *. pi_.{i});
done;
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} /. !mr;
done;
done
(* val jc69 :: ANY ALPHABET size *)
let m_jc69 pi_ mu a_size gap_r =
let srm = create_ba2 a_size a_size in
Bigarray.Array2.fill srm mu;
let () = match gap_r with
| None ->
let diag = -. mu *. float (a_size-1) in
for i = 0 to (a_size-1) do
srm.{i,i} <- diag
done;
| Some (i,r) ->
let diag = -. mu *. (r +. float (a_size-2)) in
for j = 0 to (a_size-1) do
srm.{i,j} <- mu *. r;
srm.{j,i} <- mu *. r;
srm.{j,j} <- diag;
done;
srm.{i,i} <- -. mu *. r *. float (a_size-1)
in
(* normalize by mean-rate *)
let mr = ref 0.0 and wght = 1.0 /. float a_size in
for i = 0 to (a_size-1) do
mr := !mr +. (~-.(srm.{i,i}) *. wght );
done;
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} /. !mr;
done;
done;
srm
val k2p : : only 4 or 5 characters
let m_k2p pi_ alpha beta a_size gap_r =
if not ((a_size = 4) || (a_size = 5)) then begin
raise (LikelihoodModelError "Alphabet does not support this model")
end;
let srm = create_ba2 a_size a_size in
let beta = if beta >. 0.0 then beta else Numerical.minimum in
Bigarray.Array2.fill srm beta;
(* modify transition elements to alpha *)
srm.{1, 3} <- alpha; srm.{3, 1} <- alpha;
srm.{2, 0} <- alpha; srm.{0, 2} <- alpha;
(* set up the diagonal elements *)
let () = match gap_r with
| None ->
let diag =
if a_size = 4 then
-. alpha -. beta -. beta
else begin
assert ( a_size = 5 );
-. alpha -. beta *. 3.0
end
in
for i = 0 to (a_size-1) do
srm.{i,i} <- diag
done;
| Some (i,r) ->
assert( a_size = 5 );
let diag = -. alpha -. beta *. 3.0 -. beta *. r in
for j = 0 to (a_size-1) do
srm.{i,j} <- beta *. r;
srm.{j,i} <- beta *. r;
srm.{j,j} <- diag;
done;
srm.{i,i} <- -. beta *. r *. float (a_size-1)
in
(* normalize by mean-rate *)
let mr = ref 0.0 and wght = 1.0 /. float a_size in
for i = 0 to (a_size-1) do
mr := !mr +. (~-.(srm.{i,i}) *. wght );
done;
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} /. !mr;
done;
done;
srm
val tn93 : : only 4 or 5 characters
let m_tn93 pi_ alpha beta gamma a_size gap_r =
if not ((a_size = 4) || (a_size = 5)) then begin
raise (LikelihoodModelError "Alphabet size does not support this model")
end;
let srm = create_ba2 a_size a_size in
let gamma = if gamma >. 0.0 then gamma else Numerical.minimum in
Bigarray.Array2.fill srm gamma;
ACGT -- R = AG -- Y = CT
srm.{2,0} <- alpha; srm.{3,1} <- beta; (* 0123 -- R=02 -- Y=13 *)
let () = match gap_r with
| None ->
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} *. pi_.{j};
done;
done;
| Some (k,r) ->
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} *. pi_.{j};
done;
srm.{i,k} <- gamma *. r *. pi_.{k};
srm.{k,i} <- gamma *. r *. pi_.{i};
done;
in
normalize diagonal so row sums to 0
for i = 0 to (a_size-1) do
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
done;
m_meanrate srm pi_;
srm
let m_tn93_ratio pi_ kappa1 kappa2 a_size gap_r =
let beta = (pi_.{0} *. pi_.{2} *. kappa1) +. (pi_.{1} *. pi_.{3} *. kappa2) +.
((pi_.{0} +. pi_.{2}) *. (pi_.{1}+.pi_.{3})) in
let beta = 1.0 /. (2.0 *. beta) in
let alpha1 = kappa1 *. beta and alpha2 = kappa2 *. beta in
m_tn93 pi_ alpha1 alpha2 beta a_size gap_r
(* val f81 :: ANY ALPHABET size *)
let m_f81 pi_ lambda a_size gap_r =
let srm = create_ba2 a_size a_size in
let lambda = if lambda >. 0.0 then lambda else Numerical.minimum in
let () = match gap_r with
| None ->
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
if i = j then ()
else srm.{i,j} <- pi_.{j} *. lambda;
done;
done;
| Some (k,r) ->
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
if i = j then ()
else if k = j then srm.{i,j} <- pi_.{j} *. r
else srm.{i,j} <- pi_.{j} *. lambda;
done;
done;
in
for i = 0 to (a_size-1) do
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
done;
m_meanrate srm pi_;
srm
val hky85 : : only 4 or 5 characters
let m_hky85 pi_ kappa a_size gap_r =
let beta = (pi_.{0} *. pi_.{2} *. kappa) +. (pi_.{1} *. pi_.{3} *. kappa) +.
((pi_.{0} +. pi_.{2}) *. (pi_.{1}+.pi_.{3}) ) in
let beta = 1.0 /. (2.0 *. beta) in
let alpha = kappa *. beta in
m_tn93 pi_ alpha alpha beta a_size gap_r
val f84 : : only 4 or 5 characters
let m_f84 pi_ gamma kappa a_size gap_r =
let gamma = if gamma >. 0.0 then gamma else Numerical.minimum in
let y = pi_.{1} +. pi_.{3} in (* Y = C + T *)
let r = pi_.{0} +. pi_.{2} in (* R = A + G *)
let alpha = (1.0+.kappa/.r) *. gamma in
let beta = (1.0+.kappa/.y) *. gamma in
m_tn93 pi_ alpha beta gamma a_size gap_r
normalize against two characters that are not gaps ; unless its the only choice
let normalize ?(m=Numerical.minimum) alph gap_state vec = match gap_state with
| `Independent ->
let normalize_factor = max m vec.((Array.length vec) - 1) in
let vec = Array.map (fun i -> (max m i) /. normalize_factor) vec in
vec, `Independent
| `Coupled n ->
let normalize_factor = max m vec.((Array.length vec) - 1) in
let vec = Array.map (fun i -> (max m i) /. normalize_factor) vec in
vec, `Coupled (n/.normalize_factor)
| `Missing ->
let normalize_factor = max m vec.((Array.length vec) - 1) in
let vec = Array.map (fun i -> (max m i) /. normalize_factor) vec in
vec,`Missing
val gtr : : ANY ALPHABET size
pi _ = = n ; co _ = = ( ( n-1)*n)/2
form of lower packed storage mode , excluding diagonal ,
pi_ == n; co_ == ((n-1)*n)/2
form of lower packed storage mode, excluding diagonal, *)
let m_gtr_independent pi_ co_ a_size =
if (((a_size+1)*(a_size-2))/2) <> Array.length co_ then begin
failwithf ("Length of GTR parameters (I) is incorrect for the alphabet."
^^"They should be %d, but are %d.")
(((a_size+1)*(a_size-2))/2) (Array.length co_);
end;
last element of GTR = 1.0
let co_ =
let size = (((a_size-1)*a_size)/2) in
Array.init (size)
(fun i -> if i = (size-1) then 1.0 else co_.(i))
in
(* create matrix *)
let n = ref 0 in (* array index *)
let srm = create_ba2 a_size a_size in
for i = 0 to (a_size-1) do
for j = (i+1) to (a_size-1) do
srm.{i,j} <- co_.(!n) *. pi_.{j};
srm.{j,i} <- co_.(!n) *. pi_.{i};
incr n;
done;
done;
set diagonal so row sums to 0
for i = 0 to (a_size-1) do begin
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
end; done;
(* divide through by mean-rate *)
m_meanrate srm pi_;
srm
let m_gtr_coupled pi_ co_ a_size i_gap r_gap =
if (((a_size)*(a_size-3))/2) <> Array.length co_ then begin
failwithf ("Length of GTR parameters (%d) is incorrect for alphabet "^^
"(%d). It should be %d.")
(Array.length co_) a_size (((a_size)*(a_size-3))/2)
end;
last element of GTR = 1.0 ; add back
let co_ =
let size = Array.length co_ in
Array.init (size+1)
(fun i -> if i = (size) then 1.0 else co_.(i))
in
(* create matrix *)
let n = ref 0 in (* array index *)
let srm = create_ba2 a_size a_size in
for i = 0 to (a_size-1) do
(* set the gap and gap coefficient col/row *)
if i = i_gap then begin
for j = 0 to (a_size-1) do
srm.{j,i} <- r_gap *. pi_.{i};
srm.{i,j} <- r_gap *. pi_.{j};
done;
end else begin
for j = i+1 to (a_size-1) do
if j = i_gap then ()
else begin
srm.{i,j} <- co_.(!n) *. pi_.{j};
srm.{j,i} <- co_.(!n) *. pi_.{i};
incr n;
end;
done;
end;
done;
set diagonal so row sums to 0
for i = 0 to (a_size-1) do begin
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
end; done;
(* divide through by mean-rate *)
m_meanrate srm pi_;
srm
let m_gtr pi_ co_ a_size gap_r =
let srm = match gap_r with
| Some (i,r) -> m_gtr_coupled pi_ co_ a_size i r
| None -> m_gtr_independent pi_ co_ a_size
in
srm
(* val m_file :: any alphabet size -- recomputes diagonal and divides by meanrate *)
let m_file pi_ f_rr a_size =
assert(a_size = Array.length f_rr);
let srm = create_ba2 a_size a_size in
for r = 0 to (a_size-1) do
assert(a_size = Array.length f_rr.(r));
let diag = ref 0.0 in
for c = 0 to (a_size-1) do
if (c <> r) then begin
diag := !diag +. f_rr.(r).(c);
srm.{r,c} <- f_rr.(r).(c);
end
done;
srm.{r,r} <- ~-. !diag;
done;
m_meanrate srm pi_;
srm
let m_custom pi_ idxs ray a_size =
let idx = ref 0 in
let srm = create_ba2 a_size a_size in
for i = 0 to (a_size-1) do
for j=i+1 to (a_size-1) do
let value = ray.( All_sets.IntegerMap.find !idx idxs ) in
srm.{i,j} <- value *. pi_.{j};
srm.{j,i} <- value *. pi_.{i};
incr idx;
done;
done;
for i = 0 to (a_size-1) do begin
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
end; done;
m_meanrate srm pi_;
srm
create a custom model by two Maps . One that maps an index to it 's linked index
and another that maps that to a value . The default value if the element does
not exist is set to 1.0 . The mean rate is normalized and the priors are
multiplied through . The indexes ( see below ) ensure that we are dealing with a
symmetric matrix for the parameters ,
ex , - a a b The index association would be , 1->1 , 2->1 , 3->2 , 4->2 ,
a - b a 5->1 , 6->1 ( upper triangular ) .
a b - a Diagonal elements are always ignored , a dash is recommended .
b a a - We ensure that the parameters are coupled symmetrically .
and another that maps that to a value. The default value if the element does
not exist is set to 1.0. The mean rate is normalized and the priors are
multiplied through. The indexes (see below) ensure that we are dealing with a
symmetric matrix for the parameters,
ex, - a a b The index association would be, 1->1, 2->1, 3->2, 4->2,
a - b a 5->1, 6->1 (upper triangular).
a b - a Diagonal elements are always ignored, a dash is recommended.
b a a - We ensure that the parameters are coupled symmetrically. *)
let process_custom_model alph_size (f_aa: char array array) =
let found = ref All_sets.Integers.empty in
let assoc = ref All_sets.IntegerMap.empty in
let idx = ref 0 in
let a_size = Array.length f_aa in
if not (a_size = alph_size) then begin
raise (LikelihoodModelError "Alphabet size does not match model")
end;
for i = 0 to a_size -1 do
assert( Array.length f_aa.(i) = a_size );
for j = i+1 to a_size-1 do
let letter = Char.code f_aa.(i).(j) in
if not ( letter = Char.code f_aa.(j).(i) ) then begin
raise (LikelihoodModelError "Custom model should be symmetric")
end;
assoc := All_sets.IntegerMap.add !idx letter !assoc;
found := All_sets.Integers.add letter !found;
incr idx;
done;
done;
let length,map =
All_sets.Integers.fold
(fun v1 (i,map) ->
let map =
All_sets.IntegerMap.map
(fun v2 -> if v1 = v2 then i else v2) map
in
(i+1, map))
(!found)
(0,!assoc)
in
(map, Array.make length 1.0)
(* ------------------------------------------------ *)
(* MATRIX CALCULATION FUNCTIONS *)
A function to check for values in matrix ; catch before a diagonalization ,
since the lapack routines reeturn DGEBAL parameter illegal value instead of a
backtrace
since the lapack routines reeturn DGEBAL parameter illegal value instead of a
backtrace *)
let check_for_nan mat =
try for i = 0 to (Bigarray.Array2.dim1 mat)-1 do
for j = 0 to (Bigarray.Array2.dim1 mat)-1 do
assert( not (Numerical.is_nan mat.{i,j}));
done;
done;
true
with _ ->
false
functions to diagonalize the two types of substitution matrices
let diagonalize (sym : bool) mat =
assert( check_for_nan mat );
let alph = Bigarray.Array2.dim1 mat in
let n_u = create_ba2 alph alph in
let () = Bigarray.Array2.blit mat n_u in
let n_d = create_ba2 alph alph in
let () = Bigarray.Array2.fill n_d 0.0 in
assert( alph = Bigarray.Array2.dim2 mat);
let apply_sym sub_mat =
let () = diagonalize_sym FMatrix.scratch_space n_u n_d in
n_u, n_d, None
and apply_gtr sub_mat =
let n_ui = create_ba2 alph alph in
let () = Bigarray.Array2.fill n_ui 0.0 in
let () = diagonalize_gtr FMatrix.scratch_space n_u n_d n_ui in
n_u, n_d, Some n_ui
in
match sym with
| true -> apply_sym mat
| false -> apply_gtr mat
let compose model t = match model.ui with
| Some ui -> compose_gtr FMatrix.scratch_space model.u model.d ui t
| None -> compose_sym FMatrix.scratch_space model.u model.d t
let subst_matrix model topt =
let _gapr = match model.spec.use_gap with
| `Coupled x -> Some (Alphabet.get_gap (fst model.spec.alphabet), x)
| `Independent -> None
| `Missing -> None
and a_size = snd model.spec.alphabet
and priors = model.pi_0 in
let m = match model.spec.substitution with
| JC69 -> m_jc69 priors 1.0 a_size _gapr
| F81 -> m_f81 priors 1.0 a_size _gapr
| K2P t -> m_k2p priors t 1.0 a_size _gapr
| F84 t -> m_f84 priors t 1.0 a_size _gapr
| HKY85 t -> m_hky85 priors t a_size _gapr
| TN93 (ts,tv) -> m_tn93 priors ts tv 1.0 a_size _gapr
| GTR c -> m_gtr priors c a_size _gapr
| File (m,s) -> m_file priors m a_size
| Custom (assoc,ray,_) -> m_custom priors assoc ray a_size
in
match topt with
| Some t ->
for i = 0 to (Bigarray.Array2.dim1 m)-1 do
for j = 0 to (Bigarray.Array2.dim2 m)-1 do
m.{i,j} <- m.{i,j} *. t;
done;
done;
m
| None ->
m
let get_optimization_method m =
let meth = match m.spec.cost_fn with
| `MAL -> [Numerical.BFGS None]
| `MPL -> [Numerical.Brent_Multi None; Numerical.BFGS None]
in
Numerical.default_numerical_optimization_strategy
meth !Methods.opt_mode (count_parameters m)
print output in our nexus format or output
let output_model output output_table nexus model set =
let printf format = Printf.ksprintf output format in
let gtr_mod = ref false in
if nexus = `Nexus then begin
printf "@[Likelihood@.";
let () = match model.spec.substitution with
| JC69 -> printf "@[Model = JC69;@]@\n";
| F81 -> printf "@[Model = F81;@]";
| K2P x -> printf "@[Model = K2P;@]";
printf "@[Parameters = %f;@]" x
| F84 x -> printf "@[Model = F84;@]";
printf "@[Parameters = %f;@]" x
| HKY85 x-> printf "@[Model = HKY85;@]";
printf "@[Parameters = %f;@]" x
| TN93 (a,b) -> printf "@[Model = TN93;@]";
printf "@[Parameters = %f %f;@]" a b
| GTR xs -> printf "@[Model = GTR;@]";
printf "@[Parameters = ";
Array.iter (printf "%f ") xs;
printf ";@]";
gtr_mod := true
| File (_,str) ->
printf "@[Model = File:%s;@]" str
| Custom (_,xs,str) ->
printf "@[Model = Custom:%s;@]" str;
printf "@[Parameters = ";
Array.iter (printf "%f ") xs;
printf ";@]";
in
let () = match model.spec.base_priors with
| Equal ->
printf "@[Priors = Equal;@]"
| Estimated x | Given x ->
let first = ref true in
printf "@[Priors =";
List.iter
(fun (s,i) ->
try if !first then begin
printf "@[%s %.5f" s x.(i); first := false
end else
printf ",@]@[%s %.5f" s x.(i)
with _ -> ())
(Alphabet.to_list (fst model.spec.alphabet));
printf ";@]@]"
in
let () = match model.spec.cost_fn with
| `MPL -> printf "@[Cost = mpl;@]";
| `MAL -> printf "@[Cost = mal;@]";
in
let () = match model.spec.site_variation with
| Constant -> ()
| Gamma (c, p) ->
printf "@[Variation = gamma;@]@[alpha = %.5f@]@[sites = %d;@]" p c
| Theta (c, p, i) ->
printf ("@[Variation = theta;@]@[alpha = %.5f@]@[sites = %d;@]"
^^"@[percent = %.5f;@]") p c i
in
let () = match model.spec.use_gap with
the meaning of independent / coupled switch under gtr
| `Independent -> printf "@[gap = independent;@]"
| `Coupled x -> printf "@[gap = coupled:%f;@]" x
| `Missing -> printf "@[gap = missing;@]"
in
let () = match set with
| Some namelist ->
let first = ref true in
printf "@[CharSet = ";
List.iter
(fun s ->
if !first then begin printf "@[%s" s; first := false
end else printf ",@]@[%s" s)
namelist;
printf ";@]@]";
| None -> ()
in
printf ";@]@."
(* ---------------------------- *)
end else (* phylip *) begin
printf "@[<hov 0>Discrete gamma model: ";
let () = match model.spec.site_variation with
| Constant -> printf "No@]\n";
| Gamma (cats,param) ->
printf ("Yes@]@\n@[<hov 1>- Number of categories: %d@]\n"^^
"@[<hov 1>- Gamma Shape Parameter: %.4f@]\n") cats param
| Theta (cats,param,inv) ->
printf ("Yes@]@\n@[<hov 1>- Number of categories: %d@]\n"^^
"@[<hov 1>- Gamma Shape Parameter: %.4f@]\n") cats param;
printf ("@[<hov 1>- Proportion of invariant: %.4f@]\n") inv
in
let () = match model.spec.cost_fn with
| `MPL -> printf "@[<hov 0>Cost mode: mpl;@]@\n";
| `MAL -> printf "@[<hov 0>Cost mode: mal;@]@\n";
in
printf "@[<hov 0>Priors / Base frequencies:@\n";
let () = match model.spec.base_priors with
| Equal -> printf "@[Equal@]@]@\n"
| Estimated x | Given x ->
List.iter
(fun (s,i) ->
(* this expection handling avoids gaps when they are not
* enabled in the alphabet as an additional character *)
try printf "@[<hov 1>- f(%s)= %.5f@]@\n" s x.(i) with _ -> ())
(Alphabet.to_list (fst model.spec.alphabet));
in
printf "@[<hov 0>Model Parameters: ";
let a = (snd model.spec.alphabet) in
let () = match model.spec.substitution with
| JC69 -> printf "JC69@]@\n"
| F81 -> printf "F81@]@\n"
| K2P x ->
printf "K2P@]@\n@[<hov 1>- Transition/transversion ratio: %.5f@]@\n" x
| F84 x ->
printf "F84@]@\n@[<hov 1>- Transition/transversion ratio: %.5f@]@\n" x
| HKY85 x ->
printf "HKY85@]@\n@[<hov 1>- Transition/transversion ratio:%.5f@]@\n" x
| TN93 (a,b) ->
printf "tn93@]@\n@[<hov 1>- transition/transversion ratio:%.5f/%.5f@]@\n" a b
| GTR ray -> gtr_mod := true;
printf "GTR@]@\n@[<hov 1>- Rate Parameters: @]@\n";
let get_str i = Alphabet.match_code i (fst model.spec.alphabet)
and convert s r c = (c + (r*(s-1)) - ((r*(r+1))/2)) - 1 in
begin match model.spec.use_gap with
| `Coupled x ->
let ray =
let size = (((a-3)*a)/2) in
Array.init (size+1)
(fun i -> if i = (size) then 1.0 else ray.(i))
in
for i = 0 to a - 2 do
for j = i+1 to a - 2 do
printf "@[<hov 1>%s <-> %s - %.5f@]@\n"
(get_str i) (get_str j) ray.(convert (a-1) i j)
done;
done;
printf "@[<hov 1>%s <-> N - %.5f@]@\n"
(get_str (Alphabet.get_gap (fst model.spec.alphabet))) x
| `Missing | `Independent ->
let ray =
let size = (((a-1)*a)/2) in
Array.init (size)
(fun i -> if i = (size-1) then 1.0 else ray.(i))
in
for i = 0 to a - 1 do
for j = i+1 to a - 1 do
printf "@[<hov 1>%s <-> %s - %.5f@]@\n" (get_str i)
(get_str j) ray.(convert a i j)
done;
done
end
| File (ray,name) ->
printf "File:%s@]@\n" name;
let mat = compose model 0.0 in
printf "@[<hov 1>[";
for i = 0 to a - 1 do
printf "%s ------- " (Alphabet.match_code i (fst model.spec.alphabet))
done;
printf "]@]@\n";
for i = 0 to a - 1 do
for j = 0 to a - 1 do
printf "%.5f\t" mat.{i,j}
done;
printf "@\n";
done;
| Custom (_,xs,str) ->
printf "@[Custom:%s;@]@\n" str;
printf "@[Parameters : ";
Array.iter (printf "%f ") xs;
printf ";@]";
in
let () = match model.spec.use_gap with
| `Independent -> printf "@[<hov 0>Gap property: independent;@]@\n"
| `Coupled x -> printf "@[<hov 0>Gap property: coupled, Ratio: %f;@]@\n" x
| `Missing -> printf "@[<hov 0>Gap property: missing;@]@\n"
in
printf "@]";
printf "@[@[<hov 0>Instantaneous rate matrix:@]@\n";
match output_table with
| Some output_table ->
let table = Array.make_matrix (a+1) a "" in
let () =
let mat = compose model ~-.1.0 in
for i = 0 to a - 1 do
table.(0).(i) <- Alphabet.match_code i (fst model.spec.alphabet);
done;
for i = 0 to a - 1 do
for j = 0 to a - 1 do
table.(i+1).(j) <- string_of_float mat.{i,j}
done;
done;
in
let () = output_table table in
printf "@\n@]"
| None ->
let () =
let mat = compose model ~-.1.0 in
printf "@[<hov 1>[";
for i = 0 to a - 1 do
printf "%s ------- " (Alphabet.match_code i (fst model.spec.alphabet))
done;
printf "]";
for i = 0 to a - 1 do
printf "@]@\n@[<hov 1>";
for j = 0 to a - 1 do
printf "%8.5f " mat.{i,j}
done;
done;
in
printf "@]@\n@]"
end
(** [compose_model] compose a substitution probability matrix from branch length
and substitution rate matrix. *)
let compose_model sub_mat t =
let a_size = Bigarray.Array2.dim1 sub_mat in
let (u_,d_,ui_) =
let n_d = Bigarray.Array2.create Bigarray.float64 Bigarray.c_layout a_size a_size
and n_ui = Bigarray.Array2.create Bigarray.float64 Bigarray.c_layout a_size a_size in
Bigarray.Array2.fill n_d 0.0;
Bigarray.Array2.fill n_ui 0.0;
diagonalize_gtr FMatrix.scratch_space sub_mat n_d n_ui;
(sub_mat, n_d, n_ui)
in
compose_gtr FMatrix.scratch_space u_ d_ ui_ t
(** [integerized_model] convert a model and branch length to a probability rate
matrix and then scale by a factor of accuracy and convert to integers. *)
let integerized_model ?(sigma=4) model t =
let sigma = 10.0 ** (float_of_int sigma)
and create = match model.spec.substitution with
| JC69 | K2P _ ->
(fun s m i j -> ~-(int_of_float (s *.(log m.(i).(j)))))
| _ ->
(fun s m i j -> ~-(int_of_float (s *.(log (model.pi_0.{i} *. m.(i).(j))))))
and matrix =
barray_to_array2 (match model.ui with
| Some ui -> compose_gtr FMatrix.scratch_space model.u model.d ui t
| None -> compose_sym FMatrix.scratch_space model.u model.d t)
and imatrix =
Array.make_matrix (snd model.spec.alphabet) (snd model.spec.alphabet) 0
in
assert( (snd model.spec.alphabet) = Array.length matrix);
assert( (snd model.spec.alphabet) = Array.length matrix.(0));
for i = 0 to (Array.length matrix) - 1 do
for j = 0 to (Array.length matrix.(0)) - 1 do
imatrix.(i).(j) <- create sigma matrix i j
done;
done;
imatrix
(** create a cost matrix from a model *)
let model_to_cm model t =
let input = let t = max Numerical.minimum t in integerized_model model t in
let llst = Array.to_list (Array.map Array.to_list input) in
let res = Cost_matrix.Two_D.of_list ~suppress:true llst (snd model.spec.alphabet) in
res
ELSE
let output_model _ _ _ _ = lfailwith ()
let compose _ _ = lfailwith ()
let spec_from_classification _ _ _ _ _ _ = lfailwith ()
let compare _ _ = lfailwith ()
let classify_seq_pairs _ _ _ _ _ = lfailwith ()
let subst_matrix _ _ = lfailwith ()
let process_custom_model _ = lfailwith ()
let model_to_cm _ _ = lfailwith ()
let compose_model _ _ = lfailwith ()
let m_gtr _ _ _ _ = lfailwith ()
let m_file _ _ _ = lfailwith ()
let m_jc69 _ _ _ = lfailwith ()
let get_optimization_method _ = lfailwith ()
END
(* ------------------------------------------------ *)
(* CONVERSION/MODEL CREATION FUNCTIONS *)
(* convert a string spec (from nexus, for example) to a specification *)
let convert_string_spec alph ((name,(var,site,alpha,invar),param,priors,gap,cost,file):string_spec) =
IFDEF USE_LIKELIHOOD THEN
let gap_info = match String.uppercase (fst gap),snd gap with
| "COUPLED", None -> `Coupled default_gap_r
| "COUPLED", Some x -> `Coupled x
| "INDEPENDENT",_ -> `Independent
| "MISSING",_ -> `Missing
| "",_ -> `Missing
| x,_ ->
raise (LikelihoodModelError ("Invalid gap property, "^x))
in
let submatrix = match String.uppercase name with
| "JC69" -> begin match param with
| [] -> JC69
| _ -> failwith "Parameters don't match model" end
| "F81" -> begin match param with
| [] -> F81
| _ -> failwith "Parameters don't match model" end
| "K80" | "K2P" -> begin match param with
| ratio::[] -> K2P ratio
| [] -> K2P default_tstv
| _ -> failwith "Parameters don't match model" end
| "F84" -> begin match param with
| ratio::[] -> F84 ratio
| [] -> F84 default_tstv
| _ -> failwith "Parameters don't match model" end
| "HKY" | "HKY85" -> begin match param with
| ratio::[] -> HKY85 ratio
| [] -> HKY85 default_tstv
| _ -> failwith "Parameters don't match model" end
| "TN93" -> begin match param with
| ts::tv::[] -> TN93 (ts,tv)
| [] -> TN93 (default_tstv,default_tstv)
| _ -> failwith "Parameters don't match model" end
| "GTR" -> begin match param with
| [] -> GTR [||]
| ls -> GTR (Array.of_list ls) end
| "GIVEN"->
begin match file with
| Some name ->
name --> FileStream.read_floatmatrix
--> List.map (Array.of_list)
--> Array.of_list
--> (fun x -> File (x,name))
| None ->
raise (LikelihoodModelError "No File specified for model")
end
| "CUSTOM" ->
let alph_size = snd alph in
begin match file with
| Some name ->
let convert str = assert( String.length str = 1 ); String.get str 0 in
let matrix = Cost_matrix.Two_D.matrix_of_file convert (`Local name) in
let matrix = Array.of_list (List.map (Array.of_list) matrix) in
let assoc,ray = process_custom_model alph_size matrix in
Custom (assoc,ray,name)
| None ->
raise (LikelihoodModelError "No File specified for model")
end
(* ERROR *)
| "" -> raise (LikelihoodModelError "No model specified")
| xx -> raise (LikelihoodModelError ("Unknown likelihood model "^xx))
in
let cost_fn : Methods.ml_costfn = match String.uppercase cost with
| "MPL" -> `MPL
| "MAL" -> `MAL
| "" -> `MAL (* unmentioned default *)
| x -> raise (LikelihoodModelError ("Unknown cost mode "^x))
and variation = match String.uppercase var with
| "GAMMA" ->
let alpha =
try float_of_string alpha
with _ -> default_alpha false
in
Gamma (int_of_string site, alpha)
| "THETA" ->
let alpha =
try float_of_string alpha
with _ -> default_alpha true
in
let invar =
try float_of_string invar
with _ -> default_invar
in
Theta (int_of_string site, alpha, invar)
| "NONE" | "CONSTANT" | "" ->
Constant
| x -> raise (LikelihoodModelError ("Unknown rate variation mode "^x))
and priors = match priors with
| `Given priors -> Given (Array.of_list (List.map snd priors))
| `Equal -> Equal
| `Estimate (Some x) -> Estimated x
| `Consistent pre_calc ->
begin match submatrix, pre_calc with
| JC69, _
| K2P _, _ -> Equal
| _, Some pi -> Estimated pi
| _ , None -> assert false
end
| `Estimate None -> assert false
in
{ substitution = submatrix;
site_variation = variation;
base_priors = priors;
use_gap = gap_info;
alphabet = alph;
cost_fn = cost_fn; }
ELSE
lfailwith ()
END
* Convert Methods.ml specification to that of an MlModel spec
let convert_methods_spec (alph,alph_size) (compute_priors)
((_,talph,cst,subst,site_variation,base_priors,use_gap):Methods.ml_spec) =
let u_gap = match use_gap with
| `Independent | `Coupled _ -> true | `Missing -> false in
let alph_size =
let w_gap = if u_gap then alph_size else alph_size - 1 in
match talph with | `Min | `Max -> w_gap | `Int x -> x
in
let base_priors = match base_priors with
| `Estimate -> Estimated (compute_priors ())
| `Equal -> Equal
| `Given arr -> Given (Array.of_list arr)
| `Consistent ->
begin match subst with
| `JC69 | `K2P _ -> Equal
| _ -> Estimated (compute_priors ())
end
and site_variation = match site_variation with
| None -> Constant
| Some (`Gamma (w,y)) ->
let y = match y with
| Some x -> x
| None -> default_alpha false
in
Gamma (w,y)
| Some (`Theta (w,y)) ->
let y,p = match y with
| Some x -> x
| None -> default_alpha true, default_invar
in
Theta (w,y,p)
and substitution = match subst with
| `AIC _ | `BIC _ | `AICC _ | `NCM -> assert false
| `JC69 -> JC69
| `F81 -> F81
| `K2P [x] -> K2P x
| `K2P [] -> K2P default_tstv
| `K2P _ ->
raise (LikelihoodModelError
"Likelihood model K2P requires 1 or 0 parameters")
| `HKY85 [x] -> HKY85 x
| `HKY85 [] -> HKY85 default_tstv
| `HKY85 _ ->
raise (LikelihoodModelError
"Likelihood model HKY85 requires 1 or 0 parameters")
| `F84 [x] -> F84 x
| `F84 [] -> F84 default_tstv
| `F84 _ ->
raise (LikelihoodModelError
"Likelihood model F84 requires 1 or 0 parameters")
| `TN93 [x;y] -> TN93 (x,y)
| `TN93 [] -> TN93 (default_tstv,default_tstv)
| `TN93 _ ->
raise (LikelihoodModelError
"Likelihood model TN93 requires 2 or 0 parameters")
| `GTR xs -> GTR (Array.of_list xs)
| `File str ->
(* this needs to be changed to allow remote files as well *)
let matrix = Cost_matrix.Two_D.matrix_of_file float_of_string (`Local str) in
let matrix = Array.of_list (List.map (Array.of_list) matrix) in
Array.iter
(fun x ->
if Array.length x = alph_size then ()
else begin
raise (LikelihoodModelError "Likelihood model TN93 requires 2 or 0 parameters")
end)
(matrix);
if Array.length matrix = alph_size then
File (matrix,str)
else begin
raise (LikelihoodModelError "Likelihood model TN93 requires 2 or 0 parameters")
end;
| `Custom str ->
let convert str = assert( String.length str = 1 ); String.get str 0 in
let matrix = Cost_matrix.Two_D.matrix_of_file convert (`Local str) in
let matrix = Array.of_list (List.map (Array.of_list) matrix) in
let assoc,ray = process_custom_model alph_size matrix in
Custom (assoc,ray,str)
in
{ substitution = substitution;
site_variation = site_variation;
base_priors = base_priors;
alphabet = (alph,alph_size);
cost_fn = cst;
use_gap = use_gap; }
* check the rates so SUM(r_k*p_k ) = = 1 and SUM(p_k ) = = 1 = = |r|
let verify_rates probs rates =
let p1 = (Bigarray.Array1.dim probs) = (Bigarray.Array1.dim rates)
and p2 =
let rsps = ref 0.0 and ps = ref 0.0 in
for i = 0 to (Bigarray.Array1.dim probs) - 1 do
rsps := !rsps +. (probs.{i} *. rates.{i});
ps := !ps +. probs.{i};
done;
!rsps =. 1.0 && !ps =. 1.0
in
p1 && p2
(** create a model based on a specification and an alphabet *)
let create ?(min_prior=Numerical.minimum) lk_spec =
IFDEF USE_LIKELIHOOD THEN
let (alph,a_size) = lk_spec.alphabet in
assert( a_size > 1 );
(* set up all the probability and rates *)
let variation,probabilities,invar =
match lk_spec.site_variation with
| Constant ->
ba_of_array1 [| 1.0 |], ba_of_array1 [| 1.0 |], None
| Gamma (x,y) -> (* SITES,ALPHA *)
let p = create_ba1 x in
Bigarray.Array1.fill p (1.0 /. (float_of_int x));
Numerical.gamma_rates y y x,p,None
GAMMA_SITES , ALPHA ,
if w < 1 then
failwith "Number of rate categories must be >= 1 (if invar w/out gamma)"
else if w = 1 then begin
ba_of_array1 [| 1.0 |], ba_of_array1 [| 1.0 |], Some z
end else begin
let p = create_ba1 w in
Bigarray.Array1.fill p (1.0 /. (float_of_int w));
let r = Numerical.gamma_rates x x w in
r,p,Some z
end
in
assert( verify_rates probabilities variation );
(* extract the prior probability *)
let priors =
let p = match lk_spec.base_priors with
| Equal ->
Array.make a_size (1.0 /. (float_of_int a_size))
| Estimated p | Given p ->
let p = Array.map (fun i -> max min_prior i) p in
let sum = Array.fold_left (fun a b -> a +. b) 0.0 p in
if sum =. 1.0
then p
else Array.map (fun i -> i /. sum) p
in
if not (a_size = Array.length p) then begin
debug_printf "Alphabet = %d; Priors = %d\n%!" a_size (Array.length p);
raise (LikelihoodModelError "Priors don't match alphabet");
end;
ba_of_array1 p
in
let _gapr = match lk_spec.use_gap with
| `Coupled x ->
let gap_i =
if Alphabet.zero_indexed alph
then Alphabet.get_gap alph
else (Alphabet.get_gap alph)-1
in
Some (gap_i, x)
| `Independent -> None
| `Missing -> None
in
get the substitution rate matrix and set sym variable and to_formatter vars
let sym, sub_mat, subst_model = match lk_spec.substitution with
| JC69 -> true, m_jc69 priors 1.0 a_size _gapr, JC69
| F81 -> false, m_f81 priors 1.0 a_size _gapr, F81
| K2P t -> true, m_k2p priors t 1.0 a_size _gapr, lk_spec.substitution
| F84 t -> false, m_f84 priors t 1.0 a_size _gapr, lk_spec.substitution
| HKY85 t -> false, m_hky85 priors t a_size _gapr, lk_spec.substitution
| TN93 (ts,tv) ->
false, m_tn93 priors ts tv 1.0 a_size _gapr, lk_spec.substitution
| GTR c ->
let c = match (Array.length c), lk_spec.use_gap with
| 0, `Coupled _ -> default_gtr a_size true
| 0, _ -> default_gtr a_size false
| _, _ -> c
in
false, m_gtr priors c a_size _gapr, (GTR c)
| File (m,s)->
false, m_file priors m a_size, lk_spec.substitution
| Custom (assoc,xs,_) ->
false, m_custom priors assoc xs a_size, lk_spec.substitution
in
(* ensure that when priors are not =, we use a model that asserts that *)
let lk_spec = match lk_spec.base_priors with
| Estimated _ when sym ->
Status.user_message Status.Warning
"I@ am@ using@ equal@ priors@ as@ required@ in@ the@ selected@ likelihood@ model.";
{ lk_spec with base_priors = Equal }
| Given _ when sym ->
Status.user_message Status.Warning
"I@ am@ using@ equal@ priors@ as@ required@ in@ the@ selected@ likelihood@ model.";
{ lk_spec with base_priors = Equal }
| (Estimated _ | Equal | Given _) -> lk_spec
in
let (u_,d_,ui_) = diagonalize sym sub_mat in
{
rate = variation;
prob = probabilities;
spec = {lk_spec with substitution = subst_model; };
invar = invar;
pi_0 = priors;
s = sub_mat;
u = u_;
d = d_;
ui = ui_;
}
ELSE
lfailwith ()
END
(** Print a substitution probability matrix *)
let debug_model model t =
let subst = subst_matrix model t in
print_barray2 subst; print_newline ();
match t with | Some t -> print_barray2 (compose model t) | None -> ()
(** Replace the priors in a model with that of an array *)
let replace_priors model array =
if debug then begin
Printf.printf "Replacing Priors\n\t%!";
Array.iter (fun x -> Printf.printf "%f, " x) array;
print_newline ();
end;
create {model.spec with base_priors = Estimated array}
(** Compute the priors of a dataset by frequency and gap-counts *)
let compute_priors (alph,u_gap) freq_ (count,gcount) lengths : float array =
let size = if u_gap then (Alphabet.size alph) else (Alphabet.size alph)-1 in
let gap_contribution = (float_of_int gcount) /. (float_of_int size) in
let gap_char = Alphabet.get_gap alph in
if debug then begin
Printf.printf "Computed Priors of %d char + %d gaps: " count gcount;
Array.iter (Printf.printf "|%f") freq_;
Printf.printf "|]\n%!";
end;
let final_priors =
if u_gap then begin
let total_added_gaps =
let longest : int = List.fold_left (fun a x-> max a x) 0 lengths in
let add_gap : int = List.fold_left (fun acc x -> (longest - x) + acc) 0 lengths in
float_of_int add_gap
in
Printf.printf "Total added gaps = %f\n%!" total_added_gaps;
freq_.(gap_char) <- freq_.(gap_char) +. total_added_gaps;
let count = (float_of_int (count - gcount)) +. total_added_gaps;
and weight = (float_of_int gcount) /. (float_of_int size) in
Array.map (fun x -> (x -. weight) /. count) freq_
end else begin
Array.map (fun x -> (x -. gap_contribution) /. (float_of_int count)) freq_
end
in
let sum = Array.fold_left (fun a x -> a +. x) 0.0 final_priors in
if debug then begin
Printf.printf "Final Priors (%f): [" sum;
Array.iter (Printf.printf "|%f") final_priors;
Printf.printf "|]\n%!";
end;
final_priors
(** Add Independent Gap to a model *)
let add_gap_to_model compute_priors model =
raise (LikelihoodModelError dyno_likelihood_warning)
let add_gap_to_model compute_priors model =
match model.spec.use_gap with
| `Missing -> add_gap_to_model compute_priors model
| `Independent | `Coupled _ -> model
let remove_gamma_from_spec spec =
match spec.site_variation with
| Constant -> spec
| Gamma _ | Theta _ ->
Status.user_message Status.Warning
(Str.global_replace (Str.regexp " ") "@ " dyno_gamma_warning);
{ spec with site_variation = Constant; }
IFDEF USE_LIKELIHOOD THEN
(* ------------------------------------------------ *)
(* MODEL ESTIMATION FUNCTIONS *)
let chars2str = function
| `Packed s -> string_of_int s
| `List s -> "[ "^(String.concat " | " (List.map string_of_int s))^" ]"
* estimate the model based on two sequences with attached weights
let classify_seq_pairs leaf1 leaf2 seq1 seq2 acc =
let chars_to_list = function
| `Packed s -> BitSet.Int.list_of_packed s
| `List s -> s
and incr_map k v map =
let v = match All_sets.IntegerMap.mem k map with
| true -> v +. (All_sets.IntegerMap.find k map)
| false -> v
in
All_sets.IntegerMap.add k v map
and incr_tuple ((a,b) as k) v map =
let v = match All_sets.FullTupleMap.mem k map with
| true -> v +. (All_sets.FullTupleMap.find k map)
| false -> v
in
All_sets.FullTupleMap.add k v map
in
classify the mutation from a1 to a2 in a map
let mk_transitions (tmap,fmap) (w1,c1,s1) (w2,c2,s2) =
assert( w1 = w2 );
let s1 = chars_to_list s1 and s2 = chars_to_list s2 in
let n1 = List.length s1 and n2 = List.length s2 in
(* Count all the transitions A->B. Polymorphisms are counted as
* 1/(na*nb) each, where na and nb are the number of polymorphisms
* in and b respectively. *)
let v = w1 /. (float_of_int (n1 * n2) ) in
let tmap = (* cross product of states a and b *)
List.fold_left
(fun map1 a ->
List.fold_left
(fun map2 b -> incr_tuple (a,b) v map2)
map1 s2)
tmap s1
in
Counts the base frequencies . Polymorphisms are counted as 1 / n in
* each base , where , as above , n is the number of polymorphisms .
* each base, where, as above, n is the number of polymorphisms. *)
let n1 = w1 /. (float_of_int n1) and n2 = w2 /. (float_of_int n2) in
let fmap =
if leaf1 then
List.fold_left (fun map a -> incr_map a n1 map) fmap s1
else fmap in
let fmap =
if leaf2 then
List.fold_left (fun map a -> incr_map a n2 map) fmap s2
else fmap in
tmap,fmap
in
List.fold_left2 mk_transitions acc seq1 seq2
let get_priors f_prior alph code = match f_prior with
| Estimated x -> x.(Alphabet.match_base code alph)
| Given x -> x.(Alphabet.match_base code alph)
| Equal -> 1.0 /. (float_of_int (Alphabet.size alph))
Develop a model from a classification --created above
let spec_from_classification alph gap kind rates (priors:Methods.ml_priors) costfn (comp_map,pis) =
let tuple_sum =
All_sets.FullTupleMap.fold (fun k v a -> a +. v) comp_map 0.0
and ugap = match gap with
| `Missing -> false
| `Independent -> true
| `Coupled _ -> true
in
let f_priors,a_size = match priors,kind with
| `Equal,_ | (`Consistent | `Estimate), (`JC69 | `K2P _) ->
let size =
if ugap then (Alphabet.size alph) else (Alphabet.size alph)-1
in
Equal,size
| `Consistent,_ | `Estimate,_ ->
let sum = All_sets.IntegerMap.fold (fun k v x -> v +. x) pis 0.0
and gap_size =
try All_sets.IntegerMap.find (Alphabet.get_gap alph) pis
with | Not_found -> 0.0
in
let l =
let sum = if ugap then sum else sum -. gap_size in
List.fold_left
(fun acc (r,b) -> match b with
| b when (not ugap) && (b = Alphabet.get_gap alph) -> acc
| b ->
let c =
try (All_sets.IntegerMap.find b pis) /. sum
with Not_found -> 0.0 in
c :: acc)
[]
(Alphabet.to_list alph)
in
let ray = Array.of_list (List.rev l) in
Estimated ray, Array.length ray
| `Given xs, _ ->
let ray = Array.of_list xs in
Given ray, Array.length ray
and is_comp a b =
(* these models assume nucleotides only; T<->C=1, A<->G=2, this is
because this is used in DNA/nucleotide models only (k2p,hky85...) *)
if (Alphabet.match_base "T" alph) = a then
if (Alphabet.match_base "C" alph) = b then 1 else 0
else if (Alphabet.match_base "C" alph) = a then
if (Alphabet.match_base "T" alph) = b then 1 else 0
else if (Alphabet.match_base "A" alph) = a then
if (Alphabet.match_base "G" alph) = b then 2 else 0
else if (Alphabet.match_base "G" alph) = a then
if (Alphabet.match_base "A" alph) = b then 2 else 0
else
0
in
let get_sva comp_map =
let s1,s2,v,a =
All_sets.FullTupleMap.fold
(fun k v (sc1,sc2,vc,all) -> match k with
| k1,k2 when 1 == is_comp k1 k2 -> (sc1+.v,sc2,vc,all+.v)
| k1,k2 when 2 == is_comp k1 k2 -> (sc1,sc2+.v,vc,all+.v)
| k1,k2 when k1 != k2 -> (sc1,sc2,vc+.v,all+.v)
| _ -> (sc1,sc2,vc,all+.v) )
comp_map
(0.0,0.0,0.0,0.0)
in
s1 /. a, s2 /. a, v /. a, a
in
(* build the model *)
let m,gap = try match kind with
| `JC69 -> JC69,gap
| `F81 -> F81,gap
| `K2P _ ->
YANG : 1.12
alpha*t = -0.5 * log(1 - 2S - V ) + 0.25 * log(1 - 2V )
2*beta*t = -0.5 * log(1 - 2V )
(* k = alpha / beta *)
(* k = [log(1-2S-V)-0.5*log(1-2V)] / log(1-2V) *)
let s1,s2,v,a = get_sva comp_map in
let s = s1 +. s2 in
let numer = 2.0 *. (log (1.0-.(2.0*.s)-.v))
and denom = log (1.0-.(2.0*.v)) in
K2P ((numer /. denom)-.1.0),gap
| `GTR _ ->
let tuple_sum a1 a2 map =
let one = try All_sets.FullTupleMap.find (a1,a2) map
with | Not_found -> 0.0
and two = try All_sets.FullTupleMap.find (a2,a1) map
with | Not_found -> 0.0
in
one +. two
in
create list of transitions for GTR model creation
1 - > 2 , 1 - > 3 , 1 - > 4 ... 2 - > 3 ...
begin match gap with
| `Independent | `Missing ->
let cgap = Alphabet.get_gap alph in
let lst =
List.fold_right
(fun (s1,alph1) acc1 ->
if (not ugap) && (cgap = alph1) then
acc1
else
List.fold_right
(fun (s2,alph2) acc2 ->
if alph2 <= alph1 then acc2
else if (not ugap) && (cgap = alph2) then
acc2
else begin
let sum = tuple_sum alph1 alph2 comp_map in
sum :: acc2
end)
(Alphabet.to_list alph) acc1)
(Alphabet.to_list alph) []
in
let sum = List.fold_left (fun a x -> x +. a) 0.0 lst in
let lst = List.map (fun x -> x /. sum) lst in
let arr,gap = normalize alph gap (Array.of_list lst) in
let arr = Array.init ((List.length lst)-1) (fun i -> arr.(i)) in
GTR arr,gap
| `Coupled _ ->
let cgap = Alphabet.get_gap alph in
let lst,gap_trans =
List.fold_right
(fun (s1,alph1) acc1 ->
if cgap = alph1 then acc1
else
List.fold_right
(fun (s2,alph2) ((chrt,gapt) as acc2) ->
if alph2 <= alph1 then acc2
else if cgap = alph2 then
let sum = tuple_sum alph1 alph2 comp_map in
(chrt, sum +. gapt)
else begin
let sum = tuple_sum alph1 alph2 comp_map in
(sum :: chrt,gapt)
end)
(Alphabet.to_list alph) acc1)
(Alphabet.to_list alph)
([],0.0)
in
let sum = List.fold_left (fun a x -> x +. a) gap_trans lst in
let lst = List.map (fun x -> x /. sum) lst in
let gap = `Coupled (gap_trans /. (sum *. (float_of_int a_size))) in
let arr,gap = normalize alph gap (Array.of_list lst) in
let arr = Array.init ((List.length lst)-1) (fun i -> arr.(i)) in
GTR arr,gap
end
| `F84 _ ->
let pi_a = get_priors f_priors alph "A"
and pi_c = get_priors f_priors alph "C"
and pi_g = get_priors f_priors alph "G"
and pi_t = get_priors f_priors alph "T" in
let pi_y = pi_c +. pi_t and pi_r = pi_a +. pi_g in
let s1,s2,v,a = get_sva comp_map in let s = s1 +. s2 in
let a = ~-. (log (1.0 -. (s /. (2.0 *. (pi_t*.pi_c/.pi_y +. pi_a*.pi_g/.pi_r)))
-. (v *.(pi_t*.pi_c *.pi_r/.pi_y +.
(pi_a*.pi_g*.pi_y/.pi_r))) /.
(2.0 *. (pi_t*.pi_c *. pi_r +. pi_a *. pi_g *. pi_y))))
and b = ~-. (log (1.0 -. (v/.(2.0 *. pi_y*.pi_r)))) in
F84 (a/.b -. 1.0),gap
| `HKY85 _ ->
let pi_a = get_priors f_priors alph "A"
and pi_c = get_priors f_priors alph "C"
and pi_g = get_priors f_priors alph "G"
and pi_t = get_priors f_priors alph "T" in
let pi_y = pi_c +. pi_t and pi_r = pi_a +. pi_g in
let s1,s2,v,a = get_sva comp_map in let s = s1 +. s2 in
let a = ~-. (log (1.0 -. (s /. (2.0 *. (pi_t*.pi_c/.pi_y +. pi_a*.pi_g/.pi_r)))
-. (v *.(pi_t*.pi_c *.pi_r/.pi_y +.
(pi_a*.pi_g*.pi_y/.pi_r))) /.
(2.0 *. (pi_t*.pi_c *. pi_r +. pi_a *. pi_g *. pi_y))))
and b = ~-. (log (1.0 -. (v/.(2.0 *. pi_y*.pi_r)))) in
HKY85 (a/.b -. 1.0),gap
| `TN93 _ ->
let pi_a = get_priors f_priors alph "A"
and pi_c = get_priors f_priors alph "C"
and pi_g = get_priors f_priors alph "G"
and pi_t = get_priors f_priors alph "T" in
let pi_y = pi_c +. pi_t and pi_r = pi_a +. pi_g
and s1,s2,v,a = get_sva comp_map in
let a1 = ~-. (log (1.0 -. (pi_y*.s1/.(2.0*.pi_t*.pi_c)) -. (v/.(2.0*.pi_y))))
and a2 = ~-. (log (1.0 -. (pi_r*.s2/.(2.0*.pi_a*.pi_g)) -. (v/.(2.0*.pi_r))))
and b = ~-. (log (1.0 -. (v /. (2.0 *. pi_y *. pi_r)))) in
(* finally compute the ratios *)
let k1 = (a1 -. (pi_r *. b)) /. (pi_y *. b)
and k2 = (a2 -. (pi_y *. b)) /. (pi_r *. b) in
TN93 (k1,k2),gap
| `Custom _
| `File _ -> failwith "I cannot estimate this type of model"
with | Not_found -> failwith "Cannot find something for model"
and calc_invar all comp_map =
let same =
List.fold_left
(fun acc (_,ac) ->
acc +. (try (All_sets.FullTupleMap.find (ac,ac) comp_map)
with | Not_found -> 0.0))
0.0
(Alphabet.to_list alph)
in
same /. all
in
let v = match rates with
| None -> Constant
| Some (`Gamma (i,_)) -> Gamma (i,default_alpha false)
| Some (`Theta (i,_)) -> Theta (i,default_alpha true,calc_invar tuple_sum comp_map)
in
{
substitution = m;
site_variation = v;
base_priors = f_priors;
cost_fn = costfn;
use_gap = gap;
alphabet = (alph, a_size);
}
let convert_gapr m = function
| `Coupled x -> Some (Alphabet.get_gap (fst m.spec.alphabet),x)
| `Independent -> None
| `Missing -> None
let update_jc69 old_model gap_r =
let subst_spec = { old_model.spec with use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_jc69 old_model.pi_0 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize true subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_f81 old_model gap_r =
let subst_spec = { old_model.spec with use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_f81 old_model.pi_0 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_k2p old_model new_value gap_r =
let subst_spec = { old_model.spec with substitution = K2P new_value;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_k2p old_model.pi_0 new_value 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize true subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_hky old_model new_value gap_r =
let subst_spec = { old_model.spec with substitution = HKY85 new_value;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_hky85 old_model.pi_0 new_value (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_tn93 old_model ((x,y) as new_value) gap_r =
let subst_spec = { old_model.spec with substitution = TN93 new_value;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_tn93 old_model.pi_0 x y 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_f84 old_model new_value gap_r =
let subst_spec = { old_model.spec with substitution = F84 new_value;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_f84 old_model.pi_0 new_value 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_gtr old_model new_values gap_r =
let subst_spec = { old_model.spec with substitution = GTR new_values;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_gtr old_model.pi_0 new_values (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_custom old_model new_values =
let subst_spec,assoc = match old_model.spec.substitution with
| Custom (assoc,_,s) ->
{ old_model.spec with substitution = Custom (assoc,new_values,s); },assoc
| _ -> assert false
in
let subst_model =
m_custom old_model.pi_0 assoc new_values (snd old_model.spec.alphabet) in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_alpha old_model new_value =
let new_spec_var,new_array = match old_model.spec.site_variation with
| Gamma (i,_) -> Gamma (i,new_value),
Numerical.gamma_rates new_value new_value i
| Theta (i,_,p) -> Theta (i,new_value,p),
Numerical.gamma_rates new_value new_value i
| Constant -> Constant,old_model.rate
in
{ old_model with rate = new_array;
spec = { old_model.spec with site_variation = new_spec_var;} }
and update_alpha_invar old_model new_alpha new_invar =
let new_spec_var,new_array = match old_model.spec.site_variation with
| Gamma (i,_) -> Gamma (i,new_alpha),
Numerical.gamma_rates new_alpha new_alpha i
| Theta (i,_,_) -> Theta (i,new_alpha,new_invar),
Numerical.gamma_rates new_alpha new_alpha i
| Constant -> Constant, old_model.rate
in
{ old_model with rate = new_array;
spec = { old_model.spec with site_variation = new_spec_var; };
invar = Some new_invar; }
END
(* [to_formatter m]
* builds a formatted output of the model [m] spec. Since the spec can be
* transformed to the model, this is a much more readable form then other model
* data --the decomposed matrix for example. *)
let to_formatter (model: model) : Xml.xml Sexpr.t list =
let alph,alph_s = model.spec.alphabet in
let priors =
let inner =
Array.mapi
(fun i v ->
(PXML -[Xml.Characters.vector]
([Xml.Alphabet.value] = [`Float v])
{ `String (Alphabet.match_code i alph)} --))
(match model.spec.base_priors with
| Equal ->
Array.make alph_s (1.0 /. (float_of_int alph_s))
| Given x | Estimated x -> x)
in
(PXML -[Xml.Characters.priors] { `Set (Array.to_list inner) } --)
and get_model model = match model.spec.substitution with
| JC69 -> "jc69" | F81 -> "f81"
| K2P _ -> "k2p" | F84 _ -> "f84"
| HKY85 _ -> "hky85" | TN93 _ -> "tn93"
| GTR _ -> "gtr" | File _ -> "file"
| Custom _ -> "custom"
and get_alpha m = match m.spec.site_variation with
| Constant -> `Float 0.0
| Gamma (_,x)
| Theta (_,x,_) -> `Float x
and get_invar m = match m.spec.site_variation with
| Gamma _ | Constant -> `Float 0.0
| Theta (_,_,p) -> `Float p
and get_gap m = match m.spec.use_gap with
| `Missing -> `String "missing"
| `Independent -> `String "independent"
| `Coupled x -> `String ("coupled:"^string_of_float x)
and get_cats m = match m.spec.site_variation with
| Constant -> `Int 1
| Gamma (c,_)
| Theta (c,_,_) -> `Int c
and parameters m = match m.spec.substitution with
| JC69 | F81 -> []
| K2P x | F84 x | HKY85 x ->
[(PXML -[Xml.Data.param 1]
([Xml.Alphabet.value] = [`Float x])
{ `String "" } --)]
| TN93 (a,b) ->
(PXML -[Xml.Data.param 1]
([Xml.Alphabet.value] = [`Float a])
{ `String "" } --) ::
[(PXML -[Xml.Data.param 2]
([Xml.Alphabet.value] = [`Float b])
{ `String "" } --)]
| GTR ray ->
let r,_ =
Array.fold_left
(fun (acc,i) x ->
(PXML -[Xml.Data.param i]
([Xml.Alphabet.value] = [`Float x])
{ `String "" } --) :: acc,i+1)
([],1)
ray
in
List.rev r
| Custom (_,_,str) ->
[(PXML -[Xml.Data.param 1]
([Xml.Alphabet.value] = [`String str])
{ `String "" } --)]
| File (_,str) ->
[(PXML -[Xml.Data.param 1]
([Xml.Alphabet.value] = [`String str])
{ `String "" } --)]
in
(PXML
-[Xml.Characters.model]
([Xml.Characters.name] = [`String (get_model model)])
([Xml.Characters.categories] = [get_cats model])
([Xml.Characters.alpha] = [get_alpha model])
([Xml.Characters.invar] = [get_invar model])
([Xml.Characters.gapascharacter] = [get_gap model])
{ `Set (priors :: (parameters model)) }
--) :: []
(* -> Xml.xml Sexpr.t list *)
* produce a short readable name for the model : like JC69+G+I. We ignore data
dependent and optimality paramters ( gap as missing / independent ) and mpl / mal
dependent and optimality paramters (gap as missing/independent) and mpl/mal *)
let short_name model =
let model_name = match model.spec.substitution with
| JC69 -> "JC69" | F81 -> "F81"
| K2P _ -> "K81" | F84 _ -> "F84"
| HKY85 _ -> "HKY" | TN93 _ -> "TN93"
| GTR _ -> "GTR" | File _ -> "FILE"
| Custom _-> "CUSTOM"
and variation_name = match model.spec.site_variation with
| Theta (i,_,_) when i > 1 -> "+G+I"
| Gamma _ -> "+G"
| Theta _ -> "+I"
| Constant -> ""
in
model_name ^ variation_name
(* this assumes that the spec is consistent with the model itself, the returned
* update function ensures this consistency *)
and get_update_function_for_model model =
IFDEF USE_LIKELIHOOD THEN
let split_array ray =
ray.((Array.length ray)-1),
Array.init ((Array.length ray)-1) (fun i -> ray.(i)) in
match model.spec.substitution,model.spec.use_gap with
| JC69,`Coupled _ -> Some (fun y x -> update_jc69 y (`Coupled x.(0)))
| F81,`Coupled _ -> Some (fun y x -> update_f81 y (`Coupled x.(0)))
| K2P _,`Coupled _ -> Some (fun y x -> update_k2p y x.(0) (`Coupled x.(1)))
| TN93 _,`Coupled _ -> Some (fun y x -> update_tn93 y (x.(0),x.(1)) (`Coupled x.(2)))
| F84 _,`Coupled _ -> Some (fun y x -> update_f84 y x.(0) (`Coupled x.(1)))
| HKY85 _,`Coupled _-> Some (fun y x -> update_hky y x.(0) (`Coupled x.(1)))
| GTR _,`Coupled _ ->
Some (fun y x ->
let h,t = split_array x in update_gtr y t (`Coupled h))
no fifth state
| JC69,_ | F81,_ | File _,_ -> None
| TN93 _,z -> Some (fun y x -> update_tn93 y (x.(0),x.(1)) z)
| F84 _,z -> Some (fun y x -> update_f84 y x.(0) z)
| GTR _,z -> Some (fun y x -> update_gtr y x z)
| K2P _,z -> Some (fun y x -> update_k2p y x.(0) z)
| HKY85 _,z -> Some (fun y x -> update_hky y x.(0) z)
| Custom _,_-> Some (fun y x -> update_custom y x)
ELSE
None
END
and get_update_function_for_alpha model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.site_variation with
| Gamma _ -> Some update_alpha
| Theta _ -> Some update_alpha
| Constant -> None
ELSE
None
END
(* for model parameters *)
let get_current_parameters_for_model model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.substitution, model.spec.use_gap with
| JC69,`Coupled gapr | F81,`Coupled gapr ->
(Array.make 1 gapr)
| F84 x,`Coupled gapr | K2P x,`Coupled gapr | HKY85 x,`Coupled gapr ->
let x = Array.make 2 x in
x.(1) <- gapr;
x
| TN93 (x1,x2),`Coupled gapr ->
let y = Array.make 3 x2 in
y.(0) <- x1;
y.(2) <- gapr;
y
| GTR y,`Coupled gapr ->
let y = Array.init ((Array.length y)+1)
(fun i -> if i = Array.length y then gapr else y.(i))
in
y
(* no gap below *)
| JC69,_ | F81,_ | File _,_ -> [||]
| F84 x,_ | K2P x,_ | HKY85 x,_ ->
Array.make 1 x
| TN93 (x1,x2),_ ->
let y = Array.make 2 x2 in
y.(0) <- x1;
y
| GTR x,_ -> x
| Custom (_,xs,_),_ -> xs
ELSE
[||]
END
(* for alpha parameter *)
and get_current_parameters_for_alpha model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.site_variation with
| Gamma (cat,alpha) -> Some alpha
| Theta (cat,alpha,invar) -> Some alpha
| Constant -> None
ELSE
None
END
let get_update_function_for_priors model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.base_priors with
| Given _ | Equal -> None
| Estimated x ->
let olen = (Array.length x) -1 and len = Array.length x in
Some
(fun pm n ->
let s = Array.fold_left (fun a x -> a +. x) 0.0 n in
let n = Array.init len (fun i -> if i = olen then (1.0-.s) else n.(i)) in
{pm.spec with base_priors = Estimated n} --> create)
ELSE
None
END
and get_current_parameters_for_priors model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.base_priors with
| Given _ | Equal -> [||]
| Estimated x -> Array.sub x 0 ((Array.length x)-1)
ELSE
[||]
END
| null | https://raw.githubusercontent.com/amnh/poy5/da563a2339d3fa9c0110ae86cc35fad576f728ab/src/mlModel.ml | ocaml |
This program is free software; you can redistribute it and/or modify
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
type to help the parsing of specification data
the default when commands are left off from the interactive console / scripts
* [default_tstv] default ratio for models wth tstv rates; same as phyml
Coupled
* [default_alpha] default value for alpha parameter; these are the same as
phyml. p is if theta is being used (as in is a percentage)
* [default_invar] default percent for invariant sites
* [default_gap_r] default gap rate, for coupled gap parameters
* Define how characters can be sent to the classification function
* Define a distribution that branch lengths can be part of
| Given of (float * float) array
* Define the substitution rate model, between characters
* Define how base frequencies are calculated and used
* Define the Model; here we store a diagonalized matrix, priors in C-format
big-array, along with some other minor details
* This is a mapping to the codes on the C-side for determining median
calculation functions from the cost-style
* Return the alphabet for the characters
* Return the size of the alphabet for this model; includes gaps if necessary
just knowing that they are different is enough
* Categorize a list of codes by model
* Count the number of parameters in the model; used for xIC functions *
------------------------------------------------
------------------------------------------------
MODEL CALCULATION FUNCTIONS
val jc69 :: ANY ALPHABET size
normalize by mean-rate
modify transition elements to alpha
set up the diagonal elements
normalize by mean-rate
0123 -- R=02 -- Y=13
val f81 :: ANY ALPHABET size
Y = C + T
R = A + G
create matrix
array index
divide through by mean-rate
create matrix
array index
set the gap and gap coefficient col/row
divide through by mean-rate
val m_file :: any alphabet size -- recomputes diagonal and divides by meanrate
------------------------------------------------
MATRIX CALCULATION FUNCTIONS
----------------------------
phylip
this expection handling avoids gaps when they are not
* enabled in the alphabet as an additional character
* [compose_model] compose a substitution probability matrix from branch length
and substitution rate matrix.
* [integerized_model] convert a model and branch length to a probability rate
matrix and then scale by a factor of accuracy and convert to integers.
* create a cost matrix from a model
------------------------------------------------
CONVERSION/MODEL CREATION FUNCTIONS
convert a string spec (from nexus, for example) to a specification
ERROR
unmentioned default
this needs to be changed to allow remote files as well
* create a model based on a specification and an alphabet
set up all the probability and rates
SITES,ALPHA
extract the prior probability
ensure that when priors are not =, we use a model that asserts that
* Print a substitution probability matrix
* Replace the priors in a model with that of an array
* Compute the priors of a dataset by frequency and gap-counts
* Add Independent Gap to a model
------------------------------------------------
MODEL ESTIMATION FUNCTIONS
Count all the transitions A->B. Polymorphisms are counted as
* 1/(na*nb) each, where na and nb are the number of polymorphisms
* in and b respectively.
cross product of states a and b
these models assume nucleotides only; T<->C=1, A<->G=2, this is
because this is used in DNA/nucleotide models only (k2p,hky85...)
build the model
k = alpha / beta
k = [log(1-2S-V)-0.5*log(1-2V)] / log(1-2V)
finally compute the ratios
[to_formatter m]
* builds a formatted output of the model [m] spec. Since the spec can be
* transformed to the model, this is a much more readable form then other model
* data --the decomposed matrix for example.
-> Xml.xml Sexpr.t list
this assumes that the spec is consistent with the model itself, the returned
* update function ensures this consistency
for model parameters
no gap below
for alpha parameter | POY 5.1.1 . A phylogenetic analysis program using Dynamic Homologies .
Copyright ( C ) 2014 , , , Ward Wheeler ,
and the American Museum of Natural History .
it under the terms of the GNU General Public License as published by
the Free Software Foundation ; either version 2 of the License , or
You should have received a copy of the GNU General Public License
along with this program ; if not , write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston ,
USA
let () = SadmanOutput.register "MlModel" "$Revision: 3672 $"
open Numerical.FPInfix
let (-->) b a = a b
let failwithf format = Printf.ksprintf failwith format
let debug = false
exception LikelihoodModelError of string
let likelihood_not_enabled =
"Likelihood not enabled: download different binary or contact mailing list"
let lfailwith () =
raise (LikelihoodModelError likelihood_not_enabled)
let dyno_likelihood_warning =
"Gap as an additional character is required for the dynamic "^
"likelihood criteria. Please add argument gap:coupled, or gap:character."
let dyno_gamma_warning =
"Gamma classes for dynamic MPL are un-necessary, and are being removed."
let debug_printf msg format =
Printf.ksprintf (fun x -> if debug then print_string x; flush stdout) msg format
let ba_of_array1 x = Bigarray.Array1.of_array Bigarray.float64 Bigarray.c_layout x
and ba_of_array2 x = Bigarray.Array2.of_array Bigarray.float64 Bigarray.c_layout x
let create_ba1 x = Bigarray.Array1.create Bigarray.float64 Bigarray.c_layout x
and create_ba2 x y = Bigarray.Array2.create Bigarray.float64 Bigarray.c_layout x y
let barray_to_array2 bray =
let a = Bigarray.Array2.dim1 bray and b = Bigarray.Array2.dim2 bray in
let r = Array.make_matrix a b 0.0 in
for i = 0 to a-1 do for j = 0 to b-1 do
r.(i).(j) <- bray.{i,j};
done; done; r
let print_barray1 a =
for i = 0 to (Bigarray.Array1.dim a)-1 do
Printf.printf "%2.10f\t" a.{i};
done; Printf.printf "\n%!"; ()
and print_barray2 a =
for i = 0 to (Bigarray.Array2.dim1 a)-1 do
for j = 0 to (Bigarray.Array2.dim2 a)-1 do
Printf.printf "%2.10f\t" a.{i,j};
done; Printf.printf "\n";
done; Printf.printf "\n%!"; ()
type string_spec = string * (string * string * string * string) * float list
* [ `Given of (string * float) list | `Estimate of float array option
| `Consistent of float array option | `Equal ]
* (string * float option) * string * string option
let empty_str_spec : string_spec = ("",("","","",""),[],`Consistent None,("",None),"",None)
let default_command = (`Max, `MAL,`GTR [],None,`Consistent,`Missing)
let default_tstv = 4.0
* [ default_gtr ] the default parameter rates for GTR ; all 1 's . False for
coupled . otherwise , true
coupled. otherwise, true *)
let default_gtr a =
function | false -> Array.make (((a-2)*(a+1))/2) 1.0
let default_alpha p = if p then 0.2 else 1.0
let default_invar = 0.2
let default_gap_r = 0.15
type chars = [ `List of int list | `Packed of int ]
type site_var =
| Gamma of int * float
| Theta of int * float * float
| Constant
type subst_model =
| JC69
| F81
| K2P of float
| F84 of float
| HKY85 of float
| TN93 of (float * float)
| GTR of float array
| File of float array array * string
| Custom of (int All_sets.IntegerMap.t * float array * string)
type priors =
| Estimated of float array
| Given of float array
| Equal
* This is a specification of a model ; and provides a one - to - one mapping to a
full model defined below *
full model defined below **)
type spec = {
substitution : subst_model;
site_variation : site_var;
base_priors : priors;
cost_fn : Methods.ml_costfn;
use_gap : Methods.ml_gap;
alphabet : Alphabet.a * int;
}
type model = {
spec : spec;
pi_0 : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array1.t;
invar : float option;
rate : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array1.t;
prob : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array1.t;
s : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t;
u : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t;
d : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t;
ui : (float, Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t option;
}
let get_costfn_code a = match a.spec.cost_fn with
| `MPL -> 1
| `MAL -> 0
let get_alphabet m = fst m.spec.alphabet
let get_alphabet_size m = snd m.spec.alphabet
* Compare two models ; not to be used for a total ordering ( ret neg or zero )
let compare a b =
let compare_array x y =
let results = ref true in
for i = 0 to (snd a.spec.alphabet) - 1 do
results := !results && (x.(i) =. y.(i));
done;
!results
in
let compare_priors a b = match a.spec.base_priors ,a.spec.base_priors with
| _ when (snd a.spec.alphabet) != (snd b.spec.alphabet) -> false
| Equal , Equal -> true
| Estimated x, Estimated y
| Given x, Given y -> compare_array x y
| (Equal | Estimated _ | Given _), _ -> false
in
let m_compare = match a.spec.substitution,b.spec.substitution with
| JC69 , JC69 | F81 , F81 -> 0
| K2P x, K2P y | F84 x, F84 y | HKY85 x, HKY85 y when x = y -> 0
| Custom _, Custom _ -> 0
| TN93 (x1,x2), TN93 (y1,y2) when x1 = y1 && x2 = y2 -> 0
| GTR xs, GTR ys when compare_array xs ys -> 0
| File (_,x), File (_,y) when x = y -> 0
| _,_ -> ~-1
and c_compare = if a.spec.cost_fn = b.spec.cost_fn then 0 else ~-1
and v_compare = match a.spec.site_variation,b.spec.site_variation with
| Gamma (ix,ax), Gamma (iy,ay) ->
if ix=iy && ax=ay then 0 else ~-1
| Theta (ix,ax,bx), Theta (iy,ay,by) ->
if ix=iy && ax=ay && bx=by then 0 else ~-1
| Constant, Constant -> 0
| (Gamma _|Theta _|Constant), _ -> ~-1
and g_compare = match a.spec.use_gap,b.spec.use_gap with
| `Missing, `Missing
| `Independent, `Independent -> 0
| `Coupled x, `Coupled y when x=y-> 0
| (`Missing | `Independent | `Coupled _), _ -> ~-1
and p_compare = if compare_priors a b then 0 else ~-1 in
if debug then begin
Printf.printf "Models : %b\n%!" (m_compare = 0);
Printf.printf "Rate : %b\n%!" (v_compare = 0);
Printf.printf "Use Gap: %b\n%!" (g_compare = 0);
Printf.printf "Priors : %b\n%!" (p_compare = 0);
Printf.printf "Cost : %b\n%!" (c_compare = 0);
end;
m_compare + v_compare + g_compare + p_compare + c_compare
module OrderedML = struct
we could choose model or spec , but spec can use Pervasives.compare
type t = spec
let compare a b = Pervasives.compare a b
end
module MlModelMap = Map.Make (OrderedML)
let categorize_by_model get_fn codes =
let set_codes,non_lk_codes =
List.fold_left
(fun (acc,oth) code ->
try let spec = get_fn code in
try let old = MlModelMap.find spec acc in
(MlModelMap.add spec (code::old) acc,oth)
with | Not_found ->
(MlModelMap.add spec ([code]) acc,oth)
with | _ -> (acc,code::oth))
(MlModelMap.empty,[])
codes
in
let init = match non_lk_codes with | [] -> [] | xs -> [xs] in
MlModelMap.fold (fun _ e a -> e :: a) set_codes init
let count_parameters model : int =
let num_subst = match model.spec.substitution with
| Custom (_,x,_) -> (Array.length x) - 1
| JC69 | F81 | File _ -> 0
| K2P _ | F84 _ | HKY85 _ -> 1
| TN93 _ -> 2
| GTR _ ->
let a = snd model.spec.alphabet in
((a*(a-1))/2)-1
and num_rates = match model.spec.site_variation with
| Constant -> 0
| Gamma _ -> 1
| Theta (x,_,_) when x = 1 -> 1
| Theta _ -> 2
and num_priors = match model.spec.base_priors with
| Estimated f -> (Array.length f) - 1
| Given _ -> 0
| Equal -> 0
in
num_subst + num_priors + num_rates
* Return a list of all the models with default parameters ; requires alphabet
to determine if tstv models are valid and length of GTR parameters
to determine if tstv models are valid and length of GTR parameters *)
let get_all_models alph gap est_prior =
[ (JC69,Equal);
(F81,est_prior);
(K2P default_tstv,Equal);
(F84 default_tstv,est_prior);
(HKY85 default_tstv,est_prior);
(TN93 (default_tstv,default_tstv),est_prior);
(GTR [||],est_prior)]
IFDEF USE_LIKELIHOOD THEN
EXTERNAL FUNCTIONS -- maintained in likelihood.c
diagonalize a symmetric or gtr matrix , WARNING : modifies passed matrices
U D Ui
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
unit = "likelihood_CAML_diagonalize_gtr"
U D
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
unit = "likelihood_CAML_diagonalize_sym"
compose matrices -- for testing purposes , as this composition is
* usually done on the C side exclusively . If the time is less then zero , the
* instantaneious rate matrix will be returned instead ( which is just UDUi ) .
* usually done on the C side exclusively. If the time is less then zero, the
* instantaneious rate matrix will be returned instead (which is just UDUi). *)
U D Ui t
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t -> float
-> (float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t =
"likelihood_CAML_compose_gtr"
U D
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t ->
(float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t -> float
-> (float,Bigarray.float64_elt, Bigarray.c_layout) Bigarray.Array2.t =
"likelihood_CAML_compose_sym"
divide a matrix by the mean rate so it will equal 1
let m_meanrate srm pi_ =
let mr = ref 0.0 and a_size = Bigarray.Array2.dim1 srm in
for i = 0 to (a_size-1) do
mr := !mr +. (~-.(srm.{i,i}) *. pi_.{i});
done;
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} /. !mr;
done;
done
let m_jc69 pi_ mu a_size gap_r =
let srm = create_ba2 a_size a_size in
Bigarray.Array2.fill srm mu;
let () = match gap_r with
| None ->
let diag = -. mu *. float (a_size-1) in
for i = 0 to (a_size-1) do
srm.{i,i} <- diag
done;
| Some (i,r) ->
let diag = -. mu *. (r +. float (a_size-2)) in
for j = 0 to (a_size-1) do
srm.{i,j} <- mu *. r;
srm.{j,i} <- mu *. r;
srm.{j,j} <- diag;
done;
srm.{i,i} <- -. mu *. r *. float (a_size-1)
in
let mr = ref 0.0 and wght = 1.0 /. float a_size in
for i = 0 to (a_size-1) do
mr := !mr +. (~-.(srm.{i,i}) *. wght );
done;
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} /. !mr;
done;
done;
srm
val k2p : : only 4 or 5 characters
let m_k2p pi_ alpha beta a_size gap_r =
if not ((a_size = 4) || (a_size = 5)) then begin
raise (LikelihoodModelError "Alphabet does not support this model")
end;
let srm = create_ba2 a_size a_size in
let beta = if beta >. 0.0 then beta else Numerical.minimum in
Bigarray.Array2.fill srm beta;
srm.{1, 3} <- alpha; srm.{3, 1} <- alpha;
srm.{2, 0} <- alpha; srm.{0, 2} <- alpha;
let () = match gap_r with
| None ->
let diag =
if a_size = 4 then
-. alpha -. beta -. beta
else begin
assert ( a_size = 5 );
-. alpha -. beta *. 3.0
end
in
for i = 0 to (a_size-1) do
srm.{i,i} <- diag
done;
| Some (i,r) ->
assert( a_size = 5 );
let diag = -. alpha -. beta *. 3.0 -. beta *. r in
for j = 0 to (a_size-1) do
srm.{i,j} <- beta *. r;
srm.{j,i} <- beta *. r;
srm.{j,j} <- diag;
done;
srm.{i,i} <- -. beta *. r *. float (a_size-1)
in
let mr = ref 0.0 and wght = 1.0 /. float a_size in
for i = 0 to (a_size-1) do
mr := !mr +. (~-.(srm.{i,i}) *. wght );
done;
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} /. !mr;
done;
done;
srm
val tn93 : : only 4 or 5 characters
let m_tn93 pi_ alpha beta gamma a_size gap_r =
if not ((a_size = 4) || (a_size = 5)) then begin
raise (LikelihoodModelError "Alphabet size does not support this model")
end;
let srm = create_ba2 a_size a_size in
let gamma = if gamma >. 0.0 then gamma else Numerical.minimum in
Bigarray.Array2.fill srm gamma;
ACGT -- R = AG -- Y = CT
let () = match gap_r with
| None ->
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} *. pi_.{j};
done;
done;
| Some (k,r) ->
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
srm.{i,j} <- srm.{i,j} *. pi_.{j};
done;
srm.{i,k} <- gamma *. r *. pi_.{k};
srm.{k,i} <- gamma *. r *. pi_.{i};
done;
in
normalize diagonal so row sums to 0
for i = 0 to (a_size-1) do
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
done;
m_meanrate srm pi_;
srm
let m_tn93_ratio pi_ kappa1 kappa2 a_size gap_r =
let beta = (pi_.{0} *. pi_.{2} *. kappa1) +. (pi_.{1} *. pi_.{3} *. kappa2) +.
((pi_.{0} +. pi_.{2}) *. (pi_.{1}+.pi_.{3})) in
let beta = 1.0 /. (2.0 *. beta) in
let alpha1 = kappa1 *. beta and alpha2 = kappa2 *. beta in
m_tn93 pi_ alpha1 alpha2 beta a_size gap_r
let m_f81 pi_ lambda a_size gap_r =
let srm = create_ba2 a_size a_size in
let lambda = if lambda >. 0.0 then lambda else Numerical.minimum in
let () = match gap_r with
| None ->
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
if i = j then ()
else srm.{i,j} <- pi_.{j} *. lambda;
done;
done;
| Some (k,r) ->
for i = 0 to (a_size-1) do
for j = 0 to (a_size-1) do
if i = j then ()
else if k = j then srm.{i,j} <- pi_.{j} *. r
else srm.{i,j} <- pi_.{j} *. lambda;
done;
done;
in
for i = 0 to (a_size-1) do
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
done;
m_meanrate srm pi_;
srm
val hky85 : : only 4 or 5 characters
let m_hky85 pi_ kappa a_size gap_r =
let beta = (pi_.{0} *. pi_.{2} *. kappa) +. (pi_.{1} *. pi_.{3} *. kappa) +.
((pi_.{0} +. pi_.{2}) *. (pi_.{1}+.pi_.{3}) ) in
let beta = 1.0 /. (2.0 *. beta) in
let alpha = kappa *. beta in
m_tn93 pi_ alpha alpha beta a_size gap_r
val f84 : : only 4 or 5 characters
let m_f84 pi_ gamma kappa a_size gap_r =
let gamma = if gamma >. 0.0 then gamma else Numerical.minimum in
let alpha = (1.0+.kappa/.r) *. gamma in
let beta = (1.0+.kappa/.y) *. gamma in
m_tn93 pi_ alpha beta gamma a_size gap_r
normalize against two characters that are not gaps ; unless its the only choice
let normalize ?(m=Numerical.minimum) alph gap_state vec = match gap_state with
| `Independent ->
let normalize_factor = max m vec.((Array.length vec) - 1) in
let vec = Array.map (fun i -> (max m i) /. normalize_factor) vec in
vec, `Independent
| `Coupled n ->
let normalize_factor = max m vec.((Array.length vec) - 1) in
let vec = Array.map (fun i -> (max m i) /. normalize_factor) vec in
vec, `Coupled (n/.normalize_factor)
| `Missing ->
let normalize_factor = max m vec.((Array.length vec) - 1) in
let vec = Array.map (fun i -> (max m i) /. normalize_factor) vec in
vec,`Missing
val gtr : : ANY ALPHABET size
pi _ = = n ; co _ = = ( ( n-1)*n)/2
form of lower packed storage mode , excluding diagonal ,
pi_ == n; co_ == ((n-1)*n)/2
form of lower packed storage mode, excluding diagonal, *)
let m_gtr_independent pi_ co_ a_size =
if (((a_size+1)*(a_size-2))/2) <> Array.length co_ then begin
failwithf ("Length of GTR parameters (I) is incorrect for the alphabet."
^^"They should be %d, but are %d.")
(((a_size+1)*(a_size-2))/2) (Array.length co_);
end;
last element of GTR = 1.0
let co_ =
let size = (((a_size-1)*a_size)/2) in
Array.init (size)
(fun i -> if i = (size-1) then 1.0 else co_.(i))
in
let srm = create_ba2 a_size a_size in
for i = 0 to (a_size-1) do
for j = (i+1) to (a_size-1) do
srm.{i,j} <- co_.(!n) *. pi_.{j};
srm.{j,i} <- co_.(!n) *. pi_.{i};
incr n;
done;
done;
set diagonal so row sums to 0
for i = 0 to (a_size-1) do begin
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
end; done;
m_meanrate srm pi_;
srm
let m_gtr_coupled pi_ co_ a_size i_gap r_gap =
if (((a_size)*(a_size-3))/2) <> Array.length co_ then begin
failwithf ("Length of GTR parameters (%d) is incorrect for alphabet "^^
"(%d). It should be %d.")
(Array.length co_) a_size (((a_size)*(a_size-3))/2)
end;
last element of GTR = 1.0 ; add back
let co_ =
let size = Array.length co_ in
Array.init (size+1)
(fun i -> if i = (size) then 1.0 else co_.(i))
in
let srm = create_ba2 a_size a_size in
for i = 0 to (a_size-1) do
if i = i_gap then begin
for j = 0 to (a_size-1) do
srm.{j,i} <- r_gap *. pi_.{i};
srm.{i,j} <- r_gap *. pi_.{j};
done;
end else begin
for j = i+1 to (a_size-1) do
if j = i_gap then ()
else begin
srm.{i,j} <- co_.(!n) *. pi_.{j};
srm.{j,i} <- co_.(!n) *. pi_.{i};
incr n;
end;
done;
end;
done;
set diagonal so row sums to 0
for i = 0 to (a_size-1) do begin
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
end; done;
m_meanrate srm pi_;
srm
let m_gtr pi_ co_ a_size gap_r =
let srm = match gap_r with
| Some (i,r) -> m_gtr_coupled pi_ co_ a_size i r
| None -> m_gtr_independent pi_ co_ a_size
in
srm
let m_file pi_ f_rr a_size =
assert(a_size = Array.length f_rr);
let srm = create_ba2 a_size a_size in
for r = 0 to (a_size-1) do
assert(a_size = Array.length f_rr.(r));
let diag = ref 0.0 in
for c = 0 to (a_size-1) do
if (c <> r) then begin
diag := !diag +. f_rr.(r).(c);
srm.{r,c} <- f_rr.(r).(c);
end
done;
srm.{r,r} <- ~-. !diag;
done;
m_meanrate srm pi_;
srm
let m_custom pi_ idxs ray a_size =
let idx = ref 0 in
let srm = create_ba2 a_size a_size in
for i = 0 to (a_size-1) do
for j=i+1 to (a_size-1) do
let value = ray.( All_sets.IntegerMap.find !idx idxs ) in
srm.{i,j} <- value *. pi_.{j};
srm.{j,i} <- value *. pi_.{i};
incr idx;
done;
done;
for i = 0 to (a_size-1) do begin
let diag = ref 0.0 in
for j = 0 to (a_size-1) do
if (i <> j) then diag := !diag +. srm.{i,j};
done;
srm.{i,i} <- -. !diag;
end; done;
m_meanrate srm pi_;
srm
create a custom model by two Maps . One that maps an index to it 's linked index
and another that maps that to a value . The default value if the element does
not exist is set to 1.0 . The mean rate is normalized and the priors are
multiplied through . The indexes ( see below ) ensure that we are dealing with a
symmetric matrix for the parameters ,
ex , - a a b The index association would be , 1->1 , 2->1 , 3->2 , 4->2 ,
a - b a 5->1 , 6->1 ( upper triangular ) .
a b - a Diagonal elements are always ignored , a dash is recommended .
b a a - We ensure that the parameters are coupled symmetrically .
and another that maps that to a value. The default value if the element does
not exist is set to 1.0. The mean rate is normalized and the priors are
multiplied through. The indexes (see below) ensure that we are dealing with a
symmetric matrix for the parameters,
ex, - a a b The index association would be, 1->1, 2->1, 3->2, 4->2,
a - b a 5->1, 6->1 (upper triangular).
a b - a Diagonal elements are always ignored, a dash is recommended.
b a a - We ensure that the parameters are coupled symmetrically. *)
let process_custom_model alph_size (f_aa: char array array) =
let found = ref All_sets.Integers.empty in
let assoc = ref All_sets.IntegerMap.empty in
let idx = ref 0 in
let a_size = Array.length f_aa in
if not (a_size = alph_size) then begin
raise (LikelihoodModelError "Alphabet size does not match model")
end;
for i = 0 to a_size -1 do
assert( Array.length f_aa.(i) = a_size );
for j = i+1 to a_size-1 do
let letter = Char.code f_aa.(i).(j) in
if not ( letter = Char.code f_aa.(j).(i) ) then begin
raise (LikelihoodModelError "Custom model should be symmetric")
end;
assoc := All_sets.IntegerMap.add !idx letter !assoc;
found := All_sets.Integers.add letter !found;
incr idx;
done;
done;
let length,map =
All_sets.Integers.fold
(fun v1 (i,map) ->
let map =
All_sets.IntegerMap.map
(fun v2 -> if v1 = v2 then i else v2) map
in
(i+1, map))
(!found)
(0,!assoc)
in
(map, Array.make length 1.0)
A function to check for values in matrix ; catch before a diagonalization ,
since the lapack routines reeturn DGEBAL parameter illegal value instead of a
backtrace
since the lapack routines reeturn DGEBAL parameter illegal value instead of a
backtrace *)
let check_for_nan mat =
try for i = 0 to (Bigarray.Array2.dim1 mat)-1 do
for j = 0 to (Bigarray.Array2.dim1 mat)-1 do
assert( not (Numerical.is_nan mat.{i,j}));
done;
done;
true
with _ ->
false
functions to diagonalize the two types of substitution matrices
let diagonalize (sym : bool) mat =
assert( check_for_nan mat );
let alph = Bigarray.Array2.dim1 mat in
let n_u = create_ba2 alph alph in
let () = Bigarray.Array2.blit mat n_u in
let n_d = create_ba2 alph alph in
let () = Bigarray.Array2.fill n_d 0.0 in
assert( alph = Bigarray.Array2.dim2 mat);
let apply_sym sub_mat =
let () = diagonalize_sym FMatrix.scratch_space n_u n_d in
n_u, n_d, None
and apply_gtr sub_mat =
let n_ui = create_ba2 alph alph in
let () = Bigarray.Array2.fill n_ui 0.0 in
let () = diagonalize_gtr FMatrix.scratch_space n_u n_d n_ui in
n_u, n_d, Some n_ui
in
match sym with
| true -> apply_sym mat
| false -> apply_gtr mat
let compose model t = match model.ui with
| Some ui -> compose_gtr FMatrix.scratch_space model.u model.d ui t
| None -> compose_sym FMatrix.scratch_space model.u model.d t
let subst_matrix model topt =
let _gapr = match model.spec.use_gap with
| `Coupled x -> Some (Alphabet.get_gap (fst model.spec.alphabet), x)
| `Independent -> None
| `Missing -> None
and a_size = snd model.spec.alphabet
and priors = model.pi_0 in
let m = match model.spec.substitution with
| JC69 -> m_jc69 priors 1.0 a_size _gapr
| F81 -> m_f81 priors 1.0 a_size _gapr
| K2P t -> m_k2p priors t 1.0 a_size _gapr
| F84 t -> m_f84 priors t 1.0 a_size _gapr
| HKY85 t -> m_hky85 priors t a_size _gapr
| TN93 (ts,tv) -> m_tn93 priors ts tv 1.0 a_size _gapr
| GTR c -> m_gtr priors c a_size _gapr
| File (m,s) -> m_file priors m a_size
| Custom (assoc,ray,_) -> m_custom priors assoc ray a_size
in
match topt with
| Some t ->
for i = 0 to (Bigarray.Array2.dim1 m)-1 do
for j = 0 to (Bigarray.Array2.dim2 m)-1 do
m.{i,j} <- m.{i,j} *. t;
done;
done;
m
| None ->
m
let get_optimization_method m =
let meth = match m.spec.cost_fn with
| `MAL -> [Numerical.BFGS None]
| `MPL -> [Numerical.Brent_Multi None; Numerical.BFGS None]
in
Numerical.default_numerical_optimization_strategy
meth !Methods.opt_mode (count_parameters m)
print output in our nexus format or output
let output_model output output_table nexus model set =
let printf format = Printf.ksprintf output format in
let gtr_mod = ref false in
if nexus = `Nexus then begin
printf "@[Likelihood@.";
let () = match model.spec.substitution with
| JC69 -> printf "@[Model = JC69;@]@\n";
| F81 -> printf "@[Model = F81;@]";
| K2P x -> printf "@[Model = K2P;@]";
printf "@[Parameters = %f;@]" x
| F84 x -> printf "@[Model = F84;@]";
printf "@[Parameters = %f;@]" x
| HKY85 x-> printf "@[Model = HKY85;@]";
printf "@[Parameters = %f;@]" x
| TN93 (a,b) -> printf "@[Model = TN93;@]";
printf "@[Parameters = %f %f;@]" a b
| GTR xs -> printf "@[Model = GTR;@]";
printf "@[Parameters = ";
Array.iter (printf "%f ") xs;
printf ";@]";
gtr_mod := true
| File (_,str) ->
printf "@[Model = File:%s;@]" str
| Custom (_,xs,str) ->
printf "@[Model = Custom:%s;@]" str;
printf "@[Parameters = ";
Array.iter (printf "%f ") xs;
printf ";@]";
in
let () = match model.spec.base_priors with
| Equal ->
printf "@[Priors = Equal;@]"
| Estimated x | Given x ->
let first = ref true in
printf "@[Priors =";
List.iter
(fun (s,i) ->
try if !first then begin
printf "@[%s %.5f" s x.(i); first := false
end else
printf ",@]@[%s %.5f" s x.(i)
with _ -> ())
(Alphabet.to_list (fst model.spec.alphabet));
printf ";@]@]"
in
let () = match model.spec.cost_fn with
| `MPL -> printf "@[Cost = mpl;@]";
| `MAL -> printf "@[Cost = mal;@]";
in
let () = match model.spec.site_variation with
| Constant -> ()
| Gamma (c, p) ->
printf "@[Variation = gamma;@]@[alpha = %.5f@]@[sites = %d;@]" p c
| Theta (c, p, i) ->
printf ("@[Variation = theta;@]@[alpha = %.5f@]@[sites = %d;@]"
^^"@[percent = %.5f;@]") p c i
in
let () = match model.spec.use_gap with
the meaning of independent / coupled switch under gtr
| `Independent -> printf "@[gap = independent;@]"
| `Coupled x -> printf "@[gap = coupled:%f;@]" x
| `Missing -> printf "@[gap = missing;@]"
in
let () = match set with
| Some namelist ->
let first = ref true in
printf "@[CharSet = ";
List.iter
(fun s ->
if !first then begin printf "@[%s" s; first := false
end else printf ",@]@[%s" s)
namelist;
printf ";@]@]";
| None -> ()
in
printf ";@]@."
printf "@[<hov 0>Discrete gamma model: ";
let () = match model.spec.site_variation with
| Constant -> printf "No@]\n";
| Gamma (cats,param) ->
printf ("Yes@]@\n@[<hov 1>- Number of categories: %d@]\n"^^
"@[<hov 1>- Gamma Shape Parameter: %.4f@]\n") cats param
| Theta (cats,param,inv) ->
printf ("Yes@]@\n@[<hov 1>- Number of categories: %d@]\n"^^
"@[<hov 1>- Gamma Shape Parameter: %.4f@]\n") cats param;
printf ("@[<hov 1>- Proportion of invariant: %.4f@]\n") inv
in
let () = match model.spec.cost_fn with
| `MPL -> printf "@[<hov 0>Cost mode: mpl;@]@\n";
| `MAL -> printf "@[<hov 0>Cost mode: mal;@]@\n";
in
printf "@[<hov 0>Priors / Base frequencies:@\n";
let () = match model.spec.base_priors with
| Equal -> printf "@[Equal@]@]@\n"
| Estimated x | Given x ->
List.iter
(fun (s,i) ->
try printf "@[<hov 1>- f(%s)= %.5f@]@\n" s x.(i) with _ -> ())
(Alphabet.to_list (fst model.spec.alphabet));
in
printf "@[<hov 0>Model Parameters: ";
let a = (snd model.spec.alphabet) in
let () = match model.spec.substitution with
| JC69 -> printf "JC69@]@\n"
| F81 -> printf "F81@]@\n"
| K2P x ->
printf "K2P@]@\n@[<hov 1>- Transition/transversion ratio: %.5f@]@\n" x
| F84 x ->
printf "F84@]@\n@[<hov 1>- Transition/transversion ratio: %.5f@]@\n" x
| HKY85 x ->
printf "HKY85@]@\n@[<hov 1>- Transition/transversion ratio:%.5f@]@\n" x
| TN93 (a,b) ->
printf "tn93@]@\n@[<hov 1>- transition/transversion ratio:%.5f/%.5f@]@\n" a b
| GTR ray -> gtr_mod := true;
printf "GTR@]@\n@[<hov 1>- Rate Parameters: @]@\n";
let get_str i = Alphabet.match_code i (fst model.spec.alphabet)
and convert s r c = (c + (r*(s-1)) - ((r*(r+1))/2)) - 1 in
begin match model.spec.use_gap with
| `Coupled x ->
let ray =
let size = (((a-3)*a)/2) in
Array.init (size+1)
(fun i -> if i = (size) then 1.0 else ray.(i))
in
for i = 0 to a - 2 do
for j = i+1 to a - 2 do
printf "@[<hov 1>%s <-> %s - %.5f@]@\n"
(get_str i) (get_str j) ray.(convert (a-1) i j)
done;
done;
printf "@[<hov 1>%s <-> N - %.5f@]@\n"
(get_str (Alphabet.get_gap (fst model.spec.alphabet))) x
| `Missing | `Independent ->
let ray =
let size = (((a-1)*a)/2) in
Array.init (size)
(fun i -> if i = (size-1) then 1.0 else ray.(i))
in
for i = 0 to a - 1 do
for j = i+1 to a - 1 do
printf "@[<hov 1>%s <-> %s - %.5f@]@\n" (get_str i)
(get_str j) ray.(convert a i j)
done;
done
end
| File (ray,name) ->
printf "File:%s@]@\n" name;
let mat = compose model 0.0 in
printf "@[<hov 1>[";
for i = 0 to a - 1 do
printf "%s ------- " (Alphabet.match_code i (fst model.spec.alphabet))
done;
printf "]@]@\n";
for i = 0 to a - 1 do
for j = 0 to a - 1 do
printf "%.5f\t" mat.{i,j}
done;
printf "@\n";
done;
| Custom (_,xs,str) ->
printf "@[Custom:%s;@]@\n" str;
printf "@[Parameters : ";
Array.iter (printf "%f ") xs;
printf ";@]";
in
let () = match model.spec.use_gap with
| `Independent -> printf "@[<hov 0>Gap property: independent;@]@\n"
| `Coupled x -> printf "@[<hov 0>Gap property: coupled, Ratio: %f;@]@\n" x
| `Missing -> printf "@[<hov 0>Gap property: missing;@]@\n"
in
printf "@]";
printf "@[@[<hov 0>Instantaneous rate matrix:@]@\n";
match output_table with
| Some output_table ->
let table = Array.make_matrix (a+1) a "" in
let () =
let mat = compose model ~-.1.0 in
for i = 0 to a - 1 do
table.(0).(i) <- Alphabet.match_code i (fst model.spec.alphabet);
done;
for i = 0 to a - 1 do
for j = 0 to a - 1 do
table.(i+1).(j) <- string_of_float mat.{i,j}
done;
done;
in
let () = output_table table in
printf "@\n@]"
| None ->
let () =
let mat = compose model ~-.1.0 in
printf "@[<hov 1>[";
for i = 0 to a - 1 do
printf "%s ------- " (Alphabet.match_code i (fst model.spec.alphabet))
done;
printf "]";
for i = 0 to a - 1 do
printf "@]@\n@[<hov 1>";
for j = 0 to a - 1 do
printf "%8.5f " mat.{i,j}
done;
done;
in
printf "@]@\n@]"
end
let compose_model sub_mat t =
let a_size = Bigarray.Array2.dim1 sub_mat in
let (u_,d_,ui_) =
let n_d = Bigarray.Array2.create Bigarray.float64 Bigarray.c_layout a_size a_size
and n_ui = Bigarray.Array2.create Bigarray.float64 Bigarray.c_layout a_size a_size in
Bigarray.Array2.fill n_d 0.0;
Bigarray.Array2.fill n_ui 0.0;
diagonalize_gtr FMatrix.scratch_space sub_mat n_d n_ui;
(sub_mat, n_d, n_ui)
in
compose_gtr FMatrix.scratch_space u_ d_ ui_ t
let integerized_model ?(sigma=4) model t =
let sigma = 10.0 ** (float_of_int sigma)
and create = match model.spec.substitution with
| JC69 | K2P _ ->
(fun s m i j -> ~-(int_of_float (s *.(log m.(i).(j)))))
| _ ->
(fun s m i j -> ~-(int_of_float (s *.(log (model.pi_0.{i} *. m.(i).(j))))))
and matrix =
barray_to_array2 (match model.ui with
| Some ui -> compose_gtr FMatrix.scratch_space model.u model.d ui t
| None -> compose_sym FMatrix.scratch_space model.u model.d t)
and imatrix =
Array.make_matrix (snd model.spec.alphabet) (snd model.spec.alphabet) 0
in
assert( (snd model.spec.alphabet) = Array.length matrix);
assert( (snd model.spec.alphabet) = Array.length matrix.(0));
for i = 0 to (Array.length matrix) - 1 do
for j = 0 to (Array.length matrix.(0)) - 1 do
imatrix.(i).(j) <- create sigma matrix i j
done;
done;
imatrix
let model_to_cm model t =
let input = let t = max Numerical.minimum t in integerized_model model t in
let llst = Array.to_list (Array.map Array.to_list input) in
let res = Cost_matrix.Two_D.of_list ~suppress:true llst (snd model.spec.alphabet) in
res
ELSE
let output_model _ _ _ _ = lfailwith ()
let compose _ _ = lfailwith ()
let spec_from_classification _ _ _ _ _ _ = lfailwith ()
let compare _ _ = lfailwith ()
let classify_seq_pairs _ _ _ _ _ = lfailwith ()
let subst_matrix _ _ = lfailwith ()
let process_custom_model _ = lfailwith ()
let model_to_cm _ _ = lfailwith ()
let compose_model _ _ = lfailwith ()
let m_gtr _ _ _ _ = lfailwith ()
let m_file _ _ _ = lfailwith ()
let m_jc69 _ _ _ = lfailwith ()
let get_optimization_method _ = lfailwith ()
END
let convert_string_spec alph ((name,(var,site,alpha,invar),param,priors,gap,cost,file):string_spec) =
IFDEF USE_LIKELIHOOD THEN
let gap_info = match String.uppercase (fst gap),snd gap with
| "COUPLED", None -> `Coupled default_gap_r
| "COUPLED", Some x -> `Coupled x
| "INDEPENDENT",_ -> `Independent
| "MISSING",_ -> `Missing
| "",_ -> `Missing
| x,_ ->
raise (LikelihoodModelError ("Invalid gap property, "^x))
in
let submatrix = match String.uppercase name with
| "JC69" -> begin match param with
| [] -> JC69
| _ -> failwith "Parameters don't match model" end
| "F81" -> begin match param with
| [] -> F81
| _ -> failwith "Parameters don't match model" end
| "K80" | "K2P" -> begin match param with
| ratio::[] -> K2P ratio
| [] -> K2P default_tstv
| _ -> failwith "Parameters don't match model" end
| "F84" -> begin match param with
| ratio::[] -> F84 ratio
| [] -> F84 default_tstv
| _ -> failwith "Parameters don't match model" end
| "HKY" | "HKY85" -> begin match param with
| ratio::[] -> HKY85 ratio
| [] -> HKY85 default_tstv
| _ -> failwith "Parameters don't match model" end
| "TN93" -> begin match param with
| ts::tv::[] -> TN93 (ts,tv)
| [] -> TN93 (default_tstv,default_tstv)
| _ -> failwith "Parameters don't match model" end
| "GTR" -> begin match param with
| [] -> GTR [||]
| ls -> GTR (Array.of_list ls) end
| "GIVEN"->
begin match file with
| Some name ->
name --> FileStream.read_floatmatrix
--> List.map (Array.of_list)
--> Array.of_list
--> (fun x -> File (x,name))
| None ->
raise (LikelihoodModelError "No File specified for model")
end
| "CUSTOM" ->
let alph_size = snd alph in
begin match file with
| Some name ->
let convert str = assert( String.length str = 1 ); String.get str 0 in
let matrix = Cost_matrix.Two_D.matrix_of_file convert (`Local name) in
let matrix = Array.of_list (List.map (Array.of_list) matrix) in
let assoc,ray = process_custom_model alph_size matrix in
Custom (assoc,ray,name)
| None ->
raise (LikelihoodModelError "No File specified for model")
end
| "" -> raise (LikelihoodModelError "No model specified")
| xx -> raise (LikelihoodModelError ("Unknown likelihood model "^xx))
in
let cost_fn : Methods.ml_costfn = match String.uppercase cost with
| "MPL" -> `MPL
| "MAL" -> `MAL
| x -> raise (LikelihoodModelError ("Unknown cost mode "^x))
and variation = match String.uppercase var with
| "GAMMA" ->
let alpha =
try float_of_string alpha
with _ -> default_alpha false
in
Gamma (int_of_string site, alpha)
| "THETA" ->
let alpha =
try float_of_string alpha
with _ -> default_alpha true
in
let invar =
try float_of_string invar
with _ -> default_invar
in
Theta (int_of_string site, alpha, invar)
| "NONE" | "CONSTANT" | "" ->
Constant
| x -> raise (LikelihoodModelError ("Unknown rate variation mode "^x))
and priors = match priors with
| `Given priors -> Given (Array.of_list (List.map snd priors))
| `Equal -> Equal
| `Estimate (Some x) -> Estimated x
| `Consistent pre_calc ->
begin match submatrix, pre_calc with
| JC69, _
| K2P _, _ -> Equal
| _, Some pi -> Estimated pi
| _ , None -> assert false
end
| `Estimate None -> assert false
in
{ substitution = submatrix;
site_variation = variation;
base_priors = priors;
use_gap = gap_info;
alphabet = alph;
cost_fn = cost_fn; }
ELSE
lfailwith ()
END
* Convert Methods.ml specification to that of an MlModel spec
let convert_methods_spec (alph,alph_size) (compute_priors)
((_,talph,cst,subst,site_variation,base_priors,use_gap):Methods.ml_spec) =
let u_gap = match use_gap with
| `Independent | `Coupled _ -> true | `Missing -> false in
let alph_size =
let w_gap = if u_gap then alph_size else alph_size - 1 in
match talph with | `Min | `Max -> w_gap | `Int x -> x
in
let base_priors = match base_priors with
| `Estimate -> Estimated (compute_priors ())
| `Equal -> Equal
| `Given arr -> Given (Array.of_list arr)
| `Consistent ->
begin match subst with
| `JC69 | `K2P _ -> Equal
| _ -> Estimated (compute_priors ())
end
and site_variation = match site_variation with
| None -> Constant
| Some (`Gamma (w,y)) ->
let y = match y with
| Some x -> x
| None -> default_alpha false
in
Gamma (w,y)
| Some (`Theta (w,y)) ->
let y,p = match y with
| Some x -> x
| None -> default_alpha true, default_invar
in
Theta (w,y,p)
and substitution = match subst with
| `AIC _ | `BIC _ | `AICC _ | `NCM -> assert false
| `JC69 -> JC69
| `F81 -> F81
| `K2P [x] -> K2P x
| `K2P [] -> K2P default_tstv
| `K2P _ ->
raise (LikelihoodModelError
"Likelihood model K2P requires 1 or 0 parameters")
| `HKY85 [x] -> HKY85 x
| `HKY85 [] -> HKY85 default_tstv
| `HKY85 _ ->
raise (LikelihoodModelError
"Likelihood model HKY85 requires 1 or 0 parameters")
| `F84 [x] -> F84 x
| `F84 [] -> F84 default_tstv
| `F84 _ ->
raise (LikelihoodModelError
"Likelihood model F84 requires 1 or 0 parameters")
| `TN93 [x;y] -> TN93 (x,y)
| `TN93 [] -> TN93 (default_tstv,default_tstv)
| `TN93 _ ->
raise (LikelihoodModelError
"Likelihood model TN93 requires 2 or 0 parameters")
| `GTR xs -> GTR (Array.of_list xs)
| `File str ->
let matrix = Cost_matrix.Two_D.matrix_of_file float_of_string (`Local str) in
let matrix = Array.of_list (List.map (Array.of_list) matrix) in
Array.iter
(fun x ->
if Array.length x = alph_size then ()
else begin
raise (LikelihoodModelError "Likelihood model TN93 requires 2 or 0 parameters")
end)
(matrix);
if Array.length matrix = alph_size then
File (matrix,str)
else begin
raise (LikelihoodModelError "Likelihood model TN93 requires 2 or 0 parameters")
end;
| `Custom str ->
let convert str = assert( String.length str = 1 ); String.get str 0 in
let matrix = Cost_matrix.Two_D.matrix_of_file convert (`Local str) in
let matrix = Array.of_list (List.map (Array.of_list) matrix) in
let assoc,ray = process_custom_model alph_size matrix in
Custom (assoc,ray,str)
in
{ substitution = substitution;
site_variation = site_variation;
base_priors = base_priors;
alphabet = (alph,alph_size);
cost_fn = cst;
use_gap = use_gap; }
* check the rates so SUM(r_k*p_k ) = = 1 and SUM(p_k ) = = 1 = = |r|
let verify_rates probs rates =
let p1 = (Bigarray.Array1.dim probs) = (Bigarray.Array1.dim rates)
and p2 =
let rsps = ref 0.0 and ps = ref 0.0 in
for i = 0 to (Bigarray.Array1.dim probs) - 1 do
rsps := !rsps +. (probs.{i} *. rates.{i});
ps := !ps +. probs.{i};
done;
!rsps =. 1.0 && !ps =. 1.0
in
p1 && p2
let create ?(min_prior=Numerical.minimum) lk_spec =
IFDEF USE_LIKELIHOOD THEN
let (alph,a_size) = lk_spec.alphabet in
assert( a_size > 1 );
let variation,probabilities,invar =
match lk_spec.site_variation with
| Constant ->
ba_of_array1 [| 1.0 |], ba_of_array1 [| 1.0 |], None
let p = create_ba1 x in
Bigarray.Array1.fill p (1.0 /. (float_of_int x));
Numerical.gamma_rates y y x,p,None
GAMMA_SITES , ALPHA ,
if w < 1 then
failwith "Number of rate categories must be >= 1 (if invar w/out gamma)"
else if w = 1 then begin
ba_of_array1 [| 1.0 |], ba_of_array1 [| 1.0 |], Some z
end else begin
let p = create_ba1 w in
Bigarray.Array1.fill p (1.0 /. (float_of_int w));
let r = Numerical.gamma_rates x x w in
r,p,Some z
end
in
assert( verify_rates probabilities variation );
let priors =
let p = match lk_spec.base_priors with
| Equal ->
Array.make a_size (1.0 /. (float_of_int a_size))
| Estimated p | Given p ->
let p = Array.map (fun i -> max min_prior i) p in
let sum = Array.fold_left (fun a b -> a +. b) 0.0 p in
if sum =. 1.0
then p
else Array.map (fun i -> i /. sum) p
in
if not (a_size = Array.length p) then begin
debug_printf "Alphabet = %d; Priors = %d\n%!" a_size (Array.length p);
raise (LikelihoodModelError "Priors don't match alphabet");
end;
ba_of_array1 p
in
let _gapr = match lk_spec.use_gap with
| `Coupled x ->
let gap_i =
if Alphabet.zero_indexed alph
then Alphabet.get_gap alph
else (Alphabet.get_gap alph)-1
in
Some (gap_i, x)
| `Independent -> None
| `Missing -> None
in
get the substitution rate matrix and set sym variable and to_formatter vars
let sym, sub_mat, subst_model = match lk_spec.substitution with
| JC69 -> true, m_jc69 priors 1.0 a_size _gapr, JC69
| F81 -> false, m_f81 priors 1.0 a_size _gapr, F81
| K2P t -> true, m_k2p priors t 1.0 a_size _gapr, lk_spec.substitution
| F84 t -> false, m_f84 priors t 1.0 a_size _gapr, lk_spec.substitution
| HKY85 t -> false, m_hky85 priors t a_size _gapr, lk_spec.substitution
| TN93 (ts,tv) ->
false, m_tn93 priors ts tv 1.0 a_size _gapr, lk_spec.substitution
| GTR c ->
let c = match (Array.length c), lk_spec.use_gap with
| 0, `Coupled _ -> default_gtr a_size true
| 0, _ -> default_gtr a_size false
| _, _ -> c
in
false, m_gtr priors c a_size _gapr, (GTR c)
| File (m,s)->
false, m_file priors m a_size, lk_spec.substitution
| Custom (assoc,xs,_) ->
false, m_custom priors assoc xs a_size, lk_spec.substitution
in
let lk_spec = match lk_spec.base_priors with
| Estimated _ when sym ->
Status.user_message Status.Warning
"I@ am@ using@ equal@ priors@ as@ required@ in@ the@ selected@ likelihood@ model.";
{ lk_spec with base_priors = Equal }
| Given _ when sym ->
Status.user_message Status.Warning
"I@ am@ using@ equal@ priors@ as@ required@ in@ the@ selected@ likelihood@ model.";
{ lk_spec with base_priors = Equal }
| (Estimated _ | Equal | Given _) -> lk_spec
in
let (u_,d_,ui_) = diagonalize sym sub_mat in
{
rate = variation;
prob = probabilities;
spec = {lk_spec with substitution = subst_model; };
invar = invar;
pi_0 = priors;
s = sub_mat;
u = u_;
d = d_;
ui = ui_;
}
ELSE
lfailwith ()
END
let debug_model model t =
let subst = subst_matrix model t in
print_barray2 subst; print_newline ();
match t with | Some t -> print_barray2 (compose model t) | None -> ()
let replace_priors model array =
if debug then begin
Printf.printf "Replacing Priors\n\t%!";
Array.iter (fun x -> Printf.printf "%f, " x) array;
print_newline ();
end;
create {model.spec with base_priors = Estimated array}
let compute_priors (alph,u_gap) freq_ (count,gcount) lengths : float array =
let size = if u_gap then (Alphabet.size alph) else (Alphabet.size alph)-1 in
let gap_contribution = (float_of_int gcount) /. (float_of_int size) in
let gap_char = Alphabet.get_gap alph in
if debug then begin
Printf.printf "Computed Priors of %d char + %d gaps: " count gcount;
Array.iter (Printf.printf "|%f") freq_;
Printf.printf "|]\n%!";
end;
let final_priors =
if u_gap then begin
let total_added_gaps =
let longest : int = List.fold_left (fun a x-> max a x) 0 lengths in
let add_gap : int = List.fold_left (fun acc x -> (longest - x) + acc) 0 lengths in
float_of_int add_gap
in
Printf.printf "Total added gaps = %f\n%!" total_added_gaps;
freq_.(gap_char) <- freq_.(gap_char) +. total_added_gaps;
let count = (float_of_int (count - gcount)) +. total_added_gaps;
and weight = (float_of_int gcount) /. (float_of_int size) in
Array.map (fun x -> (x -. weight) /. count) freq_
end else begin
Array.map (fun x -> (x -. gap_contribution) /. (float_of_int count)) freq_
end
in
let sum = Array.fold_left (fun a x -> a +. x) 0.0 final_priors in
if debug then begin
Printf.printf "Final Priors (%f): [" sum;
Array.iter (Printf.printf "|%f") final_priors;
Printf.printf "|]\n%!";
end;
final_priors
let add_gap_to_model compute_priors model =
raise (LikelihoodModelError dyno_likelihood_warning)
let add_gap_to_model compute_priors model =
match model.spec.use_gap with
| `Missing -> add_gap_to_model compute_priors model
| `Independent | `Coupled _ -> model
let remove_gamma_from_spec spec =
match spec.site_variation with
| Constant -> spec
| Gamma _ | Theta _ ->
Status.user_message Status.Warning
(Str.global_replace (Str.regexp " ") "@ " dyno_gamma_warning);
{ spec with site_variation = Constant; }
IFDEF USE_LIKELIHOOD THEN
let chars2str = function
| `Packed s -> string_of_int s
| `List s -> "[ "^(String.concat " | " (List.map string_of_int s))^" ]"
* estimate the model based on two sequences with attached weights
let classify_seq_pairs leaf1 leaf2 seq1 seq2 acc =
let chars_to_list = function
| `Packed s -> BitSet.Int.list_of_packed s
| `List s -> s
and incr_map k v map =
let v = match All_sets.IntegerMap.mem k map with
| true -> v +. (All_sets.IntegerMap.find k map)
| false -> v
in
All_sets.IntegerMap.add k v map
and incr_tuple ((a,b) as k) v map =
let v = match All_sets.FullTupleMap.mem k map with
| true -> v +. (All_sets.FullTupleMap.find k map)
| false -> v
in
All_sets.FullTupleMap.add k v map
in
classify the mutation from a1 to a2 in a map
let mk_transitions (tmap,fmap) (w1,c1,s1) (w2,c2,s2) =
assert( w1 = w2 );
let s1 = chars_to_list s1 and s2 = chars_to_list s2 in
let n1 = List.length s1 and n2 = List.length s2 in
let v = w1 /. (float_of_int (n1 * n2) ) in
List.fold_left
(fun map1 a ->
List.fold_left
(fun map2 b -> incr_tuple (a,b) v map2)
map1 s2)
tmap s1
in
Counts the base frequencies . Polymorphisms are counted as 1 / n in
* each base , where , as above , n is the number of polymorphisms .
* each base, where, as above, n is the number of polymorphisms. *)
let n1 = w1 /. (float_of_int n1) and n2 = w2 /. (float_of_int n2) in
let fmap =
if leaf1 then
List.fold_left (fun map a -> incr_map a n1 map) fmap s1
else fmap in
let fmap =
if leaf2 then
List.fold_left (fun map a -> incr_map a n2 map) fmap s2
else fmap in
tmap,fmap
in
List.fold_left2 mk_transitions acc seq1 seq2
let get_priors f_prior alph code = match f_prior with
| Estimated x -> x.(Alphabet.match_base code alph)
| Given x -> x.(Alphabet.match_base code alph)
| Equal -> 1.0 /. (float_of_int (Alphabet.size alph))
Develop a model from a classification --created above
let spec_from_classification alph gap kind rates (priors:Methods.ml_priors) costfn (comp_map,pis) =
let tuple_sum =
All_sets.FullTupleMap.fold (fun k v a -> a +. v) comp_map 0.0
and ugap = match gap with
| `Missing -> false
| `Independent -> true
| `Coupled _ -> true
in
let f_priors,a_size = match priors,kind with
| `Equal,_ | (`Consistent | `Estimate), (`JC69 | `K2P _) ->
let size =
if ugap then (Alphabet.size alph) else (Alphabet.size alph)-1
in
Equal,size
| `Consistent,_ | `Estimate,_ ->
let sum = All_sets.IntegerMap.fold (fun k v x -> v +. x) pis 0.0
and gap_size =
try All_sets.IntegerMap.find (Alphabet.get_gap alph) pis
with | Not_found -> 0.0
in
let l =
let sum = if ugap then sum else sum -. gap_size in
List.fold_left
(fun acc (r,b) -> match b with
| b when (not ugap) && (b = Alphabet.get_gap alph) -> acc
| b ->
let c =
try (All_sets.IntegerMap.find b pis) /. sum
with Not_found -> 0.0 in
c :: acc)
[]
(Alphabet.to_list alph)
in
let ray = Array.of_list (List.rev l) in
Estimated ray, Array.length ray
| `Given xs, _ ->
let ray = Array.of_list xs in
Given ray, Array.length ray
and is_comp a b =
if (Alphabet.match_base "T" alph) = a then
if (Alphabet.match_base "C" alph) = b then 1 else 0
else if (Alphabet.match_base "C" alph) = a then
if (Alphabet.match_base "T" alph) = b then 1 else 0
else if (Alphabet.match_base "A" alph) = a then
if (Alphabet.match_base "G" alph) = b then 2 else 0
else if (Alphabet.match_base "G" alph) = a then
if (Alphabet.match_base "A" alph) = b then 2 else 0
else
0
in
let get_sva comp_map =
let s1,s2,v,a =
All_sets.FullTupleMap.fold
(fun k v (sc1,sc2,vc,all) -> match k with
| k1,k2 when 1 == is_comp k1 k2 -> (sc1+.v,sc2,vc,all+.v)
| k1,k2 when 2 == is_comp k1 k2 -> (sc1,sc2+.v,vc,all+.v)
| k1,k2 when k1 != k2 -> (sc1,sc2,vc+.v,all+.v)
| _ -> (sc1,sc2,vc,all+.v) )
comp_map
(0.0,0.0,0.0,0.0)
in
s1 /. a, s2 /. a, v /. a, a
in
let m,gap = try match kind with
| `JC69 -> JC69,gap
| `F81 -> F81,gap
| `K2P _ ->
YANG : 1.12
alpha*t = -0.5 * log(1 - 2S - V ) + 0.25 * log(1 - 2V )
2*beta*t = -0.5 * log(1 - 2V )
let s1,s2,v,a = get_sva comp_map in
let s = s1 +. s2 in
let numer = 2.0 *. (log (1.0-.(2.0*.s)-.v))
and denom = log (1.0-.(2.0*.v)) in
K2P ((numer /. denom)-.1.0),gap
| `GTR _ ->
let tuple_sum a1 a2 map =
let one = try All_sets.FullTupleMap.find (a1,a2) map
with | Not_found -> 0.0
and two = try All_sets.FullTupleMap.find (a2,a1) map
with | Not_found -> 0.0
in
one +. two
in
create list of transitions for GTR model creation
1 - > 2 , 1 - > 3 , 1 - > 4 ... 2 - > 3 ...
begin match gap with
| `Independent | `Missing ->
let cgap = Alphabet.get_gap alph in
let lst =
List.fold_right
(fun (s1,alph1) acc1 ->
if (not ugap) && (cgap = alph1) then
acc1
else
List.fold_right
(fun (s2,alph2) acc2 ->
if alph2 <= alph1 then acc2
else if (not ugap) && (cgap = alph2) then
acc2
else begin
let sum = tuple_sum alph1 alph2 comp_map in
sum :: acc2
end)
(Alphabet.to_list alph) acc1)
(Alphabet.to_list alph) []
in
let sum = List.fold_left (fun a x -> x +. a) 0.0 lst in
let lst = List.map (fun x -> x /. sum) lst in
let arr,gap = normalize alph gap (Array.of_list lst) in
let arr = Array.init ((List.length lst)-1) (fun i -> arr.(i)) in
GTR arr,gap
| `Coupled _ ->
let cgap = Alphabet.get_gap alph in
let lst,gap_trans =
List.fold_right
(fun (s1,alph1) acc1 ->
if cgap = alph1 then acc1
else
List.fold_right
(fun (s2,alph2) ((chrt,gapt) as acc2) ->
if alph2 <= alph1 then acc2
else if cgap = alph2 then
let sum = tuple_sum alph1 alph2 comp_map in
(chrt, sum +. gapt)
else begin
let sum = tuple_sum alph1 alph2 comp_map in
(sum :: chrt,gapt)
end)
(Alphabet.to_list alph) acc1)
(Alphabet.to_list alph)
([],0.0)
in
let sum = List.fold_left (fun a x -> x +. a) gap_trans lst in
let lst = List.map (fun x -> x /. sum) lst in
let gap = `Coupled (gap_trans /. (sum *. (float_of_int a_size))) in
let arr,gap = normalize alph gap (Array.of_list lst) in
let arr = Array.init ((List.length lst)-1) (fun i -> arr.(i)) in
GTR arr,gap
end
| `F84 _ ->
let pi_a = get_priors f_priors alph "A"
and pi_c = get_priors f_priors alph "C"
and pi_g = get_priors f_priors alph "G"
and pi_t = get_priors f_priors alph "T" in
let pi_y = pi_c +. pi_t and pi_r = pi_a +. pi_g in
let s1,s2,v,a = get_sva comp_map in let s = s1 +. s2 in
let a = ~-. (log (1.0 -. (s /. (2.0 *. (pi_t*.pi_c/.pi_y +. pi_a*.pi_g/.pi_r)))
-. (v *.(pi_t*.pi_c *.pi_r/.pi_y +.
(pi_a*.pi_g*.pi_y/.pi_r))) /.
(2.0 *. (pi_t*.pi_c *. pi_r +. pi_a *. pi_g *. pi_y))))
and b = ~-. (log (1.0 -. (v/.(2.0 *. pi_y*.pi_r)))) in
F84 (a/.b -. 1.0),gap
| `HKY85 _ ->
let pi_a = get_priors f_priors alph "A"
and pi_c = get_priors f_priors alph "C"
and pi_g = get_priors f_priors alph "G"
and pi_t = get_priors f_priors alph "T" in
let pi_y = pi_c +. pi_t and pi_r = pi_a +. pi_g in
let s1,s2,v,a = get_sva comp_map in let s = s1 +. s2 in
let a = ~-. (log (1.0 -. (s /. (2.0 *. (pi_t*.pi_c/.pi_y +. pi_a*.pi_g/.pi_r)))
-. (v *.(pi_t*.pi_c *.pi_r/.pi_y +.
(pi_a*.pi_g*.pi_y/.pi_r))) /.
(2.0 *. (pi_t*.pi_c *. pi_r +. pi_a *. pi_g *. pi_y))))
and b = ~-. (log (1.0 -. (v/.(2.0 *. pi_y*.pi_r)))) in
HKY85 (a/.b -. 1.0),gap
| `TN93 _ ->
let pi_a = get_priors f_priors alph "A"
and pi_c = get_priors f_priors alph "C"
and pi_g = get_priors f_priors alph "G"
and pi_t = get_priors f_priors alph "T" in
let pi_y = pi_c +. pi_t and pi_r = pi_a +. pi_g
and s1,s2,v,a = get_sva comp_map in
let a1 = ~-. (log (1.0 -. (pi_y*.s1/.(2.0*.pi_t*.pi_c)) -. (v/.(2.0*.pi_y))))
and a2 = ~-. (log (1.0 -. (pi_r*.s2/.(2.0*.pi_a*.pi_g)) -. (v/.(2.0*.pi_r))))
and b = ~-. (log (1.0 -. (v /. (2.0 *. pi_y *. pi_r)))) in
let k1 = (a1 -. (pi_r *. b)) /. (pi_y *. b)
and k2 = (a2 -. (pi_y *. b)) /. (pi_r *. b) in
TN93 (k1,k2),gap
| `Custom _
| `File _ -> failwith "I cannot estimate this type of model"
with | Not_found -> failwith "Cannot find something for model"
and calc_invar all comp_map =
let same =
List.fold_left
(fun acc (_,ac) ->
acc +. (try (All_sets.FullTupleMap.find (ac,ac) comp_map)
with | Not_found -> 0.0))
0.0
(Alphabet.to_list alph)
in
same /. all
in
let v = match rates with
| None -> Constant
| Some (`Gamma (i,_)) -> Gamma (i,default_alpha false)
| Some (`Theta (i,_)) -> Theta (i,default_alpha true,calc_invar tuple_sum comp_map)
in
{
substitution = m;
site_variation = v;
base_priors = f_priors;
cost_fn = costfn;
use_gap = gap;
alphabet = (alph, a_size);
}
let convert_gapr m = function
| `Coupled x -> Some (Alphabet.get_gap (fst m.spec.alphabet),x)
| `Independent -> None
| `Missing -> None
let update_jc69 old_model gap_r =
let subst_spec = { old_model.spec with use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_jc69 old_model.pi_0 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize true subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_f81 old_model gap_r =
let subst_spec = { old_model.spec with use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_f81 old_model.pi_0 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_k2p old_model new_value gap_r =
let subst_spec = { old_model.spec with substitution = K2P new_value;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_k2p old_model.pi_0 new_value 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize true subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_hky old_model new_value gap_r =
let subst_spec = { old_model.spec with substitution = HKY85 new_value;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_hky85 old_model.pi_0 new_value (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_tn93 old_model ((x,y) as new_value) gap_r =
let subst_spec = { old_model.spec with substitution = TN93 new_value;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_tn93 old_model.pi_0 x y 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_f84 old_model new_value gap_r =
let subst_spec = { old_model.spec with substitution = F84 new_value;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_f84 old_model.pi_0 new_value 1.0 (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_gtr old_model new_values gap_r =
let subst_spec = { old_model.spec with substitution = GTR new_values;
use_gap = gap_r; }
and gap_r = convert_gapr old_model gap_r in
let subst_model =
m_gtr old_model.pi_0 new_values (snd old_model.spec.alphabet) gap_r in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_custom old_model new_values =
let subst_spec,assoc = match old_model.spec.substitution with
| Custom (assoc,_,s) ->
{ old_model.spec with substitution = Custom (assoc,new_values,s); },assoc
| _ -> assert false
in
let subst_model =
m_custom old_model.pi_0 assoc new_values (snd old_model.spec.alphabet) in
let u,d,ui = diagonalize false subst_model in
{ old_model with spec = subst_spec; s = subst_model; u = u; d = d; ui = ui; }
and update_alpha old_model new_value =
let new_spec_var,new_array = match old_model.spec.site_variation with
| Gamma (i,_) -> Gamma (i,new_value),
Numerical.gamma_rates new_value new_value i
| Theta (i,_,p) -> Theta (i,new_value,p),
Numerical.gamma_rates new_value new_value i
| Constant -> Constant,old_model.rate
in
{ old_model with rate = new_array;
spec = { old_model.spec with site_variation = new_spec_var;} }
and update_alpha_invar old_model new_alpha new_invar =
let new_spec_var,new_array = match old_model.spec.site_variation with
| Gamma (i,_) -> Gamma (i,new_alpha),
Numerical.gamma_rates new_alpha new_alpha i
| Theta (i,_,_) -> Theta (i,new_alpha,new_invar),
Numerical.gamma_rates new_alpha new_alpha i
| Constant -> Constant, old_model.rate
in
{ old_model with rate = new_array;
spec = { old_model.spec with site_variation = new_spec_var; };
invar = Some new_invar; }
END
let to_formatter (model: model) : Xml.xml Sexpr.t list =
let alph,alph_s = model.spec.alphabet in
let priors =
let inner =
Array.mapi
(fun i v ->
(PXML -[Xml.Characters.vector]
([Xml.Alphabet.value] = [`Float v])
{ `String (Alphabet.match_code i alph)} --))
(match model.spec.base_priors with
| Equal ->
Array.make alph_s (1.0 /. (float_of_int alph_s))
| Given x | Estimated x -> x)
in
(PXML -[Xml.Characters.priors] { `Set (Array.to_list inner) } --)
and get_model model = match model.spec.substitution with
| JC69 -> "jc69" | F81 -> "f81"
| K2P _ -> "k2p" | F84 _ -> "f84"
| HKY85 _ -> "hky85" | TN93 _ -> "tn93"
| GTR _ -> "gtr" | File _ -> "file"
| Custom _ -> "custom"
and get_alpha m = match m.spec.site_variation with
| Constant -> `Float 0.0
| Gamma (_,x)
| Theta (_,x,_) -> `Float x
and get_invar m = match m.spec.site_variation with
| Gamma _ | Constant -> `Float 0.0
| Theta (_,_,p) -> `Float p
and get_gap m = match m.spec.use_gap with
| `Missing -> `String "missing"
| `Independent -> `String "independent"
| `Coupled x -> `String ("coupled:"^string_of_float x)
and get_cats m = match m.spec.site_variation with
| Constant -> `Int 1
| Gamma (c,_)
| Theta (c,_,_) -> `Int c
and parameters m = match m.spec.substitution with
| JC69 | F81 -> []
| K2P x | F84 x | HKY85 x ->
[(PXML -[Xml.Data.param 1]
([Xml.Alphabet.value] = [`Float x])
{ `String "" } --)]
| TN93 (a,b) ->
(PXML -[Xml.Data.param 1]
([Xml.Alphabet.value] = [`Float a])
{ `String "" } --) ::
[(PXML -[Xml.Data.param 2]
([Xml.Alphabet.value] = [`Float b])
{ `String "" } --)]
| GTR ray ->
let r,_ =
Array.fold_left
(fun (acc,i) x ->
(PXML -[Xml.Data.param i]
([Xml.Alphabet.value] = [`Float x])
{ `String "" } --) :: acc,i+1)
([],1)
ray
in
List.rev r
| Custom (_,_,str) ->
[(PXML -[Xml.Data.param 1]
([Xml.Alphabet.value] = [`String str])
{ `String "" } --)]
| File (_,str) ->
[(PXML -[Xml.Data.param 1]
([Xml.Alphabet.value] = [`String str])
{ `String "" } --)]
in
(PXML
-[Xml.Characters.model]
([Xml.Characters.name] = [`String (get_model model)])
([Xml.Characters.categories] = [get_cats model])
([Xml.Characters.alpha] = [get_alpha model])
([Xml.Characters.invar] = [get_invar model])
([Xml.Characters.gapascharacter] = [get_gap model])
{ `Set (priors :: (parameters model)) }
--) :: []
* produce a short readable name for the model : like JC69+G+I. We ignore data
dependent and optimality paramters ( gap as missing / independent ) and mpl / mal
dependent and optimality paramters (gap as missing/independent) and mpl/mal *)
let short_name model =
let model_name = match model.spec.substitution with
| JC69 -> "JC69" | F81 -> "F81"
| K2P _ -> "K81" | F84 _ -> "F84"
| HKY85 _ -> "HKY" | TN93 _ -> "TN93"
| GTR _ -> "GTR" | File _ -> "FILE"
| Custom _-> "CUSTOM"
and variation_name = match model.spec.site_variation with
| Theta (i,_,_) when i > 1 -> "+G+I"
| Gamma _ -> "+G"
| Theta _ -> "+I"
| Constant -> ""
in
model_name ^ variation_name
and get_update_function_for_model model =
IFDEF USE_LIKELIHOOD THEN
let split_array ray =
ray.((Array.length ray)-1),
Array.init ((Array.length ray)-1) (fun i -> ray.(i)) in
match model.spec.substitution,model.spec.use_gap with
| JC69,`Coupled _ -> Some (fun y x -> update_jc69 y (`Coupled x.(0)))
| F81,`Coupled _ -> Some (fun y x -> update_f81 y (`Coupled x.(0)))
| K2P _,`Coupled _ -> Some (fun y x -> update_k2p y x.(0) (`Coupled x.(1)))
| TN93 _,`Coupled _ -> Some (fun y x -> update_tn93 y (x.(0),x.(1)) (`Coupled x.(2)))
| F84 _,`Coupled _ -> Some (fun y x -> update_f84 y x.(0) (`Coupled x.(1)))
| HKY85 _,`Coupled _-> Some (fun y x -> update_hky y x.(0) (`Coupled x.(1)))
| GTR _,`Coupled _ ->
Some (fun y x ->
let h,t = split_array x in update_gtr y t (`Coupled h))
no fifth state
| JC69,_ | F81,_ | File _,_ -> None
| TN93 _,z -> Some (fun y x -> update_tn93 y (x.(0),x.(1)) z)
| F84 _,z -> Some (fun y x -> update_f84 y x.(0) z)
| GTR _,z -> Some (fun y x -> update_gtr y x z)
| K2P _,z -> Some (fun y x -> update_k2p y x.(0) z)
| HKY85 _,z -> Some (fun y x -> update_hky y x.(0) z)
| Custom _,_-> Some (fun y x -> update_custom y x)
ELSE
None
END
and get_update_function_for_alpha model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.site_variation with
| Gamma _ -> Some update_alpha
| Theta _ -> Some update_alpha
| Constant -> None
ELSE
None
END
let get_current_parameters_for_model model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.substitution, model.spec.use_gap with
| JC69,`Coupled gapr | F81,`Coupled gapr ->
(Array.make 1 gapr)
| F84 x,`Coupled gapr | K2P x,`Coupled gapr | HKY85 x,`Coupled gapr ->
let x = Array.make 2 x in
x.(1) <- gapr;
x
| TN93 (x1,x2),`Coupled gapr ->
let y = Array.make 3 x2 in
y.(0) <- x1;
y.(2) <- gapr;
y
| GTR y,`Coupled gapr ->
let y = Array.init ((Array.length y)+1)
(fun i -> if i = Array.length y then gapr else y.(i))
in
y
| JC69,_ | F81,_ | File _,_ -> [||]
| F84 x,_ | K2P x,_ | HKY85 x,_ ->
Array.make 1 x
| TN93 (x1,x2),_ ->
let y = Array.make 2 x2 in
y.(0) <- x1;
y
| GTR x,_ -> x
| Custom (_,xs,_),_ -> xs
ELSE
[||]
END
and get_current_parameters_for_alpha model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.site_variation with
| Gamma (cat,alpha) -> Some alpha
| Theta (cat,alpha,invar) -> Some alpha
| Constant -> None
ELSE
None
END
let get_update_function_for_priors model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.base_priors with
| Given _ | Equal -> None
| Estimated x ->
let olen = (Array.length x) -1 and len = Array.length x in
Some
(fun pm n ->
let s = Array.fold_left (fun a x -> a +. x) 0.0 n in
let n = Array.init len (fun i -> if i = olen then (1.0-.s) else n.(i)) in
{pm.spec with base_priors = Estimated n} --> create)
ELSE
None
END
and get_current_parameters_for_priors model =
IFDEF USE_LIKELIHOOD THEN
match model.spec.base_priors with
| Given _ | Equal -> [||]
| Estimated x -> Array.sub x 0 ((Array.length x)-1)
ELSE
[||]
END
|
c7f4d893ac507b2d51cb14f0b321377a12172c57a53f3825f3bcc83afaa96b47 | retro/keechma-next-realworld-app | subscription.cljs | (ns keechma.next.controllers.subscription
(:require [keechma.next.controller :as ctrl]))
(derive :keechma/subscription :keechma/controller)
(defmethod ctrl/derive-state :keechma/subscription [ctrl state deps-state]
(if-let [derive-state (:keechma.subscription/derive-state ctrl)]
(derive-state state deps-state)
(:keechma.controller/params ctrl)))
| null | https://raw.githubusercontent.com/retro/keechma-next-realworld-app/47a14f4f3f6d56be229cd82f7806d7397e559ebe/classes/production/realworld-2/keechma/next/controllers/subscription.cljs | clojure | (ns keechma.next.controllers.subscription
(:require [keechma.next.controller :as ctrl]))
(derive :keechma/subscription :keechma/controller)
(defmethod ctrl/derive-state :keechma/subscription [ctrl state deps-state]
(if-let [derive-state (:keechma.subscription/derive-state ctrl)]
(derive-state state deps-state)
(:keechma.controller/params ctrl)))
| |
9131d7dc4710bf755cd91c6e50f2368bb7540a2a187b3b9f535da592f845bb22 | everpeace/programming-erlang-code | lib_io_widget.erl | -module(lib_io_widget).
-export([start/1, test/0,
set_handler/2, set_prompt/2, set_title/2, insert_str/2]).
start(Pid) ->
gs:start(),
spawn_link(fun() -> widget(Pid) end).
set_title(Pid, Str) -> Pid ! {title, Str}.
set_handler(Pid, Fun) -> Pid ! {handler, Fun}.
set_prompt(Pid, Str) -> Pid ! {prompt, Str}.
insert_str(Pid, Str) -> Pid ! {insert, Str}.
widget(Pid) ->
Size = [{width,500},{height,200}],
Win = gs:window(gs:start(),
[{map,true},{configure,true},{title,"window"}|Size]),
gs:frame(packer, Win,[{packer_x, [{stretch,1,500}]},
{packer_y, [{stretch,10,120,100},
{stretch,1,15,15}]}]),
gs:create(editor,editor,packer, [{pack_x,1},{pack_y,1},{vscroll,right}]),
gs:create(entry, entry, packer, [{pack_x,1},{pack_y,2},{keypress,true}]),
gs:config(packer, Size),
Prompt = " > ",
gs:config(entry, {insert,{0,Prompt}}),
loop(Win, Pid, Prompt, fun parse/1).
loop(Win, Pid, Prompt, Parse) ->
receive
{handler, Fun} ->
loop(Win, Pid, Prompt, Fun);
{prompt, Str} ->
%% this clobbers the line being input ...
%% this could be fixed - hint
gs:config(entry, {delete,{0,last}}),
gs:config(entry, {insert,{0,Str}}),
loop(Win, Pid, Str, Parse);
{title, Str} ->
gs:config(Win, [{title, Str}]),
loop(Win, Pid, Prompt, Parse);
{insert, Str} ->
gs:config(editor, {insert,{'end',Str}}),
scroll_to_show_last_line(),
loop(Win, Pid, Prompt, Parse);
{gs,_,destroy,_,_} ->
io:format("Destroyed~n",[]),
Pid ! {self(), closed};
{gs, entry,keypress,_,['Return'|_]} ->
Text = gs:read(entry, text),
io:format("Read:~p~n",[Text]),
gs:config(entry, {delete,{0,last}}),
gs:config(entry, {insert,{0,Prompt}}),
case (catch Parse(Text)) of
{'EXIT', _Error} ->
self() ! {insert, "** bad input**\n** /h for help\n"};
Term ->
Pid ! {self(), Term}
end,
loop(Win, Pid, Prompt, Parse);
{gs,_,configure,[],[W,H,_,_]} ->
gs:config(packer, [{width,W},{height,H}]),
loop(Win, Pid, Prompt, Parse);
{gs, entry,keypress,_,_} ->
loop(Win, Pid, Prompt, Parse);
Any ->
io:format("Discarded:~p~n",[Any]),
loop(Win, Pid, Prompt, Parse)
end.
scroll_to_show_last_line() ->
Size = gs:read(editor, size),
Height = gs:read(editor, height),
CharHeight = gs:read(editor, char_height),
TopRow = Size - Height/CharHeight,
if TopRow > 0 -> gs:config(editor, {vscrollpos, TopRow});
true -> gs:config(editor, {vscrollpos, 0})
end.
test() ->
spawn(fun() -> test1() end).
test1() ->
W = io_widget:start(self()),
io_widget:set_title(W, "Test window"),
loop(W).
loop(W) ->
receive
{W, {str, Str}} ->
Str1 = Str ++ "\n",
io_widget:insert_str(W, Str1),
loop(W)
end.
parse(Str) ->
{str, Str}.
| null | https://raw.githubusercontent.com/everpeace/programming-erlang-code/8ef31aa13d15b41754dda225c50284915c29cb48/code/lib_io_widget.erl | erlang | this clobbers the line being input ...
this could be fixed - hint | -module(lib_io_widget).
-export([start/1, test/0,
set_handler/2, set_prompt/2, set_title/2, insert_str/2]).
start(Pid) ->
gs:start(),
spawn_link(fun() -> widget(Pid) end).
set_title(Pid, Str) -> Pid ! {title, Str}.
set_handler(Pid, Fun) -> Pid ! {handler, Fun}.
set_prompt(Pid, Str) -> Pid ! {prompt, Str}.
insert_str(Pid, Str) -> Pid ! {insert, Str}.
widget(Pid) ->
Size = [{width,500},{height,200}],
Win = gs:window(gs:start(),
[{map,true},{configure,true},{title,"window"}|Size]),
gs:frame(packer, Win,[{packer_x, [{stretch,1,500}]},
{packer_y, [{stretch,10,120,100},
{stretch,1,15,15}]}]),
gs:create(editor,editor,packer, [{pack_x,1},{pack_y,1},{vscroll,right}]),
gs:create(entry, entry, packer, [{pack_x,1},{pack_y,2},{keypress,true}]),
gs:config(packer, Size),
Prompt = " > ",
gs:config(entry, {insert,{0,Prompt}}),
loop(Win, Pid, Prompt, fun parse/1).
loop(Win, Pid, Prompt, Parse) ->
receive
{handler, Fun} ->
loop(Win, Pid, Prompt, Fun);
{prompt, Str} ->
gs:config(entry, {delete,{0,last}}),
gs:config(entry, {insert,{0,Str}}),
loop(Win, Pid, Str, Parse);
{title, Str} ->
gs:config(Win, [{title, Str}]),
loop(Win, Pid, Prompt, Parse);
{insert, Str} ->
gs:config(editor, {insert,{'end',Str}}),
scroll_to_show_last_line(),
loop(Win, Pid, Prompt, Parse);
{gs,_,destroy,_,_} ->
io:format("Destroyed~n",[]),
Pid ! {self(), closed};
{gs, entry,keypress,_,['Return'|_]} ->
Text = gs:read(entry, text),
io:format("Read:~p~n",[Text]),
gs:config(entry, {delete,{0,last}}),
gs:config(entry, {insert,{0,Prompt}}),
case (catch Parse(Text)) of
{'EXIT', _Error} ->
self() ! {insert, "** bad input**\n** /h for help\n"};
Term ->
Pid ! {self(), Term}
end,
loop(Win, Pid, Prompt, Parse);
{gs,_,configure,[],[W,H,_,_]} ->
gs:config(packer, [{width,W},{height,H}]),
loop(Win, Pid, Prompt, Parse);
{gs, entry,keypress,_,_} ->
loop(Win, Pid, Prompt, Parse);
Any ->
io:format("Discarded:~p~n",[Any]),
loop(Win, Pid, Prompt, Parse)
end.
scroll_to_show_last_line() ->
Size = gs:read(editor, size),
Height = gs:read(editor, height),
CharHeight = gs:read(editor, char_height),
TopRow = Size - Height/CharHeight,
if TopRow > 0 -> gs:config(editor, {vscrollpos, TopRow});
true -> gs:config(editor, {vscrollpos, 0})
end.
test() ->
spawn(fun() -> test1() end).
test1() ->
W = io_widget:start(self()),
io_widget:set_title(W, "Test window"),
loop(W).
loop(W) ->
receive
{W, {str, Str}} ->
Str1 = Str ++ "\n",
io_widget:insert_str(W, Str1),
loop(W)
end.
parse(Str) ->
{str, Str}.
|
0914c65309955bc7a582d4af35de2fdf4c8c30d17b4f558983f854ecb19b1fa4 | samrocketman/home | text-neon-logo.scm | ; Another neon-like logo
Written by
; Released under GPL v.2
(define (script-fu-text-neon-logo text
size
font
grow
halogrow
neon-color
dazzle-color
halo-color
bg-color)
(let* (
(old-fg (car (gimp-context-get-foreground)))
(old-bg (car (gimp-context-get-background)))
(img (car (gimp-image-new 256 256 RGB)))
(border (/ size 4))
(neon-layer (car (gimp-text-fontname img -1 0 0 text border TRUE size PIXELS font)))
(width (car (gimp-drawable-width neon-layer)))
(height (car (gimp-drawable-height neon-layer)))
(bg-layer (car (gimp-layer-new img width height RGBA-IMAGE "Background" 100 NORMAL-MODE)))
(outline-layer 0)
(halo-layer 0)
)
; Sets the layers.
(gimp-context-set-foreground halo-color)
(gimp-image-resize img width height 0 0)
; Enlarge or shrink the font before copying the layer.
(if (> grow 0)
(while (> grow 0)
(plug-in-vpropagate 1 img neon-layer 6 15 1 15 0 255)
(set! grow (- grow 1))
)
)
(if (< grow 0)
(while (< grow 0)
(plug-in-vpropagate 1 img neon-layer 7 15 1 15 0 255)
(set! grow (+ grow 1))
)
)
(gimp-selection-layer-alpha neon-layer)
(gimp-edit-fill neon-layer FOREGROUND-FILL)
(gimp-selection-none img)
(set! outline-layer (car (gimp-layer-copy neon-layer TRUE)))
(set! halo-layer (car (gimp-layer-copy neon-layer TRUE)))
(gimp-drawable-set-name neon-layer text)
(gimp-drawable-set-name outline-layer "Outline")
(gimp-drawable-set-name halo-layer "Glow")
(gimp-image-add-layer img outline-layer 1)
(gimp-image-add-layer img halo-layer 2)
(gimp-image-add-layer img bg-layer 3)
; Background.
(gimp-context-set-background bg-color)
(gimp-edit-fill bg-layer BACKGROUND-FILL)
Halo .
(while (> halogrow 0)
(plug-in-vpropagate 1 img halo-layer 6 15 1 15 0 255)
(set! halogrow (- halogrow 1))
)
(plug-in-gauss-iir2 1 img halo-layer 50 50)
; Neon tubes.
(gimp-context-set-foreground dazzle-color)
(gimp-context-set-background neon-color)
(gimp-selection-layer-alpha neon-layer)
(gimp-edit-blend neon-layer 0 NORMAL-MODE 7 100 0 0 FALSE FALSE 1 0 TRUE 0 0 1 1)
(gimp-selection-none img)
; Outline.
XXX : Why does n't the edge detect recognise the text edges ? ?
(gimp-context-set-foreground halo-color)
(gimp-context-set-background bg-color)
(gimp-selection-layer-alpha outline-layer)
(gimp-edit-fill outline-layer BACKGROUND-FILL)
(gimp-selection-none img)
(plug-in-sobel 1 img outline-layer TRUE TRUE TRUE)
;(gimp-layer-set-mode outline-layer SCREEN-MODE)
(gimp-selection-layer-alpha outline-layer)
(gimp-edit-fill outline-layer FOREGROUND-FILL)
(gimp-selection-none img)
(gimp-context-set-background old-bg)
(gimp-context-set-foreground old-fg)
(gimp-display-new img)
)
)
;(script-fu-register "script-fu-text-neon-logo"
; _"<Toolbox>/Xtns/Script-Fu/Logos/Neon Like Text..."
; "Very customisable neon-like logo"
" aka "
" aka "
" 2003 " " "
; SF-STRING _"Text" "-*-eras-medium-*-*-*-24-*-*-*-*-*-*-*"
SF - ADJUSTMENT _ " Font size ( pixels ) " ' ( 160 2 1000 1 10 0 1 )
SF - FONT _ " " " "
; SF-ADJUSTMENT _"Text Enlargment Factor" '(0 -10 10 1 10 0 1)
SF - ADJUSTMENT _ " Halo Enlargment Factor " ' ( 8 0 16 1 10 0 1 )
SF - COLOR _ " Dazzle Neon Color " ' ( 0 255 255 )
SF - COLOR _ " Dazzle Neon Color " ' ( 239 255 255 )
SF - COLOR _ " Halo color " ' ( 0 0 255 )
SF - COLOR _ " Background color " ' ( 0 0 0 )
; )
(script-fu-register "script-fu-text-neon-logo"
_"Neon Like Text..."
" "
"Laurence Colombet aka Laura Dove"
"Laurence Colombet aka Laura Dove"
"2003" ""
SF-STRING _"Text" "NEON"
SF-ADJUSTMENT _"Font size (pixels)" '(160 2 1000 1 10 0 1)
SF-FONT _"Font" "Blippo"
SF-ADJUSTMENT _" " '(0 -10 10 1 10 0 1)
SF-ADJUSTMENT _" " '(8 0 16 1 10 0 1)
SF-COLOR _" " '(0 255 255)
SF-COLOR _" " '(239 255 255)
SF-COLOR _" " '(0 0 255)
SF-COLOR _" " '(0 0 0)
)
(script-fu-menu-register "script-fu-text-neon-logo"
_"<Toolbox>/Xtns/Extra Logos") | null | https://raw.githubusercontent.com/samrocketman/home/63a8668a71dc594ea9ed76ec56bf8ca43b2a86ca/dotfiles/.gimp/scripts/text-neon-logo.scm | scheme | Another neon-like logo
Released under GPL v.2
Sets the layers.
Enlarge or shrink the font before copying the layer.
Background.
Neon tubes.
Outline.
(gimp-layer-set-mode outline-layer SCREEN-MODE)
(script-fu-register "script-fu-text-neon-logo"
_"<Toolbox>/Xtns/Script-Fu/Logos/Neon Like Text..."
"Very customisable neon-like logo"
SF-STRING _"Text" "-*-eras-medium-*-*-*-24-*-*-*-*-*-*-*"
SF-ADJUSTMENT _"Text Enlargment Factor" '(0 -10 10 1 10 0 1)
) | Written by
(define (script-fu-text-neon-logo text
size
font
grow
halogrow
neon-color
dazzle-color
halo-color
bg-color)
(let* (
(old-fg (car (gimp-context-get-foreground)))
(old-bg (car (gimp-context-get-background)))
(img (car (gimp-image-new 256 256 RGB)))
(border (/ size 4))
(neon-layer (car (gimp-text-fontname img -1 0 0 text border TRUE size PIXELS font)))
(width (car (gimp-drawable-width neon-layer)))
(height (car (gimp-drawable-height neon-layer)))
(bg-layer (car (gimp-layer-new img width height RGBA-IMAGE "Background" 100 NORMAL-MODE)))
(outline-layer 0)
(halo-layer 0)
)
(gimp-context-set-foreground halo-color)
(gimp-image-resize img width height 0 0)
(if (> grow 0)
(while (> grow 0)
(plug-in-vpropagate 1 img neon-layer 6 15 1 15 0 255)
(set! grow (- grow 1))
)
)
(if (< grow 0)
(while (< grow 0)
(plug-in-vpropagate 1 img neon-layer 7 15 1 15 0 255)
(set! grow (+ grow 1))
)
)
(gimp-selection-layer-alpha neon-layer)
(gimp-edit-fill neon-layer FOREGROUND-FILL)
(gimp-selection-none img)
(set! outline-layer (car (gimp-layer-copy neon-layer TRUE)))
(set! halo-layer (car (gimp-layer-copy neon-layer TRUE)))
(gimp-drawable-set-name neon-layer text)
(gimp-drawable-set-name outline-layer "Outline")
(gimp-drawable-set-name halo-layer "Glow")
(gimp-image-add-layer img outline-layer 1)
(gimp-image-add-layer img halo-layer 2)
(gimp-image-add-layer img bg-layer 3)
(gimp-context-set-background bg-color)
(gimp-edit-fill bg-layer BACKGROUND-FILL)
Halo .
(while (> halogrow 0)
(plug-in-vpropagate 1 img halo-layer 6 15 1 15 0 255)
(set! halogrow (- halogrow 1))
)
(plug-in-gauss-iir2 1 img halo-layer 50 50)
(gimp-context-set-foreground dazzle-color)
(gimp-context-set-background neon-color)
(gimp-selection-layer-alpha neon-layer)
(gimp-edit-blend neon-layer 0 NORMAL-MODE 7 100 0 0 FALSE FALSE 1 0 TRUE 0 0 1 1)
(gimp-selection-none img)
XXX : Why does n't the edge detect recognise the text edges ? ?
(gimp-context-set-foreground halo-color)
(gimp-context-set-background bg-color)
(gimp-selection-layer-alpha outline-layer)
(gimp-edit-fill outline-layer BACKGROUND-FILL)
(gimp-selection-none img)
(plug-in-sobel 1 img outline-layer TRUE TRUE TRUE)
(gimp-selection-layer-alpha outline-layer)
(gimp-edit-fill outline-layer FOREGROUND-FILL)
(gimp-selection-none img)
(gimp-context-set-background old-bg)
(gimp-context-set-foreground old-fg)
(gimp-display-new img)
)
)
" aka "
" aka "
" 2003 " " "
SF - ADJUSTMENT _ " Font size ( pixels ) " ' ( 160 2 1000 1 10 0 1 )
SF - FONT _ " " " "
SF - ADJUSTMENT _ " Halo Enlargment Factor " ' ( 8 0 16 1 10 0 1 )
SF - COLOR _ " Dazzle Neon Color " ' ( 0 255 255 )
SF - COLOR _ " Dazzle Neon Color " ' ( 239 255 255 )
SF - COLOR _ " Halo color " ' ( 0 0 255 )
SF - COLOR _ " Background color " ' ( 0 0 0 )
(script-fu-register "script-fu-text-neon-logo"
_"Neon Like Text..."
" "
"Laurence Colombet aka Laura Dove"
"Laurence Colombet aka Laura Dove"
"2003" ""
SF-STRING _"Text" "NEON"
SF-ADJUSTMENT _"Font size (pixels)" '(160 2 1000 1 10 0 1)
SF-FONT _"Font" "Blippo"
SF-ADJUSTMENT _" " '(0 -10 10 1 10 0 1)
SF-ADJUSTMENT _" " '(8 0 16 1 10 0 1)
SF-COLOR _" " '(0 255 255)
SF-COLOR _" " '(239 255 255)
SF-COLOR _" " '(0 0 255)
SF-COLOR _" " '(0 0 0)
)
(script-fu-menu-register "script-fu-text-neon-logo"
_"<Toolbox>/Xtns/Extra Logos") |
40890317e7c95df3c5d96522e469f17b32510f8e02365a2dbacc912bed3e9538 | cacay/regexp | DFASpec.hs | {-# LANGUAGE GADTs #-}
# LANGUAGE OverloadedLists #
module RegExp.Internal.DFASpec where
import Test.Hspec
import Test.QuickCheck
import Helpers
import Data.Either(isRight)
import RegExp.RegExp
import RegExp.Internal.DFA
import RegExp.Derivative(equivalent)
import Data.GSet()
spec :: Spec
spec = do
describe "regexp" $ do
it "is the inverse of fromRegExp" $ do
mapSize (`div` 4) $
property $ \(r :: RegExp Helpers.Small) ->
regexp (fromRegExp r) `shouldSatisfy` (isRight . equivalent r)
| null | https://raw.githubusercontent.com/cacay/regexp/25fd123edb00ce0dbd8b6fd6732a7aeca37e4a47/test/RegExp/Internal/DFASpec.hs | haskell | # LANGUAGE GADTs # | # LANGUAGE OverloadedLists #
module RegExp.Internal.DFASpec where
import Test.Hspec
import Test.QuickCheck
import Helpers
import Data.Either(isRight)
import RegExp.RegExp
import RegExp.Internal.DFA
import RegExp.Derivative(equivalent)
import Data.GSet()
spec :: Spec
spec = do
describe "regexp" $ do
it "is the inverse of fromRegExp" $ do
mapSize (`div` 4) $
property $ \(r :: RegExp Helpers.Small) ->
regexp (fromRegExp r) `shouldSatisfy` (isRight . equivalent r)
|
69b07175f8d791dc6aff06f652a005d00dbe0857a663ad094631149e73c087c3 | gonzojive/sbcl | ntrace.lisp | ;;;; a tracing facility
This software is part of the SBCL system . See the README file for
;;;; more information.
;;;;
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
;;;; public domain. The software is in the public domain and is
;;;; provided with absolutely no warranty. See the COPYING and CREDITS
;;;; files for more information.
( SB- , not SB ! , since we 're built in warm load . )
;;; FIXME: Why, oh why, doesn't the SB-DEBUG package use the SB-DI
;;; package? That would let us get rid of a whole lot of stupid
;;; prefixes..
(defvar *trace-values* nil
#+sb-doc
"This is bound to the returned values when evaluating :BREAK-AFTER and
:PRINT-AFTER forms.")
(defvar *trace-indentation-step* 2
#+sb-doc
"the increase in trace indentation at each call level")
(defvar *max-trace-indentation* 40
#+sb-doc
"If the trace indentation exceeds this value, then indentation restarts at
0.")
(defvar *trace-encapsulate-default* t
#+sb-doc
"the default value for the :ENCAPSULATE option to TRACE")
;;;; internal state
a hash table that maps each traced function to the TRACE - INFO . The
;;; entry for a closure is the shared function entry object.
(defvar *traced-funs* (make-hash-table :test 'eq :synchronized t))
;;; A TRACE-INFO object represents all the information we need to
;;; trace a given function.
(def!struct (trace-info
(:make-load-form-fun sb-kernel:just-dump-it-normally)
(:print-object (lambda (x stream)
(print-unreadable-object (x stream :type t)
(prin1 (trace-info-what x) stream)))))
;; the original representation of the thing traced
(what nil :type (or function cons symbol))
;; Is WHAT a function name whose definition we should track?
(named nil)
;; Is tracing to be done by encapsulation rather than breakpoints?
;; T implies NAMED.
(encapsulated *trace-encapsulate-default*)
;; Has this trace been untraced?
(untraced nil)
;; breakpoints we set up to trigger tracing
(start-breakpoint nil :type (or sb-di:breakpoint null))
(end-breakpoint nil :type (or sb-di:breakpoint null))
the list of function names for WHEREIN , or NIL if unspecified
(wherein nil :type list)
;; should we trace methods given a generic function to trace?
(methods nil)
;; The following slots represent the forms that we are supposed to
;; evaluate on each iteration. Each form is represented by a cons
;; (Form . Function), where the Function is the cached result of
;; coercing Form to a function. Forms which use the current
;; environment are converted with PREPROCESS-FOR-EVAL, which gives
us a one - arg function . Null environment forms also have one - arg
;; functions, but the argument is ignored. NIL means unspecified
;; (the default.)
;; current environment forms
(condition nil)
(break nil)
;; List of current environment forms
(print () :type list)
;; null environment forms
(condition-after nil)
(break-after nil)
;; list of null environment forms
(print-after () :type list))
;;; This is a list of conses (fun-end-cookie . condition-satisfied),
;;; which we use to note distinct dynamic entries into functions. When
;;; we enter a traced function, we add a entry to this list holding
;;; the new end-cookie and whether the trace condition was satisfied.
;;; We must save the trace condition so that the after breakpoint
;;; knows whether to print. The length of this list tells us the
indentation to use for printing TRACE messages .
;;;
This list also helps us synchronize the TRACE facility dynamically
;;; for detecting non-local flow of control. Whenever execution hits a
;;; :FUN-END breakpoint used for TRACE'ing, we look for the
FUN - END - COOKIE at the top of * TRACED - ENTRIES * . If it is not
;;; there, we discard any entries that come before our cookie.
;;;
;;; When we trace using encapsulation, we bind this variable and add
( NIL . CONDITION - SATISFIED ) , so a NIL " cookie " marks an
;;; encapsulated tracing.
(defvar *traced-entries* ())
(declaim (list *traced-entries*))
;;; This variable is used to discourage infinite recursions when some
;;; trace action invokes a function that is itself traced. In this
;;; case, we quietly ignore the inner tracing.
(defvar *in-trace* nil)
;;;; utilities
;;; Given a function name, a function or a macro name, return the raw
;;; definition and some information. "Raw" means that if the result is
;;; a closure, we strip off the closure and return the bare code. The
second value is T if the argument was a function name . The third
value is one of : COMPILED , : COMPILED - CLOSURE , : INTERPRETED ,
: INTERPRETED - CLOSURE and : FUNCALLABLE - INSTANCE .
(defun trace-fdefinition (x)
(multiple-value-bind (res named-p)
(typecase x
(symbol
(cond ((special-operator-p x)
(error "can't trace special form ~S" x))
((macro-function x))
(t
(values (fdefinition x) t))))
(function x)
(t (values (fdefinition x) t)))
(typecase res
(closure
(values (sb-kernel:%closure-fun res)
named-p
:compiled-closure))
(funcallable-instance
(values res named-p :funcallable-instance))
FIXME : What about SB!EVAL : INTERPRETED - FUNCTION -- it gets picked off
;; by the FIN above, is that right?
(t
(values res named-p :compiled)))))
;;; When a function name is redefined, and we were tracing that name,
;;; then untrace the old definition and trace the new one.
(defun trace-redefined-update (fname new-value)
(when (fboundp fname)
(let* ((fun (trace-fdefinition fname))
(info (gethash fun *traced-funs*)))
(when (and info (trace-info-named info))
(untrace-1 fname)
(trace-1 fname info new-value)))))
(push #'trace-redefined-update *setf-fdefinition-hook*)
;;; Annotate a FORM to evaluate with pre-converted functions. FORM is
really a cons ( EXP . FUNCTION ) . LOC is the code location to use
for the lexical environment . If LOC is NIL , evaluate in the null
environment . If FORM is NIL , just return NIL .
(defun coerce-form (form loc)
(when form
(let ((exp (car form)))
(if (sb-di:code-location-p loc)
(let ((fun (sb-di:preprocess-for-eval exp loc)))
(declare (type function fun))
(cons exp
(lambda (frame)
(let ((*current-frame* frame))
(funcall fun frame)))))
(let* ((bod (ecase loc
((nil) exp)
(:encapsulated
`(locally (declare (disable-package-locks sb-debug:arg arg-list))
(flet ((sb-debug:arg (n)
(declare (special arg-list))
(elt arg-list n)))
(declare (ignorable #'sb-debug:arg)
(enable-package-locks sb-debug:arg arg-list))
,exp)))))
(fun (coerce `(lambda () ,bod) 'function)))
(cons exp
(lambda (frame)
(declare (ignore frame))
(let ((*current-frame* nil))
(funcall fun)))))))))
(defun coerce-form-list (forms loc)
(mapcar (lambda (x) (coerce-form x loc)) forms))
;;; Print indentation according to the number of trace entries.
;;; Entries whose condition was false don't count.
(defun print-trace-indentation ()
(let ((depth 0))
(dolist (entry *traced-entries*)
(when (cdr entry) (incf depth)))
(format t
"~V,0@T~W: "
(+ (mod (* depth *trace-indentation-step*)
(- *max-trace-indentation* *trace-indentation-step*))
*trace-indentation-step*)
depth)))
;;; Return true if any of the NAMES appears on the stack below FRAME.
(defun trace-wherein-p (frame names)
(do ((frame (sb-di:frame-down frame) (sb-di:frame-down frame)))
((not frame) nil)
(when (member (sb-di:debug-fun-name (sb-di:frame-debug-fun frame))
names
:test #'equal)
(return t))))
;;; Handle PRINT and PRINT-AFTER options.
(defun trace-print (frame forms)
(dolist (ele forms)
(fresh-line)
(print-trace-indentation)
(format t "~@<~S ~_= ~S~:>" (car ele) (funcall (cdr ele) frame))
(terpri)))
;;; Test a BREAK option, and if true, break.
(defun trace-maybe-break (info break where frame)
(when (and break (funcall (cdr break) frame))
(sb-di:flush-frames-above frame)
(let ((*stack-top-hint* frame))
(break "breaking ~A traced call to ~S:"
where
(trace-info-what info)))))
;;; Discard any invalid cookies on our simulated stack. Encapsulated
;;; entries are always valid, since we bind *TRACED-ENTRIES* in the
;;; encapsulation.
(defun discard-invalid-entries (frame)
(loop
(when (or (null *traced-entries*)
(let ((cookie (caar *traced-entries*)))
(or (not cookie)
(sb-di:fun-end-cookie-valid-p frame cookie))))
(return))
(pop *traced-entries*)))
;;;; hook functions
;;; Return a closure that can be used for a function start breakpoint
hook function and a closure that can be used as the FUN - END - COOKIE
function . The first communicates the sense of the
TRACE - INFO - CONDITION to the second via a closure variable .
(defun trace-start-breakpoint-fun (info)
(let (conditionp)
(values
(lambda (frame bpt)
(declare (ignore bpt))
(discard-invalid-entries frame)
(let ((condition (trace-info-condition info))
(wherein (trace-info-wherein info)))
(setq conditionp
(and (not *in-trace*)
(or (not condition)
(funcall (cdr condition) frame))
(or (not wherein)
(trace-wherein-p frame wherein)))))
(when conditionp
(let ((sb-kernel:*current-level-in-print* 0)
(*standard-output* (make-string-output-stream))
(*in-trace* t))
(fresh-line)
(print-trace-indentation)
(if (trace-info-encapsulated info)
;; FIXME: These special variables should be given
;; *FOO*-style names, and probably declared globally
;; with DEFVAR.
(locally
(declare (special basic-definition arg-list))
(prin1 `(,(trace-info-what info)
,@(mapcar #'ensure-printable-object arg-list))))
(print-frame-call frame *standard-output*))
(terpri)
(trace-print frame (trace-info-print info))
(write-sequence (get-output-stream-string *standard-output*)
*trace-output*)
(finish-output *trace-output*))
(trace-maybe-break info (trace-info-break info) "before" frame)))
(lambda (frame cookie)
(declare (ignore frame))
(push (cons cookie conditionp) *traced-entries*)))))
;;; This prints a representation of the return values delivered.
First , this checks to see that cookie is at the top of
;;; *TRACED-ENTRIES*; if it is not, then we need to adjust this list
;;; to determine the correct indentation for output. We then check to
;;; see whether the function is still traced and that the condition
;;; succeeded before printing anything.
(declaim (ftype (function (trace-info) function) trace-end-breakpoint-fun))
(defun trace-end-breakpoint-fun (info)
(lambda (frame bpt *trace-values* cookie)
(declare (ignore bpt))
(unless (eq cookie (caar *traced-entries*))
(setf *traced-entries*
(member cookie *traced-entries* :key #'car)))
(let ((entry (pop *traced-entries*)))
(when (and (not (trace-info-untraced info))
(or (cdr entry)
(let ((cond (trace-info-condition-after info)))
(and cond (funcall (cdr cond) frame)))))
(let ((sb-kernel:*current-level-in-print* 0)
(*standard-output* (make-string-output-stream))
(*in-trace* t))
(fresh-line)
(let ((*print-pretty* t))
(pprint-logical-block (*standard-output* nil)
(print-trace-indentation)
(pprint-indent :current 2)
(format t "~S returned" (trace-info-what info))
(dolist (v *trace-values*)
(write-char #\space)
(pprint-newline :linear)
(prin1 (ensure-printable-object v))))
(terpri))
(trace-print frame (trace-info-print-after info))
(write-sequence (get-output-stream-string *standard-output*)
*trace-output*)
(finish-output *trace-output*))
(trace-maybe-break info
(trace-info-break-after info)
"after"
frame)))))
;;; This function is called by the trace encapsulation. It calls the
;;; breakpoint hook functions with NIL for the breakpoint and cookie,
;;; which we have cleverly contrived to work for our hook functions.
(defun trace-call (info)
(multiple-value-bind (start cookie) (trace-start-breakpoint-fun info)
(declare (type function start cookie))
(let ((frame (sb-di:frame-down (sb-di:top-frame))))
(funcall start frame nil)
(let ((*traced-entries* *traced-entries*))
(declare (special basic-definition arg-list))
(funcall cookie frame nil)
(let ((vals
(multiple-value-list
(apply basic-definition arg-list))))
(funcall (trace-end-breakpoint-fun info) frame nil vals nil)
(values-list vals))))))
Trace one function according to the specified options . We copy the
;;; trace info (it was a quoted constant), fill in the functions, and
;;; then install the breakpoints or encapsulation.
;;;
;;; If non-null, DEFINITION is the new definition of a function that
;;; we are automatically retracing.
(defun trace-1 (function-or-name info &optional definition)
(multiple-value-bind (fun named kind)
(if definition
(values definition t
(nth-value 2 (trace-fdefinition definition)))
(trace-fdefinition function-or-name))
(when (gethash fun *traced-funs*)
(warn "~S is already TRACE'd, untracing it first." function-or-name)
(untrace-1 fun))
(let* ((debug-fun (sb-di:fun-debug-fun fun))
(encapsulated
(if (eq (trace-info-encapsulated info) :default)
(ecase kind
(:compiled nil)
(:compiled-closure
(unless (functionp function-or-name)
(warn "tracing shared code for ~S:~% ~S"
function-or-name
fun))
nil)
((:interpreted :interpreted-closure :funcallable-instance)
t))
(trace-info-encapsulated info)))
(loc (if encapsulated
:encapsulated
(sb-di:debug-fun-start-location debug-fun)))
(info (make-trace-info
:what function-or-name
:named named
:encapsulated encapsulated
:wherein (trace-info-wherein info)
:methods (trace-info-methods info)
:condition (coerce-form (trace-info-condition info) loc)
:break (coerce-form (trace-info-break info) loc)
:print (coerce-form-list (trace-info-print info) loc)
:break-after (coerce-form (trace-info-break-after info) nil)
:condition-after
(coerce-form (trace-info-condition-after info) nil)
:print-after
(coerce-form-list (trace-info-print-after info) nil))))
(dolist (wherein (trace-info-wherein info))
(unless (or (stringp wherein)
(fboundp wherein))
(warn ":WHEREIN name ~S is not a defined global function."
wherein)))
(cond
(encapsulated
(unless named
(error "can't use encapsulation to trace anonymous function ~S"
fun))
(encapsulate function-or-name 'trace `(trace-call ',info)))
(t
(multiple-value-bind (start-fun cookie-fun)
(trace-start-breakpoint-fun info)
(let ((start (sb-di:make-breakpoint start-fun debug-fun
:kind :fun-start))
(end (sb-di:make-breakpoint
(trace-end-breakpoint-fun info)
debug-fun :kind :fun-end
:fun-end-cookie cookie-fun)))
(setf (trace-info-start-breakpoint info) start)
(setf (trace-info-end-breakpoint info) end)
The next two forms must be in the order in which they
;; appear, since the start breakpoint must run before the
;; fun-end breakpoint's start helper (which calls the
cookie function . ) One reason is that cookie function
requires that the CONDITIONP shared closure variable be
;; initialized.
(sb-di:activate-breakpoint start)
(sb-di:activate-breakpoint end)))))
(setf (gethash fun *traced-funs*) info))
(when (and (typep fun 'generic-function)
(trace-info-methods info)
;; we are going to trace the method functions directly.
(not (trace-info-encapsulated info)))
(dolist (method (sb-mop:generic-function-methods fun))
(let ((mf (sb-mop:method-function method)))
;; NOTE: this direct style of tracing methods -- tracing the
pcl - internal method functions -- is only one possible
;; alternative. It fails (a) when encapulation is
;; requested, because the function objects themselves are
;; stored in the method object; (b) when the method in
;; question is particularly simple, when the method
functionality is in the dfun . See src / pcl / env.lisp for a
;; stub implementation of encapsulating through a
;; traced-method class.
(trace-1 mf info)
(when (typep mf 'sb-pcl::%method-function)
(trace-1 (sb-pcl::%method-function-fast-function mf) info))))))
function-or-name)
;;;; the TRACE macro
Parse leading trace options off of SPECS , modifying INFO
;;; accordingly. The remaining portion of the list is returned when we
;;; encounter a plausible function name.
(defun parse-trace-options (specs info)
(let ((current specs))
(loop
(when (endp current) (return))
(let ((option (first current))
(value (cons (second current) nil)))
(case option
(:report (error "stub: The :REPORT option is not yet implemented."))
(:condition (setf (trace-info-condition info) value))
(:condition-after
(setf (trace-info-condition info) (cons nil nil))
(setf (trace-info-condition-after info) value))
(:condition-all
(setf (trace-info-condition info) value)
(setf (trace-info-condition-after info) value))
(:wherein
(setf (trace-info-wherein info)
(if (listp (car value)) (car value) value)))
(:encapsulate
(setf (trace-info-encapsulated info) (car value)))
(:methods
(setf (trace-info-methods info) (car value)))
(:break (setf (trace-info-break info) value))
(:break-after (setf (trace-info-break-after info) value))
(:break-all
(setf (trace-info-break info) value)
(setf (trace-info-break-after info) value))
(:print
(setf (trace-info-print info)
(append (trace-info-print info) (list value))))
(:print-after
(setf (trace-info-print-after info)
(append (trace-info-print-after info) (list value))))
(:print-all
(setf (trace-info-print info)
(append (trace-info-print info) (list value)))
(setf (trace-info-print-after info)
(append (trace-info-print-after info) (list value))))
(t (return)))
(pop current)
(unless current
(error "missing argument to ~S TRACE option" option))
(pop current)))
current))
Compute the expansion of TRACE in the non - trivial case ( arguments
;;; specified.)
(defun expand-trace (specs)
(collect ((binds)
(forms))
(let* ((global-options (make-trace-info))
(current (parse-trace-options specs global-options)))
(loop
(when (endp current) (return))
(let ((name (pop current))
(options (copy-trace-info global-options)))
(cond
((eq name :function)
(let ((temp (gensym)))
(binds `(,temp ,(pop current)))
(forms `(trace-1 ,temp ',options))))
((and (keywordp name)
(not (or (fboundp name) (macro-function name))))
(error "unknown TRACE option: ~S" name))
((stringp name)
(let ((package (find-undeleted-package-or-lose name)))
(do-all-symbols (symbol (find-package name))
(when (eql package (symbol-package symbol))
(when (and (fboundp symbol)
(not (macro-function symbol))
(not (special-operator-p symbol)))
(forms `(trace-1 ',symbol ',options)))
(let ((setf-name `(setf ,symbol)))
(when (fboundp setf-name)
(forms `(trace-1 ',setf-name ',options))))))))
;; special-case METHOD: it itself is not a general function
name symbol , but it ( at least here ) designates one of a
;; pair of such.
((and (consp name) (eq (car name) 'method))
(when (fboundp (list* 'sb-pcl::slow-method (cdr name)))
(forms `(trace-1 ',(list* 'sb-pcl::slow-method (cdr name))
',options)))
(when (fboundp (list* 'sb-pcl::fast-method (cdr name)))
(forms `(trace-1 ',(list* 'sb-pcl::fast-method (cdr name))
',options))))
(t
(forms `(trace-1 ',name ',options))))
(setq current (parse-trace-options current options)))))
`(let ,(binds)
(list ,@(forms)))))
(defun %list-traced-funs ()
(loop for x being each hash-value in *traced-funs*
collect (trace-info-what x)))
(defmacro trace (&rest specs)
#+sb-doc
"TRACE {Option Global-Value}* {Name {Option Value}*}*
TRACE is a debugging tool that provides information when specified
functions are called. In its simplest form:
(TRACE NAME-1 NAME-2 ...)
The NAMEs are not evaluated. Each may be a symbol, denoting an
individual function, or a string, denoting all functions fbound to
symbols whose home package is the package with the given name.
Options allow modification of the default behavior. Each option is a
pair of an option keyword and a value form. Global options are
specified before the first name, and affect all functions traced by a
given use of TRACE. Options may also be interspersed with function
names, in which case they act as local options, only affecting tracing
of the immediately preceding function name. Local options override
global options.
By default, TRACE causes a printout on *TRACE-OUTPUT* each time that
one of the named functions is entered or returns. (This is the basic,
ANSI Common Lisp behavior of TRACE.) As an SBCL extension, the
:REPORT SB-EXT:PROFILE option can be used to instead cause information
to be silently recorded to be inspected later using the SB-EXT:PROFILE
function.
The following options are defined:
:REPORT Report-Type
If Report-Type is TRACE (the default) then information is reported
by printing immediately. If Report-Type is SB-EXT:PROFILE, information
is recorded for later summary by calls to SB-EXT:PROFILE. If
Report-Type is NIL, then the only effect of the trace is to execute
other options (e.g. PRINT or BREAK).
:CONDITION Form
:CONDITION-AFTER Form
:CONDITION-ALL Form
If :CONDITION is specified, then TRACE does nothing unless Form
evaluates to true at the time of the call. :CONDITION-AFTER is
similar, but suppresses the initial printout, and is tested when the
function returns. :CONDITION-ALL tries both before and after.
This option is not supported with :REPORT PROFILE.
:BREAK Form
:BREAK-AFTER Form
:BREAK-ALL Form
If specified, and Form evaluates to true, then the debugger is invoked
at the start of the function, at the end of the function, or both,
according to the respective option.
:PRINT Form
:PRINT-AFTER Form
:PRINT-ALL Form
In addition to the usual printout, the result of evaluating Form is
printed at the start of the function, at the end of the function, or
both, according to the respective option. Multiple print options cause
multiple values to be printed.
:WHEREIN Names
If specified, Names is a function name or list of names. TRACE does
nothing unless a call to one of those functions encloses the call to
this function (i.e. it would appear in a backtrace.) Anonymous
functions have string names like \"DEFUN FOO\". This option is not
supported with :REPORT PROFILE.
:ENCAPSULATE {:DEFAULT | T | NIL}
If T, the tracing is done via encapsulation (redefining the function
name) rather than by modifying the function. :DEFAULT is the default,
and means to use encapsulation for interpreted functions and funcallable
instances, breakpoints otherwise. When encapsulation is used, forms are
*not* evaluated in the function's lexical environment, but SB-DEBUG:ARG
can still be used.
:METHODS {T | NIL}
If T, any function argument naming a generic function will have its
methods traced in addition to the generic function itself.
:FUNCTION Function-Form
This is a not really an option, but rather another way of specifying
what function to trace. The Function-Form is evaluated immediately,
and the resulting function is instrumented, i.e. traced or profiled
as specified in REPORT.
:CONDITION, :BREAK and :PRINT forms are evaluated in a context which
mocks up the lexical environment of the called function, so that
SB-DEBUG:VAR and SB-DEBUG:ARG can be used. The -AFTER and -ALL forms
are evaluated in the null environment."
(if specs
(expand-trace specs)
'(%list-traced-funs)))
;;;; untracing
Untrace one function .
(defun untrace-1 (function-or-name)
(let* ((fun (trace-fdefinition function-or-name))
(info (gethash fun *traced-funs*)))
(cond
((not info)
(warn "Function is not TRACEd: ~S" function-or-name))
(t
(cond
((trace-info-encapsulated info)
(unencapsulate (trace-info-what info) 'trace))
(t
(sb-di:delete-breakpoint (trace-info-start-breakpoint info))
(sb-di:delete-breakpoint (trace-info-end-breakpoint info))))
(setf (trace-info-untraced info) t)
(remhash fun *traced-funs*)))))
Untrace all traced functions .
(defun untrace-all ()
(dolist (fun (%list-traced-funs))
(untrace-1 fun))
t)
(defun untrace-package (name)
(let ((package (find-package name)))
(when package
(dolist (fun (%list-traced-funs))
(cond ((and (symbolp fun) (eq package (symbol-package fun)))
(untrace-1 fun))
((and (consp fun) (eq 'setf (car fun))
(symbolp (second fun))
(eq package (symbol-package (second fun))))
(untrace-1 fun)))))))
(defmacro untrace (&rest specs)
#+sb-doc
"Remove tracing from the specified functions. Untraces all
functions when called with no arguments."
(if specs
`(progn
,@(loop while specs
for name = (pop specs)
collect (cond ((eq name :function)
`(untrace-1 ,(pop specs)))
((stringp name)
`(untrace-package ,name))
(t
`(untrace-1 ',name))))
t)
'(untrace-all)))
| null | https://raw.githubusercontent.com/gonzojive/sbcl/3210d8ed721541d5bba85cbf51831238990e33f1/src/code/ntrace.lisp | lisp | a tracing facility
more information.
public domain. The software is in the public domain and is
provided with absolutely no warranty. See the COPYING and CREDITS
files for more information.
FIXME: Why, oh why, doesn't the SB-DEBUG package use the SB-DI
package? That would let us get rid of a whole lot of stupid
prefixes..
internal state
entry for a closure is the shared function entry object.
A TRACE-INFO object represents all the information we need to
trace a given function.
the original representation of the thing traced
Is WHAT a function name whose definition we should track?
Is tracing to be done by encapsulation rather than breakpoints?
T implies NAMED.
Has this trace been untraced?
breakpoints we set up to trigger tracing
should we trace methods given a generic function to trace?
The following slots represent the forms that we are supposed to
evaluate on each iteration. Each form is represented by a cons
(Form . Function), where the Function is the cached result of
coercing Form to a function. Forms which use the current
environment are converted with PREPROCESS-FOR-EVAL, which gives
functions, but the argument is ignored. NIL means unspecified
(the default.)
current environment forms
List of current environment forms
null environment forms
list of null environment forms
This is a list of conses (fun-end-cookie . condition-satisfied),
which we use to note distinct dynamic entries into functions. When
we enter a traced function, we add a entry to this list holding
the new end-cookie and whether the trace condition was satisfied.
We must save the trace condition so that the after breakpoint
knows whether to print. The length of this list tells us the
for detecting non-local flow of control. Whenever execution hits a
:FUN-END breakpoint used for TRACE'ing, we look for the
there, we discard any entries that come before our cookie.
When we trace using encapsulation, we bind this variable and add
encapsulated tracing.
This variable is used to discourage infinite recursions when some
trace action invokes a function that is itself traced. In this
case, we quietly ignore the inner tracing.
utilities
Given a function name, a function or a macro name, return the raw
definition and some information. "Raw" means that if the result is
a closure, we strip off the closure and return the bare code. The
by the FIN above, is that right?
When a function name is redefined, and we were tracing that name,
then untrace the old definition and trace the new one.
Annotate a FORM to evaluate with pre-converted functions. FORM is
Print indentation according to the number of trace entries.
Entries whose condition was false don't count.
Return true if any of the NAMES appears on the stack below FRAME.
Handle PRINT and PRINT-AFTER options.
Test a BREAK option, and if true, break.
Discard any invalid cookies on our simulated stack. Encapsulated
entries are always valid, since we bind *TRACED-ENTRIES* in the
encapsulation.
hook functions
Return a closure that can be used for a function start breakpoint
FIXME: These special variables should be given
*FOO*-style names, and probably declared globally
with DEFVAR.
This prints a representation of the return values delivered.
*TRACED-ENTRIES*; if it is not, then we need to adjust this list
to determine the correct indentation for output. We then check to
see whether the function is still traced and that the condition
succeeded before printing anything.
This function is called by the trace encapsulation. It calls the
breakpoint hook functions with NIL for the breakpoint and cookie,
which we have cleverly contrived to work for our hook functions.
trace info (it was a quoted constant), fill in the functions, and
then install the breakpoints or encapsulation.
If non-null, DEFINITION is the new definition of a function that
we are automatically retracing.
appear, since the start breakpoint must run before the
fun-end breakpoint's start helper (which calls the
initialized.
we are going to trace the method functions directly.
NOTE: this direct style of tracing methods -- tracing the
alternative. It fails (a) when encapulation is
requested, because the function objects themselves are
stored in the method object; (b) when the method in
question is particularly simple, when the method
stub implementation of encapsulating through a
traced-method class.
the TRACE macro
accordingly. The remaining portion of the list is returned when we
encounter a plausible function name.
specified.)
special-case METHOD: it itself is not a general function
pair of such.
untracing |
This software is part of the SBCL system . See the README file for
This software is derived from the CMU CL system , which was
written at Carnegie Mellon University and released into the
( SB- , not SB ! , since we 're built in warm load . )
(defvar *trace-values* nil
#+sb-doc
"This is bound to the returned values when evaluating :BREAK-AFTER and
:PRINT-AFTER forms.")
(defvar *trace-indentation-step* 2
#+sb-doc
"the increase in trace indentation at each call level")
(defvar *max-trace-indentation* 40
#+sb-doc
"If the trace indentation exceeds this value, then indentation restarts at
0.")
(defvar *trace-encapsulate-default* t
#+sb-doc
"the default value for the :ENCAPSULATE option to TRACE")
a hash table that maps each traced function to the TRACE - INFO . The
(defvar *traced-funs* (make-hash-table :test 'eq :synchronized t))
(def!struct (trace-info
(:make-load-form-fun sb-kernel:just-dump-it-normally)
(:print-object (lambda (x stream)
(print-unreadable-object (x stream :type t)
(prin1 (trace-info-what x) stream)))))
(what nil :type (or function cons symbol))
(named nil)
(encapsulated *trace-encapsulate-default*)
(untraced nil)
(start-breakpoint nil :type (or sb-di:breakpoint null))
(end-breakpoint nil :type (or sb-di:breakpoint null))
the list of function names for WHEREIN , or NIL if unspecified
(wherein nil :type list)
(methods nil)
us a one - arg function . Null environment forms also have one - arg
(condition nil)
(break nil)
(print () :type list)
(condition-after nil)
(break-after nil)
(print-after () :type list))
indentation to use for printing TRACE messages .
This list also helps us synchronize the TRACE facility dynamically
FUN - END - COOKIE at the top of * TRACED - ENTRIES * . If it is not
( NIL . CONDITION - SATISFIED ) , so a NIL " cookie " marks an
(defvar *traced-entries* ())
(declaim (list *traced-entries*))
(defvar *in-trace* nil)
second value is T if the argument was a function name . The third
value is one of : COMPILED , : COMPILED - CLOSURE , : INTERPRETED ,
: INTERPRETED - CLOSURE and : FUNCALLABLE - INSTANCE .
(defun trace-fdefinition (x)
(multiple-value-bind (res named-p)
(typecase x
(symbol
(cond ((special-operator-p x)
(error "can't trace special form ~S" x))
((macro-function x))
(t
(values (fdefinition x) t))))
(function x)
(t (values (fdefinition x) t)))
(typecase res
(closure
(values (sb-kernel:%closure-fun res)
named-p
:compiled-closure))
(funcallable-instance
(values res named-p :funcallable-instance))
FIXME : What about SB!EVAL : INTERPRETED - FUNCTION -- it gets picked off
(t
(values res named-p :compiled)))))
(defun trace-redefined-update (fname new-value)
(when (fboundp fname)
(let* ((fun (trace-fdefinition fname))
(info (gethash fun *traced-funs*)))
(when (and info (trace-info-named info))
(untrace-1 fname)
(trace-1 fname info new-value)))))
(push #'trace-redefined-update *setf-fdefinition-hook*)
really a cons ( EXP . FUNCTION ) . LOC is the code location to use
for the lexical environment . If LOC is NIL , evaluate in the null
environment . If FORM is NIL , just return NIL .
(defun coerce-form (form loc)
(when form
(let ((exp (car form)))
(if (sb-di:code-location-p loc)
(let ((fun (sb-di:preprocess-for-eval exp loc)))
(declare (type function fun))
(cons exp
(lambda (frame)
(let ((*current-frame* frame))
(funcall fun frame)))))
(let* ((bod (ecase loc
((nil) exp)
(:encapsulated
`(locally (declare (disable-package-locks sb-debug:arg arg-list))
(flet ((sb-debug:arg (n)
(declare (special arg-list))
(elt arg-list n)))
(declare (ignorable #'sb-debug:arg)
(enable-package-locks sb-debug:arg arg-list))
,exp)))))
(fun (coerce `(lambda () ,bod) 'function)))
(cons exp
(lambda (frame)
(declare (ignore frame))
(let ((*current-frame* nil))
(funcall fun)))))))))
(defun coerce-form-list (forms loc)
(mapcar (lambda (x) (coerce-form x loc)) forms))
(defun print-trace-indentation ()
(let ((depth 0))
(dolist (entry *traced-entries*)
(when (cdr entry) (incf depth)))
(format t
"~V,0@T~W: "
(+ (mod (* depth *trace-indentation-step*)
(- *max-trace-indentation* *trace-indentation-step*))
*trace-indentation-step*)
depth)))
(defun trace-wherein-p (frame names)
(do ((frame (sb-di:frame-down frame) (sb-di:frame-down frame)))
((not frame) nil)
(when (member (sb-di:debug-fun-name (sb-di:frame-debug-fun frame))
names
:test #'equal)
(return t))))
(defun trace-print (frame forms)
(dolist (ele forms)
(fresh-line)
(print-trace-indentation)
(format t "~@<~S ~_= ~S~:>" (car ele) (funcall (cdr ele) frame))
(terpri)))
(defun trace-maybe-break (info break where frame)
(when (and break (funcall (cdr break) frame))
(sb-di:flush-frames-above frame)
(let ((*stack-top-hint* frame))
(break "breaking ~A traced call to ~S:"
where
(trace-info-what info)))))
(defun discard-invalid-entries (frame)
(loop
(when (or (null *traced-entries*)
(let ((cookie (caar *traced-entries*)))
(or (not cookie)
(sb-di:fun-end-cookie-valid-p frame cookie))))
(return))
(pop *traced-entries*)))
hook function and a closure that can be used as the FUN - END - COOKIE
function . The first communicates the sense of the
TRACE - INFO - CONDITION to the second via a closure variable .
(defun trace-start-breakpoint-fun (info)
(let (conditionp)
(values
(lambda (frame bpt)
(declare (ignore bpt))
(discard-invalid-entries frame)
(let ((condition (trace-info-condition info))
(wherein (trace-info-wherein info)))
(setq conditionp
(and (not *in-trace*)
(or (not condition)
(funcall (cdr condition) frame))
(or (not wherein)
(trace-wherein-p frame wherein)))))
(when conditionp
(let ((sb-kernel:*current-level-in-print* 0)
(*standard-output* (make-string-output-stream))
(*in-trace* t))
(fresh-line)
(print-trace-indentation)
(if (trace-info-encapsulated info)
(locally
(declare (special basic-definition arg-list))
(prin1 `(,(trace-info-what info)
,@(mapcar #'ensure-printable-object arg-list))))
(print-frame-call frame *standard-output*))
(terpri)
(trace-print frame (trace-info-print info))
(write-sequence (get-output-stream-string *standard-output*)
*trace-output*)
(finish-output *trace-output*))
(trace-maybe-break info (trace-info-break info) "before" frame)))
(lambda (frame cookie)
(declare (ignore frame))
(push (cons cookie conditionp) *traced-entries*)))))
First , this checks to see that cookie is at the top of
(declaim (ftype (function (trace-info) function) trace-end-breakpoint-fun))
(defun trace-end-breakpoint-fun (info)
(lambda (frame bpt *trace-values* cookie)
(declare (ignore bpt))
(unless (eq cookie (caar *traced-entries*))
(setf *traced-entries*
(member cookie *traced-entries* :key #'car)))
(let ((entry (pop *traced-entries*)))
(when (and (not (trace-info-untraced info))
(or (cdr entry)
(let ((cond (trace-info-condition-after info)))
(and cond (funcall (cdr cond) frame)))))
(let ((sb-kernel:*current-level-in-print* 0)
(*standard-output* (make-string-output-stream))
(*in-trace* t))
(fresh-line)
(let ((*print-pretty* t))
(pprint-logical-block (*standard-output* nil)
(print-trace-indentation)
(pprint-indent :current 2)
(format t "~S returned" (trace-info-what info))
(dolist (v *trace-values*)
(write-char #\space)
(pprint-newline :linear)
(prin1 (ensure-printable-object v))))
(terpri))
(trace-print frame (trace-info-print-after info))
(write-sequence (get-output-stream-string *standard-output*)
*trace-output*)
(finish-output *trace-output*))
(trace-maybe-break info
(trace-info-break-after info)
"after"
frame)))))
(defun trace-call (info)
(multiple-value-bind (start cookie) (trace-start-breakpoint-fun info)
(declare (type function start cookie))
(let ((frame (sb-di:frame-down (sb-di:top-frame))))
(funcall start frame nil)
(let ((*traced-entries* *traced-entries*))
(declare (special basic-definition arg-list))
(funcall cookie frame nil)
(let ((vals
(multiple-value-list
(apply basic-definition arg-list))))
(funcall (trace-end-breakpoint-fun info) frame nil vals nil)
(values-list vals))))))
Trace one function according to the specified options . We copy the
(defun trace-1 (function-or-name info &optional definition)
(multiple-value-bind (fun named kind)
(if definition
(values definition t
(nth-value 2 (trace-fdefinition definition)))
(trace-fdefinition function-or-name))
(when (gethash fun *traced-funs*)
(warn "~S is already TRACE'd, untracing it first." function-or-name)
(untrace-1 fun))
(let* ((debug-fun (sb-di:fun-debug-fun fun))
(encapsulated
(if (eq (trace-info-encapsulated info) :default)
(ecase kind
(:compiled nil)
(:compiled-closure
(unless (functionp function-or-name)
(warn "tracing shared code for ~S:~% ~S"
function-or-name
fun))
nil)
((:interpreted :interpreted-closure :funcallable-instance)
t))
(trace-info-encapsulated info)))
(loc (if encapsulated
:encapsulated
(sb-di:debug-fun-start-location debug-fun)))
(info (make-trace-info
:what function-or-name
:named named
:encapsulated encapsulated
:wherein (trace-info-wherein info)
:methods (trace-info-methods info)
:condition (coerce-form (trace-info-condition info) loc)
:break (coerce-form (trace-info-break info) loc)
:print (coerce-form-list (trace-info-print info) loc)
:break-after (coerce-form (trace-info-break-after info) nil)
:condition-after
(coerce-form (trace-info-condition-after info) nil)
:print-after
(coerce-form-list (trace-info-print-after info) nil))))
(dolist (wherein (trace-info-wherein info))
(unless (or (stringp wherein)
(fboundp wherein))
(warn ":WHEREIN name ~S is not a defined global function."
wherein)))
(cond
(encapsulated
(unless named
(error "can't use encapsulation to trace anonymous function ~S"
fun))
(encapsulate function-or-name 'trace `(trace-call ',info)))
(t
(multiple-value-bind (start-fun cookie-fun)
(trace-start-breakpoint-fun info)
(let ((start (sb-di:make-breakpoint start-fun debug-fun
:kind :fun-start))
(end (sb-di:make-breakpoint
(trace-end-breakpoint-fun info)
debug-fun :kind :fun-end
:fun-end-cookie cookie-fun)))
(setf (trace-info-start-breakpoint info) start)
(setf (trace-info-end-breakpoint info) end)
The next two forms must be in the order in which they
cookie function . ) One reason is that cookie function
requires that the CONDITIONP shared closure variable be
(sb-di:activate-breakpoint start)
(sb-di:activate-breakpoint end)))))
(setf (gethash fun *traced-funs*) info))
(when (and (typep fun 'generic-function)
(trace-info-methods info)
(not (trace-info-encapsulated info)))
(dolist (method (sb-mop:generic-function-methods fun))
(let ((mf (sb-mop:method-function method)))
pcl - internal method functions -- is only one possible
functionality is in the dfun . See src / pcl / env.lisp for a
(trace-1 mf info)
(when (typep mf 'sb-pcl::%method-function)
(trace-1 (sb-pcl::%method-function-fast-function mf) info))))))
function-or-name)
Parse leading trace options off of SPECS , modifying INFO
(defun parse-trace-options (specs info)
(let ((current specs))
(loop
(when (endp current) (return))
(let ((option (first current))
(value (cons (second current) nil)))
(case option
(:report (error "stub: The :REPORT option is not yet implemented."))
(:condition (setf (trace-info-condition info) value))
(:condition-after
(setf (trace-info-condition info) (cons nil nil))
(setf (trace-info-condition-after info) value))
(:condition-all
(setf (trace-info-condition info) value)
(setf (trace-info-condition-after info) value))
(:wherein
(setf (trace-info-wherein info)
(if (listp (car value)) (car value) value)))
(:encapsulate
(setf (trace-info-encapsulated info) (car value)))
(:methods
(setf (trace-info-methods info) (car value)))
(:break (setf (trace-info-break info) value))
(:break-after (setf (trace-info-break-after info) value))
(:break-all
(setf (trace-info-break info) value)
(setf (trace-info-break-after info) value))
(:print
(setf (trace-info-print info)
(append (trace-info-print info) (list value))))
(:print-after
(setf (trace-info-print-after info)
(append (trace-info-print-after info) (list value))))
(:print-all
(setf (trace-info-print info)
(append (trace-info-print info) (list value)))
(setf (trace-info-print-after info)
(append (trace-info-print-after info) (list value))))
(t (return)))
(pop current)
(unless current
(error "missing argument to ~S TRACE option" option))
(pop current)))
current))
Compute the expansion of TRACE in the non - trivial case ( arguments
(defun expand-trace (specs)
(collect ((binds)
(forms))
(let* ((global-options (make-trace-info))
(current (parse-trace-options specs global-options)))
(loop
(when (endp current) (return))
(let ((name (pop current))
(options (copy-trace-info global-options)))
(cond
((eq name :function)
(let ((temp (gensym)))
(binds `(,temp ,(pop current)))
(forms `(trace-1 ,temp ',options))))
((and (keywordp name)
(not (or (fboundp name) (macro-function name))))
(error "unknown TRACE option: ~S" name))
((stringp name)
(let ((package (find-undeleted-package-or-lose name)))
(do-all-symbols (symbol (find-package name))
(when (eql package (symbol-package symbol))
(when (and (fboundp symbol)
(not (macro-function symbol))
(not (special-operator-p symbol)))
(forms `(trace-1 ',symbol ',options)))
(let ((setf-name `(setf ,symbol)))
(when (fboundp setf-name)
(forms `(trace-1 ',setf-name ',options))))))))
name symbol , but it ( at least here ) designates one of a
((and (consp name) (eq (car name) 'method))
(when (fboundp (list* 'sb-pcl::slow-method (cdr name)))
(forms `(trace-1 ',(list* 'sb-pcl::slow-method (cdr name))
',options)))
(when (fboundp (list* 'sb-pcl::fast-method (cdr name)))
(forms `(trace-1 ',(list* 'sb-pcl::fast-method (cdr name))
',options))))
(t
(forms `(trace-1 ',name ',options))))
(setq current (parse-trace-options current options)))))
`(let ,(binds)
(list ,@(forms)))))
(defun %list-traced-funs ()
(loop for x being each hash-value in *traced-funs*
collect (trace-info-what x)))
(defmacro trace (&rest specs)
#+sb-doc
"TRACE {Option Global-Value}* {Name {Option Value}*}*
TRACE is a debugging tool that provides information when specified
functions are called. In its simplest form:
(TRACE NAME-1 NAME-2 ...)
The NAMEs are not evaluated. Each may be a symbol, denoting an
individual function, or a string, denoting all functions fbound to
symbols whose home package is the package with the given name.
Options allow modification of the default behavior. Each option is a
pair of an option keyword and a value form. Global options are
specified before the first name, and affect all functions traced by a
given use of TRACE. Options may also be interspersed with function
names, in which case they act as local options, only affecting tracing
of the immediately preceding function name. Local options override
global options.
By default, TRACE causes a printout on *TRACE-OUTPUT* each time that
one of the named functions is entered or returns. (This is the basic,
ANSI Common Lisp behavior of TRACE.) As an SBCL extension, the
:REPORT SB-EXT:PROFILE option can be used to instead cause information
to be silently recorded to be inspected later using the SB-EXT:PROFILE
function.
The following options are defined:
:REPORT Report-Type
If Report-Type is TRACE (the default) then information is reported
by printing immediately. If Report-Type is SB-EXT:PROFILE, information
is recorded for later summary by calls to SB-EXT:PROFILE. If
Report-Type is NIL, then the only effect of the trace is to execute
other options (e.g. PRINT or BREAK).
:CONDITION Form
:CONDITION-AFTER Form
:CONDITION-ALL Form
If :CONDITION is specified, then TRACE does nothing unless Form
evaluates to true at the time of the call. :CONDITION-AFTER is
similar, but suppresses the initial printout, and is tested when the
function returns. :CONDITION-ALL tries both before and after.
This option is not supported with :REPORT PROFILE.
:BREAK Form
:BREAK-AFTER Form
:BREAK-ALL Form
If specified, and Form evaluates to true, then the debugger is invoked
at the start of the function, at the end of the function, or both,
according to the respective option.
:PRINT Form
:PRINT-AFTER Form
:PRINT-ALL Form
In addition to the usual printout, the result of evaluating Form is
printed at the start of the function, at the end of the function, or
both, according to the respective option. Multiple print options cause
multiple values to be printed.
:WHEREIN Names
If specified, Names is a function name or list of names. TRACE does
nothing unless a call to one of those functions encloses the call to
this function (i.e. it would appear in a backtrace.) Anonymous
functions have string names like \"DEFUN FOO\". This option is not
supported with :REPORT PROFILE.
:ENCAPSULATE {:DEFAULT | T | NIL}
If T, the tracing is done via encapsulation (redefining the function
name) rather than by modifying the function. :DEFAULT is the default,
and means to use encapsulation for interpreted functions and funcallable
instances, breakpoints otherwise. When encapsulation is used, forms are
*not* evaluated in the function's lexical environment, but SB-DEBUG:ARG
can still be used.
:METHODS {T | NIL}
If T, any function argument naming a generic function will have its
methods traced in addition to the generic function itself.
:FUNCTION Function-Form
This is a not really an option, but rather another way of specifying
what function to trace. The Function-Form is evaluated immediately,
and the resulting function is instrumented, i.e. traced or profiled
as specified in REPORT.
:CONDITION, :BREAK and :PRINT forms are evaluated in a context which
mocks up the lexical environment of the called function, so that
SB-DEBUG:VAR and SB-DEBUG:ARG can be used. The -AFTER and -ALL forms
are evaluated in the null environment."
(if specs
(expand-trace specs)
'(%list-traced-funs)))
Untrace one function .
(defun untrace-1 (function-or-name)
(let* ((fun (trace-fdefinition function-or-name))
(info (gethash fun *traced-funs*)))
(cond
((not info)
(warn "Function is not TRACEd: ~S" function-or-name))
(t
(cond
((trace-info-encapsulated info)
(unencapsulate (trace-info-what info) 'trace))
(t
(sb-di:delete-breakpoint (trace-info-start-breakpoint info))
(sb-di:delete-breakpoint (trace-info-end-breakpoint info))))
(setf (trace-info-untraced info) t)
(remhash fun *traced-funs*)))))
Untrace all traced functions .
(defun untrace-all ()
(dolist (fun (%list-traced-funs))
(untrace-1 fun))
t)
(defun untrace-package (name)
(let ((package (find-package name)))
(when package
(dolist (fun (%list-traced-funs))
(cond ((and (symbolp fun) (eq package (symbol-package fun)))
(untrace-1 fun))
((and (consp fun) (eq 'setf (car fun))
(symbolp (second fun))
(eq package (symbol-package (second fun))))
(untrace-1 fun)))))))
(defmacro untrace (&rest specs)
#+sb-doc
"Remove tracing from the specified functions. Untraces all
functions when called with no arguments."
(if specs
`(progn
,@(loop while specs
for name = (pop specs)
collect (cond ((eq name :function)
`(untrace-1 ,(pop specs)))
((stringp name)
`(untrace-package ,name))
(t
`(untrace-1 ',name))))
t)
'(untrace-all)))
|
7f4f77ce6ae6494f876132e4c0089e697f6bd35840884358e677b04826aa7ed2 | michiakig/sicp | ex-1.06.scm | ;;;; Structure and Interpretation of Computer Programs
Chapter 1 Section 1 Elements of Programming
Exercise 1.06
does n't see why if needs to be provided as a special form . ` ` Why ca n't I just define it as an ordinary procedure in terms of cond ? '' she asks . 's friend claims this can indeed be done , and she defines a new version of if :
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))
Delighted , uses new - if to rewrite the square - root program :
(define (sqrt-iter guess x)
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
What happens when attempts to use this to compute square roots ? Explain .
;
; A: Infinite loop, because of Scheme's applicative-order evaluation, (sqrt-iter (improve guess x) x) is
; evaluated before new-if is completely evaluated, resulting in an infinite loop.
(define (improve guess x) (average guess (/ x guess)))
(define (average x y) (/ (+ x y) 2))
| null | https://raw.githubusercontent.com/michiakig/sicp/1aa445f00b7895dbfaa29cf6984b825b4e5af492/ch1/ex-1.06.scm | scheme | Structure and Interpretation of Computer Programs
A: Infinite loop, because of Scheme's applicative-order evaluation, (sqrt-iter (improve guess x) x) is
evaluated before new-if is completely evaluated, resulting in an infinite loop. | Chapter 1 Section 1 Elements of Programming
Exercise 1.06
does n't see why if needs to be provided as a special form . ` ` Why ca n't I just define it as an ordinary procedure in terms of cond ? '' she asks . 's friend claims this can indeed be done , and she defines a new version of if :
(define (new-if predicate then-clause else-clause)
(cond (predicate then-clause)
(else else-clause)))
Delighted , uses new - if to rewrite the square - root program :
(define (sqrt-iter guess x)
(new-if (good-enough? guess x)
guess
(sqrt-iter (improve guess x)
x)))
What happens when attempts to use this to compute square roots ? Explain .
(define (improve guess x) (average guess (/ x guess)))
(define (average x y) (/ (+ x y) 2))
|
c2b13856220c23137eeb0b1d773511429487b4add7d4dd04a0c031b2d98354f4 | CyberCat-Institute/open-game-engine | Diagnostics.hs | # LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
# LANGUAGE TypeApplications #
# LANGUAGE AllowAmbiguousTypes #
module OpenGames.Engine.Diagnostics
( DiagnosticInfoBayesian(..)
, generateOutput
, generateIsEq
) where
import OpenGames.Engine.OpticClass
import OpenGames.Engine.TLL
--------------------------------------------------------
-- Diagnosticinformation and processesing of information
-- for standard game-theoretic analysis
-- Defining the necessary types for outputting information of a BayesianGame
data DiagnosticInfoBayesian x y = DiagnosticInfoBayesian
{ equilibrium :: Bool
, player :: String
, optimalMove :: y
, strategy :: Stochastic y
, optimalPayoff :: Double
, context :: (y -> Double)
, payoff :: Double
, state :: x
, unobservedState :: String}
prepare string information for Bayesian game
showDiagnosticInfo :: (Show y, Ord y, Show x) => DiagnosticInfoBayesian x y -> String
showDiagnosticInfo info =
"\n" ++ "Player: " ++ player info
++ "\n" ++ "Optimal Move: " ++ (show $ optimalMove info)
++ "\n" ++ "Current Strategy: " ++ (show $ strategy info)
++ "\n" ++ "Optimal Payoff: " ++ (show $ optimalPayoff info)
++ "\n" ++ "Current Payoff: " ++ (show $ payoff info)
++ "\n" ++ "Observable State: " ++ (show $ state info)
++ "\n" ++ "Unobservable State: " ++ (show $ unobservedState info)
-- output string information for a subgame expressions containing information from several players - bayesian
showDiagnosticInfoL :: (Show y, Ord y, Show x) => [DiagnosticInfoBayesian x y] -> String
showDiagnosticInfoL [] = "\n --No more information--"
showDiagnosticInfoL (x:xs) = showDiagnosticInfo x ++ "\n --other game-- " ++ showDiagnosticInfoL xs
-- checks equilibrium and if not outputs relevant deviations
checkEqL :: (Show y, Ord y, Show x) => [DiagnosticInfoBayesian x y] -> String
checkEqL ls = let xs = fmap equilibrium ls
ys = filter (\x -> equilibrium x == False) ls
isEq = and xs
in if isEq == True then "\n Strategies are in equilibrium"
else "\n Strategies are NOT in equilibrium. Consider the following profitable deviations: \n" ++ showDiagnosticInfoL ys
----------------------------------------------------------
-- providing the relevant functionality at the type level
-- for show output
data ShowDiagnosticOutput = ShowDiagnosticOutput
instance (Show y, Ord y, Show x) => Apply ShowDiagnosticOutput [DiagnosticInfoBayesian x y] String where
apply _ x = showDiagnosticInfoL x
data PrintIsEq = PrintIsEq
instance (Show y, Ord y, Show x) => Apply PrintIsEq [DiagnosticInfoBayesian x y] String where
apply _ x = checkEqL x
instance (Show y, Ord y, Show x) => Apply PrintIsEq (Maybe [DiagnosticInfoBayesian x y]) String where
apply _ x = checkEqL (maybe [] id x)
data PrintOutput = PrintOutput
instance (Show y, Ord y, Show x) => Apply PrintOutput [DiagnosticInfoBayesian x y] String where
apply _ x = showDiagnosticInfoL x
instance (Show y, Ord y, Show x) => Apply PrintOutput (Maybe [DiagnosticInfoBayesian x y]) String where
apply _ x = showDiagnosticInfoL (maybe [] id x)
data Concat = Concat
instance Apply Concat String (String -> String) where
apply _ x = \y -> x ++ "\n NEWGAME: \n" ++ y
---------------------
-- main functionality
-- all information for all players
generateOutput :: forall xs.
( MapL PrintOutput xs (ConstMap String xs)
, FoldrL Concat String (ConstMap String xs)
) => List xs -> IO ()
generateOutput hlist = putStrLn $
"----Analytics begin----" ++ (foldrL Concat "" $ mapL @_ @_ @(ConstMap String xs) PrintOutput hlist) ++ "----Analytics end----\n"
-- output equilibrium relevant information
generateIsEq :: forall xs.
( MapL PrintIsEq xs (ConstMap String xs)
, FoldrL Concat String (ConstMap String xs)
) => List xs -> IO ()
generateIsEq hlist = putStrLn $
"----Analytics begin----" ++ (foldrL Concat "" $ mapL @_ @_ @(ConstMap String xs) PrintIsEq hlist) ++ "----Analytics end----\n"
| null | https://raw.githubusercontent.com/CyberCat-Institute/open-game-engine/86031c42bf13178554c21cd7ab9e9d18f1ca6963/src/OpenGames/Engine/Diagnostics.hs | haskell | ------------------------------------------------------
Diagnosticinformation and processesing of information
for standard game-theoretic analysis
Defining the necessary types for outputting information of a BayesianGame
output string information for a subgame expressions containing information from several players - bayesian
checks equilibrium and if not outputs relevant deviations
--------------------------------------------------------
providing the relevant functionality at the type level
for show output
-------------------
main functionality
all information for all players
output equilibrium relevant information | # LANGUAGE DataKinds #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
# LANGUAGE FlexibleContexts #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
# LANGUAGE TypeApplications #
# LANGUAGE AllowAmbiguousTypes #
module OpenGames.Engine.Diagnostics
( DiagnosticInfoBayesian(..)
, generateOutput
, generateIsEq
) where
import OpenGames.Engine.OpticClass
import OpenGames.Engine.TLL
data DiagnosticInfoBayesian x y = DiagnosticInfoBayesian
{ equilibrium :: Bool
, player :: String
, optimalMove :: y
, strategy :: Stochastic y
, optimalPayoff :: Double
, context :: (y -> Double)
, payoff :: Double
, state :: x
, unobservedState :: String}
prepare string information for Bayesian game
showDiagnosticInfo :: (Show y, Ord y, Show x) => DiagnosticInfoBayesian x y -> String
showDiagnosticInfo info =
"\n" ++ "Player: " ++ player info
++ "\n" ++ "Optimal Move: " ++ (show $ optimalMove info)
++ "\n" ++ "Current Strategy: " ++ (show $ strategy info)
++ "\n" ++ "Optimal Payoff: " ++ (show $ optimalPayoff info)
++ "\n" ++ "Current Payoff: " ++ (show $ payoff info)
++ "\n" ++ "Observable State: " ++ (show $ state info)
++ "\n" ++ "Unobservable State: " ++ (show $ unobservedState info)
showDiagnosticInfoL :: (Show y, Ord y, Show x) => [DiagnosticInfoBayesian x y] -> String
showDiagnosticInfoL [] = "\n --No more information--"
showDiagnosticInfoL (x:xs) = showDiagnosticInfo x ++ "\n --other game-- " ++ showDiagnosticInfoL xs
checkEqL :: (Show y, Ord y, Show x) => [DiagnosticInfoBayesian x y] -> String
checkEqL ls = let xs = fmap equilibrium ls
ys = filter (\x -> equilibrium x == False) ls
isEq = and xs
in if isEq == True then "\n Strategies are in equilibrium"
else "\n Strategies are NOT in equilibrium. Consider the following profitable deviations: \n" ++ showDiagnosticInfoL ys
data ShowDiagnosticOutput = ShowDiagnosticOutput
instance (Show y, Ord y, Show x) => Apply ShowDiagnosticOutput [DiagnosticInfoBayesian x y] String where
apply _ x = showDiagnosticInfoL x
data PrintIsEq = PrintIsEq
instance (Show y, Ord y, Show x) => Apply PrintIsEq [DiagnosticInfoBayesian x y] String where
apply _ x = checkEqL x
instance (Show y, Ord y, Show x) => Apply PrintIsEq (Maybe [DiagnosticInfoBayesian x y]) String where
apply _ x = checkEqL (maybe [] id x)
data PrintOutput = PrintOutput
instance (Show y, Ord y, Show x) => Apply PrintOutput [DiagnosticInfoBayesian x y] String where
apply _ x = showDiagnosticInfoL x
instance (Show y, Ord y, Show x) => Apply PrintOutput (Maybe [DiagnosticInfoBayesian x y]) String where
apply _ x = showDiagnosticInfoL (maybe [] id x)
data Concat = Concat
instance Apply Concat String (String -> String) where
apply _ x = \y -> x ++ "\n NEWGAME: \n" ++ y
generateOutput :: forall xs.
( MapL PrintOutput xs (ConstMap String xs)
, FoldrL Concat String (ConstMap String xs)
) => List xs -> IO ()
generateOutput hlist = putStrLn $
"----Analytics begin----" ++ (foldrL Concat "" $ mapL @_ @_ @(ConstMap String xs) PrintOutput hlist) ++ "----Analytics end----\n"
generateIsEq :: forall xs.
( MapL PrintIsEq xs (ConstMap String xs)
, FoldrL Concat String (ConstMap String xs)
) => List xs -> IO ()
generateIsEq hlist = putStrLn $
"----Analytics begin----" ++ (foldrL Concat "" $ mapL @_ @_ @(ConstMap String xs) PrintIsEq hlist) ++ "----Analytics end----\n"
|
535ca9664b9caa59e706ed2fe844600e4532434d7c81fecd6e2de0ecef23308a | pedestal/pedestal-app | test.clj | Copyright 2013 Relevance , Inc.
; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 ( )
; which can be found in the file epl-v10.html at the root of this distribution.
;
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
;
; You must not remove this notice, or any other, from this software.
(ns io.pedestal.app.util.test
(:require [io.pedestal.app :as app]
[io.pedestal.app.util.platform :as platform]))
(defn run-sync! [app script & {:keys [begin timeout wait-for]}]
(assert (or (nil? begin)
(= begin :default)
(vector? begin))
"begin must be nil, the keyword :default or a vector of messages")
(assert (or (nil? wait-for)
(every? #(contains? #{:output :app-model} %) wait-for))
"wait-for must be nil or a seq with a subset of #{:output :app-model}")
(let [timeout (or timeout 1000)
script (conj (vec (butlast script)) (with-meta (last script) {::last true}))
record-states (atom [@(:state app)])]
(add-watch (:state app) :state-watch
(fn [_ _ _ n]
(swap! record-states conj n)))
;; Run begin messages
(cond (= begin :default) (app/begin app)
(vector? begin) (app/begin app begin))
;; Run script
(app/run! app script)
;; Wait for all messages to be processed
(loop [tout timeout]
(let [last-input (-> app :state deref :io.pedestal.app/input)]
(when (not= (meta last-input) {::last true})
(if (neg? tout)
(throw (Exception. (str "Test timeout after " timeout "ms.\n"
" Last input: " last-input "\n"
" Meta: " (meta last-input))))
(do (Thread/sleep 20)
(recur (- tout 20)))))))
;; Wait for specified queues to be consumed
(if (seq wait-for)
(doseq [k wait-for]
(loop [queue (:queue @(.state (k app)))
c 0]
(when (> c 3)
(throw (Exception. (str "The queue " k " is not being consumed."))))
(when-not (zero? (count queue))
(Thread/sleep 20)
(let [new-queue (:queue @(.state (k app)))]
(recur new-queue
(if (= new-queue queue)
(inc c)
0)))))))
@record-states))
(defmacro refer-privates
"Refer private functions into the current namespace. Use
(refer-privates :all)
to refer all privates."
[ns s & syms]
(let [xs (if (= s :all)
(for [[_ v] (ns-interns ns)
:when (:private (meta v))]
[(:name (meta v)) v])
(mapv (fn [sym] [sym (ns-resolve ns sym)]) (cons s syms))) ]
`(do ~@(mapv (fn [[s v]] `(def ~s ~v)) xs))))
| null | https://raw.githubusercontent.com/pedestal/pedestal-app/509ab766a54921c0fbb2dd7c6a3cb20223b8e1a1/app/src/io/pedestal/app/util/test.clj | clojure | The use and distribution terms for this software are covered by the
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
Run begin messages
Run script
Wait for all messages to be processed
Wait for specified queues to be consumed | Copyright 2013 Relevance , Inc.
Eclipse Public License 1.0 ( )
(ns io.pedestal.app.util.test
(:require [io.pedestal.app :as app]
[io.pedestal.app.util.platform :as platform]))
(defn run-sync! [app script & {:keys [begin timeout wait-for]}]
(assert (or (nil? begin)
(= begin :default)
(vector? begin))
"begin must be nil, the keyword :default or a vector of messages")
(assert (or (nil? wait-for)
(every? #(contains? #{:output :app-model} %) wait-for))
"wait-for must be nil or a seq with a subset of #{:output :app-model}")
(let [timeout (or timeout 1000)
script (conj (vec (butlast script)) (with-meta (last script) {::last true}))
record-states (atom [@(:state app)])]
(add-watch (:state app) :state-watch
(fn [_ _ _ n]
(swap! record-states conj n)))
(cond (= begin :default) (app/begin app)
(vector? begin) (app/begin app begin))
(app/run! app script)
(loop [tout timeout]
(let [last-input (-> app :state deref :io.pedestal.app/input)]
(when (not= (meta last-input) {::last true})
(if (neg? tout)
(throw (Exception. (str "Test timeout after " timeout "ms.\n"
" Last input: " last-input "\n"
" Meta: " (meta last-input))))
(do (Thread/sleep 20)
(recur (- tout 20)))))))
(if (seq wait-for)
(doseq [k wait-for]
(loop [queue (:queue @(.state (k app)))
c 0]
(when (> c 3)
(throw (Exception. (str "The queue " k " is not being consumed."))))
(when-not (zero? (count queue))
(Thread/sleep 20)
(let [new-queue (:queue @(.state (k app)))]
(recur new-queue
(if (= new-queue queue)
(inc c)
0)))))))
@record-states))
(defmacro refer-privates
"Refer private functions into the current namespace. Use
(refer-privates :all)
to refer all privates."
[ns s & syms]
(let [xs (if (= s :all)
(for [[_ v] (ns-interns ns)
:when (:private (meta v))]
[(:name (meta v)) v])
(mapv (fn [sym] [sym (ns-resolve ns sym)]) (cons s syms))) ]
`(do ~@(mapv (fn [[s v]] `(def ~s ~v)) xs))))
|
178d28d4bc636f78c2fa21fcb51fcdf332668baedabf203c3dfd1b7f3ce479ea | bobzhang/fan | regress6.ml |
let pos0 = -lb.lex_abs_pos;;
(* if 0> 0 then begin end else begin end ;; *)
let highlight_dumb ppf lb loc =
for pos = 0 to end_pos do
if c <> '\n' then begin
if a then
b
end else begin end
done
| null | https://raw.githubusercontent.com/bobzhang/fan/7ed527d96c5a006da43d3813f32ad8a5baa31b7f/src/todoml/test/printer/regress6.ml | ocaml | if 0> 0 then begin end else begin end ;; |
let pos0 = -lb.lex_abs_pos;;
let highlight_dumb ppf lb loc =
for pos = 0 to end_pos do
if c <> '\n' then begin
if a then
b
end else begin end
done
|
0fcd83a16f9fdabb6ffd8a0a37e4d69dbcd26aab14e75efeb89b66f2aa60f38d | nitrogen/simple_bridge | yaws_simple_bridge.erl | % vim: ts=4 sw=4 et
% Simple Bridge
Copyright ( c ) 2008 - 2010
Copyright ( c ) 2011 - 2016
See MIT - LICENSE for licensing information .
-module(yaws_simple_bridge).
-behaviour(simple_bridge).
%% REQUEST EXPORTS
-include("simple_bridge.hrl").
-export ([
init/1,
request_method/1, protocol/1, host/1, path/1, uri/1,
peer_ip/1, peer_port/1,
headers/1, cookies/1,
native_header_type/0,
query_params/1, post_params/1, request_body/1,
socket/1, recv_from_socket/3, protocol_version/1
]).
%% RESPONSE EXPORTS
-export([
build_response/2
]).
%% REQUEST
init(Req) ->
Req.
protocol(Arg) ->
case yaws_api:arg_clisock(Arg) of
S when is_tuple(S), element(1, S) =:= sslsocket -> https;
S when is_tuple(S), element(1, S) =:= ssl -> https;
_ -> http
end.
host(Arg) ->
@TODO : Can we get the full URL without parsing and printing or importing an internal yaws .hrl ?
URL = yaws_api:request_url(Arg),
[_Scheme, Host, _Port, _Path, _QueryPart] = yaws_api:format_url(URL),
Headers = yaws_api:arg_headers(Arg),
XForwardedFor = yaws_api:headers_x_forwarded_for(Headers) ,
simple_bridge_util:infer_host(undefined, Host, XForwardedFor).
request_method(Arg) ->
yaws_api:http_request_method(yaws_api:arg_req(Arg)).
path(Arg) ->
yaws_api:arg_server_path(Arg).
uri(Arg) ->
{abs_path, Path} = yaws_api:http_request_path(yaws_api:arg_req(Arg)),
Path.
peer_ip(Arg) ->
Socket = socket(Arg),
{ok, {IP, _Port}} =
case Socket of
{ssl, S} ->
ssl:peername(S);
_ ->
inet:peername(Socket)
end,
IP.
peer_port(Arg) ->
Socket = socket(Arg),
{ok, {_IP, Port}} =
case Socket of
{ssl, S} ->
ssl:peername(S);
_ ->
inet:peername(Socket)
end,
Port.
native_header_type() ->
map.
headers(Arg) ->
Headers = yaws_api:arg_headers(Arg),
HeadersMap = #{
<<"connection">> => yaws_api:headers_connection(Headers),
<<"accept">> => yaws_api:headers_accept(Headers),
<<"host">> => yaws_api:headers_host(Headers),
<<"if-modified-since">> => yaws_api:headers_if_modified_since(Headers),
<<"if-match">> => yaws_api:headers_if_match(Headers),
<<"if-none-match">> => yaws_api:headers_if_none_match(Headers),
<<"if-range">> => yaws_api:headers_if_range(Headers),
<<"if-unmodified-since">> => yaws_api:headers_if_unmodified_since(Headers),
<<"range">> => yaws_api:headers_range(Headers),
<<"referer">> => yaws_api:headers_referer(Headers),
<<"user-agent">> => yaws_api:headers_user_agent(Headers),
<<"accept-ranges">> => yaws_api:headers_accept_ranges(Headers),
<<"cookie">> => yaws_api:headers_cookie(Headers),
<<"keep-alive">> => yaws_api:headers_keep_alive(Headers),
<<"location">> => yaws_api:headers_location(Headers),
<<"content-length">> => yaws_api:headers_content_length(Headers),
<<"content-type">> => yaws_api:headers_content_type(Headers),
<<"content-encoding">> => yaws_api:headers_content_encoding(Headers),
<<"authorization">> => yaws_api:headers_authorization(Headers),
<<"transfer-encoding">> => yaws_api:headers_transfer_encoding(Headers),
<<"x-forwarded-for">> => yaws_api:headers_x_forwarded_for(Headers)
},
%% Get the other headers and format them to fit the paradigm we're using above
Others = yaws_api:headers_other(Headers),
Stick those headers into the map
lists:foldl(fun({http_header, _Num, K, _, V}, Hdrs) ->
maps:put(K, V, Hdrs)
end, HeadersMap, Others).
cookies(Req) ->
Headers = yaws_api:arg_headers(Req),
CookieList0 = yaws_api:headers_cookie(Headers),
CookieList = string:join(CookieList0, ";"),
simple_bridge_util:parse_cookie_header(CookieList).
query_params(Arg) ->
yaws_api:parse_query(Arg).
post_params(Arg) ->
case should_we_parse_post_params(request_method(Arg)) of
true -> yaws_api:parse_post(Arg);
_ -> []
end.
should_we_parse_post_params('GET') -> false;
should_we_parse_post_params(_) -> true.
request_body(Arg) ->
case yaws_api:arg_clidata(Arg) of
{partial, Data} -> Data;
Data -> Data
end.
socket(Arg) ->
yaws_api:arg_clisock(Arg).
recv_from_socket(Length, Timeout, Arg) ->
Socket = socket(Arg),
case gen_tcp:recv(Socket, Length, Timeout) of
{ok, Data} -> Data;
_ -> exit(normal)
end.
protocol_version(Arg) ->
yaws_api:http_request_version(yaws_api:arg_req(Arg)).
%% RESPONSE
build_response(_Arg, Res) ->
% Get vars...
Code = Res#response.status_code,
%% Assemble headers...
Headers = assemble_headers(Res),
case Res#response.data of
{data, Body} ->
%% Get the content type...
ContentType = get_content_type(Res),
% Send the yaws response...
lists:flatten([
{status, Code},
Headers,
{content, ContentType, Body}
]);
{file, Path} ->
%% Note: This section should only be entered in the event that a static file is
requested that is n't found in the ' appmod ' section of the yaws.conf file .
%% I've not found a way to "pass the buck" back to yaws and say "even though this
directory is n't found in the appmod , I want you to serve it anyway " . This
%% means that with the current implementation, you don't want to be serving files
big files that are n't covered in the appmod section , primarily because this little
%% snippet loads the entire file into memory then passes it off to yaws to be served,
rather than streaming it . I 'll need to look further into to either 1 ) Pass the buck
completely back to Yaws , or 2 ) how the streamcontent return types work as define in
%% yaws_server:handle_out_reply
Static Content should have an expires date . If not , we 're going to make one
Headers2 = ensure_expires_header(Res, Headers),
%% Docroot needed to find file in Path
Docroot = yaws_api:arg_docroot(_Arg),
FullPath = [Docroot,Path],
%% Get the content type as defined by yaws
ContentType = yaws_api:mime_type(Path),
%% Get the file content
FullResponse = case file:read_file(FullPath) of
{error,enoent} ->
yaws_outmod:out404(_Arg);
{ok,Bin} ->
[
{status, Code},
Headers2,
{content, ContentType, Bin}
]
end,
lists:flatten(FullResponse)
end.
assemble_headers(Res) ->
lists:flatten([
[{header, {yaws_kosher_header(X#header.name), X#header.value}} || X <- Res#response.headers],
[create_cookie(X) || X <- Res#response.cookies]
]).
yaws_kosher_header(A) when is_atom(A) -> A;
yaws_kosher_header(B) when is_binary(B) -> binary_to_list(B);
yaws_kosher_header(L) when is_list(L) -> L.
%% This is slightly different from the one in simple_bridge_util due to the
formatting of the yaws headers is n't just a simple proplist .
ensure_expires_header(Res,Headers) ->
case simple_bridge_util:needs_expires_header(Res#response.headers) of
true ->
{Header, Value} = simple_bridge_util:default_static_expires_header(),
ExpiresHeader = {yaws_kosher_header(Header), Value},
[{header, ExpiresHeader} | Headers];
false -> Headers
end.
get_content_type(Res) ->
coalesce([
kvl3(content_type, Res#response.headers),
kvl3("content-type", Res#response.headers),
kvl3("Content-Type", Res#response.headers),
kvl3("CONTENT-TYPE", Res#response.headers),
"text/html"
]).
kvl3(Key,L) ->
case lists:keysearch(Key,2,L) of
{value, {_,_,Val}} -> Val;
_ -> undefined
end.
coalesce([]) -> undefined;
coalesce([undefined|T]) -> coalesce(T);
coalesce([H|_T]) -> H.
create_cookie(Cookie) ->
Name = simple_bridge_util:to_list(Cookie#cookie.name),
Value = simple_bridge_util:to_list(Cookie#cookie.value),
FieldsAndValues = [
{max_age, Cookie#cookie.max_age},
{secure, Cookie#cookie.secure},
{path, Cookie#cookie.path},
{http_only, Cookie#cookie.http_only},
{domain, Cookie#cookie.domain},
{same_site, Cookie#cookie.same_site}
],
Options = lists:foldl(fun({Field, Val}, Acc) ->
cookie_opt(Field, Val) ++ Acc
end, [], FieldsAndValues),
yaws_api:set_cookie(Name, Value, Options).
cookie_opt(max_age, MaxAge) ->
[{max_age, MaxAge}];
cookie_opt(secure, true) ->
[secure];
cookie_opt(http_only, true) ->
[http_only];
cookie_opt(domain, Domain) when Domain=/=undefined, Domain=/="", Domain =/= <<"">> ->
[{domain, simple_bridge_util:to_list(Domain)}];
cookie_opt(path, Path) when Path=/=undefined, Path=/="", Path =/= <<"">> ->
[{path, simple_bridge_util:to_list(Path)}];
cookie_opt(same_site, SameSite) when SameSite=/=undefined, SameSite=/="", SameSite =/= <<"">> ->
[{same_site, simple_bridge_util:to_existing_atom(SameSite)}];
cookie_opt(_, _) ->
[].
| null | https://raw.githubusercontent.com/nitrogen/simple_bridge/0b33e15759b23050c151912374a68e18f2a3b83d/src/yaws_bridge_modules/yaws_simple_bridge.erl | erlang | vim: ts=4 sw=4 et
Simple Bridge
REQUEST EXPORTS
RESPONSE EXPORTS
REQUEST
Get the other headers and format them to fit the paradigm we're using above
RESPONSE
Get vars...
Assemble headers...
Get the content type...
Send the yaws response...
Note: This section should only be entered in the event that a static file is
I've not found a way to "pass the buck" back to yaws and say "even though this
means that with the current implementation, you don't want to be serving files
snippet loads the entire file into memory then passes it off to yaws to be served,
yaws_server:handle_out_reply
Docroot needed to find file in Path
Get the content type as defined by yaws
Get the file content
This is slightly different from the one in simple_bridge_util due to the | Copyright ( c ) 2008 - 2010
Copyright ( c ) 2011 - 2016
See MIT - LICENSE for licensing information .
-module(yaws_simple_bridge).
-behaviour(simple_bridge).
-include("simple_bridge.hrl").
-export ([
init/1,
request_method/1, protocol/1, host/1, path/1, uri/1,
peer_ip/1, peer_port/1,
headers/1, cookies/1,
native_header_type/0,
query_params/1, post_params/1, request_body/1,
socket/1, recv_from_socket/3, protocol_version/1
]).
-export([
build_response/2
]).
init(Req) ->
Req.
protocol(Arg) ->
case yaws_api:arg_clisock(Arg) of
S when is_tuple(S), element(1, S) =:= sslsocket -> https;
S when is_tuple(S), element(1, S) =:= ssl -> https;
_ -> http
end.
host(Arg) ->
@TODO : Can we get the full URL without parsing and printing or importing an internal yaws .hrl ?
URL = yaws_api:request_url(Arg),
[_Scheme, Host, _Port, _Path, _QueryPart] = yaws_api:format_url(URL),
Headers = yaws_api:arg_headers(Arg),
XForwardedFor = yaws_api:headers_x_forwarded_for(Headers) ,
simple_bridge_util:infer_host(undefined, Host, XForwardedFor).
request_method(Arg) ->
yaws_api:http_request_method(yaws_api:arg_req(Arg)).
path(Arg) ->
yaws_api:arg_server_path(Arg).
uri(Arg) ->
{abs_path, Path} = yaws_api:http_request_path(yaws_api:arg_req(Arg)),
Path.
peer_ip(Arg) ->
Socket = socket(Arg),
{ok, {IP, _Port}} =
case Socket of
{ssl, S} ->
ssl:peername(S);
_ ->
inet:peername(Socket)
end,
IP.
peer_port(Arg) ->
Socket = socket(Arg),
{ok, {_IP, Port}} =
case Socket of
{ssl, S} ->
ssl:peername(S);
_ ->
inet:peername(Socket)
end,
Port.
native_header_type() ->
map.
headers(Arg) ->
Headers = yaws_api:arg_headers(Arg),
HeadersMap = #{
<<"connection">> => yaws_api:headers_connection(Headers),
<<"accept">> => yaws_api:headers_accept(Headers),
<<"host">> => yaws_api:headers_host(Headers),
<<"if-modified-since">> => yaws_api:headers_if_modified_since(Headers),
<<"if-match">> => yaws_api:headers_if_match(Headers),
<<"if-none-match">> => yaws_api:headers_if_none_match(Headers),
<<"if-range">> => yaws_api:headers_if_range(Headers),
<<"if-unmodified-since">> => yaws_api:headers_if_unmodified_since(Headers),
<<"range">> => yaws_api:headers_range(Headers),
<<"referer">> => yaws_api:headers_referer(Headers),
<<"user-agent">> => yaws_api:headers_user_agent(Headers),
<<"accept-ranges">> => yaws_api:headers_accept_ranges(Headers),
<<"cookie">> => yaws_api:headers_cookie(Headers),
<<"keep-alive">> => yaws_api:headers_keep_alive(Headers),
<<"location">> => yaws_api:headers_location(Headers),
<<"content-length">> => yaws_api:headers_content_length(Headers),
<<"content-type">> => yaws_api:headers_content_type(Headers),
<<"content-encoding">> => yaws_api:headers_content_encoding(Headers),
<<"authorization">> => yaws_api:headers_authorization(Headers),
<<"transfer-encoding">> => yaws_api:headers_transfer_encoding(Headers),
<<"x-forwarded-for">> => yaws_api:headers_x_forwarded_for(Headers)
},
Others = yaws_api:headers_other(Headers),
Stick those headers into the map
lists:foldl(fun({http_header, _Num, K, _, V}, Hdrs) ->
maps:put(K, V, Hdrs)
end, HeadersMap, Others).
cookies(Req) ->
Headers = yaws_api:arg_headers(Req),
CookieList0 = yaws_api:headers_cookie(Headers),
CookieList = string:join(CookieList0, ";"),
simple_bridge_util:parse_cookie_header(CookieList).
query_params(Arg) ->
yaws_api:parse_query(Arg).
post_params(Arg) ->
case should_we_parse_post_params(request_method(Arg)) of
true -> yaws_api:parse_post(Arg);
_ -> []
end.
should_we_parse_post_params('GET') -> false;
should_we_parse_post_params(_) -> true.
request_body(Arg) ->
case yaws_api:arg_clidata(Arg) of
{partial, Data} -> Data;
Data -> Data
end.
socket(Arg) ->
yaws_api:arg_clisock(Arg).
recv_from_socket(Length, Timeout, Arg) ->
Socket = socket(Arg),
case gen_tcp:recv(Socket, Length, Timeout) of
{ok, Data} -> Data;
_ -> exit(normal)
end.
protocol_version(Arg) ->
yaws_api:http_request_version(yaws_api:arg_req(Arg)).
build_response(_Arg, Res) ->
Code = Res#response.status_code,
Headers = assemble_headers(Res),
case Res#response.data of
{data, Body} ->
ContentType = get_content_type(Res),
lists:flatten([
{status, Code},
Headers,
{content, ContentType, Body}
]);
{file, Path} ->
requested that is n't found in the ' appmod ' section of the yaws.conf file .
directory is n't found in the appmod , I want you to serve it anyway " . This
big files that are n't covered in the appmod section , primarily because this little
rather than streaming it . I 'll need to look further into to either 1 ) Pass the buck
completely back to Yaws , or 2 ) how the streamcontent return types work as define in
Static Content should have an expires date . If not , we 're going to make one
Headers2 = ensure_expires_header(Res, Headers),
Docroot = yaws_api:arg_docroot(_Arg),
FullPath = [Docroot,Path],
ContentType = yaws_api:mime_type(Path),
FullResponse = case file:read_file(FullPath) of
{error,enoent} ->
yaws_outmod:out404(_Arg);
{ok,Bin} ->
[
{status, Code},
Headers2,
{content, ContentType, Bin}
]
end,
lists:flatten(FullResponse)
end.
assemble_headers(Res) ->
lists:flatten([
[{header, {yaws_kosher_header(X#header.name), X#header.value}} || X <- Res#response.headers],
[create_cookie(X) || X <- Res#response.cookies]
]).
yaws_kosher_header(A) when is_atom(A) -> A;
yaws_kosher_header(B) when is_binary(B) -> binary_to_list(B);
yaws_kosher_header(L) when is_list(L) -> L.
formatting of the yaws headers is n't just a simple proplist .
ensure_expires_header(Res,Headers) ->
case simple_bridge_util:needs_expires_header(Res#response.headers) of
true ->
{Header, Value} = simple_bridge_util:default_static_expires_header(),
ExpiresHeader = {yaws_kosher_header(Header), Value},
[{header, ExpiresHeader} | Headers];
false -> Headers
end.
get_content_type(Res) ->
coalesce([
kvl3(content_type, Res#response.headers),
kvl3("content-type", Res#response.headers),
kvl3("Content-Type", Res#response.headers),
kvl3("CONTENT-TYPE", Res#response.headers),
"text/html"
]).
kvl3(Key,L) ->
case lists:keysearch(Key,2,L) of
{value, {_,_,Val}} -> Val;
_ -> undefined
end.
coalesce([]) -> undefined;
coalesce([undefined|T]) -> coalesce(T);
coalesce([H|_T]) -> H.
create_cookie(Cookie) ->
Name = simple_bridge_util:to_list(Cookie#cookie.name),
Value = simple_bridge_util:to_list(Cookie#cookie.value),
FieldsAndValues = [
{max_age, Cookie#cookie.max_age},
{secure, Cookie#cookie.secure},
{path, Cookie#cookie.path},
{http_only, Cookie#cookie.http_only},
{domain, Cookie#cookie.domain},
{same_site, Cookie#cookie.same_site}
],
Options = lists:foldl(fun({Field, Val}, Acc) ->
cookie_opt(Field, Val) ++ Acc
end, [], FieldsAndValues),
yaws_api:set_cookie(Name, Value, Options).
cookie_opt(max_age, MaxAge) ->
[{max_age, MaxAge}];
cookie_opt(secure, true) ->
[secure];
cookie_opt(http_only, true) ->
[http_only];
cookie_opt(domain, Domain) when Domain=/=undefined, Domain=/="", Domain =/= <<"">> ->
[{domain, simple_bridge_util:to_list(Domain)}];
cookie_opt(path, Path) when Path=/=undefined, Path=/="", Path =/= <<"">> ->
[{path, simple_bridge_util:to_list(Path)}];
cookie_opt(same_site, SameSite) when SameSite=/=undefined, SameSite=/="", SameSite =/= <<"">> ->
[{same_site, simple_bridge_util:to_existing_atom(SameSite)}];
cookie_opt(_, _) ->
[].
|
8a13ad349db510a01937fee54f481cb434fe3f7de5cddee5a7740d03665113a0 | sylphbio/pontiff | run.scm | (module command.run (run)
(import scheme)
(import chicken.base)
(import chicken.type)
(import chicken.string)
(import chicken.format)
(import chicken.process)
(import chicken.process-context)
(import chicken.pathname)
(import tabulae)
(import ix)
(import (prefix state state:))
(import util)
(define (run argv)
(define exe (symbol->string ((^.v (keyw :artifact) (keyw :name)) argv)))
(printf "running ~A...\n" exe)
(process-join (process-create (make-pathname `(,(state:working-path) ,(state:build-dir)) exe)
(map ix:unwrap ((^.v (keyw :exec-args)) argv))
(state:env))))
)
| null | https://raw.githubusercontent.com/sylphbio/pontiff/8af6c1932e687b5f4219d2c649c1aa4bb92d543a/src/command/run.scm | scheme | (module command.run (run)
(import scheme)
(import chicken.base)
(import chicken.type)
(import chicken.string)
(import chicken.format)
(import chicken.process)
(import chicken.process-context)
(import chicken.pathname)
(import tabulae)
(import ix)
(import (prefix state state:))
(import util)
(define (run argv)
(define exe (symbol->string ((^.v (keyw :artifact) (keyw :name)) argv)))
(printf "running ~A...\n" exe)
(process-join (process-create (make-pathname `(,(state:working-path) ,(state:build-dir)) exe)
(map ix:unwrap ((^.v (keyw :exec-args)) argv))
(state:env))))
)
| |
a832addde7b9c6561d0c8feb0ed6c962066d6b23193f8b6c9ebde558333353b3 | beoliver/clj-arangodb | cursor_test.clj | (ns clj-arangodb.arangodb.cursor-test
(:require
[clj-arangodb.arangodb.databases :as d]
[clj-arangodb.arangodb.aql :as aql]
[clj-arangodb.arangodb.adapter :as adapter]
[clj-arangodb.arangodb.cursor :as cursor]
[clj-arangodb.arangodb.helper :as h]
[clojure.test :refer :all]))
(deftest cursor-stats-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:RETURN true])
stats (cursor/get-stats res)]
(is (= (:class stats)
com.arangodb.entity.CursorEntity$Stats))
(is (= (set (keys stats))
#{:class :executionTime :filtered :fullCount
:scannedFull :scannedIndex :writesExecuted
:writesIgnored :peakMemoryUsage})))))
(deftest cursor-count-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil {:count true} Integer)]
(is (= 5 (cursor/get-count res))))
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]])]
(is (= 5 (cursor/count res))))))
(deftest cursor-cache-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]])]
(is (= false (cursor/is-cached res))))))
(deftest cursor-collect-into-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)
xs (cursor/collect-into res (java.util.ArrayList.))]
(is (= [1 2 3 4 5] xs))
(testing "collect-into consumes the contents of the cursor"
(is (= false (cursor/has-next res)))))
(let [res (d/query db [:FOR ["x" [1 1 2 2 3]] [:RETURN "x"]] nil nil Integer)
xs (cursor/collect-into res (java.util.HashSet.))]
(is (= #{1 2 3} xs)))))
(deftest cursor-seq-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)
xs (seq res)]
(is (= (type xs) clojure.lang.LazySeq))
(is (= [1 2 3 4 5] xs)))
(testing "can map deserialize-doc"
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]])
xs (map adapter/deserialize-doc res)]
(is (= (type xs) clojure.lang.LazySeq))
(is (= [1 2 3 4 5] xs))))))
(deftest cursor-predicate-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)]
(is (= true (cursor/all-match res (partial >= 5))))
(testing "can only test once"
(is (= false (cursor/all-match res nat-int?)))))))
(deftest cursor-map-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)
xs (cursor/map res inc)]
(is (= [1 2 3 4 5] (seq res)))
(is (= nil (seq xs))))
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)
xs (cursor/map res inc)]
(is (= [2 3 4 5 6] (seq xs)))
(is (= (seq res) nil))) ))
(deftest cursor-first-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..3"] [:RETURN "x"]] nil nil Integer)]
(is (= 1 (cursor/first res)))
(is (= 2 (cursor/first res)))
(is (= 3 (cursor/first res)))
(is (nil? (cursor/first res))))))
(deftest cursor-foreach-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..3"] [:RETURN "x"]] nil nil Integer)
state (atom 0)]
(cursor/foreach res (fn [x] (swap! state + x)))
(is (nil? (cursor/first res)))
(is (= @state 6)))))
(deftest multi-batch-tests
(h/with-temp-db [db "testDB"]
(let [res (d/query db
[:FOR ["x" "0..99"] [:RETURN "x"]]
nil
{:batchSize (int 5)}
Integer)]
(is (= (range 100) (seq res))))
(let [res (d/query db
[:FOR ["x" "1..3"] [:RETURN "x"]]
nil
{:batchSize (int 1)}
Integer)]
(while (cursor/has-next res)
(is (nat-int? (cursor/next res)))))))
| null | https://raw.githubusercontent.com/beoliver/clj-arangodb/a6b2c835278573e2fee3521c63917838e86703eb/test/clj_arangodb/arangodb/cursor_test.clj | clojure | (ns clj-arangodb.arangodb.cursor-test
(:require
[clj-arangodb.arangodb.databases :as d]
[clj-arangodb.arangodb.aql :as aql]
[clj-arangodb.arangodb.adapter :as adapter]
[clj-arangodb.arangodb.cursor :as cursor]
[clj-arangodb.arangodb.helper :as h]
[clojure.test :refer :all]))
(deftest cursor-stats-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:RETURN true])
stats (cursor/get-stats res)]
(is (= (:class stats)
com.arangodb.entity.CursorEntity$Stats))
(is (= (set (keys stats))
#{:class :executionTime :filtered :fullCount
:scannedFull :scannedIndex :writesExecuted
:writesIgnored :peakMemoryUsage})))))
(deftest cursor-count-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil {:count true} Integer)]
(is (= 5 (cursor/get-count res))))
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]])]
(is (= 5 (cursor/count res))))))
(deftest cursor-cache-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]])]
(is (= false (cursor/is-cached res))))))
(deftest cursor-collect-into-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)
xs (cursor/collect-into res (java.util.ArrayList.))]
(is (= [1 2 3 4 5] xs))
(testing "collect-into consumes the contents of the cursor"
(is (= false (cursor/has-next res)))))
(let [res (d/query db [:FOR ["x" [1 1 2 2 3]] [:RETURN "x"]] nil nil Integer)
xs (cursor/collect-into res (java.util.HashSet.))]
(is (= #{1 2 3} xs)))))
(deftest cursor-seq-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)
xs (seq res)]
(is (= (type xs) clojure.lang.LazySeq))
(is (= [1 2 3 4 5] xs)))
(testing "can map deserialize-doc"
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]])
xs (map adapter/deserialize-doc res)]
(is (= (type xs) clojure.lang.LazySeq))
(is (= [1 2 3 4 5] xs))))))
(deftest cursor-predicate-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)]
(is (= true (cursor/all-match res (partial >= 5))))
(testing "can only test once"
(is (= false (cursor/all-match res nat-int?)))))))
(deftest cursor-map-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)
xs (cursor/map res inc)]
(is (= [1 2 3 4 5] (seq res)))
(is (= nil (seq xs))))
(let [res (d/query db [:FOR ["x" "1..5"] [:RETURN "x"]] nil nil Integer)
xs (cursor/map res inc)]
(is (= [2 3 4 5 6] (seq xs)))
(is (= (seq res) nil))) ))
(deftest cursor-first-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..3"] [:RETURN "x"]] nil nil Integer)]
(is (= 1 (cursor/first res)))
(is (= 2 (cursor/first res)))
(is (= 3 (cursor/first res)))
(is (nil? (cursor/first res))))))
(deftest cursor-foreach-test
(h/with-temp-db [db "testDB"]
(let [res (d/query db [:FOR ["x" "1..3"] [:RETURN "x"]] nil nil Integer)
state (atom 0)]
(cursor/foreach res (fn [x] (swap! state + x)))
(is (nil? (cursor/first res)))
(is (= @state 6)))))
(deftest multi-batch-tests
(h/with-temp-db [db "testDB"]
(let [res (d/query db
[:FOR ["x" "0..99"] [:RETURN "x"]]
nil
{:batchSize (int 5)}
Integer)]
(is (= (range 100) (seq res))))
(let [res (d/query db
[:FOR ["x" "1..3"] [:RETURN "x"]]
nil
{:batchSize (int 1)}
Integer)]
(while (cursor/has-next res)
(is (nat-int? (cursor/next res)))))))
| |
d45b235c81f614645de3ca07bea928bc65a6e76c8b194299f84e290386f4ba59 | processone/pkix | pkix_sup.erl | %%%-------------------------------------------------------------------
Created : 22 Sep 2018 by < >
%%%
Copyright ( C ) 2002 - 2022 ProcessOne , SARL . 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(pkix_sup).
-behaviour(supervisor).
%% API
-export([start_link/0]).
%% Supervisor callbacks
-export([init/1]).
-define(SHUTDOWN_TIMEOUT, timer:seconds(30)).
%%%===================================================================
%%% API functions
%%%===================================================================
-spec start_link() -> {ok, Pid :: pid()} |
{error, {already_started, Pid :: pid()}} |
{error, {shutdown, term()}} |
{error, term()} |
ignore.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
-spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}.
init([]) ->
Spec = {pkix, {pkix, start_link, []}, permanent,
?SHUTDOWN_TIMEOUT, worker, [pkix]},
{ok, {{one_for_all, 10, 1}, [Spec]}}.
%%%===================================================================
Internal functions
%%%===================================================================
| null | https://raw.githubusercontent.com/processone/pkix/0368e4dc04817d6374e296ae0506a92fd8a8ccf7/src/pkix_sup.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.
-------------------------------------------------------------------
API
Supervisor callbacks
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
===================================================================
===================================================================
=================================================================== | Created : 22 Sep 2018 by < >
Copyright ( C ) 2002 - 2022 ProcessOne , SARL . 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(pkix_sup).
-behaviour(supervisor).
-export([start_link/0]).
-export([init/1]).
-define(SHUTDOWN_TIMEOUT, timer:seconds(30)).
-spec start_link() -> {ok, Pid :: pid()} |
{error, {already_started, Pid :: pid()}} |
{error, {shutdown, term()}} |
{error, term()} |
ignore.
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
-spec init([]) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}.
init([]) ->
Spec = {pkix, {pkix, start_link, []}, permanent,
?SHUTDOWN_TIMEOUT, worker, [pkix]},
{ok, {{one_for_all, 10, 1}, [Spec]}}.
Internal functions
|
fd520edafa01fbba03143a3d86010a6732ec8dc6e26f3667a9002f04e22a396e | wireapp/wire-server | Event_conversation.hs | # LANGUAGE OverloadedLists #
-- This file is part of the Wire Server implementation.
--
Copyright ( C ) 2022 Wire Swiss GmbH < >
--
-- This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
-- later version.
--
-- This program is distributed in the hope that it will be useful, but WITHOUT
-- ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
-- FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
-- details.
--
You should have received a copy of the GNU Affero General Public License along
-- with this program. If not, see </>.
module Test.Wire.API.Golden.Generated.Event_conversation where
import Data.Code
import Data.Domain (Domain (..))
import Data.Id
import Data.Misc (HttpsUrl (HttpsUrl))
import Data.Qualified (Qualified (..))
import Data.Range
import Data.Time
import qualified Data.UUID as UUID
import GHC.Exts (IsList (fromList))
import Imports
import URI.ByteString (Authority (..), Host (..), Query (..), Scheme (..), URIRef (..))
import Wire.API.Conversation (Access (..), MutedStatus (..))
import Wire.API.Conversation.Role
import Wire.API.Conversation.Typing
import Wire.API.Event.Conversation
testObject_Event_conversation_1 :: Event
testObject_Event_conversation_1 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "oym59-06.i423w"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "n8nl6tp.h5"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdConvCodeDelete
}
testObject_Event_conversation_2 :: Event
testObject_Event_conversation_2 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "2m99----34.id7u09"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "b.0-7.0.rg"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData =
EdMemberUpdate
( MemberUpdateData
{ misTarget = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "oy8yz.f1"}},
misOtrMutedStatus = Just (MutedStatus {fromMutedStatus = 1}),
misOtrMutedRef = Nothing,
misOtrArchived = Nothing,
misOtrArchivedRef = Nothing,
misHidden = Nothing,
misHiddenRef = Nothing,
misConvRoleName = Just roleNameWireAdmin
}
)
}
testObject_Event_conversation_3 :: Event
testObject_Event_conversation_3 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "91.ii9vf.mbwj9k7lmk"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "k3.f.z"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData =
EdConvCodeUpdate
( ConversationCode
{ conversationKey = Key {asciiKey = unsafeRange "CRdONS7988O2QdyndJs1"},
conversationCode = Value {asciiValue = unsafeRange "7d6713"},
conversationUri = Just $ HttpsUrl (URI {uriScheme = Scheme {schemeBS = "https"}, uriAuthority = Just (Authority {authorityUserInfo = Nothing, authorityHost = Host {hostBS = "example.com"}, authorityPort = Nothing}), uriPath = "", uriQuery = Query {queryPairs = []}, uriFragment = Nothing})
}
)
}
testObject_Event_conversation_4 :: Event
testObject_Event_conversation_4 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "ma--6us.i8o--0440"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "97k-u0.b-5c"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdConvAccessUpdate (ConversationAccessData {cupAccess = fromList [PrivateAccess, CodeAccess], cupAccessRoles = fromList []})
}
testObject_Event_conversation_5 :: Event
testObject_Event_conversation_5 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "q.6lm833.o95.l.y2"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "7.m4f7p.ez4zs61"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdMLSWelcome ""
}
testObject_Event_conversation_6 :: Event
testObject_Event_conversation_6 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "391.r"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "8.0-6.t7pxv"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdOtrMessage (OtrMessage {otrSender = ClientId {client = "1"}, otrRecipient = ClientId {client = "1"}, otrCiphertext = "", otrData = Just "I\68655"})
}
testObject_Event_conversation_7 :: Event
testObject_Event_conversation_7 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "b2.ue4k"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "64b3--h.u"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdOtrMessage (OtrMessage {otrSender = ClientId {client = "3"}, otrRecipient = ClientId {client = "3"}, otrCiphertext = "%\SI", otrData = Nothing})
}
testObject_Event_conversation_8 :: Event
testObject_Event_conversation_8 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "36.e9.s-o-17"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "0--gy.705nsa8.j4m"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdTyping StartedTyping
}
testObject_Event_conversation_9 :: Event
testObject_Event_conversation_9 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "743846p6-pp33.1.ktb9.0bmn.efm2bly"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "9--5grmn.j39y3--9n"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData =
EdMembersLeave
( QualifiedUserIdList
{ qualifiedUserIdList =
[ Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "ow8i3fhr.v"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "8kshw-2l.3w44.6c8763a-77r4.gk13zq"}},
Qualified
{ qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")),
qDomain = Domain {_domainText = "xk-no.m5--f8b7"}
},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "x02.p.69y-6.8ncr.u"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "1-47tume1e5l32i.v75is-q4-o.u7qc"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "8ay.ec.k-8"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "u-8.m-42ns2c"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "08kh83-8.vu.i24"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "t1t683.o3--2.3k5.it-5.e1"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "q.ajw-5"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "73m4g.c24em3.v"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "i7zn.li"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "42y78.yekf"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "n63-p87m2.dtq"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "ns.v2p"}}
]
}
)
}
testObject_Event_conversation_10 :: Event
testObject_Event_conversation_10 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "1852a.o-4"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "4-p.d7b8d3.6.c8--jds3-1acy"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdMLSMessage "s\b\138w\236\231P(\ESC\216\205"
}
testObject_Event_conversation_11 :: Event
testObject_Event_conversation_11 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "wwzw-ly4jk5.6790-y.j04o-21.ltl"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "70-o.ncd"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdTyping StoppedTyping
}
| null | https://raw.githubusercontent.com/wireapp/wire-server/9ab536b4c4915c9a0442c7643f8f78eb953a0217/libs/wire-api/test/golden/Test/Wire/API/Golden/Generated/Event_conversation.hs | haskell | This file is part of the Wire Server implementation.
This program is free software: you can redistribute it and/or modify it under
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
with this program. If not, see </>. | # LANGUAGE OverloadedLists #
Copyright ( C ) 2022 Wire Swiss GmbH < >
the terms of the GNU Affero General Public License as published by the Free
Software Foundation , either version 3 of the License , or ( at your option ) any
You should have received a copy of the GNU Affero General Public License along
module Test.Wire.API.Golden.Generated.Event_conversation where
import Data.Code
import Data.Domain (Domain (..))
import Data.Id
import Data.Misc (HttpsUrl (HttpsUrl))
import Data.Qualified (Qualified (..))
import Data.Range
import Data.Time
import qualified Data.UUID as UUID
import GHC.Exts (IsList (fromList))
import Imports
import URI.ByteString (Authority (..), Host (..), Query (..), Scheme (..), URIRef (..))
import Wire.API.Conversation (Access (..), MutedStatus (..))
import Wire.API.Conversation.Role
import Wire.API.Conversation.Typing
import Wire.API.Event.Conversation
testObject_Event_conversation_1 :: Event
testObject_Event_conversation_1 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "oym59-06.i423w"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "n8nl6tp.h5"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdConvCodeDelete
}
testObject_Event_conversation_2 :: Event
testObject_Event_conversation_2 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "2m99----34.id7u09"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "b.0-7.0.rg"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData =
EdMemberUpdate
( MemberUpdateData
{ misTarget = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "oy8yz.f1"}},
misOtrMutedStatus = Just (MutedStatus {fromMutedStatus = 1}),
misOtrMutedRef = Nothing,
misOtrArchived = Nothing,
misOtrArchivedRef = Nothing,
misHidden = Nothing,
misHiddenRef = Nothing,
misConvRoleName = Just roleNameWireAdmin
}
)
}
testObject_Event_conversation_3 :: Event
testObject_Event_conversation_3 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "91.ii9vf.mbwj9k7lmk"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "k3.f.z"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData =
EdConvCodeUpdate
( ConversationCode
{ conversationKey = Key {asciiKey = unsafeRange "CRdONS7988O2QdyndJs1"},
conversationCode = Value {asciiValue = unsafeRange "7d6713"},
conversationUri = Just $ HttpsUrl (URI {uriScheme = Scheme {schemeBS = "https"}, uriAuthority = Just (Authority {authorityUserInfo = Nothing, authorityHost = Host {hostBS = "example.com"}, authorityPort = Nothing}), uriPath = "", uriQuery = Query {queryPairs = []}, uriFragment = Nothing})
}
)
}
testObject_Event_conversation_4 :: Event
testObject_Event_conversation_4 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "ma--6us.i8o--0440"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "97k-u0.b-5c"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdConvAccessUpdate (ConversationAccessData {cupAccess = fromList [PrivateAccess, CodeAccess], cupAccessRoles = fromList []})
}
testObject_Event_conversation_5 :: Event
testObject_Event_conversation_5 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "q.6lm833.o95.l.y2"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "7.m4f7p.ez4zs61"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdMLSWelcome ""
}
testObject_Event_conversation_6 :: Event
testObject_Event_conversation_6 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "391.r"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "8.0-6.t7pxv"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdOtrMessage (OtrMessage {otrSender = ClientId {client = "1"}, otrRecipient = ClientId {client = "1"}, otrCiphertext = "", otrData = Just "I\68655"})
}
testObject_Event_conversation_7 :: Event
testObject_Event_conversation_7 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "b2.ue4k"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "64b3--h.u"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdOtrMessage (OtrMessage {otrSender = ClientId {client = "3"}, otrRecipient = ClientId {client = "3"}, otrCiphertext = "%\SI", otrData = Nothing})
}
testObject_Event_conversation_8 :: Event
testObject_Event_conversation_8 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "36.e9.s-o-17"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "0--gy.705nsa8.j4m"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdTyping StartedTyping
}
testObject_Event_conversation_9 :: Event
testObject_Event_conversation_9 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "743846p6-pp33.1.ktb9.0bmn.efm2bly"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "9--5grmn.j39y3--9n"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData =
EdMembersLeave
( QualifiedUserIdList
{ qualifiedUserIdList =
[ Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "ow8i3fhr.v"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "8kshw-2l.3w44.6c8763a-77r4.gk13zq"}},
Qualified
{ qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")),
qDomain = Domain {_domainText = "xk-no.m5--f8b7"}
},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "x02.p.69y-6.8ncr.u"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "1-47tume1e5l32i.v75is-q4-o.u7qc"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "8ay.ec.k-8"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "u-8.m-42ns2c"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "08kh83-8.vu.i24"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "t1t683.o3--2.3k5.it-5.e1"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "q.ajw-5"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "73m4g.c24em3.v"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "i7zn.li"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "42y78.yekf"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "n63-p87m2.dtq"}},
Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "ns.v2p"}}
]
}
)
}
testObject_Event_conversation_10 :: Event
testObject_Event_conversation_10 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "1852a.o-4"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "4-p.d7b8d3.6.c8--jds3-1acy"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdMLSMessage "s\b\138w\236\231P(\ESC\216\205"
}
testObject_Event_conversation_11 :: Event
testObject_Event_conversation_11 =
Event
{ evtConv = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "wwzw-ly4jk5.6790-y.j04o-21.ltl"}},
evtSubConv = Nothing,
evtFrom = Qualified {qUnqualified = Id (fromJust (UUID.fromString "2126ea99-ca79-43ea-ad99-a59616468e8e")), qDomain = Domain {_domainText = "70-o.ncd"}},
evtTime = UTCTime {utctDay = ModifiedJulianDay 58119, utctDayTime = 0},
evtData = EdTyping StoppedTyping
}
|
5b698091903f383666cdd4874bab2d09ef2b86fb50e5baeb76eba6c87fa1e523 | a9032676/Codewars-Haskell | FoldingThroughAFixedPoint.hs | # LANGUAGE DeriveFunctor #
# LANGUAGE LambdaCase #
{-# LANGUAGE RankNTypes, ExistentialQuantification #-}
module FoldingThroughAFixedPoint where
import Control.Applicative
Consider the two following types
newtype Least f
= Least (forall r . (f r -> r) -> r)
data Greatest f
= forall s . Greatest (s -> f s) s
-- They each have a special non-recursive relationship with 'f' when
-- it is a 'Functor'
unwrap :: Functor f => Greatest f -> f (Greatest f)
unwrap (Greatest u s) = Greatest u <$> u s
wrap :: Functor f => f (Least f) -> Least f
wrap f = Least (\k -> k (fold k <$> f))
-- They each are closely tied to the notions of folding and unfolding
-- as well
fold :: (f r -> r) -> (Least f -> r)
fold k (Least g) = g k
unfold :: (s -> f s) -> (s -> Greatest f)
unfold = Greatest
-- It is the case that any "strictly positive"
type in Haskell is representable using Least .
We first need the data tyundefinedpe 's " signature functor " .
-- For instance, here is one for []
data ListF a x = Nil | Cons a x deriving Functor
-- Then we can map into and out of lists
listLeast :: [a] -> Least (ListF a)
listLeast l = Least $ \k -> k $ case l of
[] -> Nil
a : as -> Cons a (fold k (listLeast as))
leastList :: Least (ListF a) -> [a]
leastList = fold $ \case
Nil -> []
Cons a as -> a : as
-- It is also the case that these types are representable using
-- Greatest.
listGreatest :: [a] -> Greatest (ListF a)
listGreatest = unfold $ \case
[] -> Nil
a:as -> Cons a as
greatestList :: Greatest (ListF a) -> [a]
greatestList (Greatest u s) = case u s of
Nil -> []
Cons a s' -> a : greatestList (unfold u s')
-- Given all of these types are isomorphic, we ought to be able to go
-- directly from least to greatest fixed points and visa versa. Can
-- you write the functions which witness this last isomorphism
-- generally for any functor?
-- r := Already fold elements
-- s := unfold elements
-- Look as anamorphism:
-- f
-- s ----------> Least f
-- | ^
Coalg | | wrap
-- v |
-- f s -------> f (Least f)
-- fmap m
-- (forall s . (s -> f s) s) -> (forall r . (f r -> r) -> r)
greatestLeast :: Functor f => Greatest f -> Least f
greatestLeast ( Greatest coalg s ) = wrap . fmap ( greatestLeast . Greatest coalg ) . coalg $ s
greatestLeast = wrap . fmap greatestLeast . unwrap
-- Look as catamorphism:
-- fmap m
-- f (Greatest f) --------> f r
-- | |
-- ??? | | alg
-- v v
-- Greatest f <------------ r
--
-- (forall r . (f r -> r) -> r) -> (forall s . (s -> f s) s)
-- (s -> f s)
-- ((f r -> r) -> r) -> f (f r -> r) -> r)
leastGreatest :: Functor f => Least f -> Greatest f
leastGreatest (Least l) = l . Greatest . fmap $ unwrap | null | https://raw.githubusercontent.com/a9032676/Codewars-Haskell/6eccd81e9b6ae31b5c0a28ecc16b933f3abae1a5/src/FoldingThroughAFixedPoint.hs | haskell | # LANGUAGE RankNTypes, ExistentialQuantification #
They each have a special non-recursive relationship with 'f' when
it is a 'Functor'
They each are closely tied to the notions of folding and unfolding
as well
It is the case that any "strictly positive"
For instance, here is one for []
Then we can map into and out of lists
It is also the case that these types are representable using
Greatest.
Given all of these types are isomorphic, we ought to be able to go
directly from least to greatest fixed points and visa versa. Can
you write the functions which witness this last isomorphism
generally for any functor?
r := Already fold elements
s := unfold elements
Look as anamorphism:
f
s ----------> Least f
| ^
v |
f s -------> f (Least f)
fmap m
(forall s . (s -> f s) s) -> (forall r . (f r -> r) -> r)
Look as catamorphism:
fmap m
f (Greatest f) --------> f r
| |
??? | | alg
v v
Greatest f <------------ r
(forall r . (f r -> r) -> r) -> (forall s . (s -> f s) s)
(s -> f s)
((f r -> r) -> r) -> f (f r -> r) -> r) | # LANGUAGE DeriveFunctor #
# LANGUAGE LambdaCase #
module FoldingThroughAFixedPoint where
import Control.Applicative
Consider the two following types
newtype Least f
= Least (forall r . (f r -> r) -> r)
data Greatest f
= forall s . Greatest (s -> f s) s
unwrap :: Functor f => Greatest f -> f (Greatest f)
unwrap (Greatest u s) = Greatest u <$> u s
wrap :: Functor f => f (Least f) -> Least f
wrap f = Least (\k -> k (fold k <$> f))
fold :: (f r -> r) -> (Least f -> r)
fold k (Least g) = g k
unfold :: (s -> f s) -> (s -> Greatest f)
unfold = Greatest
type in Haskell is representable using Least .
We first need the data tyundefinedpe 's " signature functor " .
data ListF a x = Nil | Cons a x deriving Functor
listLeast :: [a] -> Least (ListF a)
listLeast l = Least $ \k -> k $ case l of
[] -> Nil
a : as -> Cons a (fold k (listLeast as))
leastList :: Least (ListF a) -> [a]
leastList = fold $ \case
Nil -> []
Cons a as -> a : as
listGreatest :: [a] -> Greatest (ListF a)
listGreatest = unfold $ \case
[] -> Nil
a:as -> Cons a as
greatestList :: Greatest (ListF a) -> [a]
greatestList (Greatest u s) = case u s of
Nil -> []
Cons a s' -> a : greatestList (unfold u s')
Coalg | | wrap
greatestLeast :: Functor f => Greatest f -> Least f
greatestLeast ( Greatest coalg s ) = wrap . fmap ( greatestLeast . Greatest coalg ) . coalg $ s
greatestLeast = wrap . fmap greatestLeast . unwrap
leastGreatest :: Functor f => Least f -> Greatest f
leastGreatest (Least l) = l . Greatest . fmap $ unwrap |
4da1efb49f148d3479ec60ffdf8780941a485e49727d83324e3ed41f0a9e544f | openmusic-project/openmusic | helpfiles.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 :
;=========================================================================
DocFile
; helpfiles patches
; an alternative to tutorial files
; This will import the patches in the workspace
; making them editable
DocFile
(in-package :om)
;;=========THIS IS THE SPECIAL FOLDER WITH help files===================
(defvar *om-helpfolder* nil "The helpfiles folder in the workspace.")
(defclass OMhelpFolder (OMWorkSpace) ()
(:documentation "This is the special folder which contains help files. #enddoc#
#seealso# (OMFolder OMinstance) #seealso#"))
;--------------------------------------------------
;INTERFACE
;--------------------------------------------------
(defmethod get-elements ((self OMhelpFolder))
"helpfiles folder's elements are OMinstances." (elements self))
( defmethod get - class - icon ( ( self OMhelpFolder ) ) ' globals - folder - icon )
(defmethod get-editor-class ((self OMhelpFolder)) 'HelpFilesEditor)
(defmethod OpenEditorframe ((self OMhelpFolder))
"Show the globals folder 'self' as a container."
(or (editorframe self)
(panel (open-new-nonrelationFrame self "Help Files" (get-elements self)))))
(defmethod elements-pathname ((self OMhelpfolder))
(om-make-pathname
:device (mypathname self)
:directory (pathname-directory (mypathname self))))
;from ws-load-element
(defun help-load-element (path &optional (i 0))
(let* ((*package* (find-package :om))
newicon newobj)
(handler-bind (
(error #'(lambda (c)
(om-message-dialog (format nil "Error while loading ~A in WorkSpace: ~D"
(namestring path)
(om-report-condition c)
)
:size (om-make-point 300 300))
(om-abort)
)))
(if (and (directoryp path) (not (systemdirectoryp path)))
(let ((j -1) (elements (om-directory path :files t :directories t)))
(setf newobj (omNG-make-new-folder (car (last (pathname-directory path)))))
(setf (mypathname newobj) (make-pathname
:device (pathname-device path)
:directory (append (butlast (pathname-directory path)) (list (name newobj)))))
(setf (elements newobj) (remove nil (mapcar #'(lambda (elt) (ws-load-element elt (incf j))) elements))))
(when (and (stringp (pathname-name path))
(not (string-equal "" (pathname-name path))))
(let ((type (pathname-type path)))
(when (string-equal type "tmp")
(let* ((newpath1 (namestring (om-make-pathname :directory (pathname-directory path) :name (pathname-name path))))
(newpath2 (om-make-pathname :directory (pathname-directory path) :name (string+ (pathname-name newpath1) " (recovered)")
:type (pathname-type newpath1))))
(rename-file path newpath2)
(setq path newpath2))))
(let ((obj (object-from-file path)))
(when obj
(setf (mypathname obj) path)
(setf newobj obj)
))))
(when newobj
(let* ((wsparams (get-init-wsparams path))
(wspar (subseq wsparams 2 5))
(doc (str-with-nl (nth 5 wsparams))))
(setf newicon (nth 6 wsparams))
(setf (wsparams newobj) (loop for item in wspar collect (eval item)))
(setf (doc newobj) doc)
(setf (omversion newobj) (car wsparams))
(setf (create-info newobj) (list (nth 8 wsparams) (nth 9 wsparams)))
(when (directoryp path) (setf (presentation newobj) (or (nth 7 wsparams) 0)))
(when newicon (setf (icon newobj) (eval newicon)))
(pushr (format nil "Element ~s loaded" path) *import-log*)
newobj)))))
(defmethod load-elements ((self OMhelpfolder))
"Make instances for all elements in 'self', but their are not yet loaded."
(let ((j -1)
(elements (om-directory
(om-make-pathname :device (mypathname self)
:directory (pathname-directory (mypathname self)))
:files t :directories t)))
(setf *loading-ws* t)
(setf (elements self) (remove nil (mapcar #'(lambda (x) (help-load-element x (incf j))) elements) :test 'equal))
(setf *loading-ws* nil)
))
;--------------------------------------------------
;Tools
;--------------------------------------------------
(defun init-helpfolder ()
"Make an instance of helpfiles folder and store it in the *om-helpfolder* variable."
(setf *om-helpfolder* (omNG-protect-object (make-instance 'OMhelpFolder
:Name "helpfiles"
:icon 23
)))
(setf (mypathname *om-helpfolder*)
(make-pathname :directory (append (pathname-directory (mypathname *current-workSpace*))
(list "helpfiles"))))
(load-elements *om-helpfolder*)
)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun open-helpfile (patch)
(let* ((container (editorframe *current-workSpace*))
(pos (om-make-point 0 0))
(directory (merge-pathnames (make-pathname :directory '(:relative "resources" "online")) *om-root*))
(ref (reference (object patch)))
(name (if (omclass-p ref) (name ref) ref))
(name (if (special-name-for-tutorial name)
(special-name-for-tutorial name)
(format nil "~S" name)))
(file (format nil "~A.omp" name))
(helpfile (merge-pathnames (string+ file) directory))
(wshelp (merge-pathnames (make-pathname :directory '(:relative "helpfiles"))
(mypathname *current-workSpace*))))
needed to init the folder in the wskp
(init-helpfolder)
( oa::om - delete - directory wshelp )
;create if necesary heplfiles folder:
(if (not (check-folder wshelp))
(make-new-folder container folder (om-make-point 0 0)))
;create and put helpfile in folder:
(if (probe-file helpfile)
(progn
(ws-import-element helpfile wshelp)
;necessary to update new imported:
(load-elements *current-workSpace*)
(load-elements *om-helpfolder*)
;open patch:
(let* ((names (mapcar #'name (get-elements *om-helpfolder*)))
(poshelp (position name names :test 'equal))
(ifpos (if (special-name-for-tutorial name)
(special-name-for-tutorial name)))
)
;THIS OPENS THE PATCH FROM THE CURRENT WS:
(openobjecteditor (nth poshelp (get-elements *om-helpfolder*)))
))
(progn
;(openobjecteditor (special-name-for-tutorial name))
(capi::display-message "Not Available Yet...")))
))
| null | https://raw.githubusercontent.com/openmusic-project/openmusic/e45fdac8079b7effd5a8271c21000f2b48344563/OPENMUSIC/code/kernel/doc/helpfiles.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.
=========================================================================
helpfiles patches
an alternative to tutorial files
This will import the patches in the workspace
making them editable
=========THIS IS THE SPECIAL FOLDER WITH help files===================
--------------------------------------------------
INTERFACE
--------------------------------------------------
from ws-load-element
--------------------------------------------------
Tools
--------------------------------------------------
create if necesary heplfiles folder:
create and put helpfile in folder:
necessary to update new imported:
open patch:
THIS OPENS THE PATCH FROM THE CURRENT WS:
(openobjecteditor (special-name-for-tutorial name)) | 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 :
DocFile
DocFile
(in-package :om)
(defvar *om-helpfolder* nil "The helpfiles folder in the workspace.")
(defclass OMhelpFolder (OMWorkSpace) ()
(:documentation "This is the special folder which contains help files. #enddoc#
#seealso# (OMFolder OMinstance) #seealso#"))
(defmethod get-elements ((self OMhelpFolder))
"helpfiles folder's elements are OMinstances." (elements self))
( defmethod get - class - icon ( ( self OMhelpFolder ) ) ' globals - folder - icon )
(defmethod get-editor-class ((self OMhelpFolder)) 'HelpFilesEditor)
(defmethod OpenEditorframe ((self OMhelpFolder))
"Show the globals folder 'self' as a container."
(or (editorframe self)
(panel (open-new-nonrelationFrame self "Help Files" (get-elements self)))))
(defmethod elements-pathname ((self OMhelpfolder))
(om-make-pathname
:device (mypathname self)
:directory (pathname-directory (mypathname self))))
(defun help-load-element (path &optional (i 0))
(let* ((*package* (find-package :om))
newicon newobj)
(handler-bind (
(error #'(lambda (c)
(om-message-dialog (format nil "Error while loading ~A in WorkSpace: ~D"
(namestring path)
(om-report-condition c)
)
:size (om-make-point 300 300))
(om-abort)
)))
(if (and (directoryp path) (not (systemdirectoryp path)))
(let ((j -1) (elements (om-directory path :files t :directories t)))
(setf newobj (omNG-make-new-folder (car (last (pathname-directory path)))))
(setf (mypathname newobj) (make-pathname
:device (pathname-device path)
:directory (append (butlast (pathname-directory path)) (list (name newobj)))))
(setf (elements newobj) (remove nil (mapcar #'(lambda (elt) (ws-load-element elt (incf j))) elements))))
(when (and (stringp (pathname-name path))
(not (string-equal "" (pathname-name path))))
(let ((type (pathname-type path)))
(when (string-equal type "tmp")
(let* ((newpath1 (namestring (om-make-pathname :directory (pathname-directory path) :name (pathname-name path))))
(newpath2 (om-make-pathname :directory (pathname-directory path) :name (string+ (pathname-name newpath1) " (recovered)")
:type (pathname-type newpath1))))
(rename-file path newpath2)
(setq path newpath2))))
(let ((obj (object-from-file path)))
(when obj
(setf (mypathname obj) path)
(setf newobj obj)
))))
(when newobj
(let* ((wsparams (get-init-wsparams path))
(wspar (subseq wsparams 2 5))
(doc (str-with-nl (nth 5 wsparams))))
(setf newicon (nth 6 wsparams))
(setf (wsparams newobj) (loop for item in wspar collect (eval item)))
(setf (doc newobj) doc)
(setf (omversion newobj) (car wsparams))
(setf (create-info newobj) (list (nth 8 wsparams) (nth 9 wsparams)))
(when (directoryp path) (setf (presentation newobj) (or (nth 7 wsparams) 0)))
(when newicon (setf (icon newobj) (eval newicon)))
(pushr (format nil "Element ~s loaded" path) *import-log*)
newobj)))))
(defmethod load-elements ((self OMhelpfolder))
"Make instances for all elements in 'self', but their are not yet loaded."
(let ((j -1)
(elements (om-directory
(om-make-pathname :device (mypathname self)
:directory (pathname-directory (mypathname self)))
:files t :directories t)))
(setf *loading-ws* t)
(setf (elements self) (remove nil (mapcar #'(lambda (x) (help-load-element x (incf j))) elements) :test 'equal))
(setf *loading-ws* nil)
))
(defun init-helpfolder ()
"Make an instance of helpfiles folder and store it in the *om-helpfolder* variable."
(setf *om-helpfolder* (omNG-protect-object (make-instance 'OMhelpFolder
:Name "helpfiles"
:icon 23
)))
(setf (mypathname *om-helpfolder*)
(make-pathname :directory (append (pathname-directory (mypathname *current-workSpace*))
(list "helpfiles"))))
(load-elements *om-helpfolder*)
)
(defun open-helpfile (patch)
(let* ((container (editorframe *current-workSpace*))
(pos (om-make-point 0 0))
(directory (merge-pathnames (make-pathname :directory '(:relative "resources" "online")) *om-root*))
(ref (reference (object patch)))
(name (if (omclass-p ref) (name ref) ref))
(name (if (special-name-for-tutorial name)
(special-name-for-tutorial name)
(format nil "~S" name)))
(file (format nil "~A.omp" name))
(helpfile (merge-pathnames (string+ file) directory))
(wshelp (merge-pathnames (make-pathname :directory '(:relative "helpfiles"))
(mypathname *current-workSpace*))))
needed to init the folder in the wskp
(init-helpfolder)
( oa::om - delete - directory wshelp )
(if (not (check-folder wshelp))
(make-new-folder container folder (om-make-point 0 0)))
(if (probe-file helpfile)
(progn
(ws-import-element helpfile wshelp)
(load-elements *current-workSpace*)
(load-elements *om-helpfolder*)
(let* ((names (mapcar #'name (get-elements *om-helpfolder*)))
(poshelp (position name names :test 'equal))
(ifpos (if (special-name-for-tutorial name)
(special-name-for-tutorial name)))
)
(openobjecteditor (nth poshelp (get-elements *om-helpfolder*)))
))
(progn
(capi::display-message "Not Available Yet...")))
))
|
fd56df5ab2d17ee3577b5e2d1dfd3efc91b036dc0c1a0fd36c9c504219ccdd4e | patricoferris/ocaml-multicore-monorepo | log.ml | let () =
Eio_main.run @@ fun env ->
Dream.run env
@@ Dream.logger
@@ Dream.router [
Dream.get "/"
(fun request ->
Dream.log "Sending greeting to %s!" (Dream.client request);
Dream.html "Good morning, world!");
Dream.get "/fail"
(fun _ ->
Dream.warning (fun log -> log "Raising an exception!");
raise (Failure "The Web app failed!"));
]
@@ Dream.not_found
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/dream/example/a-log/log.ml | ocaml | let () =
Eio_main.run @@ fun env ->
Dream.run env
@@ Dream.logger
@@ Dream.router [
Dream.get "/"
(fun request ->
Dream.log "Sending greeting to %s!" (Dream.client request);
Dream.html "Good morning, world!");
Dream.get "/fail"
(fun _ ->
Dream.warning (fun log -> log "Raising an exception!");
raise (Failure "The Web app failed!"));
]
@@ Dream.not_found
| |
a17631c3bfc59be9ac24820a6c63f2541cc741da6808e68e5f41d75b127d179d | kazu-yamamoto/quic | Stream.hs | module Network.QUIC.Stream (
-- * Types
Stream
, streamId
, streamConnection
, newStream
, TxStreamData(..)
, Flow(..)
, defaultFlow
, StreamState(..)
, RecvStreamQ(..)
, RxStreamData(..)
, Length
, syncFinTx
, waitFinTx
-- * Misc
, getTxStreamOffset
, isTxStreamClosed
, setTxStreamClosed
, getRxStreamOffset
, isRxStreamClosed
, setRxStreamClosed
, readStreamFlowTx
, addTxStreamData
, setTxMaxStreamData
, readStreamFlowRx
, addRxStreamData
, setRxMaxStreamData
, addRxMaxStreamData
, getRxMaxStreamData
, getRxStreamWindow
, flowWindow
*
, takeRecvStreamQwithSize
, putRxStreamData
, tryReassemble
-- * Table
, StreamTable
, emptyStreamTable
, lookupStream
, insertStream
, deleteStream
, insertCryptoStreams
, deleteCryptoStream
, lookupCryptoStream
) where
import Network.QUIC.Stream.Misc
import Network.QUIC.Stream.Reass
import Network.QUIC.Stream.Table
import Network.QUIC.Stream.Types
| null | https://raw.githubusercontent.com/kazu-yamamoto/quic/6b9500c8057ac3d974a47543b74b5db11e29ecc0/Network/QUIC/Stream.hs | haskell | * Types
* Misc
* Table | module Network.QUIC.Stream (
Stream
, streamId
, streamConnection
, newStream
, TxStreamData(..)
, Flow(..)
, defaultFlow
, StreamState(..)
, RecvStreamQ(..)
, RxStreamData(..)
, Length
, syncFinTx
, waitFinTx
, getTxStreamOffset
, isTxStreamClosed
, setTxStreamClosed
, getRxStreamOffset
, isRxStreamClosed
, setRxStreamClosed
, readStreamFlowTx
, addTxStreamData
, setTxMaxStreamData
, readStreamFlowRx
, addRxStreamData
, setRxMaxStreamData
, addRxMaxStreamData
, getRxMaxStreamData
, getRxStreamWindow
, flowWindow
*
, takeRecvStreamQwithSize
, putRxStreamData
, tryReassemble
, StreamTable
, emptyStreamTable
, lookupStream
, insertStream
, deleteStream
, insertCryptoStreams
, deleteCryptoStream
, lookupCryptoStream
) where
import Network.QUIC.Stream.Misc
import Network.QUIC.Stream.Reass
import Network.QUIC.Stream.Table
import Network.QUIC.Stream.Types
|
0eb101e6b6c1991b964b7b4b182a31b2e4a0d4dae9c488b85cd97099dc42ade1 | scalaris-team/scalaris | rrepair_proto_sched_SUITE.erl | 2014 Zuse Institute Berlin
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.
@author < >
%% @doc Tests for the replica repair modules.
%% @end
%% @version $Id$
-module(rrepair_proto_sched_SUITE).
-author('').
-vsn('$Id$').
%% start proto scheduler for this suite
-define(proto_sched(Action), proto_sched_fun(Action)).
-include("rrepair_SUITE.hrl").
%% number of executions per test (sub-) group
-define(NUM_EXECUTIONS, 5).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
all() ->
[
{group, gsession_ttl},
{group, repair}
].
groups() ->
[
{gsession_ttl, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], [session_ttl]},
{repair, [sequence],
[
{upd_trivial, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{upd_shash, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{upd_bloom, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{upd_merkle, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{upd_art, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{regen_trivial,[{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{regen_shash, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{regen_bloom, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{regen_merkle, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{regen_art, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{mixed_trivial,[{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{mixed_shash, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{mixed_bloom, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{mixed_merkle, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{mixed_art, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()}
]}
].
suite() -> [ {timetrap, {seconds, 20}} ].
init_per_group_special(_Group, Config) ->
Config.
end_per_group_special(_Group, Config) ->
Config.
-spec proto_sched_fun(start | stop) -> ok.
proto_sched_fun(start) ->
%% ct:pal("Starting proto scheduler"),
proto_sched:thread_num(1),
proto_sched:thread_begin();
proto_sched_fun(stop) ->
%% is a ring running?
case erlang:whereis(pid_groups) =:= undefined
orelse pid_groups:find_a(proto_sched) =:= failed of
true -> ok;
false ->
%% then finalize proto_sched run:
%% try to call thread_end(): if this
%% process was running the proto_sched
%% thats fine, otherwise thread_end()
%% will raise an exception
proto_sched:thread_end(),
proto_sched:wait_for_end(),
unittest_helper:print_proto_sched_stats(at_end_if_failed),
proto_sched:cleanup()
end.
| null | https://raw.githubusercontent.com/scalaris-team/scalaris/feb894d54e642bb3530e709e730156b0ecc1635f/test/rrepair_proto_sched_SUITE.erl | erlang | you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@doc Tests for the replica repair modules.
@end
@version $Id$
start proto scheduler for this suite
number of executions per test (sub-) group
ct:pal("Starting proto scheduler"),
is a ring running?
then finalize proto_sched run:
try to call thread_end(): if this
process was running the proto_sched
thats fine, otherwise thread_end()
will raise an exception | 2014 Zuse Institute Berlin
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@author < >
-module(rrepair_proto_sched_SUITE).
-author('').
-vsn('$Id$').
-define(proto_sched(Action), proto_sched_fun(Action)).
-include("rrepair_SUITE.hrl").
-define(NUM_EXECUTIONS, 5).
all() ->
[
{group, gsession_ttl},
{group, repair}
].
groups() ->
[
{gsession_ttl, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], [session_ttl]},
{repair, [sequence],
[
{upd_trivial, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{upd_shash, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{upd_bloom, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{upd_merkle, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{upd_art, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{regen_trivial,[{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{regen_shash, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{regen_bloom, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{regen_merkle, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{regen_art, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default() ++ regen_special()},
{mixed_trivial,[{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{mixed_shash, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{mixed_bloom, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{mixed_merkle, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()},
{mixed_art, [{repeat_until_any_fail, ?NUM_EXECUTIONS}], repair_default()}
]}
].
suite() -> [ {timetrap, {seconds, 20}} ].
init_per_group_special(_Group, Config) ->
Config.
end_per_group_special(_Group, Config) ->
Config.
-spec proto_sched_fun(start | stop) -> ok.
proto_sched_fun(start) ->
proto_sched:thread_num(1),
proto_sched:thread_begin();
proto_sched_fun(stop) ->
case erlang:whereis(pid_groups) =:= undefined
orelse pid_groups:find_a(proto_sched) =:= failed of
true -> ok;
false ->
proto_sched:thread_end(),
proto_sched:wait_for_end(),
unittest_helper:print_proto_sched_stats(at_end_if_failed),
proto_sched:cleanup()
end.
|
c818a27d534c6f59c9f1668b9d4a21ed968a10fbc89942adfee616910ce43015 | boomerang-lang/boomerang | berror.ml | (******************************************************************************)
The Harmony Project
(******************************************************************************)
Copyright ( C ) 2008 and
(* *)
(* This library is free software; you can redistribute it and/or *)
(* modify it under the terms of the GNU Lesser General Public *)
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
(* *)
(* This library is distributed in the hope that it will be useful, *)
(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)
(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *)
(* Lesser General Public License for more details. *)
(******************************************************************************)
(* /src/berror.ml *)
(* Boomerang errors *)
$ I d : berror.ml 4607 2009 - 08 - 03 16:53:28Z ddavi $
(******************************************************************************)
open Hbase
open Ubase
let msg = Util.format
(* static errors in the interpreter *)
let static_error i msg_thk = raise
(Error.Harmony_error
(fun () ->
msg "@[%s:@ static error@\n" (Info.string_of_t i);
msg_thk ();
msg "@]@\n"))
(* checked run-time errors, triggered when contracts fail *)
let blame_error i msg_thk = raise
(Error.Harmony_error
(fun () ->
msg "@[%s:@ run-time@ checking@ error@\n" (Info.string_of_t i);
msg_thk ();
msg "@]"))
(* unexpected run-time errors *)
let run_error i msg_thk = raise
(Error.Harmony_error
(fun () ->
msg "@[%s:@ unexpected@ run-time@ error@\n" (Info.string_of_t i);
msg_thk ();
msg "@]"))
| null | https://raw.githubusercontent.com/boomerang-lang/boomerang/b42c2bfc72030bbe5c32752c236c0aad3b17d149/lib/berror.ml | ocaml | ****************************************************************************
****************************************************************************
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
****************************************************************************
/src/berror.ml
Boomerang errors
****************************************************************************
static errors in the interpreter
checked run-time errors, triggered when contracts fail
unexpected run-time errors | The Harmony Project
Copyright ( C ) 2008 and
License as published by the Free Software Foundation ; either
version 2.1 of the License , or ( at your option ) any later version .
$ I d : berror.ml 4607 2009 - 08 - 03 16:53:28Z ddavi $
open Hbase
open Ubase
let msg = Util.format
let static_error i msg_thk = raise
(Error.Harmony_error
(fun () ->
msg "@[%s:@ static error@\n" (Info.string_of_t i);
msg_thk ();
msg "@]@\n"))
let blame_error i msg_thk = raise
(Error.Harmony_error
(fun () ->
msg "@[%s:@ run-time@ checking@ error@\n" (Info.string_of_t i);
msg_thk ();
msg "@]"))
let run_error i msg_thk = raise
(Error.Harmony_error
(fun () ->
msg "@[%s:@ unexpected@ run-time@ error@\n" (Info.string_of_t i);
msg_thk ();
msg "@]"))
|
3272fcc0ea3eda1fdbacea0f8df4a3c5be5f1976cfb3119ee0743c6970aa102c | jberryman/unagi-chan | UnagiUnboxed.hs | # LANGUAGE RankNTypes , ScopedTypeVariables , BangPatterns #
# LANGUAGE TypeSynonymInstances , FlexibleInstances , CPP #
module UnagiUnboxed (unagiUnboxedMain) where
Unagi - chan - specific tests
--
Forked from tests / Unagi.hs at 337600f
import Control.Concurrent.Chan.Unagi.Unboxed
import qualified Control.Concurrent.Chan.Unagi.Unboxed.Internal as UI
import Control.Monad
import qualified Data.Primitive as P
import Data.IORef
import Data.Int(Int8,Int16,Int32,Int64)
import Data.Word
import Data.Maybe
import Data.Typeable
import Control.Concurrent(forkIO,threadDelay)
import Control.Concurrent.MVar
import Control.Exception
import Data.Atomics.Counter.Fat
import Prelude
primitive 0.7.0 got rid of Addr
#if MIN_VERSION_primitive(0,7,0)
import qualified Data.Primitive.Ptr as P
type Addr = P.Ptr Word8
nullAddr :: Addr
nullAddr = P.nullPtr
plusAddr :: Addr -> Int -> Addr
plusAddr = P.advancePtr
#else
import qualified Data.Primitive (Addr, nullAddr)
-- TODO Maybe refactor & get rid of these
instance Show Addr where
show _ = "<addr>"
#endif
unagiUnboxedMain :: IO ()
unagiUnboxedMain = do
putStrLn "==================="
putStrLn "Testing Unagi.Unboxed details:"
-- ------
putStr "Smoke test at different starting offsets, spanning overflow... "
mapM_ smoke $ [ (maxBound - UI.sEGMENT_LENGTH - 1) .. maxBound]
++ [minBound .. (minBound + UI.sEGMENT_LENGTH + 1)]
putStrLn "OK"
-- ------
putStr "segSource sanity... "
applyToAllPrim segSourceMagicSanity
putStrLn "OK"
-- ------
putStr "Atomicity of atomic unicorns... "
applyToAllPrim atomicUnicornAtomicicity
putStrLn "OK"
-- ------
putStr "Correct first write... "
mapM_ correctFirstWrite [ (maxBound - 7), maxBound, minBound, 0]
putStrLn "OK"
-- ------
putStr "Correct initial writes... "
mapM_ correctInitialWrites [ (maxBound - UI.sEGMENT_LENGTH), (maxBound - UI.sEGMENT_LENGTH) - 1, maxBound, minBound, 0]
putStrLn "OK"
-- ------
let tries = 10000
putStrLn $ "Checking for deadlocks from killed Unagi reader in a fancy way, x"++show tries
checkDeadlocksReaderUnagi tries
smoke :: Int -> IO ()
smoke n = do
smoke1 n
smoke2 n
test each of UnagiPrim
applyToAllPrim smokeManyElement
test for atomicUnicorns
applyToAllPrim smokeManyUnicorn
test a function against each Prim type elements not equal to atomicUnicorn
applyToAllPrim :: (forall e. (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()) -> IO ()
applyToAllPrim f = do
f ('c' :: Char)
f (3.14159 :: Float)
f (-1.000000000000001 :: Double)
f (maxBound :: Int)
f (minBound :: Int8)
f (maxBound :: Int16)
f (minBound :: Int32)
f (maxBound :: Int64)
f (maxBound :: Word)
f (maxBound :: Word8)
f (minBound :: Word16)
f (minBound :: Word32)
f (minBound :: Word64)
f (nullAddr `plusAddr` 1024 :: Addr)
-- TODO Maybe refactor & get rid of these
instance Num Addr where
instance Num Char where
-- www.../rrr... spanning overflow
smoke1 :: Int -> IO ()
smoke1 n = do
(i,o) <- UI.newChanStarting n
let inp = [0 .. (UI.sEGMENT_LENGTH * 3)]
mapM_ (writeChan i) inp
outp <- getChanContents o
unless (and (zipWith (==) inp outp)) $
error $ "Smoke test failed with starting offset of: "++(show n)
-- w/r/w/r... spanning overflow
smoke2 :: Int -> IO ()
smoke2 n = do
(i,o) <- UI.newChanStarting n
let inp = [0 .. (UI.sEGMENT_LENGTH * 3)]
mapM_ (check i o) inp
where check i o x = do
writeChan i x
x' <- readChan o
unless (x == x') $
error $ "Smoke test failed with starting offset of: "++(show n)++"at write: "++(show x)
for smoke checking size , and alignment of different Prim types , and allowing
-- testing of writing atomicUnicorn
smokeManyElement :: (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()
smokeManyElement e = do
(i,o) <- newChan
let n = UI.sEGMENT_LENGTH*2 + 1
replicateM_ n (writeChan i e)
outp <- getChanContents o
unless (all (== e) $ take n outp) $
error $ "smokeManyElement failed with type "++(show $ typeOf e)++": "++(show e)++" /= "++(show outp)
-- smokeManyElement for atomicUnicorn values
smokeManyUnicorn :: forall e. (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()
smokeManyUnicorn _ =
maybe (return ()) smokeManyElement (atomicUnicorn :: Maybe e)
check our segSource is doing what we expect with magic values :
segSourceMagicSanity :: forall e. (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()
segSourceMagicSanity _ =
case atomicUnicorn :: Maybe e of
Nothing -> return ()
Just e -> do
(_,eArr) <- UI.segSource :: IO (UI.SignalIntArray, UI.ElementArray e)
forM_ [0.. UI.sEGMENT_LENGTH-1] $ \i-> do
e' <- UI.readElementArray eArr i
unless (e == e') $
error $ "in segSource, with type "++(show $ typeOf e)++", "++(show e)++" /= "++(show e')
-- -------------
-- Make sure we get no tearing of adjacent word-size or smaller (as determined
-- by atomicUnicorn instantiation) values, making sure we cross a cache-line.
atomicUnicornAtomicicity :: forall e. (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()
atomicUnicornAtomicicity _e =
when (isJust (atomicUnicorn :: Maybe e)) $ do
(_,eArr) <- UI.segSource :: IO (UI.SignalIntArray, UI.ElementArray e)
let iters = (64 `quot` P.sizeOf _e) + 1
when (iters >= UI.sEGMENT_LENGTH) $
error "Our sEGMENT_LENGTH is smaller than expected; please fix test"
just skip Addr for now :
unless ( isJust (cast _e :: Maybe Addr)
|| isJust (cast _e :: Maybe Char)) $
forM_ [0.. iters] $ \i0 -> do
let i1 = i0+1
rd = UI.readElementArray eArr
first0 <- rd i0
first1 <- rd i1
v0 <- newEmptyMVar
v1 <- newEmptyMVar
let incr f v i = go
where go _ 0 = putMVar v ()
go expected n = do
val <- rd i
unless (val == expected) $
error $ "atomicUnicornAtomicicity with type "++(show $ typeOf val)++" "++(show val)++" /= "++(show expected)
let !next = f val
UI.writeElementArray eArr i next
go next (n-1)
let counts = 1000000 :: Int
_ <- forkIO $ incr (+1) v0 i0 first0 counts
_ <- forkIO $ incr (subtract 1) v1 i1 first1 counts
BlockedIndefinitelyOnMVar means a problem TODO make better
takeMVar v0 >> takeMVar v1
correctFirstWrite :: Int -> IO ()
correctFirstWrite n = do
(i,UI.OutChan (UI.ChanEnd _ arrRef)) <- UI.newChanStarting n
writeChan i (7::Int)
(UI.StreamHead _ (UI.Stream sigArr eArr _ _)) <- readIORef arrRef
cell <- UI.readElementArray eArr 0 :: IO Int
case cell of
7 -> return ()
_ -> error "Expected a write at index 0 of 7"
sigCell <- P.readByteArray sigArr 0 :: IO Int
i.e. cellWritten
error "Expected cellWritten at sigArr!0"
-- check writes by doing a segment+1-worth of reads by hand
-- also check that segments pre-allocated as expected
correctInitialWrites :: Int -> IO ()
correctInitialWrites startN = do
(i,(UI.OutChan (UI.ChanEnd _ arrRef))) <- UI.newChanStarting startN
let writes = [0..UI.sEGMENT_LENGTH]
mapM_ (writeChan i) writes
(UI.StreamHead _ (UI.Stream sigArr eArr _ next)) <- readIORef arrRef
check all of first segment :
forM_ (init writes) $ \ix-> do
cell <- UI.readElementArray eArr ix :: IO Int
sigCell <- P.readByteArray sigArr ix :: IO Int
unless (cell == ix && sigCell == 1) $
error $ "Expected a write at index "++(show ix)++" of same value but got "++(show cell)++" with signal "++(show sigCell)
-- check last write:
lastSeg <- readIORef next
case lastSeg of
(UI.Next (UI.Stream sigArr2 eArr2 _ next2)) -> do
cell <- UI.readElementArray eArr2 0 :: IO Int
sigCell <- P.readByteArray sigArr2 0 :: IO Int
unless (cell == last writes && sigCell == 1) $
error $ "Expected last write at index "++(show $ last writes)++" of same value but got "++(show cell)
-- check pre-allocation:
n2 <- readIORef next2
case n2 of
(UI.Next (UI.Stream _ _ _ next3)) -> do
n3 <- readIORef next3
case n3 of
UI.NoSegment -> return ()
_ -> error "Too many segments pre-allocated!"
_ -> error "Next segment was not pre-allocated!"
_ -> error "No last segment present!"
NOTE : we would like this to pass ( see trac # 9030 ) but are happy to note that
- it fails which somewhat validates the test below
testBlockedRecovery = do
( i , o ) < - newChan
v < - newEmptyMVar
rid < - forkIO ( putMVar v ( ) > > readChan o )
takeMVar v
threadDelay 1000
throwTo rid ThreadKilled
-- we race the exception - handler in ` readChan ` here ...
writeChan i ( )
-- In a buggy implementation , this would consistently win failing by losing
-- the message and raising BlockedIndefinitely here :
readChan o
- it fails which somewhat validates the test below
testBlockedRecovery = do
(i,o) <- newChan
v <- newEmptyMVar
rid <- forkIO (putMVar v () >> readChan o)
takeMVar v
threadDelay 1000
throwTo rid ThreadKilled
-- we race the exception-handler in `readChan` here...
writeChan i ()
-- In a buggy implementation, this would consistently win failing by losing
-- the message and raising BlockedIndefinitely here:
readChan o
-}
-- test for deadlocks caused by async exceptions in reader.
checkDeadlocksReaderUnagi :: Int -> IO ()
checkDeadlocksReaderUnagi times = do
let run 0 normalRetries numRace = putStrLn $ "Lates: "++(show normalRetries)++", Races: "++(show numRace)
run n normalRetries numRace
| (normalRetries + numRace) > (times `div` 3) = error "This test is taking too long. Please retry, and if still failing send the log to me"
| otherwise = do
we 'll kill the reader with our special exception half the time ,
-- expecting that we never get our race condition on those runs:
let usingReadChanOnException = even n
(i,o) <- UI.newChanStarting 0
preload a chan with 0s
let numPreloaded = 10000
replicateM_ numPreloaded $ writeChan i (0::Int)
rStart <- newEmptyMVar
saved <- newEmptyMVar -- for holding potential saved (IO a) from blocked readChanOnException
rid <- forkIO $ (\rd-> putMVar rStart () >> (forever $ void $ rd o)) $
if usingReadChanOnException
then flip readChanOnException ( putMVar saved )
else readChan
takeMVar rStart >> threadDelay 1
throwTo rid ThreadKilled
-- did killing reader damage queue for reads or writes?
writeChan i 1 `onException` ( putStrLn "Exception from first writeChan!")
writeChan i 2 `onException` ( putStrLn "Exception from second writeChan!")
finalRead <- readChan o `onException` ( putStrLn "Exception from final readChan!")
oCnt <- readCounter $ (\(UI.OutChan(UI.ChanEnd cntr _))-> cntr) o
iCnt <- readCounter $ (\(UI.InChan (UI.ChanEnd cntr _))-> cntr) i
unless (iCnt == numPreloaded + 2) $
error "The InChan counter doesn't match what we'd expect from numPreloaded!"
case finalRead of
0 -> if oCnt <= 0 -- (technically, -1 means hasn't started yet)
-- reader didn't have a chance to get started
then putStr "0" >> run n (normalRetries+1) numRace
-- normal run; we tested that killing a reader didn't
-- break chan for other readers/writers:
else putStr "." >> run (n-1) normalRetries numRace
--
-- Rare. Reader was killed after reading all pre-loaded messages
-- but before starting what would be the blocking read:
1 | oCnt == numPreloaded+1 -> putStr "X" >> run n normalRetries (numRace + 1)
| otherwise -> error $ "Having read final 1, "++
"Expecting a counter value of "++(show $ numPreloaded+1)++
" but got: "++(show oCnt)
2 -> do when usingReadChanOnException $ do
shouldBe1 <- join $ takeMVar saved
unless (shouldBe1 == 1) $
error "The handler for our readChanOnException should only have returned 1"
unless (oCnt == numPreloaded + 2) $
error $ "Having read final 2, "++
"Expecting a counter value of "++(show $ numPreloaded+2)++
" but got: "++(show oCnt)
putStr "+" >> run n (normalRetries + 1) numRace
_ -> error "Fix your #$%@ test!"
run times 0 0
putStrLn ""
| null | https://raw.githubusercontent.com/jberryman/unagi-chan/03f62bb6989fcfa3372a93925b7bc0294b51a65d/tests/UnagiUnboxed.hs | haskell |
TODO Maybe refactor & get rid of these
------
------
------
------
------
------
TODO Maybe refactor & get rid of these
www.../rrr... spanning overflow
w/r/w/r... spanning overflow
testing of writing atomicUnicorn
smokeManyElement for atomicUnicorn values
-------------
Make sure we get no tearing of adjacent word-size or smaller (as determined
by atomicUnicorn instantiation) values, making sure we cross a cache-line.
check writes by doing a segment+1-worth of reads by hand
also check that segments pre-allocated as expected
check last write:
check pre-allocation:
we race the exception - handler in ` readChan ` here ...
In a buggy implementation , this would consistently win failing by losing
the message and raising BlockedIndefinitely here :
we race the exception-handler in `readChan` here...
In a buggy implementation, this would consistently win failing by losing
the message and raising BlockedIndefinitely here:
test for deadlocks caused by async exceptions in reader.
expecting that we never get our race condition on those runs:
for holding potential saved (IO a) from blocked readChanOnException
did killing reader damage queue for reads or writes?
(technically, -1 means hasn't started yet)
reader didn't have a chance to get started
normal run; we tested that killing a reader didn't
break chan for other readers/writers:
Rare. Reader was killed after reading all pre-loaded messages
but before starting what would be the blocking read: | # LANGUAGE RankNTypes , ScopedTypeVariables , BangPatterns #
# LANGUAGE TypeSynonymInstances , FlexibleInstances , CPP #
module UnagiUnboxed (unagiUnboxedMain) where
Unagi - chan - specific tests
Forked from tests / Unagi.hs at 337600f
import Control.Concurrent.Chan.Unagi.Unboxed
import qualified Control.Concurrent.Chan.Unagi.Unboxed.Internal as UI
import Control.Monad
import qualified Data.Primitive as P
import Data.IORef
import Data.Int(Int8,Int16,Int32,Int64)
import Data.Word
import Data.Maybe
import Data.Typeable
import Control.Concurrent(forkIO,threadDelay)
import Control.Concurrent.MVar
import Control.Exception
import Data.Atomics.Counter.Fat
import Prelude
primitive 0.7.0 got rid of Addr
#if MIN_VERSION_primitive(0,7,0)
import qualified Data.Primitive.Ptr as P
type Addr = P.Ptr Word8
nullAddr :: Addr
nullAddr = P.nullPtr
plusAddr :: Addr -> Int -> Addr
plusAddr = P.advancePtr
#else
import qualified Data.Primitive (Addr, nullAddr)
instance Show Addr where
show _ = "<addr>"
#endif
unagiUnboxedMain :: IO ()
unagiUnboxedMain = do
putStrLn "==================="
putStrLn "Testing Unagi.Unboxed details:"
putStr "Smoke test at different starting offsets, spanning overflow... "
mapM_ smoke $ [ (maxBound - UI.sEGMENT_LENGTH - 1) .. maxBound]
++ [minBound .. (minBound + UI.sEGMENT_LENGTH + 1)]
putStrLn "OK"
putStr "segSource sanity... "
applyToAllPrim segSourceMagicSanity
putStrLn "OK"
putStr "Atomicity of atomic unicorns... "
applyToAllPrim atomicUnicornAtomicicity
putStrLn "OK"
putStr "Correct first write... "
mapM_ correctFirstWrite [ (maxBound - 7), maxBound, minBound, 0]
putStrLn "OK"
putStr "Correct initial writes... "
mapM_ correctInitialWrites [ (maxBound - UI.sEGMENT_LENGTH), (maxBound - UI.sEGMENT_LENGTH) - 1, maxBound, minBound, 0]
putStrLn "OK"
let tries = 10000
putStrLn $ "Checking for deadlocks from killed Unagi reader in a fancy way, x"++show tries
checkDeadlocksReaderUnagi tries
smoke :: Int -> IO ()
smoke n = do
smoke1 n
smoke2 n
test each of UnagiPrim
applyToAllPrim smokeManyElement
test for atomicUnicorns
applyToAllPrim smokeManyUnicorn
test a function against each Prim type elements not equal to atomicUnicorn
applyToAllPrim :: (forall e. (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()) -> IO ()
applyToAllPrim f = do
f ('c' :: Char)
f (3.14159 :: Float)
f (-1.000000000000001 :: Double)
f (maxBound :: Int)
f (minBound :: Int8)
f (maxBound :: Int16)
f (minBound :: Int32)
f (maxBound :: Int64)
f (maxBound :: Word)
f (maxBound :: Word8)
f (minBound :: Word16)
f (minBound :: Word32)
f (minBound :: Word64)
f (nullAddr `plusAddr` 1024 :: Addr)
instance Num Addr where
instance Num Char where
smoke1 :: Int -> IO ()
smoke1 n = do
(i,o) <- UI.newChanStarting n
let inp = [0 .. (UI.sEGMENT_LENGTH * 3)]
mapM_ (writeChan i) inp
outp <- getChanContents o
unless (and (zipWith (==) inp outp)) $
error $ "Smoke test failed with starting offset of: "++(show n)
smoke2 :: Int -> IO ()
smoke2 n = do
(i,o) <- UI.newChanStarting n
let inp = [0 .. (UI.sEGMENT_LENGTH * 3)]
mapM_ (check i o) inp
where check i o x = do
writeChan i x
x' <- readChan o
unless (x == x') $
error $ "Smoke test failed with starting offset of: "++(show n)++"at write: "++(show x)
for smoke checking size , and alignment of different Prim types , and allowing
smokeManyElement :: (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()
smokeManyElement e = do
(i,o) <- newChan
let n = UI.sEGMENT_LENGTH*2 + 1
replicateM_ n (writeChan i e)
outp <- getChanContents o
unless (all (== e) $ take n outp) $
error $ "smokeManyElement failed with type "++(show $ typeOf e)++": "++(show e)++" /= "++(show outp)
smokeManyUnicorn :: forall e. (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()
smokeManyUnicorn _ =
maybe (return ()) smokeManyElement (atomicUnicorn :: Maybe e)
check our segSource is doing what we expect with magic values :
segSourceMagicSanity :: forall e. (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()
segSourceMagicSanity _ =
case atomicUnicorn :: Maybe e of
Nothing -> return ()
Just e -> do
(_,eArr) <- UI.segSource :: IO (UI.SignalIntArray, UI.ElementArray e)
forM_ [0.. UI.sEGMENT_LENGTH-1] $ \i-> do
e' <- UI.readElementArray eArr i
unless (e == e') $
error $ "in segSource, with type "++(show $ typeOf e)++", "++(show e)++" /= "++(show e')
atomicUnicornAtomicicity :: forall e. (Num e, Typeable e, Show e, UnagiPrim e)=> e -> IO ()
atomicUnicornAtomicicity _e =
when (isJust (atomicUnicorn :: Maybe e)) $ do
(_,eArr) <- UI.segSource :: IO (UI.SignalIntArray, UI.ElementArray e)
let iters = (64 `quot` P.sizeOf _e) + 1
when (iters >= UI.sEGMENT_LENGTH) $
error "Our sEGMENT_LENGTH is smaller than expected; please fix test"
just skip Addr for now :
unless ( isJust (cast _e :: Maybe Addr)
|| isJust (cast _e :: Maybe Char)) $
forM_ [0.. iters] $ \i0 -> do
let i1 = i0+1
rd = UI.readElementArray eArr
first0 <- rd i0
first1 <- rd i1
v0 <- newEmptyMVar
v1 <- newEmptyMVar
let incr f v i = go
where go _ 0 = putMVar v ()
go expected n = do
val <- rd i
unless (val == expected) $
error $ "atomicUnicornAtomicicity with type "++(show $ typeOf val)++" "++(show val)++" /= "++(show expected)
let !next = f val
UI.writeElementArray eArr i next
go next (n-1)
let counts = 1000000 :: Int
_ <- forkIO $ incr (+1) v0 i0 first0 counts
_ <- forkIO $ incr (subtract 1) v1 i1 first1 counts
BlockedIndefinitelyOnMVar means a problem TODO make better
takeMVar v0 >> takeMVar v1
correctFirstWrite :: Int -> IO ()
correctFirstWrite n = do
(i,UI.OutChan (UI.ChanEnd _ arrRef)) <- UI.newChanStarting n
writeChan i (7::Int)
(UI.StreamHead _ (UI.Stream sigArr eArr _ _)) <- readIORef arrRef
cell <- UI.readElementArray eArr 0 :: IO Int
case cell of
7 -> return ()
_ -> error "Expected a write at index 0 of 7"
sigCell <- P.readByteArray sigArr 0 :: IO Int
i.e. cellWritten
error "Expected cellWritten at sigArr!0"
correctInitialWrites :: Int -> IO ()
correctInitialWrites startN = do
(i,(UI.OutChan (UI.ChanEnd _ arrRef))) <- UI.newChanStarting startN
let writes = [0..UI.sEGMENT_LENGTH]
mapM_ (writeChan i) writes
(UI.StreamHead _ (UI.Stream sigArr eArr _ next)) <- readIORef arrRef
check all of first segment :
forM_ (init writes) $ \ix-> do
cell <- UI.readElementArray eArr ix :: IO Int
sigCell <- P.readByteArray sigArr ix :: IO Int
unless (cell == ix && sigCell == 1) $
error $ "Expected a write at index "++(show ix)++" of same value but got "++(show cell)++" with signal "++(show sigCell)
lastSeg <- readIORef next
case lastSeg of
(UI.Next (UI.Stream sigArr2 eArr2 _ next2)) -> do
cell <- UI.readElementArray eArr2 0 :: IO Int
sigCell <- P.readByteArray sigArr2 0 :: IO Int
unless (cell == last writes && sigCell == 1) $
error $ "Expected last write at index "++(show $ last writes)++" of same value but got "++(show cell)
n2 <- readIORef next2
case n2 of
(UI.Next (UI.Stream _ _ _ next3)) -> do
n3 <- readIORef next3
case n3 of
UI.NoSegment -> return ()
_ -> error "Too many segments pre-allocated!"
_ -> error "Next segment was not pre-allocated!"
_ -> error "No last segment present!"
NOTE : we would like this to pass ( see trac # 9030 ) but are happy to note that
- it fails which somewhat validates the test below
testBlockedRecovery = do
( i , o ) < - newChan
v < - newEmptyMVar
rid < - forkIO ( putMVar v ( ) > > readChan o )
takeMVar v
threadDelay 1000
throwTo rid ThreadKilled
writeChan i ( )
readChan o
- it fails which somewhat validates the test below
testBlockedRecovery = do
(i,o) <- newChan
v <- newEmptyMVar
rid <- forkIO (putMVar v () >> readChan o)
takeMVar v
threadDelay 1000
throwTo rid ThreadKilled
writeChan i ()
readChan o
-}
checkDeadlocksReaderUnagi :: Int -> IO ()
checkDeadlocksReaderUnagi times = do
let run 0 normalRetries numRace = putStrLn $ "Lates: "++(show normalRetries)++", Races: "++(show numRace)
run n normalRetries numRace
| (normalRetries + numRace) > (times `div` 3) = error "This test is taking too long. Please retry, and if still failing send the log to me"
| otherwise = do
we 'll kill the reader with our special exception half the time ,
let usingReadChanOnException = even n
(i,o) <- UI.newChanStarting 0
preload a chan with 0s
let numPreloaded = 10000
replicateM_ numPreloaded $ writeChan i (0::Int)
rStart <- newEmptyMVar
rid <- forkIO $ (\rd-> putMVar rStart () >> (forever $ void $ rd o)) $
if usingReadChanOnException
then flip readChanOnException ( putMVar saved )
else readChan
takeMVar rStart >> threadDelay 1
throwTo rid ThreadKilled
writeChan i 1 `onException` ( putStrLn "Exception from first writeChan!")
writeChan i 2 `onException` ( putStrLn "Exception from second writeChan!")
finalRead <- readChan o `onException` ( putStrLn "Exception from final readChan!")
oCnt <- readCounter $ (\(UI.OutChan(UI.ChanEnd cntr _))-> cntr) o
iCnt <- readCounter $ (\(UI.InChan (UI.ChanEnd cntr _))-> cntr) i
unless (iCnt == numPreloaded + 2) $
error "The InChan counter doesn't match what we'd expect from numPreloaded!"
case finalRead of
then putStr "0" >> run n (normalRetries+1) numRace
else putStr "." >> run (n-1) normalRetries numRace
1 | oCnt == numPreloaded+1 -> putStr "X" >> run n normalRetries (numRace + 1)
| otherwise -> error $ "Having read final 1, "++
"Expecting a counter value of "++(show $ numPreloaded+1)++
" but got: "++(show oCnt)
2 -> do when usingReadChanOnException $ do
shouldBe1 <- join $ takeMVar saved
unless (shouldBe1 == 1) $
error "The handler for our readChanOnException should only have returned 1"
unless (oCnt == numPreloaded + 2) $
error $ "Having read final 2, "++
"Expecting a counter value of "++(show $ numPreloaded+2)++
" but got: "++(show oCnt)
putStr "+" >> run n (normalRetries + 1) numRace
_ -> error "Fix your #$%@ test!"
run times 0 0
putStrLn ""
|
54bf33f514c671510241ec8d852a6b184e0cbf9430c9c48282d0d45566cd75ab | phillord/tawny-owl | render_test.clj | The contents of this file are subject to the LGPL License , Version 3.0 .
;;
Copyright ( C ) 2013 , 2017 , , Newcastle University
;;
;; 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 , 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 Lesser General Public License
;; for more details.
;;
You should have received a copy of the GNU Lesser General Public License
along with this program . If not , see /.
(ns tawny.render-test
(:use [clojure.test])
(:require [tawny.render :as r]
[tawny.owl :as o]
[tawny.fixture]
[tawny.fixture :as f]))
(def to nil)
(use-fixtures :each
(f/test-ontology-fixture-generator #'to true)
f/error-on-default-ontology-fixture)
(defn double-as-form [entity]
(vector
(r/as-form entity :terminal :object)
(r/as-form entity :terminal :object :keyword true)))
(defn multi-as-form [entity]
(vector
(r/as-form entity :terminal :object)
(r/as-form entity :terminal :object :explicit true)
(r/as-form entity :terminal :object :keyword true)
(r/as-form entity :terminal :object :explicit true :keyword true)
))
(deftest datatype
(is (= :XSD_INTEGER
(r/as-form (#'o/ensure-datatype :XSD_INTEGER)))))
(defn lit-f
([val]
(r/as-form (o/literal val)))
([val lang]
(r/as-form (o/literal val :lang lang))))
(deftest literal
(is
(= '(literal "10" :type :XSD_INTEGER)
(lit-f 10))))
;; (is
(= [ 10.0 ]
;; (lit-f 10.0)))
;; (is
;; (= [true]
;; (lit-f true)))
;; (is
;; (= ["bob"]
;; (lit-f "bob")))
;; (is
;; (= ["bob" "en"]
;; (lit-f "bob" "en"))))
(defn data-ontology []
(o/datatype-property to "rD"))
(deftest datasome-datatype
(is
(=
'(owl-some (iri "") :XSD_INTEGER)
(do (data-ontology)
(r/as-form
(o/owl-some (o/datatype-property to "rD") :XSD_INTEGER))))))
(deftest datasome-range
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['owl-some d '[span < 1]]
[:some d [:span :< 1]]]
(double-as-form
(o/owl-some d (o/span < 1))))))
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['owl-some d ['span '>< 1 1]]
[:some d [:span :>< 1 1]]]
(double-as-form
(o/owl-some d (o/span >< 1 1))))))
(deftest dataonly-range
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['only d '[span < 1]]
[:only d [:span :< 1]]]
(double-as-form
(o/owl-only d (o/span < 1))))))
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['only d ['span '>< 1 1]]
[:only d [:span :>< 1 1]]]
(double-as-form
(o/owl-only d (o/span >< 1 1))))))))
(deftest individual-fact-1
(is
(= '(individual (iri "")
:fact
(fact (iri "")
(iri "")))
(r/as-form
(o/individual to "I"
:fact (o/fact
(o/object-property to "r")
(o/individual to "I2")))))))
(deftest individual-fact-2
(is
(= '(individual (iri "")
:fact
(fact-not (iri "")
(iri "")))
(r/as-form
(o/individual
to "I"
:fact (o/fact-not
(o/object-property to "r")
(o/individual to "I2")))))))
(deftest individual-3
(is
(=
'(individual (iri "")
:fact
(fact (iri "")
(iri ""))
(fact-not (iri "")
(iri "")))
(r/as-form
(o/individual to "I"
:fact
(o/fact (o/object-property to "r")
(o/individual to "I2"))
(o/fact-not (o/object-property to "r")
(o/individual to "I2")))))))
(deftest individual-data
(is
(=
'(individual
(iri "")
:fact (fact (iri "")
(literal "10" :type :XSD_INTEGER)))
(r/as-form
(o/individual to "I"
:fact
(o/fact (o/datatype-property to "d")
10))))))
(deftest individual-data-2
(is
(= '(individual (iri "")
:fact
(fact (iri "")
(iri ""))
(fact (iri "")
(literal "10" :type :XSD_INTEGER)))
(r/as-form
(o/individual to "I"
:fact
(o/fact (o/datatype-property to "d")
10)
(o/fact (o/object-property to "r")
(o/individual to "I2")))))))
(deftest oproperty-super-test
(is
(= '(object-property
(iri "")
:super
(iri ""))
(r/as-form
(o/object-property to "r"
:super
(o/iri-for-name to "s"))))))
(defn get-some-example-subproperty-chains []
(let [r (o/object-property to "r")
s (o/object-property to "s")
t (o/object-property to "t" :subchain r s)
chains
(filter
#(= t (.getSuperProperty
^org.semanticweb.owlapi.model.OWLSubPropertyChainOfAxiom %))
(.getAxioms
^org.semanticweb.owlapi.model.OWLOntology to
org.semanticweb.owlapi.model.AxiomType/SUB_PROPERTY_CHAIN_OF))]
chains))
(deftest oproperty-form-subchain-render
(is
(get-some-example-subproperty-chains)))
(deftest oproperty-subchain-test
(is
(let [r (o/object-property to "r")
s (o/object-property to "s")
t (o/object-property to "t" :subchain r s)
f (double-as-form t)]
(and
(=
[['object-property t :subchain [r s]]
[:oproperty t :subchain [[r s]]]]
f)
;; we need to test type explicitly because we must have [r s] and not (r
;; s) for the clojure rendering
(vector?
(nth
(first f) 3))))))
(deftest dproperty-super-test
(is
(= '(datatype-property
(iri "")
:super
(iri ""))
(r/as-form
(o/datatype-property to "g"
:super
(o/iri-for-name to "h"))))))
(deftest entity-or-iri-as-iri
(is
(= ['owl-class ['iri ""]]
(r/as-form
(o/owl-class to "a")
:terminal :iri)))
(is
(= ['ontology
:iri "/"
:prefix "iri"]
(r/as-form
to
:terminal :iri))))
(deftest entity-or-iri-object
(is
(tawny.owl/with-probe-entities to
[a (o/owl-class to "a")]
(=
(r/as-form
(o/owl-and a) :terminal :object)
['owl-and a]))))
;; :some
(deftest object-some
(is
(o/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(= [
['owl-some p c]
['object-some p c]
[:some p c]
[:object-some p c]]
(multi-as-form
(o/owl-some p c))))))
(deftest data-some
(is
(o/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['owl-some d :XSD_INTEGER]
['data-some d :XSD_INTEGER]
[:some d :XSD_INTEGER]
[:data-some d :XSD_INTEGER]]
(multi-as-form
(o/owl-some d :XSD_INTEGER))))
))
;; :only
(deftest object-only
(is
(tawny.owl/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(=
[
['only p c]
['object-only p c]
[:only p c]
[:object-only p c]]
(multi-as-form
(o/only p c))))))
(deftest data-only
(is
(o/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['only d :XSD_INTEGER]
['data-only d :XSD_INTEGER]
[:only d :XSD_INTEGER]
[:data-only d :XSD_INTEGER]]
(multi-as-form
(o/only d :XSD_INTEGER))))))
;; :owl-and
(deftest object-and
(is
(o/with-probe-entities to
[b (o/owl-class to "b")
c (o/owl-class to "c")]
(= [
['owl-and b c]
['object-and b c]
[:and b c]
[:object-and b c]]
(multi-as-form
(o/owl-and b c))))))
(deftest data-and
(is
(=
[
['owl-and :XSD_INTEGER]
['data-and :XSD_INTEGER]
[:and :XSD_INTEGER]
[:data-and :XSD_INTEGER]]
(multi-as-form
(o/owl-and :XSD_INTEGER)))))
;; :owl-or
(deftest object-or
(is
(o/with-probe-entities to
[b (o/owl-class to "b")
c (o/owl-class to "c")]
(= [
['owl-or b c]
['object-or b c]
[:or b c]
[:object-or b c]]
(multi-as-form
(o/owl-or b c))))))
(deftest data-or
(is
(=
[
['owl-or :XSD_INTEGER]
['data-or :XSD_INTEGER]
[:or :XSD_INTEGER]
[:data-or :XSD_INTEGER]]
(multi-as-form
(o/owl-or :XSD_INTEGER)))))
;; :exactly
(deftest object-exactly
(is
(tawny.owl/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(=
[
['exactly 1 p c]
['object-exactly 1 p c]
[:exactly 1 p c]
[:object-exactly 1 p c]]
(multi-as-form
(o/exactly 1 p c))))))
(deftest data-exactly
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['exactly 1 d :RDFS_LITERAL]
['data-exactly 1 d :RDFS_LITERAL]
[:exactly 1 d :RDFS_LITERAL]
[:data-exactly 1 d :RDFS_LITERAL]]
(multi-as-form
(o/exactly 1 d))))))
:
(deftest object-oneof
(is
(tawny.owl/with-probe-entities to
[i (o/individual to "i")]
(=
[
['oneof i]
['object-oneof i]
[:oneof i]
[:object-oneof i]]
(multi-as-form
(o/oneof i))))))
(deftest data-oneof
(is
(=
[
['oneof ['literal "10" :type :XSD_INTEGER]]
['data-oneof ['literal "10" :type :XSD_INTEGER]]
[:oneof [:literal "10" :type :XSD_INTEGER]]
[:data-oneof [:literal "10" :type :XSD_INTEGER]]]
(multi-as-form
(o/oneof (o/literal 10))))))
;; :at-least
(deftest object-at-least
(is
(tawny.owl/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(=
[
['at-least 1 p c]
['object-at-least 1 p c]
[:at-least 1 p c]
[:object-at-least 1 p c]]
(multi-as-form
(o/at-least 1 p c))))))
(deftest data-at-least
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['at-least 1 d :RDFS_LITERAL]
['data-at-least 1 d :RDFS_LITERAL]
[:at-least 1 d :RDFS_LITERAL]
[:data-at-least 1 d :RDFS_LITERAL]]
(multi-as-form
(o/at-least 1 d))))))
;; :at-most
(deftest object-at-most
(is
(tawny.owl/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(=
[
['at-most 1 p c]
['object-at-most 1 p c]
[:at-most 1 p c]
[:object-at-most 1 p c]]
(multi-as-form
(o/at-most 1 p c))))))
(deftest data-at-most
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['at-most 1 d :RDFS_LITERAL]
['data-at-most 1 d :RDFS_LITERAL]
[:at-most 1 d :RDFS_LITERAL]
[:data-at-most 1 d :RDFS_LITERAL]]
(multi-as-form
(o/at-most 1 d))))))
;; :has-value
(deftest object-has-value
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")
i (o/individual to "i")]
(=
[['has-value r i]
['object-has-value r i]
[:has-value r i]
[:object-has-value r i]]
(multi-as-form
(o/has-value r i))))))
(deftest data-has-value
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['has-value d ['literal "10" :type :XSD_INTEGER]]
['data-has-value d ['literal "10" :type :XSD_INTEGER]]
[:has-value d [:literal "10" :type :XSD_INTEGER]]
[:data-has-value d [:literal "10" :type :XSD_INTEGER]]]
(multi-as-form
(o/has-value d 10))))))
;; :owl-not
(deftest object-owl-not
(is
(tawny.owl/with-probe-entities to
[c (o/owl-class to "c")]
(=
[['owl-not c]
['object-not c]
[:not c]
[:object-not c]]
(multi-as-form
(o/owl-not c))))))
(deftest data-owl-not
(is
(=
[['owl-not :XSD_INTEGER]
['data-not :XSD_INTEGER]
[:not :XSD_INTEGER]
[:data-not :XSD_INTEGER]]
(multi-as-form
(o/owl-not :XSD_INTEGER)))))
;; :iri
(deftest iri
(is
(=
[['iri "i"]
['iri "i"]
[:iri "i"]
[:iri "i"]]
(multi-as-form
(o/iri "i")))))
;; :label
(deftest label
(is
(=
[['label ['literal "l" :lang "en"]]
['label ['literal "l" :lang "en"]]
[:label [:literal "l" :lang "en"]]
[:label [:literal "l" :lang "en"]]]
(multi-as-form
(o/label "l")))))
;; :comment
(deftest owlcomment
(is
(=
[['owl-comment ['literal "l" :lang "en"]]
['owl-comment ['literal "l" :lang "en"]]
[:comment [:literal "l" :lang "en"]]
[:comment [:literal "l" :lang "en"]]]
(multi-as-form
(o/owl-comment "l")))))
;; :literal
(deftest literal
(is
(=
[['literal "1" :type :XSD_INTEGER]
['literal "1" :type :XSD_INTEGER]
[:literal "1" :type :XSD_INTEGER]
[:literal "1" :type :XSD_INTEGER]]
(multi-as-form
(o/literal 1)))))
;; :<
(deftest span<
(is
(=
[['span '< 0]
['span '< 0]
[:span :< 0]
[:span :< 0]]
(multi-as-form
(o/span < 0)))))
;; :<=
(deftest span<=
(is
(=
[['span '<= 0]
['span '<= 0]
[:span :<= 0]
[:span :<= 0]]
(multi-as-form
(o/span <= 0)))))
;; :>
(deftest span>
(is
(=
[['span '> 0]
['span '> 0]
[:span :> 0]
[:span :> 0]]
(multi-as-form
(o/span < 0)))))
;; :>=
(deftest span>
(is
(=
[['span '>= 0]
['span '>= 0]
[:span :>= 0]
[:span :>= 0]]
(multi-as-form
(o/span >= 0)))))
;; :has-self
(deftest hasself
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")]
(=
[['has-self r]
['has-self r]
[:has-self r]
[:has-self r]]
(multi-as-form
(o/has-self r))))))
;; :inverse
(deftest inverse
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")]
(=
[['inverse r]
['inverse r]
[:inverse r]
[:inverse r]]
(multi-as-form
(o/inverse r))))))
(deftest ontology
simplest possible -- ontology with a specific IRI
(is
(let [o (o/ontology :noname true :iri "")]
(= [
['ontology :iri ""]
[:ontology o :iri ""]
]
(double-as-form o))))
(is
(let [o (o/ontology :noname true
:iri ""
:viri "")]
(= [
['ontology :iri ""
:viri ""]
[:ontology o :iri ""
:viri ""]
]
(double-as-form o)))) )
(deftest owl-class
(is
(tawny.owl/with-probe-entities to
[c (o/owl-class to "c")
d (o/owl-class to "d")
e (o/owl-class to "e"
:super c d)]
(=
[
['owl-class e :super c d]
[:class e :super [c d]]]
(double-as-form e)))))
(deftest oproperty
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")]
(=
[['object-property r]
[:oproperty r]]
(double-as-form r)))))
(deftest individ-many-facts
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")
s (o/object-property to "s")
i (o/individual to "i")
j (o/individual
to "j"
:fact (o/fact r i) (o/fact s i))]
(=
[['individual j
:fact
['fact r i]
['fact s i]]
[:individual j
:fact
[[:fact r i]
[:fact s i]]]]
(double-as-form j)))))
;; render-annotation-frame
(deftest ontology-annotation
(is
(= '(ontology
:iri ""
:prefix "x"
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/ontology :iri ""
:prefix "x"
:noname true
:annotation
(o/label "test label"))))))
(deftest class-annotation
(is
(= '(owl-class
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/owl-class to "x"
:label
"test label")))))
(deftest individual-annotation
(is
(= '(individual
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/individual to "x"
:label
"test label")))))
(deftest oproperty-annotation
(is
(= '(object-property
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/object-property to "x"
:label
"test label")))))
(deftest dproperty-annotation
(is
(= '(datatype-property
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/datatype-property to "x"
:label
"test label")))))
(deftest aproperty-annotation
(is
(= '(annotation-property
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/annotation-property to "x"
:label
"test label")))))
(deftest oproperty-characteristic []
(let [o (o/object-property to "x" :characteristic :functional)]
(is
(=
'(object-property
(iri "")
:characteristic :functional)
(r/as-form o)))))
| null | https://raw.githubusercontent.com/phillord/tawny-owl/331e14b838a42adebbd325f80f60830fa0915d76/test/tawny/render_test.clj | clojure |
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
option) 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 Lesser General Public License
for more details.
(is
(lit-f 10.0)))
(is
(= [true]
(lit-f true)))
(is
(= ["bob"]
(lit-f "bob")))
(is
(= ["bob" "en"]
(lit-f "bob" "en"))))
we need to test type explicitly because we must have [r s] and not (r
s) for the clojure rendering
:some
:only
:owl-and
:owl-or
:exactly
:at-least
:at-most
:has-value
:owl-not
:iri
:label
:comment
:literal
:<
:<=
:>
:>=
:has-self
:inverse
render-annotation-frame | The contents of this file are subject to the LGPL License , Version 3.0 .
Copyright ( C ) 2013 , 2017 , , Newcastle University
the Free Software Foundation , either version 3 of the License , or ( at your
You should have received a copy of the GNU Lesser General Public License
along with this program . If not , see /.
(ns tawny.render-test
(:use [clojure.test])
(:require [tawny.render :as r]
[tawny.owl :as o]
[tawny.fixture]
[tawny.fixture :as f]))
(def to nil)
(use-fixtures :each
(f/test-ontology-fixture-generator #'to true)
f/error-on-default-ontology-fixture)
(defn double-as-form [entity]
(vector
(r/as-form entity :terminal :object)
(r/as-form entity :terminal :object :keyword true)))
(defn multi-as-form [entity]
(vector
(r/as-form entity :terminal :object)
(r/as-form entity :terminal :object :explicit true)
(r/as-form entity :terminal :object :keyword true)
(r/as-form entity :terminal :object :explicit true :keyword true)
))
(deftest datatype
(is (= :XSD_INTEGER
(r/as-form (#'o/ensure-datatype :XSD_INTEGER)))))
(defn lit-f
([val]
(r/as-form (o/literal val)))
([val lang]
(r/as-form (o/literal val :lang lang))))
(deftest literal
(is
(= '(literal "10" :type :XSD_INTEGER)
(lit-f 10))))
(= [ 10.0 ]
(defn data-ontology []
(o/datatype-property to "rD"))
(deftest datasome-datatype
(is
(=
'(owl-some (iri "") :XSD_INTEGER)
(do (data-ontology)
(r/as-form
(o/owl-some (o/datatype-property to "rD") :XSD_INTEGER))))))
(deftest datasome-range
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['owl-some d '[span < 1]]
[:some d [:span :< 1]]]
(double-as-form
(o/owl-some d (o/span < 1))))))
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['owl-some d ['span '>< 1 1]]
[:some d [:span :>< 1 1]]]
(double-as-form
(o/owl-some d (o/span >< 1 1))))))
(deftest dataonly-range
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['only d '[span < 1]]
[:only d [:span :< 1]]]
(double-as-form
(o/owl-only d (o/span < 1))))))
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['only d ['span '>< 1 1]]
[:only d [:span :>< 1 1]]]
(double-as-form
(o/owl-only d (o/span >< 1 1))))))))
(deftest individual-fact-1
(is
(= '(individual (iri "")
:fact
(fact (iri "")
(iri "")))
(r/as-form
(o/individual to "I"
:fact (o/fact
(o/object-property to "r")
(o/individual to "I2")))))))
(deftest individual-fact-2
(is
(= '(individual (iri "")
:fact
(fact-not (iri "")
(iri "")))
(r/as-form
(o/individual
to "I"
:fact (o/fact-not
(o/object-property to "r")
(o/individual to "I2")))))))
(deftest individual-3
(is
(=
'(individual (iri "")
:fact
(fact (iri "")
(iri ""))
(fact-not (iri "")
(iri "")))
(r/as-form
(o/individual to "I"
:fact
(o/fact (o/object-property to "r")
(o/individual to "I2"))
(o/fact-not (o/object-property to "r")
(o/individual to "I2")))))))
(deftest individual-data
(is
(=
'(individual
(iri "")
:fact (fact (iri "")
(literal "10" :type :XSD_INTEGER)))
(r/as-form
(o/individual to "I"
:fact
(o/fact (o/datatype-property to "d")
10))))))
(deftest individual-data-2
(is
(= '(individual (iri "")
:fact
(fact (iri "")
(iri ""))
(fact (iri "")
(literal "10" :type :XSD_INTEGER)))
(r/as-form
(o/individual to "I"
:fact
(o/fact (o/datatype-property to "d")
10)
(o/fact (o/object-property to "r")
(o/individual to "I2")))))))
(deftest oproperty-super-test
(is
(= '(object-property
(iri "")
:super
(iri ""))
(r/as-form
(o/object-property to "r"
:super
(o/iri-for-name to "s"))))))
(defn get-some-example-subproperty-chains []
(let [r (o/object-property to "r")
s (o/object-property to "s")
t (o/object-property to "t" :subchain r s)
chains
(filter
#(= t (.getSuperProperty
^org.semanticweb.owlapi.model.OWLSubPropertyChainOfAxiom %))
(.getAxioms
^org.semanticweb.owlapi.model.OWLOntology to
org.semanticweb.owlapi.model.AxiomType/SUB_PROPERTY_CHAIN_OF))]
chains))
(deftest oproperty-form-subchain-render
(is
(get-some-example-subproperty-chains)))
(deftest oproperty-subchain-test
(is
(let [r (o/object-property to "r")
s (o/object-property to "s")
t (o/object-property to "t" :subchain r s)
f (double-as-form t)]
(and
(=
[['object-property t :subchain [r s]]
[:oproperty t :subchain [[r s]]]]
f)
(vector?
(nth
(first f) 3))))))
(deftest dproperty-super-test
(is
(= '(datatype-property
(iri "")
:super
(iri ""))
(r/as-form
(o/datatype-property to "g"
:super
(o/iri-for-name to "h"))))))
(deftest entity-or-iri-as-iri
(is
(= ['owl-class ['iri ""]]
(r/as-form
(o/owl-class to "a")
:terminal :iri)))
(is
(= ['ontology
:iri "/"
:prefix "iri"]
(r/as-form
to
:terminal :iri))))
(deftest entity-or-iri-object
(is
(tawny.owl/with-probe-entities to
[a (o/owl-class to "a")]
(=
(r/as-form
(o/owl-and a) :terminal :object)
['owl-and a]))))
(deftest object-some
(is
(o/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(= [
['owl-some p c]
['object-some p c]
[:some p c]
[:object-some p c]]
(multi-as-form
(o/owl-some p c))))))
(deftest data-some
(is
(o/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['owl-some d :XSD_INTEGER]
['data-some d :XSD_INTEGER]
[:some d :XSD_INTEGER]
[:data-some d :XSD_INTEGER]]
(multi-as-form
(o/owl-some d :XSD_INTEGER))))
))
(deftest object-only
(is
(tawny.owl/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(=
[
['only p c]
['object-only p c]
[:only p c]
[:object-only p c]]
(multi-as-form
(o/only p c))))))
(deftest data-only
(is
(o/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['only d :XSD_INTEGER]
['data-only d :XSD_INTEGER]
[:only d :XSD_INTEGER]
[:data-only d :XSD_INTEGER]]
(multi-as-form
(o/only d :XSD_INTEGER))))))
(deftest object-and
(is
(o/with-probe-entities to
[b (o/owl-class to "b")
c (o/owl-class to "c")]
(= [
['owl-and b c]
['object-and b c]
[:and b c]
[:object-and b c]]
(multi-as-form
(o/owl-and b c))))))
(deftest data-and
(is
(=
[
['owl-and :XSD_INTEGER]
['data-and :XSD_INTEGER]
[:and :XSD_INTEGER]
[:data-and :XSD_INTEGER]]
(multi-as-form
(o/owl-and :XSD_INTEGER)))))
(deftest object-or
(is
(o/with-probe-entities to
[b (o/owl-class to "b")
c (o/owl-class to "c")]
(= [
['owl-or b c]
['object-or b c]
[:or b c]
[:object-or b c]]
(multi-as-form
(o/owl-or b c))))))
(deftest data-or
(is
(=
[
['owl-or :XSD_INTEGER]
['data-or :XSD_INTEGER]
[:or :XSD_INTEGER]
[:data-or :XSD_INTEGER]]
(multi-as-form
(o/owl-or :XSD_INTEGER)))))
(deftest object-exactly
(is
(tawny.owl/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(=
[
['exactly 1 p c]
['object-exactly 1 p c]
[:exactly 1 p c]
[:object-exactly 1 p c]]
(multi-as-form
(o/exactly 1 p c))))))
(deftest data-exactly
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['exactly 1 d :RDFS_LITERAL]
['data-exactly 1 d :RDFS_LITERAL]
[:exactly 1 d :RDFS_LITERAL]
[:data-exactly 1 d :RDFS_LITERAL]]
(multi-as-form
(o/exactly 1 d))))))
:
(deftest object-oneof
(is
(tawny.owl/with-probe-entities to
[i (o/individual to "i")]
(=
[
['oneof i]
['object-oneof i]
[:oneof i]
[:object-oneof i]]
(multi-as-form
(o/oneof i))))))
(deftest data-oneof
(is
(=
[
['oneof ['literal "10" :type :XSD_INTEGER]]
['data-oneof ['literal "10" :type :XSD_INTEGER]]
[:oneof [:literal "10" :type :XSD_INTEGER]]
[:data-oneof [:literal "10" :type :XSD_INTEGER]]]
(multi-as-form
(o/oneof (o/literal 10))))))
(deftest object-at-least
(is
(tawny.owl/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(=
[
['at-least 1 p c]
['object-at-least 1 p c]
[:at-least 1 p c]
[:object-at-least 1 p c]]
(multi-as-form
(o/at-least 1 p c))))))
(deftest data-at-least
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['at-least 1 d :RDFS_LITERAL]
['data-at-least 1 d :RDFS_LITERAL]
[:at-least 1 d :RDFS_LITERAL]
[:data-at-least 1 d :RDFS_LITERAL]]
(multi-as-form
(o/at-least 1 d))))))
(deftest object-at-most
(is
(tawny.owl/with-probe-entities to
[p (o/object-property to "p")
c (o/owl-class to "c")]
(=
[
['at-most 1 p c]
['object-at-most 1 p c]
[:at-most 1 p c]
[:object-at-most 1 p c]]
(multi-as-form
(o/at-most 1 p c))))))
(deftest data-at-most
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[
['at-most 1 d :RDFS_LITERAL]
['data-at-most 1 d :RDFS_LITERAL]
[:at-most 1 d :RDFS_LITERAL]
[:data-at-most 1 d :RDFS_LITERAL]]
(multi-as-form
(o/at-most 1 d))))))
(deftest object-has-value
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")
i (o/individual to "i")]
(=
[['has-value r i]
['object-has-value r i]
[:has-value r i]
[:object-has-value r i]]
(multi-as-form
(o/has-value r i))))))
(deftest data-has-value
(is
(tawny.owl/with-probe-entities to
[d (o/datatype-property to "d")]
(=
[['has-value d ['literal "10" :type :XSD_INTEGER]]
['data-has-value d ['literal "10" :type :XSD_INTEGER]]
[:has-value d [:literal "10" :type :XSD_INTEGER]]
[:data-has-value d [:literal "10" :type :XSD_INTEGER]]]
(multi-as-form
(o/has-value d 10))))))
(deftest object-owl-not
(is
(tawny.owl/with-probe-entities to
[c (o/owl-class to "c")]
(=
[['owl-not c]
['object-not c]
[:not c]
[:object-not c]]
(multi-as-form
(o/owl-not c))))))
(deftest data-owl-not
(is
(=
[['owl-not :XSD_INTEGER]
['data-not :XSD_INTEGER]
[:not :XSD_INTEGER]
[:data-not :XSD_INTEGER]]
(multi-as-form
(o/owl-not :XSD_INTEGER)))))
(deftest iri
(is
(=
[['iri "i"]
['iri "i"]
[:iri "i"]
[:iri "i"]]
(multi-as-form
(o/iri "i")))))
(deftest label
(is
(=
[['label ['literal "l" :lang "en"]]
['label ['literal "l" :lang "en"]]
[:label [:literal "l" :lang "en"]]
[:label [:literal "l" :lang "en"]]]
(multi-as-form
(o/label "l")))))
(deftest owlcomment
(is
(=
[['owl-comment ['literal "l" :lang "en"]]
['owl-comment ['literal "l" :lang "en"]]
[:comment [:literal "l" :lang "en"]]
[:comment [:literal "l" :lang "en"]]]
(multi-as-form
(o/owl-comment "l")))))
(deftest literal
(is
(=
[['literal "1" :type :XSD_INTEGER]
['literal "1" :type :XSD_INTEGER]
[:literal "1" :type :XSD_INTEGER]
[:literal "1" :type :XSD_INTEGER]]
(multi-as-form
(o/literal 1)))))
(deftest span<
(is
(=
[['span '< 0]
['span '< 0]
[:span :< 0]
[:span :< 0]]
(multi-as-form
(o/span < 0)))))
(deftest span<=
(is
(=
[['span '<= 0]
['span '<= 0]
[:span :<= 0]
[:span :<= 0]]
(multi-as-form
(o/span <= 0)))))
(deftest span>
(is
(=
[['span '> 0]
['span '> 0]
[:span :> 0]
[:span :> 0]]
(multi-as-form
(o/span < 0)))))
(deftest span>
(is
(=
[['span '>= 0]
['span '>= 0]
[:span :>= 0]
[:span :>= 0]]
(multi-as-form
(o/span >= 0)))))
(deftest hasself
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")]
(=
[['has-self r]
['has-self r]
[:has-self r]
[:has-self r]]
(multi-as-form
(o/has-self r))))))
(deftest inverse
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")]
(=
[['inverse r]
['inverse r]
[:inverse r]
[:inverse r]]
(multi-as-form
(o/inverse r))))))
(deftest ontology
simplest possible -- ontology with a specific IRI
(is
(let [o (o/ontology :noname true :iri "")]
(= [
['ontology :iri ""]
[:ontology o :iri ""]
]
(double-as-form o))))
(is
(let [o (o/ontology :noname true
:iri ""
:viri "")]
(= [
['ontology :iri ""
:viri ""]
[:ontology o :iri ""
:viri ""]
]
(double-as-form o)))) )
(deftest owl-class
(is
(tawny.owl/with-probe-entities to
[c (o/owl-class to "c")
d (o/owl-class to "d")
e (o/owl-class to "e"
:super c d)]
(=
[
['owl-class e :super c d]
[:class e :super [c d]]]
(double-as-form e)))))
(deftest oproperty
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")]
(=
[['object-property r]
[:oproperty r]]
(double-as-form r)))))
(deftest individ-many-facts
(is
(tawny.owl/with-probe-entities to
[r (o/object-property to "r")
s (o/object-property to "s")
i (o/individual to "i")
j (o/individual
to "j"
:fact (o/fact r i) (o/fact s i))]
(=
[['individual j
:fact
['fact r i]
['fact s i]]
[:individual j
:fact
[[:fact r i]
[:fact s i]]]]
(double-as-form j)))))
(deftest ontology-annotation
(is
(= '(ontology
:iri ""
:prefix "x"
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/ontology :iri ""
:prefix "x"
:noname true
:annotation
(o/label "test label"))))))
(deftest class-annotation
(is
(= '(owl-class
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/owl-class to "x"
:label
"test label")))))
(deftest individual-annotation
(is
(= '(individual
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/individual to "x"
:label
"test label")))))
(deftest oproperty-annotation
(is
(= '(object-property
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/object-property to "x"
:label
"test label")))))
(deftest dproperty-annotation
(is
(= '(datatype-property
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/datatype-property to "x"
:label
"test label")))))
(deftest aproperty-annotation
(is
(= '(annotation-property
(iri "")
:annotation
(label (literal "test label" :lang "en")))
(r/as-form
(o/annotation-property to "x"
:label
"test label")))))
(deftest oproperty-characteristic []
(let [o (o/object-property to "x" :characteristic :functional)]
(is
(=
'(object-property
(iri "")
:characteristic :functional)
(r/as-form o)))))
|
b8ff62968dea3c239893f7a10eda1646d84de85b6c55eac99b82446b756f14fc | nrepl/weasel | websocket.cljs | Copyright ( c ) . All rights reserved .
;; The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 ( -1.0.php )
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns weasel.impls.websocket
(:require [clojure.browser.net :as net :refer [IConnection connect transmit]]
[clojure.browser.event :as event :refer [event-types]]
[goog.net.WebSocket :as gwebsocket]))
(defprotocol IWebSocket
(open? [this]))
(defn websocket-connection
([]
(websocket-connection nil nil))
([auto-reconnect?]
(websocket-connection auto-reconnect? nil))
([auto-reconnect? next-reconnect-fn]
(goog.net.WebSocket. auto-reconnect? next-reconnect-fn)))
(extend-type goog.net.WebSocket
IWebSocket
(open? [this]
(.isOpen this ()))
net/IConnection
(connect
([this url]
(connect this url nil))
([this url protocol]
(.open this url protocol)))
(transmit [this message]
(.send this message))
(close [this]
(.close this ()))
event/IEventType
(event-types [this]
(into {}
(map
(fn [[k v]]
[(keyword (. k (toLowerCase)))
v])
(merge
(js->clj goog.net.WebSocket/EventType))))))
| null | https://raw.githubusercontent.com/nrepl/weasel/338109d3504fa96b8a15b6892fb8c4aceeb90857/src/cljs/weasel/impls/websocket.cljs | clojure | The use and distribution terms for this software are covered by the
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) . All rights reserved .
Eclipse Public License 1.0 ( -1.0.php )
(ns weasel.impls.websocket
(:require [clojure.browser.net :as net :refer [IConnection connect transmit]]
[clojure.browser.event :as event :refer [event-types]]
[goog.net.WebSocket :as gwebsocket]))
(defprotocol IWebSocket
(open? [this]))
(defn websocket-connection
([]
(websocket-connection nil nil))
([auto-reconnect?]
(websocket-connection auto-reconnect? nil))
([auto-reconnect? next-reconnect-fn]
(goog.net.WebSocket. auto-reconnect? next-reconnect-fn)))
(extend-type goog.net.WebSocket
IWebSocket
(open? [this]
(.isOpen this ()))
net/IConnection
(connect
([this url]
(connect this url nil))
([this url protocol]
(.open this url protocol)))
(transmit [this message]
(.send this message))
(close [this]
(.close this ()))
event/IEventType
(event-types [this]
(into {}
(map
(fn [[k v]]
[(keyword (. k (toLowerCase)))
v])
(merge
(js->clj goog.net.WebSocket/EventType))))))
|
88bd97a99b137cc9db783728465a67ec5453905eaf741cb38d1d98ca43e4c3e6 | miner/transmuters | test_transmuters.clj | (ns miner.test-transmuters
(:require [clojure.test :refer :all]
[miner.transmuters :refer :all]))
(defn test-take-nth [coll]
(is (= (clojure.core/take-nth 3 coll)
(my-take-nth 3 coll)
(sequence (my-take-nth 3) coll)
(transduce (my-take-nth 3) conj [] coll))))
(defn test-xtake [coll]
(is (= (sequence (xtake 3) coll)
(take 3 coll)
(transduce (xtake 3) conj [] coll)))
(let [pad ::x
len (count coll)]
(when (< len 3)
(is (= (sequence (xtake 3 pad) coll)
(concat (take 3 coll) (repeat (- 3 len) pad))
(transduce (xtake 3 pad) conj [] coll))))))
(defn test-drop-nth [coll]
(is (= (drop-nth 3 coll)
(sequence (drop-nth 3) coll)
(transduce (drop-nth 3) conj [] coll)
(keep-indexed (fn [i x] (when (pos? (mod i 3)) x)) coll)
(sequence (keep-indexed (fn [i x] (when (pos? (mod i 3)) x))) coll))))
(defn test-empty [coll]
(is (empty? (sequence (xempty) coll)))
(is (empty? (xempty coll))))
for reference only , this is " wrong " if the first item does n't satisfy f
;; Don't use this. slow-partition-when is a fix.
(defn naive-partition-when [f coll]
(map (partial apply concat) (partition-all 2 (partition-by f coll))))
;; Slow, but useful for testing
(defn slow-partition-when [f coll]
(let [ps (partition-by f coll)
ps (cond (empty? ps) ()
(when-let [p1 (ffirst ps)] (f p1)) ps
:else (conj ps ()))]
(map (partial apply concat) (partition-all 2 ps))))
(defn test-partition-when [f coll]
(is (= (slow-partition-when f coll)
(partition-when f coll)
(sequence (partition-when f) coll)
(transduce (partition-when f) conj [] coll))))
(deftest ranges
(doseq [coll (list () [1] (range 100))]
(test-take-nth coll)
(test-xtake coll)
(test-drop-nth coll)
(test-partition-when even? coll)
(test-partition-when odd? coll)
(test-empty coll)))
(deftest part-while
(is (= (partition-while >= [1 2 2 3 1 5 3])
'([1] [2 2] [3 1] [5 3])))
(is (= (partition-while > [1 2 2 3 1 5 3])
'([1] [2] [2] [3 1] [5 3])))
(is (= (partition-while <= [1 2 2 3 1 5 3])
'([1 2 2 3] [1 5] [3])))
(is (= (partition-while < [1 2 2 3 1 5 3])
'([1 2] [2 3] [1 5] [3]))))
(deftest thresholds
(let [coll (range 100)]
(is (= (sequence (partition-threshold (constantly 1) 13) coll)
(sequence (partition-all 13) coll)))
(is (= (sequence (comp (partition-all 4) (partition-threshold (app max) 100)
(map flatten) (map (app +)))
(range 100))
'(378 402 546 444 508 572 636 700 764)))
(is (= (sequence (partition-threshold identity 81) coll)
'([0 1 2 3 4 5 6 7 8 9 10 11 12 13] [14 15 16 17 18 19] [20 21 22 23]
[24 25 26 27] [28 29 30] [31 32 33] [34 35 36] [37 38 39] [40 41] [42 43]
[44 45] [46 47] [48 49] [50 51] [52 53] [54 55] [56 57] [58 59] [60 61]
[62 63] [64 65] [66 67] [68 69] [70 71] [72 73] [74 75] [76 77] [78 79]
[80 81] [82] [83] [84] [85] [86] [87] [88] [89] [90] [91] [92] [93] [94]
[95] [96] [97] [98] [99])))))
(defn sq [n] (* n n))
(deftest chaining
(let [coll (range 100)]
(is (= (sequence (chain) coll) coll))
(is (= (sequence (chain (comp)) coll) coll))
(is (= (sequence (chain (map sq)) coll) (map sq coll)))
;; (take 0) is a special case that burns on input so we need the pushback
(is (= (sequence (chain (take 0) pushback (map sq)) coll) (map sq coll)))
(is (= (sequence (chain (take 5)) coll) (take 5 coll)))
(is (= (sequence (chain (comp (drop-while #(< % 4)) (take 3)) (map -)) coll)
(sequence (chain (comp (drop 4) (take-while #(< % 7))) pushback (map -)) coll)
(concat (take 3 (drop 4 coll)) (map - (drop 7 coll)))))
(is (= (sequence (chain (comp (take 5) (map sq)) (map -)) coll)
(concat (map sq (take 5 coll)) (map - (drop 5 coll)))))
(is (= (sequence (comp (map (partial + 10)) (chain (comp (take 5) (map sq)) (map -)) ) coll)
(let [coll10 (map (partial + 10) coll)]
(concat (map sq (take 5 coll10)) (map - (drop 5 coll10))))))
;; take-while burns an extra input so you need to pushback
(is (= (sequence (chain (comp (take 5) (map sq))
(comp (take-while #(< % 20)) (map -)) pushback
(comp (take 10) (map sq))
(filter even?))
coll)
(concat (map sq (take 5 coll))
(map - (take 15 (drop 5 coll)))
(map sq (take 10 (drop 20 coll)))
(filter even? (drop 30 coll)))))))
(deftest completion-chain
(is (= (sequence (chain (comp (take 7) (partition-all 6)) (partition-all 3)) (range 20))
'([0 1 2 3 4 5] [6] [7 8 9] [10 11 12] [13 14 15] [16 17 18] [19]))))
;; handy combinator for testing
;; rem is slightly faster than mod
(defn zmod [n]
(fn [x] (zero? (rem x n))))
(deftest zzzmods
(let [coll (range 100)]
(is (= (range 0 (count coll) 3)
(filter (zmod 3) coll)
(sequence (filter (zmod 3)) coll)
(sequence (take-nth 3) coll)))))
(deftest while-accumulating
;; distinct
(is (= (into [] (take-while2 conj #{} (complement contains?)) '(1 2 3 4 2 5 6))
[1 2 3 4]))
dedupe
(is (= (into [] (take-while2 (farg 2) ::void not=) '(1 2 1 3 4 4 5 6))
[1 2 1 3 4]))
;; monotonically increasing
(is (= (into [] (take-while2 max 0 <=) '(1 2 3 4 4 1 5 6))
[1 2 3 4 4])))
(deftest sliding
(is (= (sequence (comp (slide 3 [0 0 0]) (map (app +))) (range 10))
'(0 1 3 6 9 12 15 18 21 24)))
(is (= (sequence (comp (slide 4) (map vec)) (range 10))
'([0 1 2 3] [1 2 3 4] [2 3 4 5] [3 4 5 6] [4 5 6 7] [5 6 7 8] [6 7 8 9]))))
(deftest convolutions
(is (= (sequence (convolve [0.25 0.5 0.25]) [1 2 3 4 5])
'(2.0 3.0 4.0))))
(defn limit10+
([] 0)
([a b] (let [sum (+ a b)] (if (> sum 10) (reduced sum) sum))))
(deftest xreducts
(is (= (reductions + 3 (range 20)) (sequence (reducts + 3) (range 20))))
(is (= (reductions limit10+ 3 (range 20)) (sequence (reducts limit10+ 3) (range 20)))))
(deftest prepend-append
(is (= (sequence (prepend [3 4 5]) ()) '(3 4 5)))
(is (= (sequence (comp (prepend [3 4]) (map #(* 2 %))) (range 4))
'(6 8 0 2 4 6)))
(is (= (sequence (comp (map #(* 2 %)) (prepend [3 4]) ) (range 4))
'(3 4 0 2 4 6)))
(is (= (sequence (prepend [11 12]) (range 10)) (concat [11 12] (range 10))))
(is (= (sequence (append [11 12]) (range 10)) (concat (range 10) [11 12])))
(is (= (sequence (comp (prepend [4]) (reducts limit10+ 3) (append [101])) (range 10))
'(3 7 7 8 10 13 101))))
#_
(deftest map-cycling
(is (= (sequence (map-cycle + - + + -) (range 20))
'(0 -1 2 3 -4 5 -6 7 8 -9 10 -11 12 13 -14 15 -16 17 18 -19)))
(is (= (sequence (map-cycle +) (range 20)) (range 20))))
| null | https://raw.githubusercontent.com/miner/transmuters/90bbe11c8773a0997a234f510ca8ba652791d37f/test/miner/test_transmuters.clj | clojure | Don't use this. slow-partition-when is a fix.
Slow, but useful for testing
(take 0) is a special case that burns on input so we need the pushback
take-while burns an extra input so you need to pushback
handy combinator for testing
rem is slightly faster than mod
distinct
monotonically increasing | (ns miner.test-transmuters
(:require [clojure.test :refer :all]
[miner.transmuters :refer :all]))
(defn test-take-nth [coll]
(is (= (clojure.core/take-nth 3 coll)
(my-take-nth 3 coll)
(sequence (my-take-nth 3) coll)
(transduce (my-take-nth 3) conj [] coll))))
(defn test-xtake [coll]
(is (= (sequence (xtake 3) coll)
(take 3 coll)
(transduce (xtake 3) conj [] coll)))
(let [pad ::x
len (count coll)]
(when (< len 3)
(is (= (sequence (xtake 3 pad) coll)
(concat (take 3 coll) (repeat (- 3 len) pad))
(transduce (xtake 3 pad) conj [] coll))))))
(defn test-drop-nth [coll]
(is (= (drop-nth 3 coll)
(sequence (drop-nth 3) coll)
(transduce (drop-nth 3) conj [] coll)
(keep-indexed (fn [i x] (when (pos? (mod i 3)) x)) coll)
(sequence (keep-indexed (fn [i x] (when (pos? (mod i 3)) x))) coll))))
(defn test-empty [coll]
(is (empty? (sequence (xempty) coll)))
(is (empty? (xempty coll))))
for reference only , this is " wrong " if the first item does n't satisfy f
(defn naive-partition-when [f coll]
(map (partial apply concat) (partition-all 2 (partition-by f coll))))
(defn slow-partition-when [f coll]
(let [ps (partition-by f coll)
ps (cond (empty? ps) ()
(when-let [p1 (ffirst ps)] (f p1)) ps
:else (conj ps ()))]
(map (partial apply concat) (partition-all 2 ps))))
(defn test-partition-when [f coll]
(is (= (slow-partition-when f coll)
(partition-when f coll)
(sequence (partition-when f) coll)
(transduce (partition-when f) conj [] coll))))
(deftest ranges
(doseq [coll (list () [1] (range 100))]
(test-take-nth coll)
(test-xtake coll)
(test-drop-nth coll)
(test-partition-when even? coll)
(test-partition-when odd? coll)
(test-empty coll)))
(deftest part-while
(is (= (partition-while >= [1 2 2 3 1 5 3])
'([1] [2 2] [3 1] [5 3])))
(is (= (partition-while > [1 2 2 3 1 5 3])
'([1] [2] [2] [3 1] [5 3])))
(is (= (partition-while <= [1 2 2 3 1 5 3])
'([1 2 2 3] [1 5] [3])))
(is (= (partition-while < [1 2 2 3 1 5 3])
'([1 2] [2 3] [1 5] [3]))))
(deftest thresholds
(let [coll (range 100)]
(is (= (sequence (partition-threshold (constantly 1) 13) coll)
(sequence (partition-all 13) coll)))
(is (= (sequence (comp (partition-all 4) (partition-threshold (app max) 100)
(map flatten) (map (app +)))
(range 100))
'(378 402 546 444 508 572 636 700 764)))
(is (= (sequence (partition-threshold identity 81) coll)
'([0 1 2 3 4 5 6 7 8 9 10 11 12 13] [14 15 16 17 18 19] [20 21 22 23]
[24 25 26 27] [28 29 30] [31 32 33] [34 35 36] [37 38 39] [40 41] [42 43]
[44 45] [46 47] [48 49] [50 51] [52 53] [54 55] [56 57] [58 59] [60 61]
[62 63] [64 65] [66 67] [68 69] [70 71] [72 73] [74 75] [76 77] [78 79]
[80 81] [82] [83] [84] [85] [86] [87] [88] [89] [90] [91] [92] [93] [94]
[95] [96] [97] [98] [99])))))
(defn sq [n] (* n n))
(deftest chaining
(let [coll (range 100)]
(is (= (sequence (chain) coll) coll))
(is (= (sequence (chain (comp)) coll) coll))
(is (= (sequence (chain (map sq)) coll) (map sq coll)))
(is (= (sequence (chain (take 0) pushback (map sq)) coll) (map sq coll)))
(is (= (sequence (chain (take 5)) coll) (take 5 coll)))
(is (= (sequence (chain (comp (drop-while #(< % 4)) (take 3)) (map -)) coll)
(sequence (chain (comp (drop 4) (take-while #(< % 7))) pushback (map -)) coll)
(concat (take 3 (drop 4 coll)) (map - (drop 7 coll)))))
(is (= (sequence (chain (comp (take 5) (map sq)) (map -)) coll)
(concat (map sq (take 5 coll)) (map - (drop 5 coll)))))
(is (= (sequence (comp (map (partial + 10)) (chain (comp (take 5) (map sq)) (map -)) ) coll)
(let [coll10 (map (partial + 10) coll)]
(concat (map sq (take 5 coll10)) (map - (drop 5 coll10))))))
(is (= (sequence (chain (comp (take 5) (map sq))
(comp (take-while #(< % 20)) (map -)) pushback
(comp (take 10) (map sq))
(filter even?))
coll)
(concat (map sq (take 5 coll))
(map - (take 15 (drop 5 coll)))
(map sq (take 10 (drop 20 coll)))
(filter even? (drop 30 coll)))))))
(deftest completion-chain
(is (= (sequence (chain (comp (take 7) (partition-all 6)) (partition-all 3)) (range 20))
'([0 1 2 3 4 5] [6] [7 8 9] [10 11 12] [13 14 15] [16 17 18] [19]))))
(defn zmod [n]
(fn [x] (zero? (rem x n))))
(deftest zzzmods
(let [coll (range 100)]
(is (= (range 0 (count coll) 3)
(filter (zmod 3) coll)
(sequence (filter (zmod 3)) coll)
(sequence (take-nth 3) coll)))))
(deftest while-accumulating
(is (= (into [] (take-while2 conj #{} (complement contains?)) '(1 2 3 4 2 5 6))
[1 2 3 4]))
dedupe
(is (= (into [] (take-while2 (farg 2) ::void not=) '(1 2 1 3 4 4 5 6))
[1 2 1 3 4]))
(is (= (into [] (take-while2 max 0 <=) '(1 2 3 4 4 1 5 6))
[1 2 3 4 4])))
(deftest sliding
(is (= (sequence (comp (slide 3 [0 0 0]) (map (app +))) (range 10))
'(0 1 3 6 9 12 15 18 21 24)))
(is (= (sequence (comp (slide 4) (map vec)) (range 10))
'([0 1 2 3] [1 2 3 4] [2 3 4 5] [3 4 5 6] [4 5 6 7] [5 6 7 8] [6 7 8 9]))))
(deftest convolutions
(is (= (sequence (convolve [0.25 0.5 0.25]) [1 2 3 4 5])
'(2.0 3.0 4.0))))
(defn limit10+
([] 0)
([a b] (let [sum (+ a b)] (if (> sum 10) (reduced sum) sum))))
(deftest xreducts
(is (= (reductions + 3 (range 20)) (sequence (reducts + 3) (range 20))))
(is (= (reductions limit10+ 3 (range 20)) (sequence (reducts limit10+ 3) (range 20)))))
(deftest prepend-append
(is (= (sequence (prepend [3 4 5]) ()) '(3 4 5)))
(is (= (sequence (comp (prepend [3 4]) (map #(* 2 %))) (range 4))
'(6 8 0 2 4 6)))
(is (= (sequence (comp (map #(* 2 %)) (prepend [3 4]) ) (range 4))
'(3 4 0 2 4 6)))
(is (= (sequence (prepend [11 12]) (range 10)) (concat [11 12] (range 10))))
(is (= (sequence (append [11 12]) (range 10)) (concat (range 10) [11 12])))
(is (= (sequence (comp (prepend [4]) (reducts limit10+ 3) (append [101])) (range 10))
'(3 7 7 8 10 13 101))))
#_
(deftest map-cycling
(is (= (sequence (map-cycle + - + + -) (range 20))
'(0 -1 2 3 -4 5 -6 7 8 -9 10 -11 12 13 -14 15 -16 17 18 -19)))
(is (= (sequence (map-cycle +) (range 20)) (range 20))))
|
7854e47b5a0b1b072629eff0594bb8d2924607dcf46558cd51f17fa679b76c2b | project-oak/hafnium-verification | IssueAuxData.mli |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
type t = Location.t list
val encode : t -> string
val decode : string -> t
| null | https://raw.githubusercontent.com/project-oak/hafnium-verification/6071eff162148e4d25a0fedaea003addac242ace/experiments/ownership-inference/infer/infer/src/concurrency/IssueAuxData.mli | ocaml |
* Copyright ( c ) Facebook , Inc. and its affiliates .
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree .
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
open! IStd
type t = Location.t list
val encode : t -> string
val decode : string -> t
| |
684726b14c7951d7152a35fe078536f8ad7b5f33c967460492b3e9345f0e2145 | rowangithub/DOrder | sum1.ml | let rec loop i n sn =
if (i <= n) then loop (i + 1) n (sn + 1)
else (
if (sn = n) then ()
else assert (sn = 0)
)
let main n =
loop 1 n 0
let _ = main 10
let _ = main 0
let _ = main (-1) | null | https://raw.githubusercontent.com/rowangithub/DOrder/e0d5efeb8853d2a51cc4796d7db0f8be3185d7df/tests/folprograms/ice/sum1.ml | ocaml | let rec loop i n sn =
if (i <= n) then loop (i + 1) n (sn + 1)
else (
if (sn = n) then ()
else assert (sn = 0)
)
let main n =
loop 1 n 0
let _ = main 10
let _ = main 0
let _ = main (-1) | |
7151cd51a195089e1f8d9ac22c8a86d473f0368b2c9d61d41ea6d35fd18414bd | mzp/coq-ruby | contradiction.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
$ I d : contradiction.ml 11309 2008 - 08 - 06 10:30:35Z herbelin $
open Util
open Term
open Proof_type
open Hipattern
open Tacmach
open Tacticals
open Tactics
open Coqlib
open Reductionops
open Rawterm
(* Absurd *)
let absurd c gls =
let env = pf_env gls and sigma = project gls in
let _,j = Coercion.Default.inh_coerce_to_sort dummy_loc env
(Evd.create_goal_evar_defs sigma) (Retyping.get_judgment_of env sigma c) in
let c = j.Environ.utj_val in
(tclTHENS
(tclTHEN (elim_type (build_coq_False ())) (cut c))
([(tclTHENS
(cut (applist(build_coq_not (),[c])))
([(tclTHEN intros
((fun gl ->
let ida = pf_nth_hyp_id gl 1
and idna = pf_nth_hyp_id gl 2 in
exact_no_check (applist(mkVar idna,[mkVar ida])) gl)));
tclIDTAC]));
tclIDTAC])) gls
(* Contradiction *)
let filter_hyp f tac gl =
let rec seek = function
| [] -> raise Not_found
| (id,_,t)::rest when f t -> tac id gl
| _::rest -> seek rest in
seek (pf_hyps gl)
let contradiction_context gl =
let env = pf_env gl in
let sigma = project gl in
let rec seek_neg l gl = match l with
| [] -> error "No such contradiction"
| (id,_,typ)::rest ->
let typ = whd_betadeltaiota env sigma typ in
if is_empty_type typ then
simplest_elim (mkVar id) gl
else match kind_of_term typ with
| Prod (na,t,u) when is_empty_type u ->
(try
filter_hyp (fun typ -> pf_conv_x_leq gl typ t)
(fun id' -> simplest_elim (mkApp (mkVar id,[|mkVar id'|])))
gl
with Not_found -> seek_neg rest gl)
| _ -> seek_neg rest gl in
seek_neg (pf_hyps gl) gl
let is_negation_of env sigma typ t =
match kind_of_term (whd_betadeltaiota env sigma t) with
| Prod (na,t,u) -> is_empty_type u & is_conv_leq env sigma typ t
| _ -> false
let contradiction_term (c,lbind as cl) gl =
let env = pf_env gl in
let sigma = project gl in
let typ = pf_type_of gl c in
let _, ccl = splay_prod env sigma typ in
if is_empty_type ccl then
tclTHEN (elim false cl None) (tclTRY assumption) gl
else
try
if lbind = NoBindings then
filter_hyp (is_negation_of env sigma typ)
(fun id -> simplest_elim (mkApp (mkVar id,[|c|]))) gl
else
raise Not_found
with Not_found -> error "Not a contradiction."
let contradiction = function
| None -> tclTHEN intros contradiction_context
| Some c -> contradiction_term c
| null | https://raw.githubusercontent.com/mzp/coq-ruby/99b9f87c4397f705d1210702416176b13f8769c1/tactics/contradiction.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
Absurd
Contradiction | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
$ I d : contradiction.ml 11309 2008 - 08 - 06 10:30:35Z herbelin $
open Util
open Term
open Proof_type
open Hipattern
open Tacmach
open Tacticals
open Tactics
open Coqlib
open Reductionops
open Rawterm
let absurd c gls =
let env = pf_env gls and sigma = project gls in
let _,j = Coercion.Default.inh_coerce_to_sort dummy_loc env
(Evd.create_goal_evar_defs sigma) (Retyping.get_judgment_of env sigma c) in
let c = j.Environ.utj_val in
(tclTHENS
(tclTHEN (elim_type (build_coq_False ())) (cut c))
([(tclTHENS
(cut (applist(build_coq_not (),[c])))
([(tclTHEN intros
((fun gl ->
let ida = pf_nth_hyp_id gl 1
and idna = pf_nth_hyp_id gl 2 in
exact_no_check (applist(mkVar idna,[mkVar ida])) gl)));
tclIDTAC]));
tclIDTAC])) gls
let filter_hyp f tac gl =
let rec seek = function
| [] -> raise Not_found
| (id,_,t)::rest when f t -> tac id gl
| _::rest -> seek rest in
seek (pf_hyps gl)
let contradiction_context gl =
let env = pf_env gl in
let sigma = project gl in
let rec seek_neg l gl = match l with
| [] -> error "No such contradiction"
| (id,_,typ)::rest ->
let typ = whd_betadeltaiota env sigma typ in
if is_empty_type typ then
simplest_elim (mkVar id) gl
else match kind_of_term typ with
| Prod (na,t,u) when is_empty_type u ->
(try
filter_hyp (fun typ -> pf_conv_x_leq gl typ t)
(fun id' -> simplest_elim (mkApp (mkVar id,[|mkVar id'|])))
gl
with Not_found -> seek_neg rest gl)
| _ -> seek_neg rest gl in
seek_neg (pf_hyps gl) gl
let is_negation_of env sigma typ t =
match kind_of_term (whd_betadeltaiota env sigma t) with
| Prod (na,t,u) -> is_empty_type u & is_conv_leq env sigma typ t
| _ -> false
let contradiction_term (c,lbind as cl) gl =
let env = pf_env gl in
let sigma = project gl in
let typ = pf_type_of gl c in
let _, ccl = splay_prod env sigma typ in
if is_empty_type ccl then
tclTHEN (elim false cl None) (tclTRY assumption) gl
else
try
if lbind = NoBindings then
filter_hyp (is_negation_of env sigma typ)
(fun id -> simplest_elim (mkApp (mkVar id,[|c|]))) gl
else
raise Not_found
with Not_found -> error "Not a contradiction."
let contradiction = function
| None -> tclTHEN intros contradiction_context
| Some c -> contradiction_term c
|
93564b79669ca45da83352ef092b48bb0bce71592a77466d3b128ccecaa6d8e9 | anuyts/menkar | Maybe.hs | module Data.Traversable.Maybe where
import Control.Exception.AssertFalse
import Data.Foldable
import Data.Monoid
import Data.Maybe
traverseMaybe :: (Functor t, Foldable t) => (a -> Maybe b) -> t a -> Maybe (t b)
traverseMaybe f ta =
-- If all contained elements are of the form `Just _`
if getAll . foldMap (All . isJust . f) $ ta
-- Then extract the `Just`
then Just $ fromMaybe unreachable . f <$> ta
-- Else return `Nothing`
else Nothing
sequenceMaybe :: (Functor t, Foldable t) => t (Maybe b) -> Maybe (t b)
sequenceMaybe = traverseMaybe id
| null | https://raw.githubusercontent.com/anuyts/menkar/1f00e9febd1e9ed70c138ae8232b1c72a17d31da/menkar/src/Data/Traversable/Maybe.hs | haskell | If all contained elements are of the form `Just _`
Then extract the `Just`
Else return `Nothing` | module Data.Traversable.Maybe where
import Control.Exception.AssertFalse
import Data.Foldable
import Data.Monoid
import Data.Maybe
traverseMaybe :: (Functor t, Foldable t) => (a -> Maybe b) -> t a -> Maybe (t b)
traverseMaybe f ta =
if getAll . foldMap (All . isJust . f) $ ta
then Just $ fromMaybe unreachable . f <$> ta
else Nothing
sequenceMaybe :: (Functor t, Foldable t) => t (Maybe b) -> Maybe (t b)
sequenceMaybe = traverseMaybe id
|
e9acf7c2e227efcbb304749f84a4004df80cb52204c29417b63c8a6a1d2d98ae | ds-wizard/engine-backend | LocaleService.hs | module Registry.Service.Locale.LocaleService where
import Registry.Api.Resource.Locale.LocaleDTO
import Registry.Api.Resource.Locale.LocaleDetailDTO
import Registry.Database.DAO.Locale.LocaleDAO
import Registry.Database.DAO.Organization.OrganizationDAO
import Registry.Model.Context.AppContext
import Registry.Service.Locale.LocaleMapper
import Registry.Service.Locale.LocaleUtil
import Shared.Database.DAO.Locale.LocaleDAO
import Shared.Model.Locale.Locale
import Shared.Util.Coordinate
getLocales :: [(String, String)] -> Maybe String -> AppContextM [LocaleDTO]
getLocales queryParams mRecommendedAppVersion = do
tmpls <- findLocalesFiltered queryParams mRecommendedAppVersion
orgs <- findOrganizations
return . fmap (toDTO orgs) . chooseTheNewest . groupLocales $ tmpls
getLocaleById :: String -> AppContextM LocaleDetailDTO
getLocaleById lclId = do
locale <- findLocaleById lclId
versions <- getLocaleVersions locale
org <- findOrganizationByOrgId locale.organizationId
return $ toDetailDTO locale versions org
-- --------------------------------
-- PRIVATE
-- --------------------------------
getLocaleVersions :: Locale -> AppContextM [String]
getLocaleVersions locale = do
allTmls <- findLocalesByOrganizationIdAndLocaleId locale.organizationId locale.localeId
return . fmap (.version) $ allTmls
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/0ec94a4b0545f2de8a4e59686a4376023719d5e7/engine-registry/src/Registry/Service/Locale/LocaleService.hs | haskell | --------------------------------
PRIVATE
-------------------------------- | module Registry.Service.Locale.LocaleService where
import Registry.Api.Resource.Locale.LocaleDTO
import Registry.Api.Resource.Locale.LocaleDetailDTO
import Registry.Database.DAO.Locale.LocaleDAO
import Registry.Database.DAO.Organization.OrganizationDAO
import Registry.Model.Context.AppContext
import Registry.Service.Locale.LocaleMapper
import Registry.Service.Locale.LocaleUtil
import Shared.Database.DAO.Locale.LocaleDAO
import Shared.Model.Locale.Locale
import Shared.Util.Coordinate
getLocales :: [(String, String)] -> Maybe String -> AppContextM [LocaleDTO]
getLocales queryParams mRecommendedAppVersion = do
tmpls <- findLocalesFiltered queryParams mRecommendedAppVersion
orgs <- findOrganizations
return . fmap (toDTO orgs) . chooseTheNewest . groupLocales $ tmpls
getLocaleById :: String -> AppContextM LocaleDetailDTO
getLocaleById lclId = do
locale <- findLocaleById lclId
versions <- getLocaleVersions locale
org <- findOrganizationByOrgId locale.organizationId
return $ toDetailDTO locale versions org
getLocaleVersions :: Locale -> AppContextM [String]
getLocaleVersions locale = do
allTmls <- findLocalesByOrganizationIdAndLocaleId locale.organizationId locale.localeId
return . fmap (.version) $ allTmls
|
12fe931603fb4612c59a51dde6197438619b5120fb6c83a60be66fde1ed4e5df | gwkkwg/metatilities | generic-lisp.lisp | (in-package #:metatilities)
;;; ---------------------------------------------------------------------------
;;; specify that we're using the OPENMCL interface
;;; ---------------------------------------------------------------------------
(setf (default-interface) :OPENMCL)
;;; ---------------------------------------------------------------------------
(defmethod is-interface-available-p ((interface (eql :OPENMCL)))
(values t))
;;; ---------------------------------------------------------------------------
;;; quitting
;;; ---------------------------------------------------------------------------
(defmethod quit-lisp* ((interface (eql :OPENMCL)))
(ccl:quit))
;;; ---------------------------------------------------------------------------
;;; memory management stuff
;;; ---------------------------------------------------------------------------
(defmethod total-bytes-allocated* ((interface (eql :OPENMCL)))
(values (ccl::total-bytes-allocated)))
;;; ---------------------------------------------------------------------------
(defmethod gc-time* ((interface (eql :OPENMCL)))
(values (ccl:gctime)))
;;; ---------------------------------------------------------------------------
(defmethod collect-garbage* ((interface (eql :OPENMCL)))
(ccl:gc))
;;; ***************************************************************************
;;; * End of File *
;;; *************************************************************************** | null | https://raw.githubusercontent.com/gwkkwg/metatilities/82e13df0545d0e47ae535ea35c5c99dd3a44e69e/dev/openmcl/generic-lisp.lisp | lisp | ---------------------------------------------------------------------------
specify that we're using the OPENMCL interface
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
quitting
---------------------------------------------------------------------------
---------------------------------------------------------------------------
memory management stuff
---------------------------------------------------------------------------
---------------------------------------------------------------------------
---------------------------------------------------------------------------
***************************************************************************
* End of File *
*************************************************************************** | (in-package #:metatilities)
(setf (default-interface) :OPENMCL)
(defmethod is-interface-available-p ((interface (eql :OPENMCL)))
(values t))
(defmethod quit-lisp* ((interface (eql :OPENMCL)))
(ccl:quit))
(defmethod total-bytes-allocated* ((interface (eql :OPENMCL)))
(values (ccl::total-bytes-allocated)))
(defmethod gc-time* ((interface (eql :OPENMCL)))
(values (ccl:gctime)))
(defmethod collect-garbage* ((interface (eql :OPENMCL)))
(ccl:gc))
|
aad86329d67ab1932d9e8ffb76522fb74b30581fb1103e59605565d8079e7547 | GaloisInc/surveyor | InstructionSemanticsViewer.hs | {-# LANGUAGE BangPatterns #-}
-- | A widget for displaying the semantics for an individual instruction
--
-- This is intended for displaying machine code instruction semantics. It
-- currently has no interactivity, so there is no event handler.
module Surveyor.Brick.Widget.InstructionSemanticsViewer (
InstructionSemanticsViewer,
instructionSemanticsViewer,
renderInstructionSemanticsViewer
) where
import qualified Brick as B
import Control.DeepSeq ( NFData, rnf )
import Control.Lens ( (^?), (^.) )
import qualified Data.Vector as V
import qualified Prettyprinter as PP
import qualified Prettyprinter.Render.Text as PPT
import qualified Surveyor.Core as C
import Surveyor.Brick.Names ( Names(..) )
-- The rendering only requires a view of the context, so there is no data
-- payload for the widget itself (for now)
data InstructionSemanticsViewer arch s =
InstructionSemanticsViewer
instance NFData (InstructionSemanticsViewer arch s) where
rnf !_ = ()
instructionSemanticsViewer :: InstructionSemanticsViewer arch s
instructionSemanticsViewer = InstructionSemanticsViewer
-- | Render the instructions for the selected instruction (of the base
-- architecture) if there is a single selected instruction *and* there are
-- semantics available for it
renderInstructionSemanticsViewer :: (C.Architecture arch s)
=> C.AnalysisResult arch s
-> C.ContextStack arch s
-> InstructionSemanticsViewer arch s
-> B.Widget Names
renderInstructionSemanticsViewer ares cs _
| Just ctx <- cs ^? C.currentContext
, Just blkState <- ctx ^. C.blockStateFor C.BaseRepr =
case blkState ^. C.blockStateSelection of
C.NoSelection -> B.str "No selected instruction"
C.MultipleSelection {} -> B.str "Multiple instructions selected"
C.SingleSelection ix _addr _ ->
let insns = blkState ^. C.blockStateList
in case insns V.!? ix of
Nothing -> bDoc (PP.pretty "ERROR: Instruction index out of range:" PP.<+> PP.pretty ix)
Just (_, addr, i) ->
case C.genericSemantics ares i of
Nothing -> bDoc (PP.pretty "No semantics for instruction:" PP.<+> C.prettyInstruction addr i)
Just sem -> B.txt (C.prettyParameterizedFormula sem)
| otherwise = B.str "No current block"
bDoc :: PP.Doc ann -> B.Widget n
bDoc = B.txt . PPT.renderStrict . PP.layoutCompact
| null | https://raw.githubusercontent.com/GaloisInc/surveyor/96b6748d811bc2ab9ef330307a324bd00e04819f/surveyor-brick/src/Surveyor/Brick/Widget/InstructionSemanticsViewer.hs | haskell | # LANGUAGE BangPatterns #
| A widget for displaying the semantics for an individual instruction
This is intended for displaying machine code instruction semantics. It
currently has no interactivity, so there is no event handler.
The rendering only requires a view of the context, so there is no data
payload for the widget itself (for now)
| Render the instructions for the selected instruction (of the base
architecture) if there is a single selected instruction *and* there are
semantics available for it | module Surveyor.Brick.Widget.InstructionSemanticsViewer (
InstructionSemanticsViewer,
instructionSemanticsViewer,
renderInstructionSemanticsViewer
) where
import qualified Brick as B
import Control.DeepSeq ( NFData, rnf )
import Control.Lens ( (^?), (^.) )
import qualified Data.Vector as V
import qualified Prettyprinter as PP
import qualified Prettyprinter.Render.Text as PPT
import qualified Surveyor.Core as C
import Surveyor.Brick.Names ( Names(..) )
data InstructionSemanticsViewer arch s =
InstructionSemanticsViewer
instance NFData (InstructionSemanticsViewer arch s) where
rnf !_ = ()
instructionSemanticsViewer :: InstructionSemanticsViewer arch s
instructionSemanticsViewer = InstructionSemanticsViewer
renderInstructionSemanticsViewer :: (C.Architecture arch s)
=> C.AnalysisResult arch s
-> C.ContextStack arch s
-> InstructionSemanticsViewer arch s
-> B.Widget Names
renderInstructionSemanticsViewer ares cs _
| Just ctx <- cs ^? C.currentContext
, Just blkState <- ctx ^. C.blockStateFor C.BaseRepr =
case blkState ^. C.blockStateSelection of
C.NoSelection -> B.str "No selected instruction"
C.MultipleSelection {} -> B.str "Multiple instructions selected"
C.SingleSelection ix _addr _ ->
let insns = blkState ^. C.blockStateList
in case insns V.!? ix of
Nothing -> bDoc (PP.pretty "ERROR: Instruction index out of range:" PP.<+> PP.pretty ix)
Just (_, addr, i) ->
case C.genericSemantics ares i of
Nothing -> bDoc (PP.pretty "No semantics for instruction:" PP.<+> C.prettyInstruction addr i)
Just sem -> B.txt (C.prettyParameterizedFormula sem)
| otherwise = B.str "No current block"
bDoc :: PP.Doc ann -> B.Widget n
bDoc = B.txt . PPT.renderStrict . PP.layoutCompact
|
de0d954c8246e1492c98db473bf24382ac41a7111d8a0b0c0e6a6cbe1e4551c4 | overtone/overtone | synth.clj | (ns
^{:doc "The ugen functions create a data structure representing a synthesizer
graph that can be executed on the synthesis server. This is the logic
to \"compile\" these clojure data structures into a form that can be
serialized by the byte-spec defined in synthdef.clj."
:author "Jeff Rose"}
overtone.sc.synth
(:use [overtone.helpers lib old-contrib synth]
[overtone.libs event counters]
[overtone.music time]
[overtone.sc.machinery.ugen fn-gen defaults common specs sc-ugen]
[overtone.sc.machinery synthdef]
[overtone.sc bindings ugens server node foundation-groups dyn-vars]
[overtone.helpers seq]
[clojure.pprint]
[overtone.helpers.string :only [hash-shorten]])
(:require [overtone.config.log]
[clojure.set :as set]
[overtone.sc.cgens.env :refer [hold]]
[overtone.sc.protocols :as protocols]))
(declare synth-player)
(defonce ^{:private true} __RECORDS__
(do
(defrecord-ifn Synth [name ugens sdef args params instance-fn]
(partial synth-player sdef params))))
(defn- valid-control-proxy-rate?
[rate]
(some #{rate} CONTROL-PROXY-RATES))
# # # Synth
;;
;; A Synth is a collection of unit generators that run together. They can be
;; addressed and controlled by commands to the synthesis engine. They read
;; input and write output to global audio and control buses. Synths can have
;; their own local controls that are set via commands to the server.
(defn- ugen-index [ugens ugen]
(ffirst (filter (fn [[i v]]
(= (:id v) (:id ugen)))
(indexed ugens))))
; Gets the group number (source) and param index within the group (index)
; from the params that are grouped by rate like this:
;
[ [ { : name : freq : default 440.0 : rate 1 } { : name : amp : default 0.4 : rate 1 } ]
[ { : name : adfs : default 20.23 : rate 2 } { : name : bar : default 8.6 : rate 2 } ] ]
(defn- param-input-spec [grouped-params param-proxy]
(let [param-name (:name param-proxy)
ctl-filter (fn [[idx ctl]] (= param-name (:name ctl)))
[[src group] foo] (take 1 (filter
(fn [[src grp]]
(not (empty?
(filter ctl-filter (indexed grp)))))
(indexed grouped-params)))
[[idx param] bar] (take 1 (filter ctl-filter (indexed group)))]
(if (or (nil? src) (nil? idx))
(throw (IllegalArgumentException. (str "Invalid parameter name: " param-name ". Please make sure you have named all parameters in the param map in order to use them inside the synth definition."))))
{:src src :index idx}))
(defn- inputs-from-outputs [src src-ugen]
(for [i (range (count (:outputs src-ugen)))]
{:src src :index i}))
; NOTES:
; * *All* inputs must refer to either a constant or the output of another
UGen that is higher up in the list .
(defn- with-inputs
"Returns ugen object with its input ports connected to constants and
upstream ugens according to the arguments in the initial definition."
[ugen ugens constants grouped-params]
(when-not (contains? ugen :args)
(if-not (sc-ugen? ugen)
(throw (IllegalArgumentException.
(str "Error: synth expected a ugen. Got: " ugen)))
(throw (IllegalArgumentException.
(format "The %s ugen does not have any arguments."
(:name ugen))))))
(when-not (every? #(or (sc-ugen? %) (number? %) (string? %)) (:args ugen))
(throw (IllegalArgumentException.
(format "The %s ugen has an invalid argument: %s"
(:name ugen)
(first (filter
#(not (or (sc-ugen? %) (number? %)))
(:args ugen)))))))
(let [inputs (flatten
(map (fn [arg]
(cond
; constant
(number? arg)
{:src -1 :index (index-of constants (float arg))}
; control
(control-proxy? arg)
(param-input-spec grouped-params arg)
; output proxy
(output-proxy? arg)
(let [src (ugen-index ugens (:ugen arg))]
{:src src :index (:index arg)})
child
(sc-ugen? arg)
(let [src (ugen-index ugens arg)
updated-ugen (nth ugens src)]
(inputs-from-outputs src updated-ugen))))
(:args ugen)))
ugen (assoc ugen :inputs inputs)]
(when-not (every? (fn [{:keys [src index]}]
(and (not (nil? src))
(not (nil? index))))
(:inputs ugen))
(throw (Exception.
(format "Cannot connect ugen arguments for %s ugen with args: %s" (:name ugen) (str (seq (:args ugen)))))))
Add link back to ( always at root of tree ) if
ugen is a local - buf .
(if (= "LocalBuf" (:name ugen))
(assoc ugen :inputs (concat (:inputs ugen) [{:src 0 :index 0}]))
ugen)))
TODO : Currently the output rate is hard coded to be the same as the
computation rate of the ugen . We probably need to have some meta - data
; capabilities for supporting varying output rates...
(defn- with-outputs
"Returns a ugen with its output port connections setup according to
the spec."
[ugen]
{:post [(every? (fn [val] (not (nil? val))) (:outputs %))]}
(if (contains? ugen :outputs)
ugen
(let [spec (get-ugen (:name ugen))
num-outs (or (:n-outputs ugen) 1)
outputs (take num-outs (repeat {:rate (:rate ugen)}))]
(assoc ugen :outputs outputs))))
; IMPORTANT NOTE: We need to add outputs before inputs, so that multi-channel
; outputs can be correctly connected.
(defn- detail-ugens
"Fill in all the input and output specs for each ugen."
[ugens constants grouped-params]
(let [constants (map float constants)
outs (map with-outputs ugens)
ins (map #(with-inputs %1 outs constants grouped-params) outs)]
(doall ins)))
(defn- make-control-ugens
"Controls are grouped by rate, so that a single Control ugen
represents each rate present in the params. The Control ugens are
always the top nodes in the graph, so they can be prepended to the
topologically sorted tree.
Specifically handles control proxies at :tr, :ar, :kr and :ir"
[grouped-params]
(loop [done {}
todo grouped-params
offset 0]
(if (empty? todo)
(filter #(not (nil? %))
[(:ir done) (:tr done) (:ar done) (:kr done)])
(let [group (first todo)
group-rate (:rate (first group))
group-size (count group)
ctl-proxy (case group-rate
:tr (trig-control-ugen group-size offset)
:ar (audio-control-ugen group-size offset)
:kr (control-ugen group-size offset)
:ir (inst-control-ugen group-size offset))]
(recur (assoc done group-rate ctl-proxy) (rest todo) (+ offset group-size))))))
(defn- group-params
"Groups params by rate. Groups a list of parameters into a list of
lists, one per rate."
[params]
(let [by-rate (reduce (fn [mem param]
(let [rate (:rate param)
rate-group (get mem rate [])]
(assoc mem rate (conj rate-group param))))
{} params)]
(filter #(not (nil? %1))
[(:ir by-rate) (:tr by-rate) (:ar by-rate) (:kr by-rate)])))
(def DEFAULT-RATE :kr)
(defn- ensure-param-keys!
"Throws an error if map m doesn't contain the correct
keys: :name, :default and :rate"
[m]
(when-not (and
(contains? m :name)
(contains? m :default)
(contains? m :rate))
(throw (IllegalArgumentException. (str "Invalid synth param map. Expected to find the keys :name, :default, :rate, got: " m)))))
(defn- ensure-paired-params!
"Throws an error if list l does not contain an even number of
elements"
[l]
(when-not (even? (count l))
(throw (IllegalArgumentException. (str "A synth requires either an even number of arguments in the form [control default]* i.e. [freq 440 amp 0.5] or a list of maps. You passed " (count l) " args: " l)))))
(defn- ensure-vec!
"Throws an error if list l is not a vector"
[l]
(when-not (vector? l)
(throw (IllegalArgumentException. (str "Your synth argument list is not a vector. Instead I found " (type l) ": " l)))))
(defn- ensure-valid-control-proxy-vec!
[val]
(when-not (= 2 (count val))
(throw (IllegalArgumentException. (str "Control Proxy vector must have only 2 elements i.e. [0 :tr]"))))
(when-not (number? (first val))
(throw (IllegalArgumentException. (str "Control Proxy vector must have a number as the first element i.e. [0 :tr]"))))
(when-not (valid-control-proxy-rate? (second val))
(throw (IllegalArgumentException. (str "Control Proxy rate " (second val) " not valid. Expecting one of " CONTROL-PROXY-RATES))))
val)
(defn- mapify-params
"Converts a list of param name val pairs to a param map. If the val of
a param is a vector, it assumes it's a pair of [val rate] and sets the
rate of the param accordingly. If the val is a plain number, it sets
the rate to DEFAULT-RATE. All names are converted to strings"
[params]
(for [[p-name p-val] (partition 2 params)]
(let [param-map
(cond
(vector? p-val) (do
(ensure-valid-control-proxy-vec! p-val)
{:name (str p-name)
:default (first p-val)
:rate (second p-val)})
(associative? p-val) (merge
{:name (str p-name)
:rate DEFAULT-RATE} p-val)
:else {:name (str p-name)
:default `(float (to-id ~p-val))
:rate DEFAULT-RATE})]
(ensure-param-keys! param-map)
param-map)))
(defn- stringify-names
"Takes a map and converts the val of key :name to a string"
[m]
(into {} (for [[k v] m] (if (= :name k) [k (str v)] [k v]))))
;; TODO: Figure out a better way to specify rates for synth parameters
perhaps using name post - fixes such as [ freq : kr 440 ]
(defn- parse-params
"Used by defsynth to parse the param list. Accepts either a vector of
name default pairs, name [default rate] pairs or a vector of maps:
(defsynth foo [freq 440] ...)
(defsynth foo [freq [440 :ar]] ...)
(defsynth foo [freq {:default 440 :rate :ar}] ...)
Returns a vec of param maps"
[params]
(ensure-vec! params)
(ensure-paired-params! params)
(vec (mapify-params params)))
(defn- make-params
"Create the param value vector and parameter name vector."
[grouped-params]
(let [param-list (flatten grouped-params)
pvals (map #(:default %1) param-list)
pnames (map (fn [[idx param]]
{:name (to-str (:name param))
:index idx})
(indexed param-list))]
[pvals pnames]))
(defn- ugen-form? [form]
(and (seq? form)
(= 'ugen (first form))))
(defn- fastest-rate [rates]
(REVERSE-RATES (first (reverse (sort (map RATES rates))))))
(defn- special-op-args? [args]
(some #(or (sc-ugen? %1) (keyword? %1)) args))
(defn- find-rate [args]
(fastest-rate (map #(cond
(sc-ugen? %1) (REVERSE-RATES (:rate %1))
(keyword? %1) :kr)
args)))
;; For greatest efficiency:
;;
;; * Unit generators should be listed in an order that permits efficient reuse
of connection buffers , so use a depth first topological sort of the graph .
; NOTES:
* The ugen tree is turned into a ugen list that is sorted by the order in
which nodes should be processed . ( Depth first , starting at outermost leaf
of the first branch .
;
* params are sorted by rate , and then a Control ugen per rate is created
and prepended to the ugen list
;
* finally , ugen inputs are specified using their index
in the sorted ugen list .
;
; * No feedback loops are allowed. Feedback must be accomplished via delay lines
; or through buses.
;
(defn synthdef
"Transforms a synth definition (ugen-graph) into a form that's ready
to save to disk or send to the server.
(synthdef \"pad-z\" [
"
[sname params ugens constants]
(let [grouped-params (group-params params)
[params pnames] (make-params grouped-params)
with-ctl-ugens (concat (make-control-ugens grouped-params) ugens)
detailed (detail-ugens with-ctl-ugens constants grouped-params)
full-name (if (add-current-namespace-to-synth-name?)
(hash-shorten 31 (ns-name *ns*) (str "/" sname))
sname)]
(with-meta {:name full-name
:constants constants
:params params
:pnames pnames
:ugens detailed}
{:type :overtone.sc.machinery.synthdef/synthdef})))
(defn- control-proxies
"Returns a list of param name symbols and control proxies"
[params]
(mapcat (fn [param] [(symbol (:name param))
`(control-proxy ~(:name param) ~(:default param) ~(:rate param))])
params))
(defn- gen-synth-name
"Auto generate an anonymous synth name. Intended for use in synths
that have not been defined with an explicit name. Has the form
\"anon-id\" where id is a unique integer across all anonymous
synths."
[]
(str "anon-" (next-id ::anonymous-synth)))
(defn normalize-synth-args
"Pull out and normalize the synth name, parameters, control proxies
and the ugen form from the supplied arglist resorting to defaults if
necessary."
[args]
(let [[sname args] (if (or (string? (first args))
(symbol? (first args)))
[(str (first args)) (rest args)]
[(gen-synth-name) args])
[params ugen-form] (if (vector? (first args))
[(first args) (rest args)]
[[] args])
param-proxies (control-proxies params)]
[sname params param-proxies ugen-form]))
(defn gather-ugens-and-constants
"Traverses a ugen tree and returns a vector of two sets [#{ugens}
#{constants}]."
[root]
(if (seq? root)
(reduce
(fn [[ugens constants] ugen]
(let [[us cs] (gather-ugens-and-constants ugen)]
[(set/union ugens us)
(set/union constants cs)]))
[#{} #{}]
root)
(let [args (:args root)
cur-ugens (filter sc-ugen? args)
cur-ugens (filter (comp not control-proxy?) cur-ugens)
cur-ugens (map #(if (output-proxy? %)
(:ugen %)
%)
cur-ugens)
cur-consts (filter number? args)
[child-ugens child-consts] (gather-ugens-and-constants cur-ugens)
ugens (conj (set child-ugens) root)
constants (set/union (set cur-consts) child-consts)]
[ugens (vec constants)])))
(defn- ugen-children
"Returns the children (arguments) of this ugen that are themselves
upstream ugens."
[ug]
(mapcat
#(cond
(seq? %) %
(output-proxy? %) [(:ugen %)]
:default [%])
(filter
(fn [arg]
(and (not (control-proxy? arg))
(or (sc-ugen? arg)
(and (seq? arg)
(every? sc-ugen? arg)))))
(:args ug))))
(defn topological-sort-ugens
"Sort into a vector where each node in the directed graph of ugens
will always be preceded by its upstream dependencies. Depth first,
from:
,
following the advice here:
-Definition-File-Format.html
'For greatest efficiency:
Unit generators should be listed in an order that permits efficient
reuse of connection buffers, which means that a depth first
topological sort of the graph is preferable to breadth first.'"
[ugens]
(let [visit (fn visit [[ret visited path :as acc] ug]
(cond
(visited ug) acc
(path ug) (throw (Exception. "ugen graph contains cycle"))
:else
(let [[ret visited path :as acc]
(reduce visit [ret visited (conj path ug)] (ugen-children ug))]
[(conj ret ug) (conj visited ug) path])))]
(first (reduce visit [[] #{} #{}] ugens))))
#_:clj-kondo/ignore
(comment
; Some test synths, while shaking out the bugs...
(defsynth foo [] (out 0 (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE))))
(defsynth bar [freq 220] (out 0 (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE))))
(definst faz [] (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE)))
(definst baz [freq 220] (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE)))
(run 1 (out 184 (saw (x-line:kr 10000 10 1 FREE)))))
(defn count-ugens
[ug-tree ug-name]
(let [ugens (flatten ug-tree)
local-bufs (filter #(= ug-name (:name %)) ugens)
ids (set (map :id local-bufs))]
(count ids)))
(defmacro pre-synth
"Resolve a synth def to a list of its name, params, ugens (nested if
necessary) and constants. Sets the lexical bindings of the param
names to control proxies within the synth definition"
[& args]
(let [[sname params param-proxies ugen-form] (normalize-synth-args args)]
`(let [~@param-proxies]
(binding [*ugens* []
*constants* #{}]
(let [[ugens# consts#] (gather-ugens-and-constants
(with-overloaded-ugens ~@ugen-form))
ugens# (topological-sort-ugens ugens#)
main-tree# (set ugens#)
side-tree# (filter #(not (main-tree# %)) *ugens*)
ugens# (concat ugens# side-tree#)
n-local-bufs# (count-ugens ugens# "LocalBuf")
ugens# (if (> n-local-bufs# 0)
(cons (max-local-bufs n-local-bufs#) ugens#)
ugens#)
consts# (if (> n-local-bufs# 0)
(cons n-local-bufs# consts#)
consts#)
consts# (into [] (set (concat consts# *constants*)))]
[~sname ~params ugens# consts#])))))
(defn synth-player
"Returns a player function for a named synth. Used by (synth ...)
internally, but can be used to generate a player for a pre-compiled
synth. The function generated will accept a target and position
vector of two values that must come first (see the node function
docs).
;; call foo player with default args:
(foo)
call foo player specifyign node should be at the tail of group 0
(foo [:tail 0])
;; call foo player with positional arguments
(foo 440 0.3)
;; target node to be at the tail of group 0 with positional args
(foo [:tail 0] 440 0.3)
or target node to be at the head of group 2
(foo [:head 2] 440 0.3)
;; you may also use keyword args
(foo :freq 440 :amp 0.3)
;; which allows you to re-order the args
(foo :amp 0.3 :freq 440 )
;; you can also combine a target vector with keyword args
(foo [:head 2] :amp 0.3 :freq 440)
;; finally, you can combine target vector, keywords args and
positional args . Positional args must go first .
(foo [:head 2] 440 :amp 0.3)
"
[sdef params this & args]
(let [arg-names (map keyword (map :name params))
args (or args [])
[target pos args] (extract-target-pos-args args (foundation-default-group) :tail)
args (idify args)
args (map (fn [arg] (if-let [id (:id arg)]
id
arg))
args)
defaults (into {} (map (fn [{:keys [name value]}]
[(keyword name) @value])
params))
arg-map (arg-mapper args arg-names defaults)
synth-node (node (:name sdef) arg-map {:position pos :target target} sdef)
synth-node (if (:instance-fn this)
((:instance-fn this) synth-node)
synth-node)]
(when (:instance-fn this)
(swap! active-synth-nodes* assoc (:id synth-node) synth-node))
synth-node))
(defn update-tap-data
[msg]
(let [[node-id label-id val] (:args msg)
node (get @active-synth-nodes* node-id)
label (get (:tap-labels node) label-id)
tap-atom (get (:taps node) label)]
(reset! tap-atom val)))
(on-event "/overtone/tap" #'update-tap-data ::handle-incoming-tap-data)
(defmacro synth
"Define a SuperCollider synthesizer using the library of ugen
functions provided by overtone.sc.ugen. This will return callable
record which can be used to trigger the synthesizer.
"
[& args]
`(let [[sname# params# ugens# constants#] (pre-synth ~@args)
sdef# (synthdef sname# params# ugens# constants#)
arg-names# (map :name params#)
params-with-vals# (map #(assoc % :value (atom (:default %))) params#)
instance-fn# (apply comp (map :instance-fn (filter :instance-fn (map meta ugens#))))
smap# (with-meta
(map->Synth
{:name sname#
:sdef sdef#
:args arg-names#
:params params-with-vals#
:instance-fn instance-fn#})
{:overtone.live/to-string #(str (name (:type %)) ":" (:name %))})] ;; TODO what on earth is this?
(load-synthdef sdef#)
(event :new-synth :synth smap#)
smap#))
(defn synth-form
"Internal function used to prepare synth meta-data."
[s-name s-form]
(let [[s-name s-form] (name-with-attributes s-name s-form)
_ (when (not (symbol? s-name))
(throw (IllegalArgumentException. (str "You need to specify a name for your synth using a symbol"))))
params (first s-form)
params (parse-params params)
ugen-form (concat '(do) (next s-form))
param-names (list (vec (map #(symbol (:name %)) params)))
md (assoc (meta s-name)
:name s-name
:type ::synth
:arglists (list 'quote param-names))]
[(with-meta s-name md) params ugen-form]))
(defmacro defsynth
"Define a synthesizer and return a player function. The synth
definition will be loaded immediately, and a :new-synth event will be
emitted. Expects a name, an optional doc-string, a vector of synth
params, and a ugen-form as its arguments.
(defsynth foo [freq 440]
(out 0 (sin-osc freq)))
is equivalent to:
(def foo
(synth [freq 440] (out 0 (sin-osc freq))))
Params can also be given rates. By default, they are :kr, however
another rate can be specified by using either a pair of [default rate]
or a map with keys :default and rate:
(defsynth foo [freq [440 :kr] gate [0 :tr]] ...)
(defsynth foo [freq {:default 440 :rate :kr}] ...)
A doc string can also be included:
(defsynth bar
\"The phatest space pad ever!\"
[] (...))
The function generated will accept a target vector argument that
must come first, containing position and target as elements (see the
node function docs).
;; call foo player with default args:
(foo)
call foo player specifying node should be at the tail of group 0
(foo [:tail 0])
;; call foo player with positional arguments
(foo 440 0.3)
;; target node to be at the tail of group 0 with positional args
(foo [:tail 0] 440 0.3)
or target node to be at the head of group 2
(foo [:head 2] 440 0.3)
;; you may also use keyword args
(foo :freq 440 :amp 0.3)
;; which allows you to re-order the args
(foo :amp 0.3 :freq 440 )
;; you can also combine a target vector with keyword args
(foo [:head 2] :amp 0.3 :freq 440)
;; finally, you can combine target vector, keywords args and
positional args . Positional args must go first .
(foo [:head 2] 440 :amp 0.3)"
[s-name & s-form]
{:arglists '([name doc-string? params ugen-form])}
(let [[s-name params ugen-form] (synth-form s-name s-form)]
`(def ~s-name (synth ~s-name ~params ~ugen-form))))
(defn synth-load
[file-path]
(let [{:keys [pnames params] :as sdef} (load-synth-file file-path)
[s-name params _ugen-form] (synth-form (symbol (:name sdef))
(list (vec (mapcat (fn [pname default-value]
[(symbol (:name pname)) default-value])
pnames params))
nil))]
(with-meta
(map->Synth
{:name s-name
:sdef sdef})
(merge {:overtone.live/to-string #(str (name (:type %)) ":" (:name %))}
(meta s-name)))))
(defmacro defsynth-load
"Load a synth from a compiled Synthdef file.
E.g.
(defsynth-load my-beep
\"/Users/paulo.feodrippe/dev/sonic-pi/etc/synthdefs/compiled/sonic-pi-beep.scsyndef\")
(my-beep :note 40)"
[def-name file-path]
(let [smap (synth-load file-path)]
`(def ~(with-meta def-name
(merge (dissoc (meta smap) :name)
(meta def-name)))
~smap)))
(defn synth?
"Returns true if s is a synth, false otherwise."
[s]
(= overtone.sc.synth.Synth (type s)))
(def ^{:dynamic true} *demo-time* 2000)
(defmacro run
"Run an anonymous synth definition for a fixed period of time.
Useful for experimentation. Does NOT add an out ugen - see #'demo for
that. You can specify a timeout in seconds as the first argument
otherwise it defaults to *demo-time* ms.
= > send OSC messages "
[& body]
(let [[demo-time body] (if (number? (first body))
[(* 1000 (first body)) (second body)]
[*demo-time* (first body)])]
`(let [s# (synth "audition-synth" ~body)
note# (s#)]
(after-delay ~demo-time #(node-free note#))
note#)))
(defmacro demo
"Listen to an anonymous synth definition for a fixed period of time.
Useful for experimentation. If the root node is not an out ugen, then
it will add one automatically. You can specify a timeout in seconds
as the first argument otherwise it defaults to *demo-time* ms. See
#'run for a version of demo that does not add an out ugen.
(demo (sin-osc 440)) ;=> plays a sine wave for *demo-time* ms
= > plays a sine wave for half a second "
[& body]
(let [[demo-time body] (if (number? (first body))
[(first body) (second body)]
[(* 0.001 *demo-time*) (first body)])
[out-bus body] (if (= 'out (first body))
[(second body) (nth body 2)]
[0 body])
body (list `out out-bus (list `hold body demo-time :done `FREE))]
`((synth "audition-synth" ~body))))
(defn active-synths
"Return a seq of the actively running synth nodes. If a synth or inst
are passed as the filter it will only return nodes of that type.
= > [ { : type synth : name " : i d 12 } { : type
synth :name \"my-synth\" :id 24}]
(active-synths my-synth) ;=>[{:type synth :name \"my-synth\" :id 24}]
"
[& [synth-filter]]
(let [active-nodes (filter #(= overtone.sc.node.SynthNode (type %))
(vals @active-synth-nodes*))]
(if synth-filter
(filter #(= (:name synth-filter) (:name %)) active-nodes)
active-nodes)))
(defmethod print-method ::synth [syn ^java.io.Writer w]
(let [info (meta syn)]
(.write w (format "#<synth: %s>" (:name info)))))
; TODO: pull out the default param atom stuff into a separate mechanism
(defn modify-synth-params
"Update synth parameter value atoms storing the current default
settings."
[s & params-vals]
(let [params (:params s)]
(for [[param value] (partition 2 params-vals)]
(let [val-atom (:value (first (filter #(= (:name %) (name param)) params)))]
(if val-atom
(reset! val-atom value)
(throw (IllegalArgumentException. (str "Invalid control parameter: " param))))))))
(defn reset-synth-defaults
"Reset a synth to its default settings defined at definition time."
[synth]
(doseq [param (:params synth)]
(reset! (:value param) (:default param))))
(defmacro with-no-ugen-checks [& body]
`(binding [overtone.sc.machinery.ugen.specs/*checking* false]
~@body))
(defmacro with-ugen-debugging [& body]
`(binding [overtone.sc.machinery.ugen.specs/*debugging* true]
~@body))
(defn synth-args
"Returns a seq of the synth's args as keywords"
[synth]
(map keyword (:args synth)))
(defn synth-arg-index
"Returns an integer index of synth's argument with arg-name.
For example:
(defsynth foo [freq 440 amp 0.5] (out 0 (* amp (sin-osc freq))))
(synth-arg-index foo :amp) #=> 1
(synth-arg-index foo \"freq\") #=> 0
(synth-arg-index foo :baz) #=> nil"
[synth arg-name]
(let [arg-name (name arg-name)]
(index-of (:args synth) arg-name)))
(extend Synth
protocols/IKillable
{:kill* (fn [s]
(kill (node-tree-matching-synth-ids (:name (:sdef s)))))})
(extend java.util.regex.Pattern
protocols/IKillable
{:kill* (fn [s]
(kill (node-tree-matching-synth-ids (:name (:sdef s)))))})
| null | https://raw.githubusercontent.com/overtone/overtone/9afb513297662716860a4010bc76a0e73c65ca37/src/overtone/sc/synth.clj | clojure |
A Synth is a collection of unit generators that run together. They can be
addressed and controlled by commands to the synthesis engine. They read
input and write output to global audio and control buses. Synths can have
their own local controls that are set via commands to the server.
Gets the group number (source) and param index within the group (index)
from the params that are grouped by rate like this:
NOTES:
* *All* inputs must refer to either a constant or the output of another
constant
control
output proxy
capabilities for supporting varying output rates...
IMPORTANT NOTE: We need to add outputs before inputs, so that multi-channel
outputs can be correctly connected.
TODO: Figure out a better way to specify rates for synth parameters
For greatest efficiency:
* Unit generators should be listed in an order that permits efficient reuse
NOTES:
* No feedback loops are allowed. Feedback must be accomplished via delay lines
or through buses.
Some test synths, while shaking out the bugs...
call foo player with default args:
call foo player with positional arguments
target node to be at the tail of group 0 with positional args
you may also use keyword args
which allows you to re-order the args
you can also combine a target vector with keyword args
finally, you can combine target vector, keywords args and
TODO what on earth is this?
call foo player with default args:
call foo player with positional arguments
target node to be at the tail of group 0 with positional args
you may also use keyword args
which allows you to re-order the args
you can also combine a target vector with keyword args
finally, you can combine target vector, keywords args and
=> plays a sine wave for *demo-time* ms
=>[{:type synth :name \"my-synth\" :id 24}]
TODO: pull out the default param atom stuff into a separate mechanism | (ns
^{:doc "The ugen functions create a data structure representing a synthesizer
graph that can be executed on the synthesis server. This is the logic
to \"compile\" these clojure data structures into a form that can be
serialized by the byte-spec defined in synthdef.clj."
:author "Jeff Rose"}
overtone.sc.synth
(:use [overtone.helpers lib old-contrib synth]
[overtone.libs event counters]
[overtone.music time]
[overtone.sc.machinery.ugen fn-gen defaults common specs sc-ugen]
[overtone.sc.machinery synthdef]
[overtone.sc bindings ugens server node foundation-groups dyn-vars]
[overtone.helpers seq]
[clojure.pprint]
[overtone.helpers.string :only [hash-shorten]])
(:require [overtone.config.log]
[clojure.set :as set]
[overtone.sc.cgens.env :refer [hold]]
[overtone.sc.protocols :as protocols]))
(declare synth-player)
(defonce ^{:private true} __RECORDS__
(do
(defrecord-ifn Synth [name ugens sdef args params instance-fn]
(partial synth-player sdef params))))
(defn- valid-control-proxy-rate?
[rate]
(some #{rate} CONTROL-PROXY-RATES))
# # # Synth
(defn- ugen-index [ugens ugen]
(ffirst (filter (fn [[i v]]
(= (:id v) (:id ugen)))
(indexed ugens))))
[ [ { : name : freq : default 440.0 : rate 1 } { : name : amp : default 0.4 : rate 1 } ]
[ { : name : adfs : default 20.23 : rate 2 } { : name : bar : default 8.6 : rate 2 } ] ]
(defn- param-input-spec [grouped-params param-proxy]
(let [param-name (:name param-proxy)
ctl-filter (fn [[idx ctl]] (= param-name (:name ctl)))
[[src group] foo] (take 1 (filter
(fn [[src grp]]
(not (empty?
(filter ctl-filter (indexed grp)))))
(indexed grouped-params)))
[[idx param] bar] (take 1 (filter ctl-filter (indexed group)))]
(if (or (nil? src) (nil? idx))
(throw (IllegalArgumentException. (str "Invalid parameter name: " param-name ". Please make sure you have named all parameters in the param map in order to use them inside the synth definition."))))
{:src src :index idx}))
(defn- inputs-from-outputs [src src-ugen]
(for [i (range (count (:outputs src-ugen)))]
{:src src :index i}))
UGen that is higher up in the list .
(defn- with-inputs
"Returns ugen object with its input ports connected to constants and
upstream ugens according to the arguments in the initial definition."
[ugen ugens constants grouped-params]
(when-not (contains? ugen :args)
(if-not (sc-ugen? ugen)
(throw (IllegalArgumentException.
(str "Error: synth expected a ugen. Got: " ugen)))
(throw (IllegalArgumentException.
(format "The %s ugen does not have any arguments."
(:name ugen))))))
(when-not (every? #(or (sc-ugen? %) (number? %) (string? %)) (:args ugen))
(throw (IllegalArgumentException.
(format "The %s ugen has an invalid argument: %s"
(:name ugen)
(first (filter
#(not (or (sc-ugen? %) (number? %)))
(:args ugen)))))))
(let [inputs (flatten
(map (fn [arg]
(cond
(number? arg)
{:src -1 :index (index-of constants (float arg))}
(control-proxy? arg)
(param-input-spec grouped-params arg)
(output-proxy? arg)
(let [src (ugen-index ugens (:ugen arg))]
{:src src :index (:index arg)})
child
(sc-ugen? arg)
(let [src (ugen-index ugens arg)
updated-ugen (nth ugens src)]
(inputs-from-outputs src updated-ugen))))
(:args ugen)))
ugen (assoc ugen :inputs inputs)]
(when-not (every? (fn [{:keys [src index]}]
(and (not (nil? src))
(not (nil? index))))
(:inputs ugen))
(throw (Exception.
(format "Cannot connect ugen arguments for %s ugen with args: %s" (:name ugen) (str (seq (:args ugen)))))))
Add link back to ( always at root of tree ) if
ugen is a local - buf .
(if (= "LocalBuf" (:name ugen))
(assoc ugen :inputs (concat (:inputs ugen) [{:src 0 :index 0}]))
ugen)))
TODO : Currently the output rate is hard coded to be the same as the
computation rate of the ugen . We probably need to have some meta - data
(defn- with-outputs
"Returns a ugen with its output port connections setup according to
the spec."
[ugen]
{:post [(every? (fn [val] (not (nil? val))) (:outputs %))]}
(if (contains? ugen :outputs)
ugen
(let [spec (get-ugen (:name ugen))
num-outs (or (:n-outputs ugen) 1)
outputs (take num-outs (repeat {:rate (:rate ugen)}))]
(assoc ugen :outputs outputs))))
(defn- detail-ugens
"Fill in all the input and output specs for each ugen."
[ugens constants grouped-params]
(let [constants (map float constants)
outs (map with-outputs ugens)
ins (map #(with-inputs %1 outs constants grouped-params) outs)]
(doall ins)))
(defn- make-control-ugens
"Controls are grouped by rate, so that a single Control ugen
represents each rate present in the params. The Control ugens are
always the top nodes in the graph, so they can be prepended to the
topologically sorted tree.
Specifically handles control proxies at :tr, :ar, :kr and :ir"
[grouped-params]
(loop [done {}
todo grouped-params
offset 0]
(if (empty? todo)
(filter #(not (nil? %))
[(:ir done) (:tr done) (:ar done) (:kr done)])
(let [group (first todo)
group-rate (:rate (first group))
group-size (count group)
ctl-proxy (case group-rate
:tr (trig-control-ugen group-size offset)
:ar (audio-control-ugen group-size offset)
:kr (control-ugen group-size offset)
:ir (inst-control-ugen group-size offset))]
(recur (assoc done group-rate ctl-proxy) (rest todo) (+ offset group-size))))))
(defn- group-params
"Groups params by rate. Groups a list of parameters into a list of
lists, one per rate."
[params]
(let [by-rate (reduce (fn [mem param]
(let [rate (:rate param)
rate-group (get mem rate [])]
(assoc mem rate (conj rate-group param))))
{} params)]
(filter #(not (nil? %1))
[(:ir by-rate) (:tr by-rate) (:ar by-rate) (:kr by-rate)])))
(def DEFAULT-RATE :kr)
(defn- ensure-param-keys!
"Throws an error if map m doesn't contain the correct
keys: :name, :default and :rate"
[m]
(when-not (and
(contains? m :name)
(contains? m :default)
(contains? m :rate))
(throw (IllegalArgumentException. (str "Invalid synth param map. Expected to find the keys :name, :default, :rate, got: " m)))))
(defn- ensure-paired-params!
"Throws an error if list l does not contain an even number of
elements"
[l]
(when-not (even? (count l))
(throw (IllegalArgumentException. (str "A synth requires either an even number of arguments in the form [control default]* i.e. [freq 440 amp 0.5] or a list of maps. You passed " (count l) " args: " l)))))
(defn- ensure-vec!
"Throws an error if list l is not a vector"
[l]
(when-not (vector? l)
(throw (IllegalArgumentException. (str "Your synth argument list is not a vector. Instead I found " (type l) ": " l)))))
(defn- ensure-valid-control-proxy-vec!
[val]
(when-not (= 2 (count val))
(throw (IllegalArgumentException. (str "Control Proxy vector must have only 2 elements i.e. [0 :tr]"))))
(when-not (number? (first val))
(throw (IllegalArgumentException. (str "Control Proxy vector must have a number as the first element i.e. [0 :tr]"))))
(when-not (valid-control-proxy-rate? (second val))
(throw (IllegalArgumentException. (str "Control Proxy rate " (second val) " not valid. Expecting one of " CONTROL-PROXY-RATES))))
val)
(defn- mapify-params
"Converts a list of param name val pairs to a param map. If the val of
a param is a vector, it assumes it's a pair of [val rate] and sets the
rate of the param accordingly. If the val is a plain number, it sets
the rate to DEFAULT-RATE. All names are converted to strings"
[params]
(for [[p-name p-val] (partition 2 params)]
(let [param-map
(cond
(vector? p-val) (do
(ensure-valid-control-proxy-vec! p-val)
{:name (str p-name)
:default (first p-val)
:rate (second p-val)})
(associative? p-val) (merge
{:name (str p-name)
:rate DEFAULT-RATE} p-val)
:else {:name (str p-name)
:default `(float (to-id ~p-val))
:rate DEFAULT-RATE})]
(ensure-param-keys! param-map)
param-map)))
(defn- stringify-names
"Takes a map and converts the val of key :name to a string"
[m]
(into {} (for [[k v] m] (if (= :name k) [k (str v)] [k v]))))
perhaps using name post - fixes such as [ freq : kr 440 ]
(defn- parse-params
"Used by defsynth to parse the param list. Accepts either a vector of
name default pairs, name [default rate] pairs or a vector of maps:
(defsynth foo [freq 440] ...)
(defsynth foo [freq [440 :ar]] ...)
(defsynth foo [freq {:default 440 :rate :ar}] ...)
Returns a vec of param maps"
[params]
(ensure-vec! params)
(ensure-paired-params! params)
(vec (mapify-params params)))
(defn- make-params
"Create the param value vector and parameter name vector."
[grouped-params]
(let [param-list (flatten grouped-params)
pvals (map #(:default %1) param-list)
pnames (map (fn [[idx param]]
{:name (to-str (:name param))
:index idx})
(indexed param-list))]
[pvals pnames]))
(defn- ugen-form? [form]
(and (seq? form)
(= 'ugen (first form))))
(defn- fastest-rate [rates]
(REVERSE-RATES (first (reverse (sort (map RATES rates))))))
(defn- special-op-args? [args]
(some #(or (sc-ugen? %1) (keyword? %1)) args))
(defn- find-rate [args]
(fastest-rate (map #(cond
(sc-ugen? %1) (REVERSE-RATES (:rate %1))
(keyword? %1) :kr)
args)))
of connection buffers , so use a depth first topological sort of the graph .
* The ugen tree is turned into a ugen list that is sorted by the order in
which nodes should be processed . ( Depth first , starting at outermost leaf
of the first branch .
* params are sorted by rate , and then a Control ugen per rate is created
and prepended to the ugen list
* finally , ugen inputs are specified using their index
in the sorted ugen list .
(defn synthdef
"Transforms a synth definition (ugen-graph) into a form that's ready
to save to disk or send to the server.
(synthdef \"pad-z\" [
"
[sname params ugens constants]
(let [grouped-params (group-params params)
[params pnames] (make-params grouped-params)
with-ctl-ugens (concat (make-control-ugens grouped-params) ugens)
detailed (detail-ugens with-ctl-ugens constants grouped-params)
full-name (if (add-current-namespace-to-synth-name?)
(hash-shorten 31 (ns-name *ns*) (str "/" sname))
sname)]
(with-meta {:name full-name
:constants constants
:params params
:pnames pnames
:ugens detailed}
{:type :overtone.sc.machinery.synthdef/synthdef})))
(defn- control-proxies
"Returns a list of param name symbols and control proxies"
[params]
(mapcat (fn [param] [(symbol (:name param))
`(control-proxy ~(:name param) ~(:default param) ~(:rate param))])
params))
(defn- gen-synth-name
"Auto generate an anonymous synth name. Intended for use in synths
that have not been defined with an explicit name. Has the form
\"anon-id\" where id is a unique integer across all anonymous
synths."
[]
(str "anon-" (next-id ::anonymous-synth)))
(defn normalize-synth-args
"Pull out and normalize the synth name, parameters, control proxies
and the ugen form from the supplied arglist resorting to defaults if
necessary."
[args]
(let [[sname args] (if (or (string? (first args))
(symbol? (first args)))
[(str (first args)) (rest args)]
[(gen-synth-name) args])
[params ugen-form] (if (vector? (first args))
[(first args) (rest args)]
[[] args])
param-proxies (control-proxies params)]
[sname params param-proxies ugen-form]))
(defn gather-ugens-and-constants
"Traverses a ugen tree and returns a vector of two sets [#{ugens}
#{constants}]."
[root]
(if (seq? root)
(reduce
(fn [[ugens constants] ugen]
(let [[us cs] (gather-ugens-and-constants ugen)]
[(set/union ugens us)
(set/union constants cs)]))
[#{} #{}]
root)
(let [args (:args root)
cur-ugens (filter sc-ugen? args)
cur-ugens (filter (comp not control-proxy?) cur-ugens)
cur-ugens (map #(if (output-proxy? %)
(:ugen %)
%)
cur-ugens)
cur-consts (filter number? args)
[child-ugens child-consts] (gather-ugens-and-constants cur-ugens)
ugens (conj (set child-ugens) root)
constants (set/union (set cur-consts) child-consts)]
[ugens (vec constants)])))
(defn- ugen-children
"Returns the children (arguments) of this ugen that are themselves
upstream ugens."
[ug]
(mapcat
#(cond
(seq? %) %
(output-proxy? %) [(:ugen %)]
:default [%])
(filter
(fn [arg]
(and (not (control-proxy? arg))
(or (sc-ugen? arg)
(and (seq? arg)
(every? sc-ugen? arg)))))
(:args ug))))
(defn topological-sort-ugens
"Sort into a vector where each node in the directed graph of ugens
will always be preceded by its upstream dependencies. Depth first,
from:
,
following the advice here:
-Definition-File-Format.html
'For greatest efficiency:
Unit generators should be listed in an order that permits efficient
reuse of connection buffers, which means that a depth first
topological sort of the graph is preferable to breadth first.'"
[ugens]
(let [visit (fn visit [[ret visited path :as acc] ug]
(cond
(visited ug) acc
(path ug) (throw (Exception. "ugen graph contains cycle"))
:else
(let [[ret visited path :as acc]
(reduce visit [ret visited (conj path ug)] (ugen-children ug))]
[(conj ret ug) (conj visited ug) path])))]
(first (reduce visit [[] #{} #{}] ugens))))
#_:clj-kondo/ignore
(comment
(defsynth foo [] (out 0 (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE))))
(defsynth bar [freq 220] (out 0 (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE))))
(definst faz [] (rlpf (saw [220 663]) (x-line:kr 20000 2 1 FREE)))
(definst baz [freq 220] (rlpf (saw [freq (* 3.013 freq)]) (x-line:kr 20000 2 1 FREE)))
(run 1 (out 184 (saw (x-line:kr 10000 10 1 FREE)))))
(defn count-ugens
[ug-tree ug-name]
(let [ugens (flatten ug-tree)
local-bufs (filter #(= ug-name (:name %)) ugens)
ids (set (map :id local-bufs))]
(count ids)))
(defmacro pre-synth
"Resolve a synth def to a list of its name, params, ugens (nested if
necessary) and constants. Sets the lexical bindings of the param
names to control proxies within the synth definition"
[& args]
(let [[sname params param-proxies ugen-form] (normalize-synth-args args)]
`(let [~@param-proxies]
(binding [*ugens* []
*constants* #{}]
(let [[ugens# consts#] (gather-ugens-and-constants
(with-overloaded-ugens ~@ugen-form))
ugens# (topological-sort-ugens ugens#)
main-tree# (set ugens#)
side-tree# (filter #(not (main-tree# %)) *ugens*)
ugens# (concat ugens# side-tree#)
n-local-bufs# (count-ugens ugens# "LocalBuf")
ugens# (if (> n-local-bufs# 0)
(cons (max-local-bufs n-local-bufs#) ugens#)
ugens#)
consts# (if (> n-local-bufs# 0)
(cons n-local-bufs# consts#)
consts#)
consts# (into [] (set (concat consts# *constants*)))]
[~sname ~params ugens# consts#])))))
(defn synth-player
"Returns a player function for a named synth. Used by (synth ...)
internally, but can be used to generate a player for a pre-compiled
synth. The function generated will accept a target and position
vector of two values that must come first (see the node function
docs).
(foo)
call foo player specifyign node should be at the tail of group 0
(foo [:tail 0])
(foo 440 0.3)
(foo [:tail 0] 440 0.3)
or target node to be at the head of group 2
(foo [:head 2] 440 0.3)
(foo :freq 440 :amp 0.3)
(foo :amp 0.3 :freq 440 )
(foo [:head 2] :amp 0.3 :freq 440)
positional args . Positional args must go first .
(foo [:head 2] 440 :amp 0.3)
"
[sdef params this & args]
(let [arg-names (map keyword (map :name params))
args (or args [])
[target pos args] (extract-target-pos-args args (foundation-default-group) :tail)
args (idify args)
args (map (fn [arg] (if-let [id (:id arg)]
id
arg))
args)
defaults (into {} (map (fn [{:keys [name value]}]
[(keyword name) @value])
params))
arg-map (arg-mapper args arg-names defaults)
synth-node (node (:name sdef) arg-map {:position pos :target target} sdef)
synth-node (if (:instance-fn this)
((:instance-fn this) synth-node)
synth-node)]
(when (:instance-fn this)
(swap! active-synth-nodes* assoc (:id synth-node) synth-node))
synth-node))
(defn update-tap-data
[msg]
(let [[node-id label-id val] (:args msg)
node (get @active-synth-nodes* node-id)
label (get (:tap-labels node) label-id)
tap-atom (get (:taps node) label)]
(reset! tap-atom val)))
(on-event "/overtone/tap" #'update-tap-data ::handle-incoming-tap-data)
(defmacro synth
"Define a SuperCollider synthesizer using the library of ugen
functions provided by overtone.sc.ugen. This will return callable
record which can be used to trigger the synthesizer.
"
[& args]
`(let [[sname# params# ugens# constants#] (pre-synth ~@args)
sdef# (synthdef sname# params# ugens# constants#)
arg-names# (map :name params#)
params-with-vals# (map #(assoc % :value (atom (:default %))) params#)
instance-fn# (apply comp (map :instance-fn (filter :instance-fn (map meta ugens#))))
smap# (with-meta
(map->Synth
{:name sname#
:sdef sdef#
:args arg-names#
:params params-with-vals#
:instance-fn instance-fn#})
(load-synthdef sdef#)
(event :new-synth :synth smap#)
smap#))
(defn synth-form
"Internal function used to prepare synth meta-data."
[s-name s-form]
(let [[s-name s-form] (name-with-attributes s-name s-form)
_ (when (not (symbol? s-name))
(throw (IllegalArgumentException. (str "You need to specify a name for your synth using a symbol"))))
params (first s-form)
params (parse-params params)
ugen-form (concat '(do) (next s-form))
param-names (list (vec (map #(symbol (:name %)) params)))
md (assoc (meta s-name)
:name s-name
:type ::synth
:arglists (list 'quote param-names))]
[(with-meta s-name md) params ugen-form]))
(defmacro defsynth
"Define a synthesizer and return a player function. The synth
definition will be loaded immediately, and a :new-synth event will be
emitted. Expects a name, an optional doc-string, a vector of synth
params, and a ugen-form as its arguments.
(defsynth foo [freq 440]
(out 0 (sin-osc freq)))
is equivalent to:
(def foo
(synth [freq 440] (out 0 (sin-osc freq))))
Params can also be given rates. By default, they are :kr, however
another rate can be specified by using either a pair of [default rate]
or a map with keys :default and rate:
(defsynth foo [freq [440 :kr] gate [0 :tr]] ...)
(defsynth foo [freq {:default 440 :rate :kr}] ...)
A doc string can also be included:
(defsynth bar
\"The phatest space pad ever!\"
[] (...))
The function generated will accept a target vector argument that
must come first, containing position and target as elements (see the
node function docs).
(foo)
call foo player specifying node should be at the tail of group 0
(foo [:tail 0])
(foo 440 0.3)
(foo [:tail 0] 440 0.3)
or target node to be at the head of group 2
(foo [:head 2] 440 0.3)
(foo :freq 440 :amp 0.3)
(foo :amp 0.3 :freq 440 )
(foo [:head 2] :amp 0.3 :freq 440)
positional args . Positional args must go first .
(foo [:head 2] 440 :amp 0.3)"
[s-name & s-form]
{:arglists '([name doc-string? params ugen-form])}
(let [[s-name params ugen-form] (synth-form s-name s-form)]
`(def ~s-name (synth ~s-name ~params ~ugen-form))))
(defn synth-load
[file-path]
(let [{:keys [pnames params] :as sdef} (load-synth-file file-path)
[s-name params _ugen-form] (synth-form (symbol (:name sdef))
(list (vec (mapcat (fn [pname default-value]
[(symbol (:name pname)) default-value])
pnames params))
nil))]
(with-meta
(map->Synth
{:name s-name
:sdef sdef})
(merge {:overtone.live/to-string #(str (name (:type %)) ":" (:name %))}
(meta s-name)))))
(defmacro defsynth-load
"Load a synth from a compiled Synthdef file.
E.g.
(defsynth-load my-beep
\"/Users/paulo.feodrippe/dev/sonic-pi/etc/synthdefs/compiled/sonic-pi-beep.scsyndef\")
(my-beep :note 40)"
[def-name file-path]
(let [smap (synth-load file-path)]
`(def ~(with-meta def-name
(merge (dissoc (meta smap) :name)
(meta def-name)))
~smap)))
(defn synth?
"Returns true if s is a synth, false otherwise."
[s]
(= overtone.sc.synth.Synth (type s)))
(def ^{:dynamic true} *demo-time* 2000)
(defmacro run
"Run an anonymous synth definition for a fixed period of time.
Useful for experimentation. Does NOT add an out ugen - see #'demo for
that. You can specify a timeout in seconds as the first argument
otherwise it defaults to *demo-time* ms.
= > send OSC messages "
[& body]
(let [[demo-time body] (if (number? (first body))
[(* 1000 (first body)) (second body)]
[*demo-time* (first body)])]
`(let [s# (synth "audition-synth" ~body)
note# (s#)]
(after-delay ~demo-time #(node-free note#))
note#)))
(defmacro demo
"Listen to an anonymous synth definition for a fixed period of time.
Useful for experimentation. If the root node is not an out ugen, then
it will add one automatically. You can specify a timeout in seconds
as the first argument otherwise it defaults to *demo-time* ms. See
#'run for a version of demo that does not add an out ugen.
= > plays a sine wave for half a second "
[& body]
(let [[demo-time body] (if (number? (first body))
[(first body) (second body)]
[(* 0.001 *demo-time*) (first body)])
[out-bus body] (if (= 'out (first body))
[(second body) (nth body 2)]
[0 body])
body (list `out out-bus (list `hold body demo-time :done `FREE))]
`((synth "audition-synth" ~body))))
(defn active-synths
"Return a seq of the actively running synth nodes. If a synth or inst
are passed as the filter it will only return nodes of that type.
= > [ { : type synth : name " : i d 12 } { : type
synth :name \"my-synth\" :id 24}]
"
[& [synth-filter]]
(let [active-nodes (filter #(= overtone.sc.node.SynthNode (type %))
(vals @active-synth-nodes*))]
(if synth-filter
(filter #(= (:name synth-filter) (:name %)) active-nodes)
active-nodes)))
(defmethod print-method ::synth [syn ^java.io.Writer w]
(let [info (meta syn)]
(.write w (format "#<synth: %s>" (:name info)))))
(defn modify-synth-params
"Update synth parameter value atoms storing the current default
settings."
[s & params-vals]
(let [params (:params s)]
(for [[param value] (partition 2 params-vals)]
(let [val-atom (:value (first (filter #(= (:name %) (name param)) params)))]
(if val-atom
(reset! val-atom value)
(throw (IllegalArgumentException. (str "Invalid control parameter: " param))))))))
(defn reset-synth-defaults
"Reset a synth to its default settings defined at definition time."
[synth]
(doseq [param (:params synth)]
(reset! (:value param) (:default param))))
(defmacro with-no-ugen-checks [& body]
`(binding [overtone.sc.machinery.ugen.specs/*checking* false]
~@body))
(defmacro with-ugen-debugging [& body]
`(binding [overtone.sc.machinery.ugen.specs/*debugging* true]
~@body))
(defn synth-args
"Returns a seq of the synth's args as keywords"
[synth]
(map keyword (:args synth)))
(defn synth-arg-index
"Returns an integer index of synth's argument with arg-name.
For example:
(defsynth foo [freq 440 amp 0.5] (out 0 (* amp (sin-osc freq))))
(synth-arg-index foo :amp) #=> 1
(synth-arg-index foo \"freq\") #=> 0
(synth-arg-index foo :baz) #=> nil"
[synth arg-name]
(let [arg-name (name arg-name)]
(index-of (:args synth) arg-name)))
(extend Synth
protocols/IKillable
{:kill* (fn [s]
(kill (node-tree-matching-synth-ids (:name (:sdef s)))))})
(extend java.util.regex.Pattern
protocols/IKillable
{:kill* (fn [s]
(kill (node-tree-matching-synth-ids (:name (:sdef s)))))})
|
3310eff3ae75e335f31746c14925f48f62aba641f4bba83a4db3256edc7c26b3 | acowley/concurrent-machines | Concurrent.hs | # LANGUAGE CPP , GADTs , FlexibleContexts , RankNTypes , ScopedTypeVariables ,
TupleSections #
TupleSections #-}
-- | The primary use of concurrent machines is to establish a
-- pipelined architecture that can boost overall throughput by running
-- each stage of the pipeline at the same time. The processing, or
-- production, rate of each stage may not be identical, so facilities
-- are provided to loosen the temporal coupling between pipeline
-- stages using buffers.
--
-- This architecture also lends itself to operations where multiple
-- workers are available for procesisng inputs. If each worker is to
-- process the same set of inputs, consider 'fanout' and
-- 'fanoutSteps'. If each worker is to process a disjoint set of
-- inputs, consider 'scatter'.
module Data.Machine.Concurrent (module Data.Machine,
-- * Concurrent connection
(>~>), (<~<),
-- * Buffered machines
bufferConnect, rollingConnect,
-- * Concurrent processing of shared inputs
fanout, fanoutSteps,
-- * Concurrent multiple-input machines
wye, tee, scatter, splitSum, mergeSum,
splitProd) where
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Concurrent.Async.Lifted
import Control.Monad (join)
import Control.Monad.Trans.Control
import Data.Machine hiding (tee, wye)
import Data.Machine.Concurrent.AsyncStep
import Data.Machine.Concurrent.Buffer
import Data.Machine.Concurrent.Fanout
import Data.Machine.Concurrent.Scatter
import Data.Machine.Concurrent.Wye
import Data.Machine.Concurrent.Tee
-- | Build a new 'Machine' by adding a 'Process' to the output of an
-- old 'Machine'. The upstream machine is run concurrently with
-- downstream with the aim that upstream will have a yielded value
-- ready as soon as downstream awaits. This effectively creates a
-- buffer between upstream and downstream, or source and sink, that
can contain up to one value .
--
-- @
-- ('<~<') :: 'Process' b c -> 'Process' a b -> 'Process' a c
-- ('<~<') :: 'Process' c d -> 'Data.Machine.Tee.Tee' a b c -> 'Data.Machine.Tee.Tee' a b d
-- ('<~<') :: 'Process' b c -> 'Machine' k b -> 'Machine' k c
-- @
(<~<) :: MonadBaseControl IO m
=> ProcessT m b c -> MachineT m k b -> MachineT m k c
mp <~< ma = racers ma mp
-- | Flipped ('<~<').
(>~>) :: MonadBaseControl IO m
=> MachineT m k b -> ProcessT m b c -> MachineT m k c
ma >~> mp = mp <~< ma
infixl 7 >~>
| We want the first available response .
waitEither' :: MonadBaseControl IO m
=> Maybe (Async (StM m a)) -> Async (StM m b)
-> m (Either a b)
waitEither' Nothing y = Right <$> wait y
waitEither' (Just x) y = waitEither x y
-- | Let a source and a sink chase each other, providing an effective
one - element buffer between the two . The idea is to run both
-- concurrently at all times so that as soon as the sink 'Await's, we
-- have a source-yielded value to provide it. This, of course,
-- involves eagerly running the source, percolating its 'Await's up
-- the chain as soon as possible.
racers :: forall m k a b. MonadBaseControl IO m
=> MachineT m k a -> ProcessT m a b -> MachineT m k b
racers src snk = MachineT . join $
go <$> (Just <$> asyncRun src) <*> asyncRun snk
where go :: Maybe (AsyncStep m k a)
-> AsyncStep m (Is a) b
-> m (MachineStep m k b)
go srcA snkA =
waitEither' srcA snkA >>= \n -> case n of
Left (Stop :: MachineStep m k a) -> go Nothing snkA
Left (Yield o k) -> wait snkA >>= \m -> case m of
(Stop :: MachineStep m (Is a) b) -> return Stop
Yield o' k' -> return . Yield o' . MachineT . flushDown k' $
\f -> join $ go <$> (Just <$> asyncRun k)
<*> asyncRun (f o)
Await f Refl _ -> join $ go <$> (Just <$> asyncRun k)
<*> asyncRun (f o)
Left (Await g kg fg) -> asyncAwait g kg fg $
MachineT . flip go snkA . Just
Right (Stop :: MachineStep m (Is a) b) -> return Stop
Right (Yield o k) -> asyncRun k >>=
return . Yield o . MachineT . go srcA
Right (Await f Refl ff) -> case srcA of
Nothing -> asyncRun ff >>= go Nothing
Just src' -> wait src' >>= \m -> case m of
Stop -> return Stop
Yield o k -> join $ go <$> (Just <$> asyncRun k)
<*> asyncRun (f o)
a -> feedUp (encased a) $ \o k -> join $
go <$> (Just <$> asyncRun k) <*> asyncRun (f o)
-- If we have an upstream source value ready, we must flush
-- all available values yielded by downstream until it awaits.
flushDown :: ProcessT m a b
-> ((a -> ProcessT m a b) -> m (MachineStep m k b))
-> m (MachineStep m k b)
flushDown m k = runMachineT m >>= \s -> case s of
Stop -> return Stop
Yield o m' -> return . Yield o . MachineT $ flushDown m' k
Await f Refl _ -> k f
-- If downstream is awaiting an input, we must pull in all
-- necessary upstream awaits until we have a yielded value to
-- push downstream.
feedUp :: MachineT m k a
-> (a -> MachineT m k a -> m (MachineStep m k b))
-> m (MachineStep m k b)
feedUp m k = runMachineT m >>= \s -> case s of
Stop -> return Stop
Yield o m' -> k o m'
Await g kg fg -> return $ awaitStep g kg fg (MachineT . flip feedUp k)
| null | https://raw.githubusercontent.com/acowley/concurrent-machines/70d2a8ae481e6fef503f2609c65b530bd1f96e1b/src/Data/Machine/Concurrent.hs | haskell | | The primary use of concurrent machines is to establish a
pipelined architecture that can boost overall throughput by running
each stage of the pipeline at the same time. The processing, or
production, rate of each stage may not be identical, so facilities
are provided to loosen the temporal coupling between pipeline
stages using buffers.
This architecture also lends itself to operations where multiple
workers are available for procesisng inputs. If each worker is to
process the same set of inputs, consider 'fanout' and
'fanoutSteps'. If each worker is to process a disjoint set of
inputs, consider 'scatter'.
* Concurrent connection
* Buffered machines
* Concurrent processing of shared inputs
* Concurrent multiple-input machines
| Build a new 'Machine' by adding a 'Process' to the output of an
old 'Machine'. The upstream machine is run concurrently with
downstream with the aim that upstream will have a yielded value
ready as soon as downstream awaits. This effectively creates a
buffer between upstream and downstream, or source and sink, that
@
('<~<') :: 'Process' b c -> 'Process' a b -> 'Process' a c
('<~<') :: 'Process' c d -> 'Data.Machine.Tee.Tee' a b c -> 'Data.Machine.Tee.Tee' a b d
('<~<') :: 'Process' b c -> 'Machine' k b -> 'Machine' k c
@
| Flipped ('<~<').
| Let a source and a sink chase each other, providing an effective
concurrently at all times so that as soon as the sink 'Await's, we
have a source-yielded value to provide it. This, of course,
involves eagerly running the source, percolating its 'Await's up
the chain as soon as possible.
If we have an upstream source value ready, we must flush
all available values yielded by downstream until it awaits.
If downstream is awaiting an input, we must pull in all
necessary upstream awaits until we have a yielded value to
push downstream. | # LANGUAGE CPP , GADTs , FlexibleContexts , RankNTypes , ScopedTypeVariables ,
TupleSections #
TupleSections #-}
module Data.Machine.Concurrent (module Data.Machine,
(>~>), (<~<),
bufferConnect, rollingConnect,
fanout, fanoutSteps,
wye, tee, scatter, splitSum, mergeSum,
splitProd) where
#if defined(__GLASGOW_HASKELL__) && __GLASGOW_HASKELL__ < 710
import Control.Applicative
#endif
import Control.Concurrent.Async.Lifted
import Control.Monad (join)
import Control.Monad.Trans.Control
import Data.Machine hiding (tee, wye)
import Data.Machine.Concurrent.AsyncStep
import Data.Machine.Concurrent.Buffer
import Data.Machine.Concurrent.Fanout
import Data.Machine.Concurrent.Scatter
import Data.Machine.Concurrent.Wye
import Data.Machine.Concurrent.Tee
can contain up to one value .
(<~<) :: MonadBaseControl IO m
=> ProcessT m b c -> MachineT m k b -> MachineT m k c
mp <~< ma = racers ma mp
(>~>) :: MonadBaseControl IO m
=> MachineT m k b -> ProcessT m b c -> MachineT m k c
ma >~> mp = mp <~< ma
infixl 7 >~>
| We want the first available response .
waitEither' :: MonadBaseControl IO m
=> Maybe (Async (StM m a)) -> Async (StM m b)
-> m (Either a b)
waitEither' Nothing y = Right <$> wait y
waitEither' (Just x) y = waitEither x y
one - element buffer between the two . The idea is to run both
racers :: forall m k a b. MonadBaseControl IO m
=> MachineT m k a -> ProcessT m a b -> MachineT m k b
racers src snk = MachineT . join $
go <$> (Just <$> asyncRun src) <*> asyncRun snk
where go :: Maybe (AsyncStep m k a)
-> AsyncStep m (Is a) b
-> m (MachineStep m k b)
go srcA snkA =
waitEither' srcA snkA >>= \n -> case n of
Left (Stop :: MachineStep m k a) -> go Nothing snkA
Left (Yield o k) -> wait snkA >>= \m -> case m of
(Stop :: MachineStep m (Is a) b) -> return Stop
Yield o' k' -> return . Yield o' . MachineT . flushDown k' $
\f -> join $ go <$> (Just <$> asyncRun k)
<*> asyncRun (f o)
Await f Refl _ -> join $ go <$> (Just <$> asyncRun k)
<*> asyncRun (f o)
Left (Await g kg fg) -> asyncAwait g kg fg $
MachineT . flip go snkA . Just
Right (Stop :: MachineStep m (Is a) b) -> return Stop
Right (Yield o k) -> asyncRun k >>=
return . Yield o . MachineT . go srcA
Right (Await f Refl ff) -> case srcA of
Nothing -> asyncRun ff >>= go Nothing
Just src' -> wait src' >>= \m -> case m of
Stop -> return Stop
Yield o k -> join $ go <$> (Just <$> asyncRun k)
<*> asyncRun (f o)
a -> feedUp (encased a) $ \o k -> join $
go <$> (Just <$> asyncRun k) <*> asyncRun (f o)
flushDown :: ProcessT m a b
-> ((a -> ProcessT m a b) -> m (MachineStep m k b))
-> m (MachineStep m k b)
flushDown m k = runMachineT m >>= \s -> case s of
Stop -> return Stop
Yield o m' -> return . Yield o . MachineT $ flushDown m' k
Await f Refl _ -> k f
feedUp :: MachineT m k a
-> (a -> MachineT m k a -> m (MachineStep m k b))
-> m (MachineStep m k b)
feedUp m k = runMachineT m >>= \s -> case s of
Stop -> return Stop
Yield o m' -> k o m'
Await g kg fg -> return $ awaitStep g kg fg (MachineT . flip feedUp k)
|
c93edba89a25b881ae5aa3e2278be7c6c0cbfd19317262a5bce79a05ccc9f96f | caiorss/Functional-Programming | funclist.hs | import Data.Maybe (fromJust)
f1 x = 2.4*x
f2 x = 3.5*x -10
f3 x = 4*x^^2 - 10*x + 100
dict = [('a', f1), ('b', f2), ('c', f3)]
funcdict key value = (fromJust $ lookup key dict) value
funcdict2 'a' x = f1 x
funcdict2 'b' x = f2 x
funcdict2 'c' x = f3 x
| null | https://raw.githubusercontent.com/caiorss/Functional-Programming/ef3526898e3014e9c99bf495033ff36a4530503d/codes/funclist.hs | haskell | import Data.Maybe (fromJust)
f1 x = 2.4*x
f2 x = 3.5*x -10
f3 x = 4*x^^2 - 10*x + 100
dict = [('a', f1), ('b', f2), ('c', f3)]
funcdict key value = (fromJust $ lookup key dict) value
funcdict2 'a' x = f1 x
funcdict2 'b' x = f2 x
funcdict2 'c' x = f3 x
| |
fdc48692f66dd9619b7a669304ab51a0abf1b88d8b57c69f4618978dabc370af | 40ants/openrpc | docs.lisp | (uiop:define-package #:openrpc-client/docs
(:use #:cl)
(:import-from #:40ants-doc
#:defsection)
(:import-from #:openrpc-client
#:generate-client))
(in-package #:openrpc-client/docs)
(defsection @client (:title "Client")
(openrpc-client system)
"OPENRPC-CLIENT ASDF system provides a way to build CL classes and methods for working with JSON-RPC API.
All you need is to give it an URL and all code will be created in compile-time as a result of macro-expansion.
## Generating
For example, this macro call:
```
(generate-client petshop
\":8000/openrpc.json\")
```
Will generate the whole bunch of classes and methods:
```
(defclass petshop (jsonrpc/class:client) nil)
(defun make-petshop () (make-instance 'petshop))
(defmethod describe-object ((openrpc-client/core::client petshop) stream)
(format stream \"Supported RPC methods:~2%\")
(format stream \"- ~S~%\" '(rpc-discover))
(format stream \"- ~S~%\"
'(list-pets &key (page-key nil page-key-given-p)
(limit nil limit-given-p)))
(format stream \"- ~S~%\" '(create-pet (name string) (tag string)))
(format stream \"- ~S~%\" '(get-pet (id integer))))
(defclass pet nil
((id :initform nil :initarg :id :reader pet-id)
(name :initform nil :initarg :name :reader pet-name)
(tag :initform nil :initarg :tag :reader pet-tag)))
(defmethod print-object ((openrpc-client/core::obj pet) stream)
(print-unreadable-object (openrpc-client/core::obj stream :type t)
(format stream \" ~A=~S\" 'id (pet-id openrpc-client/core::obj))
(format stream \" ~A=~S\" 'name (pet-name openrpc-client/core::obj))
(format stream \" ~A=~S\" 'tag (pet-tag openrpc-client/core::obj))))
(defmethod rpc-discover ((openrpc-client/core::client petshop))
...)
(defmethod list-pets
((openrpc-client/core::client petshop)
&key (page-key nil page-key-given-p) (limit nil limit-given-p))
...)
(defmethod create-pet
((openrpc-client/core::client petshop) (name string) (tag string))
...)
(defmethod get-pet ((openrpc-client/core::client petshop) (id integer))
...)
```
## Using
When client is generated, you need to make an instance of it and to connect
it to the server:
```
(let ((cl (make-petshop)))
(jsonrpc:client-connect cl :url \":8000/\" :mode :http)
cl)
```
You can use any transport, supported by [JSONRPC][jsonrpc] library.
DESCRIBE-OBJECT method is defined for a client, so you might see which methods are supported right in the REPL:
```common-lisp-repl
OPENRPC-EXAMPLE/CLIENT> (defvar *client* (make-test-client))
#<PETSHOP {1007AB2B13}>
OPENRPC-EXAMPLE/CLIENT> (describe *client*)
Supported RPC methods:
- (RPC-DISCOVER)
- (LIST-PETS &KEY (PAGE-KEY NIL PAGE-KEY-GIVEN-P)
(LIMIT NIL LIMIT-GIVEN-P))
- (CREATE-PET (NAME STRING) (TAG STRING))
- (GET-PET (ID INTEGER))
```
And then to call these methods as usually you do in Common Lisp. Pay attention, that
the library returns not JSON dictionaries, but ready to use CL class instances:
```common-lisp-repl
OPENRPC-EXAMPLE/CLIENT> (create-pet *client* \"Bobik\" \"the dog\")
#<PET ID=1 NAME=\"Bobik\" TAG=\"the dog\">
OPENRPC-EXAMPLE/CLIENT> (create-pet *client* \"Murzik\" \"the cat\")
#<PET ID=2 NAME=\"Murzik\" TAG=\"the cat\">
OPENRPC-EXAMPLE/CLIENT> (create-pet *client* \"Homa\" \"the hamster\")
#<PET ID=3 NAME=\"Homa\" TAG=\"the hamster\">
```
Now, pay attention how pagination does work.
```common-lisp-repl
OPENRPC-EXAMPLE/CLIENT> (list-pets *client* :limit 2)
(#<PET ID=1 NAME=\"Bobik\" TAG=\"the dog\">
#<PET ID=2 NAME=\"Murzik\" TAG=\"the cat\">)
#<FUNCTION (FLET OPENRPC-CLIENT/CORE::RETRIEVE-NEXT-PAGE :IN LIST-PETS) {1006D1F3CB}>
```
This call has returned a list of objects as the first value and a closure, which can
be called to retrive the next page. Let's retrieve it now!
```common-lisp-repl
OPENRPC-EXAMPLE/CLIENT> (funcall #v167:1)
(#<PET ID=3 NAME=\"Homa\" TAG=\"the hamster\">)
```
Now this is the last page and there is now a closure to retrieve the next page. Learn more how
to implement pagination on server-side in the OPENRPC-SERVER/DOCS::@PAGINATION section.
"
(generate-client macro))
| null | https://raw.githubusercontent.com/40ants/openrpc/8bb78c7bcf22eed95b3a8e6e634697d76b15d753/client/docs.lisp | lisp | (uiop:define-package #:openrpc-client/docs
(:use #:cl)
(:import-from #:40ants-doc
#:defsection)
(:import-from #:openrpc-client
#:generate-client))
(in-package #:openrpc-client/docs)
(defsection @client (:title "Client")
(openrpc-client system)
"OPENRPC-CLIENT ASDF system provides a way to build CL classes and methods for working with JSON-RPC API.
All you need is to give it an URL and all code will be created in compile-time as a result of macro-expansion.
## Generating
For example, this macro call:
```
(generate-client petshop
\":8000/openrpc.json\")
```
Will generate the whole bunch of classes and methods:
```
(defclass petshop (jsonrpc/class:client) nil)
(defun make-petshop () (make-instance 'petshop))
(defmethod describe-object ((openrpc-client/core::client petshop) stream)
(format stream \"Supported RPC methods:~2%\")
(format stream \"- ~S~%\" '(rpc-discover))
(format stream \"- ~S~%\"
'(list-pets &key (page-key nil page-key-given-p)
(limit nil limit-given-p)))
(format stream \"- ~S~%\" '(create-pet (name string) (tag string)))
(format stream \"- ~S~%\" '(get-pet (id integer))))
(defclass pet nil
((id :initform nil :initarg :id :reader pet-id)
(name :initform nil :initarg :name :reader pet-name)
(tag :initform nil :initarg :tag :reader pet-tag)))
(defmethod print-object ((openrpc-client/core::obj pet) stream)
(print-unreadable-object (openrpc-client/core::obj stream :type t)
(format stream \" ~A=~S\" 'id (pet-id openrpc-client/core::obj))
(format stream \" ~A=~S\" 'name (pet-name openrpc-client/core::obj))
(format stream \" ~A=~S\" 'tag (pet-tag openrpc-client/core::obj))))
(defmethod rpc-discover ((openrpc-client/core::client petshop))
...)
(defmethod list-pets
((openrpc-client/core::client petshop)
&key (page-key nil page-key-given-p) (limit nil limit-given-p))
...)
(defmethod create-pet
((openrpc-client/core::client petshop) (name string) (tag string))
...)
(defmethod get-pet ((openrpc-client/core::client petshop) (id integer))
...)
```
## Using
When client is generated, you need to make an instance of it and to connect
it to the server:
```
(let ((cl (make-petshop)))
(jsonrpc:client-connect cl :url \":8000/\" :mode :http)
cl)
```
You can use any transport, supported by [JSONRPC][jsonrpc] library.
DESCRIBE-OBJECT method is defined for a client, so you might see which methods are supported right in the REPL:
```common-lisp-repl
OPENRPC-EXAMPLE/CLIENT> (defvar *client* (make-test-client))
#<PETSHOP {1007AB2B13}>
OPENRPC-EXAMPLE/CLIENT> (describe *client*)
Supported RPC methods:
- (RPC-DISCOVER)
- (LIST-PETS &KEY (PAGE-KEY NIL PAGE-KEY-GIVEN-P)
(LIMIT NIL LIMIT-GIVEN-P))
- (CREATE-PET (NAME STRING) (TAG STRING))
- (GET-PET (ID INTEGER))
```
And then to call these methods as usually you do in Common Lisp. Pay attention, that
the library returns not JSON dictionaries, but ready to use CL class instances:
```common-lisp-repl
OPENRPC-EXAMPLE/CLIENT> (create-pet *client* \"Bobik\" \"the dog\")
#<PET ID=1 NAME=\"Bobik\" TAG=\"the dog\">
OPENRPC-EXAMPLE/CLIENT> (create-pet *client* \"Murzik\" \"the cat\")
#<PET ID=2 NAME=\"Murzik\" TAG=\"the cat\">
OPENRPC-EXAMPLE/CLIENT> (create-pet *client* \"Homa\" \"the hamster\")
#<PET ID=3 NAME=\"Homa\" TAG=\"the hamster\">
```
Now, pay attention how pagination does work.
```common-lisp-repl
OPENRPC-EXAMPLE/CLIENT> (list-pets *client* :limit 2)
(#<PET ID=1 NAME=\"Bobik\" TAG=\"the dog\">
#<PET ID=2 NAME=\"Murzik\" TAG=\"the cat\">)
#<FUNCTION (FLET OPENRPC-CLIENT/CORE::RETRIEVE-NEXT-PAGE :IN LIST-PETS) {1006D1F3CB}>
```
This call has returned a list of objects as the first value and a closure, which can
be called to retrive the next page. Let's retrieve it now!
```common-lisp-repl
OPENRPC-EXAMPLE/CLIENT> (funcall #v167:1)
(#<PET ID=3 NAME=\"Homa\" TAG=\"the hamster\">)
```
Now this is the last page and there is now a closure to retrieve the next page. Learn more how
to implement pagination on server-side in the OPENRPC-SERVER/DOCS::@PAGINATION section.
"
(generate-client macro))
| |
a00622a7614b0fee27b39bf60c2d4e62a33ad6ade451d6c1c651c13b8694be82 | BinaryAnalysisPlatform/bap-plugins | visual.ml | open Core_kernel
open Bap.Std
open Uaf_error
open Poly
class marker (error : Uaf_error.t) = object(self)
inherit Term.mapper as super
method! map_term cls t =
super#map_term cls t |> fun t ->
(* Highlight everything visited in the trace *)
(if List.mem ~equal:Tid.equal error.trace (Term.tid t)
then Term.set_attr t foreground `cyan
else t) |> fun t ->
(* Highlight use site *)
(if Term.tid t = error.use_tid
then Term.set_attr t background `red
|> fun t -> Term.set_attr t foreground `white
else t) |> fun t ->
(* Highlight free site *)
(if Term.tid t = error.free_tid
then Term.set_attr t background `yellow
|> fun t -> Term.set_attr t foreground `white
else t) |> fun t ->
(* Highlight alloc site *)
if Term.tid t = error.alloc_tid
then Term.set_attr t background `green
|> fun t -> Term.set_attr t foreground `white
else t
end
let tag_visited proj error =
let marker = new marker error in
Project.program proj |> marker#run |> Project.with_program proj
| null | https://raw.githubusercontent.com/BinaryAnalysisPlatform/bap-plugins/2e9aa5c7c24ef494d0e7db1b43c5ceedcb4196a8/uaf-checker/visual.ml | ocaml | Highlight everything visited in the trace
Highlight use site
Highlight free site
Highlight alloc site | open Core_kernel
open Bap.Std
open Uaf_error
open Poly
class marker (error : Uaf_error.t) = object(self)
inherit Term.mapper as super
method! map_term cls t =
super#map_term cls t |> fun t ->
(if List.mem ~equal:Tid.equal error.trace (Term.tid t)
then Term.set_attr t foreground `cyan
else t) |> fun t ->
(if Term.tid t = error.use_tid
then Term.set_attr t background `red
|> fun t -> Term.set_attr t foreground `white
else t) |> fun t ->
(if Term.tid t = error.free_tid
then Term.set_attr t background `yellow
|> fun t -> Term.set_attr t foreground `white
else t) |> fun t ->
if Term.tid t = error.alloc_tid
then Term.set_attr t background `green
|> fun t -> Term.set_attr t foreground `white
else t
end
let tag_visited proj error =
let marker = new marker error in
Project.program proj |> marker#run |> Project.with_program proj
|
9836d902ed763adc835d958f52456daf3625e5bdc1a235d88d3c17d64dd2a4a7 | HugoPeters1024/hs-sleuth | Records.hs | module Records where
data Big = Big
{ field00 :: Int
, field01 :: Int
, field02 :: Int
, field03 :: Int
, field04 :: Int
, field05 :: Int
, field06 :: Int
, field07 :: Int
, field08 :: Int
, field09 :: Int
, field10 :: Int
}
| null | https://raw.githubusercontent.com/HugoPeters1024/hs-sleuth/8ea5efc614b23692fd208c611f749b788f09f596/test-project/app/Records.hs | haskell | module Records where
data Big = Big
{ field00 :: Int
, field01 :: Int
, field02 :: Int
, field03 :: Int
, field04 :: Int
, field05 :: Int
, field06 :: Int
, field07 :: Int
, field08 :: Int
, field09 :: Int
, field10 :: Int
}
| |
916ae05fd3ac64fefedf59d33dcf800c1f4491b00f4a4e689178094683daa990 | camsaul/methodical | common.clj | (ns methodical.impl.method-table.common
(:require [clojure.string :as str]))
(defn- datafy-method [f]
(let [mta (meta f)]
(cond-> mta
(:ns mta)
(update :ns ns-name)
(and (:name mta)
(:ns mta))
(update :name (fn [fn-name]
(symbol (str (ns-name (:ns mta))) (str fn-name))))
true
(dissoc :dispatch-value :private) ; we already know dispatch value. Whether it's private is irrelevant
)))
(defn datafy-primary-methods
"Helper for datafying a map of dispatch value -> method."
[dispatch-value->fn]
(into {}
(map (fn [[dispatch-value f]]
[dispatch-value (datafy-method f)]))
dispatch-value->fn))
(defn- datafy-methods [fns]
(mapv datafy-method fns))
(defn datafy-aux-methods
"Helper for datafying a map of qualifier -> dispatch value -> methods."
[qualifier->dispatch-value->fns]
(into {}
(map (fn [[qualifier dispatch-value->fns]]
[qualifier (into {}
(map (fn [[dispatch-value fns]]
[dispatch-value (datafy-methods fns)]))
dispatch-value->fns)]))
qualifier->dispatch-value->fns))
(defn- describe-method
([f]
(let [{method-ns :ns, :keys [line file doc]} (meta f)]
(str/join
\space
[(when method-ns
(format "defined in [[%s]]" (ns-name method-ns)))
(cond
(and file line)
(format "(%s:%d)" file line)
file
(format "(%s)" file))
(when doc
(format "\n\nIt has the following documentation:\n\n%s" doc))])))
([dispatch-value f]
(format "* `%s`, %s" (pr-str dispatch-value) (str/join
"\n "
(str/split-lines (describe-method f))))))
(defn describe-primary-methods
"Helper for [[methodical.util.describe/describe]]ing the primary methods in a method table."
^String [dispatch-value->method]
(when (seq dispatch-value->method)
(format
"\n\nThese primary methods are known:\n\n%s"
(str/join
"\n\n"
(for [[dispatch-value f] dispatch-value->method]
(describe-method dispatch-value f))))))
(defn describe-aux-methods
"Helper for [[methodical.util.describe/describe]]ing the aux methods in a method table."
^String [qualifier->dispatch-value->methods]
(when (seq qualifier->dispatch-value->methods)
(format
"\n\nThese aux methods are known:\n\n%s"
(str/join
"\n\n"
(for [[qualifier dispatch-value->methods] (sort-by first qualifier->dispatch-value->methods)]
(format
"`%s` methods:\n\n%s"
(pr-str qualifier)
(str/join
"\n\n"
(for [[dispatch-value fns] dispatch-value->methods
f fns]
(describe-method dispatch-value f)))))))))
| null | https://raw.githubusercontent.com/camsaul/methodical/05ced088550dd212e9722c9c901183ce52bd37c0/src/methodical/impl/method_table/common.clj | clojure | we already know dispatch value. Whether it's private is irrelevant | (ns methodical.impl.method-table.common
(:require [clojure.string :as str]))
(defn- datafy-method [f]
(let [mta (meta f)]
(cond-> mta
(:ns mta)
(update :ns ns-name)
(and (:name mta)
(:ns mta))
(update :name (fn [fn-name]
(symbol (str (ns-name (:ns mta))) (str fn-name))))
true
)))
(defn datafy-primary-methods
"Helper for datafying a map of dispatch value -> method."
[dispatch-value->fn]
(into {}
(map (fn [[dispatch-value f]]
[dispatch-value (datafy-method f)]))
dispatch-value->fn))
(defn- datafy-methods [fns]
(mapv datafy-method fns))
(defn datafy-aux-methods
"Helper for datafying a map of qualifier -> dispatch value -> methods."
[qualifier->dispatch-value->fns]
(into {}
(map (fn [[qualifier dispatch-value->fns]]
[qualifier (into {}
(map (fn [[dispatch-value fns]]
[dispatch-value (datafy-methods fns)]))
dispatch-value->fns)]))
qualifier->dispatch-value->fns))
(defn- describe-method
([f]
(let [{method-ns :ns, :keys [line file doc]} (meta f)]
(str/join
\space
[(when method-ns
(format "defined in [[%s]]" (ns-name method-ns)))
(cond
(and file line)
(format "(%s:%d)" file line)
file
(format "(%s)" file))
(when doc
(format "\n\nIt has the following documentation:\n\n%s" doc))])))
([dispatch-value f]
(format "* `%s`, %s" (pr-str dispatch-value) (str/join
"\n "
(str/split-lines (describe-method f))))))
(defn describe-primary-methods
"Helper for [[methodical.util.describe/describe]]ing the primary methods in a method table."
^String [dispatch-value->method]
(when (seq dispatch-value->method)
(format
"\n\nThese primary methods are known:\n\n%s"
(str/join
"\n\n"
(for [[dispatch-value f] dispatch-value->method]
(describe-method dispatch-value f))))))
(defn describe-aux-methods
"Helper for [[methodical.util.describe/describe]]ing the aux methods in a method table."
^String [qualifier->dispatch-value->methods]
(when (seq qualifier->dispatch-value->methods)
(format
"\n\nThese aux methods are known:\n\n%s"
(str/join
"\n\n"
(for [[qualifier dispatch-value->methods] (sort-by first qualifier->dispatch-value->methods)]
(format
"`%s` methods:\n\n%s"
(pr-str qualifier)
(str/join
"\n\n"
(for [[dispatch-value fns] dispatch-value->methods
f fns]
(describe-method dispatch-value f)))))))))
|
1b422e561c44470d44a1fab4f542ce57dda1b75bcf432556c60e371cd9f049d3 | kutyel/haskell-book | Chapter30.hs | {-# LANGUAGE GADTs #-}
module Chapter30 where
import Control.Exception (ArithException (..), AsyncException (..))
import Data.Typeable (Typeable, cast)
data MyException where
MyException :: (Show e, Typeable e) => e -> MyException
instance Show MyException where
showsPrec p (MyException e) = showsPrec p e
multiError :: Int -> Either MyException Int
multiError n =
case n of
0 -> Left (MyException DivideByZero)
1 -> Left (MyException StackOverflow)
_ -> Right n
data SomeError
= Arith ArithException
| Async AsyncException
| SomethingElse
deriving (Show)
discriminateError :: MyException -> SomeError
discriminateError (MyException e) =
maybe (maybe SomethingElse Async (cast e)) Arith (cast e)
runDisc :: Int -> SomeError
runDisc = either discriminateError (const SomethingElse) . multiError
| null | https://raw.githubusercontent.com/kutyel/haskell-book/fd4dc0332b67575cfaf5e3fb0e26687dc01772a0/src/Chapter30.hs | haskell | # LANGUAGE GADTs # |
module Chapter30 where
import Control.Exception (ArithException (..), AsyncException (..))
import Data.Typeable (Typeable, cast)
data MyException where
MyException :: (Show e, Typeable e) => e -> MyException
instance Show MyException where
showsPrec p (MyException e) = showsPrec p e
multiError :: Int -> Either MyException Int
multiError n =
case n of
0 -> Left (MyException DivideByZero)
1 -> Left (MyException StackOverflow)
_ -> Right n
data SomeError
= Arith ArithException
| Async AsyncException
| SomethingElse
deriving (Show)
discriminateError :: MyException -> SomeError
discriminateError (MyException e) =
maybe (maybe SomethingElse Async (cast e)) Arith (cast e)
runDisc :: Int -> SomeError
runDisc = either discriminateError (const SomethingElse) . multiError
|
1f64d82849e3963ebaeb6e611b60cb6dafbb1851cfb3413549abf32b13b4caca | vaclavsvejcar/headroom | Types.hs | # LANGUAGE NoImplicitPrelude #
-- |
Module : Headroom . PostProcess . Types
-- Description : Data types for /post-processing/
Copyright : ( c ) 2019 - 2022
-- License : BSD-3-Clause
-- Maintainer :
-- Stability : experimental
-- Portability : POSIX
--
-- This module contains data types and /type class/ instances for the
-- /post-processing/ functions.
module Headroom.PostProcess.Types
( PostProcess (..)
)
where
import RIO
-- | Definition of /post-processor/, i.e. function, that is applied to
already rendered /license header/ , performs some logic and returns modified
text of /license header/. Given that the /reader monad/ and ' ReaderT '
-- transformer is used, any configuration is provided using the @env@
environment . When combined with the " Headroom . Data . Has " monad , it provides
-- powerful way how to combine different /post-processors/ and
-- environments.
--
-- = Structure of post-processor
--
-- @
-- __Text -> Reader env Text__
-- │ │ │
─ rendered text of license header
-- │ │
─ environment holding possible configuration
-- │
-- └─ modified license header text
-- @
newtype PostProcess env = PostProcess (Text -> Reader env Text)
instance Semigroup (PostProcess env) where
PostProcess fnX <> PostProcess fnY = PostProcess $ fnX >=> fnY
instance Monoid (PostProcess env) where
mempty = PostProcess $ \input -> pure input
| null | https://raw.githubusercontent.com/vaclavsvejcar/headroom/3b20a89568248259d59f83f274f60f6e13d16f93/src/Headroom/PostProcess/Types.hs | haskell | |
Description : Data types for /post-processing/
License : BSD-3-Clause
Maintainer :
Stability : experimental
Portability : POSIX
This module contains data types and /type class/ instances for the
/post-processing/ functions.
| Definition of /post-processor/, i.e. function, that is applied to
transformer is used, any configuration is provided using the @env@
powerful way how to combine different /post-processors/ and
environments.
= Structure of post-processor
@
__Text -> Reader env Text__
│ │ │
│ │
│
└─ modified license header text
@ | # LANGUAGE NoImplicitPrelude #
Module : Headroom . PostProcess . Types
Copyright : ( c ) 2019 - 2022
module Headroom.PostProcess.Types
( PostProcess (..)
)
where
import RIO
already rendered /license header/ , performs some logic and returns modified
text of /license header/. Given that the /reader monad/ and ' ReaderT '
environment . When combined with the " Headroom . Data . Has " monad , it provides
─ rendered text of license header
─ environment holding possible configuration
newtype PostProcess env = PostProcess (Text -> Reader env Text)
instance Semigroup (PostProcess env) where
PostProcess fnX <> PostProcess fnY = PostProcess $ fnX >=> fnY
instance Monoid (PostProcess env) where
mempty = PostProcess $ \input -> pure input
|
149767aa922c9277c6a65fd989c8f1c94c2415dfb7d13e35b9102cbf9509682c | winny-/aoc | day12-typed.rkt | #lang typed/racket
(struct instruction ([name : Symbol]
[arg1 : (U Symbol Integer)]
[arg2 : (U Symbol Integer False)])
#:transparent)
(struct state ([registers : (HashTable Symbol Integer)]
[address : (U Integer False)])
#:transparent)
(define initial-state (state #hash((a . 0)
(b . 0)
(c . 0)
(d . 0))
0))
(define initial-state-pt2
(state (hash-set (state-registers initial-state) 'c 1)
(state-address initial-state)))
(: read-instruction (Input-Port . -> . (U EOF instruction)))
(define (read-instruction ip)
(: f (String . -> . (U Symbol Integer)))
(define (f s)
(: n (U Complex False))
(define n (string->number s))
(if (exact-integer? n)
n
(string->symbol s)))
(define s (read-line ip))
(if (eof-object? s)
eof
(let ([ls (string-split s)])
(instruction (string->symbol (car ls))
(f (cadr ls))
(if (empty? (cddr ls))
#f
(f (caddr ls)))))))
(: step ((Listof instruction) state . -> . state))
(define (step ins st)
(: set-register (Symbol Integer . -> . state))
(define (set-register r v)
(state (hash-set (state-registers st) r v) (state-address st)))
(: resolve-arg ((U Symbol Integer) . -> . Integer))
(define (resolve-arg arg)
(if (number? arg)
arg
(hash-ref (state-registers st) arg)))
(: valid-address? (Integer . -> . Boolean))
(define (valid-address? address)
(and (>= address 0) (<= address (sub1 (length ins)))))
(: increment-address (state . -> . state))
(define (increment-address st)
(define addr (state-address st))
(state (state-registers st)
(if (exact-integer? addr)
(let ([n (add1 addr)])
(if (and (exact-integer? n) (valid-address? n))
n
#f))
#f)))
(define addr (state-address st))
(if (false? addr)
st
(match (list-ref ins addr)
[(instruction 'inc (and (or 'a 'b 'c 'd) r) #f) (increment-address (set-register r (add1 (resolve-arg r))))]
[(instruction 'dec (and (or 'a 'b 'c 'd) r) #f) (increment-address (set-register r (sub1 (resolve-arg r))))]
[(instruction 'cpy src (and (or 'a 'b 'c 'd) dst)) (increment-address (set-register dst (resolve-arg src)))]
[(instruction 'jnz test (and (not #f) offset)) (if (zero? (resolve-arg test))
(increment-address st)
(let ([new-address (+ addr (resolve-arg (if (false? offset) (error "offset cannot be false") offset)))])
(state (state-registers st)
(if (valid-address? new-address)
new-address
#f))))])))
(: run ([(Listof instruction)] [state] . ->* . state))
(define (run ins [initial-state initial-state])
(let loop : state ([st : state initial-state] [executions 0])
(if (state-address st)
(loop (step ins st) (add1 executions))
(begin (displayln executions)
st))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Sample input
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-syntax guard
(syntax-rules ()
[(_ a b)
(let ()
(unless (a b)
(error "guard failed"))
b)]))
(define sample-input (port->list read-instruction (open-input-string #<<EOF
cpy 41 a
inc a
inc a
dec a
jnz a 2
dec a
EOF
)))
(module* benchmark #f
(time (run (guard (λ (ls) (andmap instruction? ls)) sample-input))))
(module+ main
(define ins (port->list read-instruction))
(displayln (format "Part #1: register a is ~a" (hash-ref (state-registers (run (guard (λ (ls) (andmap instruction? ls)) ins))) 'a)))
(displayln (format "Part #2: register a is ~a" (hash-ref (state-registers (run (guard (λ (ls) (andmap instruction? ls)) ins) initial-state-pt2)) 'a))))
| null | https://raw.githubusercontent.com/winny-/aoc/d508caae19899dcab57ac665ef5d1a05b0a90c0c/2016/day12/day12-typed.rkt | racket |
Sample input
| #lang typed/racket
(struct instruction ([name : Symbol]
[arg1 : (U Symbol Integer)]
[arg2 : (U Symbol Integer False)])
#:transparent)
(struct state ([registers : (HashTable Symbol Integer)]
[address : (U Integer False)])
#:transparent)
(define initial-state (state #hash((a . 0)
(b . 0)
(c . 0)
(d . 0))
0))
(define initial-state-pt2
(state (hash-set (state-registers initial-state) 'c 1)
(state-address initial-state)))
(: read-instruction (Input-Port . -> . (U EOF instruction)))
(define (read-instruction ip)
(: f (String . -> . (U Symbol Integer)))
(define (f s)
(: n (U Complex False))
(define n (string->number s))
(if (exact-integer? n)
n
(string->symbol s)))
(define s (read-line ip))
(if (eof-object? s)
eof
(let ([ls (string-split s)])
(instruction (string->symbol (car ls))
(f (cadr ls))
(if (empty? (cddr ls))
#f
(f (caddr ls)))))))
(: step ((Listof instruction) state . -> . state))
(define (step ins st)
(: set-register (Symbol Integer . -> . state))
(define (set-register r v)
(state (hash-set (state-registers st) r v) (state-address st)))
(: resolve-arg ((U Symbol Integer) . -> . Integer))
(define (resolve-arg arg)
(if (number? arg)
arg
(hash-ref (state-registers st) arg)))
(: valid-address? (Integer . -> . Boolean))
(define (valid-address? address)
(and (>= address 0) (<= address (sub1 (length ins)))))
(: increment-address (state . -> . state))
(define (increment-address st)
(define addr (state-address st))
(state (state-registers st)
(if (exact-integer? addr)
(let ([n (add1 addr)])
(if (and (exact-integer? n) (valid-address? n))
n
#f))
#f)))
(define addr (state-address st))
(if (false? addr)
st
(match (list-ref ins addr)
[(instruction 'inc (and (or 'a 'b 'c 'd) r) #f) (increment-address (set-register r (add1 (resolve-arg r))))]
[(instruction 'dec (and (or 'a 'b 'c 'd) r) #f) (increment-address (set-register r (sub1 (resolve-arg r))))]
[(instruction 'cpy src (and (or 'a 'b 'c 'd) dst)) (increment-address (set-register dst (resolve-arg src)))]
[(instruction 'jnz test (and (not #f) offset)) (if (zero? (resolve-arg test))
(increment-address st)
(let ([new-address (+ addr (resolve-arg (if (false? offset) (error "offset cannot be false") offset)))])
(state (state-registers st)
(if (valid-address? new-address)
new-address
#f))))])))
(: run ([(Listof instruction)] [state] . ->* . state))
(define (run ins [initial-state initial-state])
(let loop : state ([st : state initial-state] [executions 0])
(if (state-address st)
(loop (step ins st) (add1 executions))
(begin (displayln executions)
st))))
(define-syntax guard
(syntax-rules ()
[(_ a b)
(let ()
(unless (a b)
(error "guard failed"))
b)]))
(define sample-input (port->list read-instruction (open-input-string #<<EOF
cpy 41 a
inc a
inc a
dec a
jnz a 2
dec a
EOF
)))
(module* benchmark #f
(time (run (guard (λ (ls) (andmap instruction? ls)) sample-input))))
(module+ main
(define ins (port->list read-instruction))
(displayln (format "Part #1: register a is ~a" (hash-ref (state-registers (run (guard (λ (ls) (andmap instruction? ls)) ins))) 'a)))
(displayln (format "Part #2: register a is ~a" (hash-ref (state-registers (run (guard (λ (ls) (andmap instruction? ls)) ins) initial-state-pt2)) 'a))))
|
145e97c05a2b2c24e582b88663cf881bdfab5b6f7331afa30a4ec9a3e5294062 | w3ntao/sicp-solution | 1-44.rkt | #lang racket
(define (even? n)
(= (remainder n 2) 0))
(define (square x)
(* x x))
(define (compose f g)
(lambda (x) (f (g x))))
(define (double f)
(lambda (x) (f (f x))))
(define (repeat f n)
(cond ((= n 1) (lambda (x) (f x)))
((even? n) (repeat (double f) (/ n 2)))
(else (compose f (repeat f (- n 1))))))
(define (smooth f)
(let ((dx 0.0001))
(lambda (x)(/ (+ (f x)
(f (- x dx))
(f (+ x dx)))
3))))
(define (smooth-n-time f n)
(repeat (smooth f) n))
((repeat square 2) 5)
| null | https://raw.githubusercontent.com/w3ntao/sicp-solution/00be3a7b4da50bb266f8a2db521a24e9f8c156be/chap-1/1-44.rkt | racket | #lang racket
(define (even? n)
(= (remainder n 2) 0))
(define (square x)
(* x x))
(define (compose f g)
(lambda (x) (f (g x))))
(define (double f)
(lambda (x) (f (f x))))
(define (repeat f n)
(cond ((= n 1) (lambda (x) (f x)))
((even? n) (repeat (double f) (/ n 2)))
(else (compose f (repeat f (- n 1))))))
(define (smooth f)
(let ((dx 0.0001))
(lambda (x)(/ (+ (f x)
(f (- x dx))
(f (+ x dx)))
3))))
(define (smooth-n-time f n)
(repeat (smooth f) n))
((repeat square 2) 5)
| |
541618696798fa22ea1dd623f574e7b1e4b6dbefc37a1d32061a0a45b169e952 | jeromesimeon/Galax | shredded_main_memory_hash.ml | (***********************************************************************)
(* *)
(* GALAX *)
(* XQuery Engine *)
(* *)
Copyright 2001 - 2007 .
(* Distributed only by permission. *)
(* *)
(***********************************************************************)
$ I d : , v 1.3 2007/02/01 22:08:54 simeon Exp $
(* Module: Shredded_main_memory_hash
Description:
This module describes a functorial interface for in memory
hash tables.
*)
exception Cursor_Error of string
module Shredded_Main_Memory_Hash_Functor
(Key : Shredded_common.Shred_Type)
(Value : Shredded_common.Shred_Type)
=
struct
type hash = (Key.t, Value.t) Hashtbl.t
type hash_key = Key.t
type hash_value = Value.t
let (hash_handles:((string ,hash) Hashtbl.t)) = Hashtbl.create 1
let hash_open filename buffersize l =
if Hashtbl.mem hash_handles filename
then Hashtbl.find hash_handles filename
else
begin
let ht =
(* This is problematic for the semantic *)
(*
if not l then
raise (Error.Query (Error.Shredded_Error ("Main memory hash only supports duplicate operations")))
else *)
Hashtbl.create buffersize
in
Hashtbl.add hash_handles filename ht;
ht
end
let hash_put sh k v = Hashtbl.add sh k v
let hash_get sh k =
if Hashtbl.mem sh k
then Some (Hashtbl.find sh k)
else None
let hash_get_all sh k = Cursor.cursor_of_list (Hashtbl.find_all sh k)
type cursor_direction = Next | Prev
let hash_delete sh k = Hashtbl.remove sh k
let hash_close sh = ()
let hash_sync sh = ()
(* HASH CURSORS ARE HORRILBY INEFFICIENT *)
type hash_cursor =
{ ht : hash;
mutable l : (Key.t * Value.t) array;
cur : int ref;
}
let hash_cursor_open sh =
let list = Hashtbl.fold (fun k v l -> (k,v) :: l) sh [] in
{ ht = sh;
l = Array.of_list list;
cur = ref 0 }
(* Where do we add this in? Order is not defined ? *)
let hash_cursor_put c k v =
hash_put c.ht k v
let hash_cursor_get_next {ht=ht;l=l;cur=cur} =
let len = Array.length l in
incr cur;
if !cur >= 0 && !cur < len then
begin
let v = l.(!cur) in
Some v
end
else
None
let hash_cursor_get_prev {ht=ht;l=l;cur=cur} =
let len = Array.length l in
decr cur;
if !cur >= 0 && !cur < len then
begin
let v = l.(!cur) in
Some v
end
else
None
let hash_cursor_get_first {ht=ht;l=l;cur=cur} =
if Array.length l > 0 then
begin
cur := 0;
Some l.(0)
end
else None
let hash_cursor_get_last {ht=ht;l=l;cur=cur} =
if Array.length l > 0 then
begin
cur := (Array.length l) - 1;
Some l.(!cur)
end
else None
let hash_cursor_to_cursor c cursor_direction =
let cursor_function =
match cursor_direction with
| Next -> (fun () -> hash_cursor_get_next c)
| Prev -> (fun () -> hash_cursor_get_prev c)
in
Cursor.cursor_of_function cursor_function
(* Both of these need key as additional parameter *)
let hash_cursor_get_set c = raise (Cursor_Error ("Hash get_set_range main memory not working"))
let hash_cursor_get_both c = raise (Cursor_Error ("Hash get_both main memory not working"))
let hash_cursor_del ({ht=ht;l=l;cur=cur} as e) =
let len = Array.length l in
if !cur >= 0 && !cur < len then
begin
let left = Array.sub l 0 !cur in
let right = Array.sub l (!cur+1) (len - 1 - !cur) in
e.l <- Array.append left right;
(* Cur remains the same *)
end
else raise (Cursor_Error "Invalid delete call")
Two things need to happen , the item disappears from the cursor
let hash_cursor_close sh = ()
end
| null | https://raw.githubusercontent.com/jeromesimeon/Galax/bc565acf782c140291911d08c1c784c9ac09b432/shredded/shredded_main_memory/shredded_main_memory_hash.ml | ocaml | *********************************************************************
GALAX
XQuery Engine
Distributed only by permission.
*********************************************************************
Module: Shredded_main_memory_hash
Description:
This module describes a functorial interface for in memory
hash tables.
This is problematic for the semantic
if not l then
raise (Error.Query (Error.Shredded_Error ("Main memory hash only supports duplicate operations")))
else
HASH CURSORS ARE HORRILBY INEFFICIENT
Where do we add this in? Order is not defined ?
Both of these need key as additional parameter
Cur remains the same | Copyright 2001 - 2007 .
$ I d : , v 1.3 2007/02/01 22:08:54 simeon Exp $
exception Cursor_Error of string
module Shredded_Main_Memory_Hash_Functor
(Key : Shredded_common.Shred_Type)
(Value : Shredded_common.Shred_Type)
=
struct
type hash = (Key.t, Value.t) Hashtbl.t
type hash_key = Key.t
type hash_value = Value.t
let (hash_handles:((string ,hash) Hashtbl.t)) = Hashtbl.create 1
let hash_open filename buffersize l =
if Hashtbl.mem hash_handles filename
then Hashtbl.find hash_handles filename
else
begin
let ht =
Hashtbl.create buffersize
in
Hashtbl.add hash_handles filename ht;
ht
end
let hash_put sh k v = Hashtbl.add sh k v
let hash_get sh k =
if Hashtbl.mem sh k
then Some (Hashtbl.find sh k)
else None
let hash_get_all sh k = Cursor.cursor_of_list (Hashtbl.find_all sh k)
type cursor_direction = Next | Prev
let hash_delete sh k = Hashtbl.remove sh k
let hash_close sh = ()
let hash_sync sh = ()
type hash_cursor =
{ ht : hash;
mutable l : (Key.t * Value.t) array;
cur : int ref;
}
let hash_cursor_open sh =
let list = Hashtbl.fold (fun k v l -> (k,v) :: l) sh [] in
{ ht = sh;
l = Array.of_list list;
cur = ref 0 }
let hash_cursor_put c k v =
hash_put c.ht k v
let hash_cursor_get_next {ht=ht;l=l;cur=cur} =
let len = Array.length l in
incr cur;
if !cur >= 0 && !cur < len then
begin
let v = l.(!cur) in
Some v
end
else
None
let hash_cursor_get_prev {ht=ht;l=l;cur=cur} =
let len = Array.length l in
decr cur;
if !cur >= 0 && !cur < len then
begin
let v = l.(!cur) in
Some v
end
else
None
let hash_cursor_get_first {ht=ht;l=l;cur=cur} =
if Array.length l > 0 then
begin
cur := 0;
Some l.(0)
end
else None
let hash_cursor_get_last {ht=ht;l=l;cur=cur} =
if Array.length l > 0 then
begin
cur := (Array.length l) - 1;
Some l.(!cur)
end
else None
let hash_cursor_to_cursor c cursor_direction =
let cursor_function =
match cursor_direction with
| Next -> (fun () -> hash_cursor_get_next c)
| Prev -> (fun () -> hash_cursor_get_prev c)
in
Cursor.cursor_of_function cursor_function
let hash_cursor_get_set c = raise (Cursor_Error ("Hash get_set_range main memory not working"))
let hash_cursor_get_both c = raise (Cursor_Error ("Hash get_both main memory not working"))
let hash_cursor_del ({ht=ht;l=l;cur=cur} as e) =
let len = Array.length l in
if !cur >= 0 && !cur < len then
begin
let left = Array.sub l 0 !cur in
let right = Array.sub l (!cur+1) (len - 1 - !cur) in
e.l <- Array.append left right;
end
else raise (Cursor_Error "Invalid delete call")
Two things need to happen , the item disappears from the cursor
let hash_cursor_close sh = ()
end
|
86702d5153b7a689e38c56f2e568f3e7de87d828ca299d13742099d1b616e454 | Ericson2314/lighthouse | Interp.hs |
Interprets the subset of well - typed Core programs for which
( a ) All constructor and primop applications are saturated
( b ) All non - trivial expressions of unlifted kind ( ' # ' ) are
scrutinized in a Case expression .
This is by no means a " minimal " interpreter , in the sense that considerably
simpler machinary could be used to run programs and get the right answers .
However , it attempts to mirror the intended use of various Core constructs ,
particularly with respect to heap usage . So considerations such as unboxed
tuples , sharing , trimming , black - holing , etc . are all covered .
The only major omission is garbage collection .
Just a sampling of primitive types and operators are included .
Interprets the subset of well-typed Core programs for which
(a) All constructor and primop applications are saturated
(b) All non-trivial expressions of unlifted kind ('#') are
scrutinized in a Case expression.
This is by no means a "minimal" interpreter, in the sense that considerably
simpler machinary could be used to run programs and get the right answers.
However, it attempts to mirror the intended use of various Core constructs,
particularly with respect to heap usage. So considerations such as unboxed
tuples, sharing, trimming, black-holing, etc. are all covered.
The only major omission is garbage collection.
Just a sampling of primitive types and operators are included.
-}
module Interp where
import Core
import Printer
import Monad
import Env
import List
import Char
import Prims
data HeapValue =
Hconstr Dcon [Value] -- constructed value (note: no qualifier needed!)
| Hclos Venv Var Exp -- function closure
| Hthunk Venv Exp -- unevaluated thunk
deriving (Show)
type Ptr = Int
data Value =
Vheap Ptr -- heap pointer (boxed)
| Vimm PrimValue -- immediate primitive value (unboxed)
| Vutuple [Value] -- unboxed tuples
deriving (Show)
type Venv = Env Var Value -- values of vars
data PrimValue = -- values of the (unboxed) primitive types
actually 31 - bit unsigned
| PIntzh Integer -- actually WORD_SIZE_IN_BITS-bit signed
| PWordzh Integer -- actually WORD_SIZE_IN_BITS-bit unsigned
| PAddrzh Integer -- actually native pointer size
actually 32 - bit
actually 64 - bit
-- etc., etc.
deriving (Eq,Show)
type Menv = Env Mname Venv -- modules
initialGlobalEnv :: Menv
initialGlobalEnv =
efromlist
[(primMname,efromlist [("realWorldzh",Vimm (PIntzh 0))])]
Heap management .
{- Nothing is said about garbage collection. -}
data Heap = Heap Ptr (Env Ptr HeapValue) -- last cell allocated; environment of allocated cells
deriving (Show)
hallocate :: Heap -> HeapValue -> (Heap,Ptr)
hallocate (Heap last contents) v =
let next = last+1
in (Heap next (eextend contents (next,v)),next)
hupdate :: Heap -> Ptr -> HeapValue -> Heap
hupdate (Heap last contents) p v =
Heap last (eextend contents (p,v))
hlookup:: Heap -> Ptr -> HeapValue
hlookup (Heap _ contents) p =
case elookup contents p of
Just v -> v
Nothing -> error "Missing heap entry (black hole?)"
hremove :: Heap -> Ptr -> Heap
hremove (Heap last contents) p =
Heap last (eremove contents p)
hempty :: Heap
hempty = Heap 0 eempty
{- The evaluation monad manages the heap and the possiblity
of exceptions. -}
type Exn = Value
newtype Eval a = Eval (Heap -> (Heap,Either a Exn))
instance Monad Eval where
(Eval m) >>= k = Eval (
\h -> case m h of
(h',Left x) -> case k x of
Eval k' -> k' h'
(h',Right exn) -> (h',Right exn))
return x = Eval (\h -> (h,Left x))
hallocateE :: HeapValue -> Eval Ptr
hallocateE v = Eval (\ h ->
let (h',p) = hallocate h v
in (h', Left p))
hupdateE :: Ptr -> HeapValue -> Eval ()
hupdateE p v = Eval (\h -> (hupdate h p v,Left ()))
hlookupE :: Ptr -> Eval HeapValue
hlookupE p = Eval (\h -> (h,Left (hlookup h p)))
hremoveE :: Ptr -> Eval ()
hremoveE p = Eval (\h -> (hremove h p, Left ()))
raiseE :: Exn -> Eval a
raiseE exn = Eval (\h -> (h,Right exn))
catchE :: Eval a -> (Exn -> Eval a) -> Eval a
catchE (Eval m) f = Eval
(\h -> case m h of
(h',Left x) -> (h',Left x)
(h',Right exn) ->
case f exn of
Eval f' -> f' h')
runE :: Eval a -> a
runE (Eval f) =
case f hempty of
(_,Left v) -> v
(_,Right exn) -> error ("evaluation failed with uncaught exception: " ++ show exn)
{- Main entry point -}
evalProgram :: [Module] -> Value
evalProgram modules =
runE(
do globalEnv <- foldM evalModule initialGlobalEnv modules
Vutuple [_,v] <- evalExp globalEnv eempty (App (Var ("Main","main")) (Var (primMname,"realWorldzh")))
return v)
{- Environments:
Evaluating a module just fills an environment with suspensions for all
the external top-level values; it doesn't actually do any evaluation
or look anything up.
By the time we actually evaluate an expression, all external values from
all modules will be in globalEnv. So evaluation just maintains an environment
of non-external values (top-level or local). In particular, only non-external
values end up in closures (all other values are accessible from globalEnv.)
Throughout:
- globalEnv contains external values (all top-level) from all modules seen so far.
In evalModule:
- e_venv contains external values (all top-level) seen so far in current module
- l_venv contains non-external values (top-level or local)
seen so far in current module.
In evalExp:
- env contains non-external values (top-level or local) seen so far
in current expression.
-}
evalModule :: Menv -> Module -> Eval Menv
evalModule globalEnv (Module mn tdefs vdefgs) =
do (e_venv,l_venv) <- foldM evalVdef (eempty,eempty) vdefgs
return (eextend globalEnv (mn,e_venv))
where
evalVdef :: (Venv,Venv) -> Vdefg -> Eval (Venv,Venv)
evalVdef (e_env,l_env) (Nonrec(Vdef((m,x),t,e))) =
do p <- hallocateE (suspendExp l_env e)
let heaps =
if m == "" then
(e_env,eextend l_env (x,Vheap p))
else
(eextend e_env (x,Vheap p),l_env)
return heaps
evalVdef (e_env,l_env) (Rec vdefs) =
do l_vs0 <- mapM preallocate l_xs
let l_env' = foldl eextend l_env (zip l_xs l_vs0)
let l_hs = map (suspendExp l_env') l_es
mapM_ reallocate (zip l_vs0 l_hs)
let e_hs = map (suspendExp l_env') e_es
e_vs <- mapM allocate e_hs
let e_env' = foldl eextend e_env (zip e_xs e_vs)
return (e_env',l_env')
where
(l_xs,l_es) = unzip [(x,e) | Vdef(("",x),_,e) <- vdefs]
(e_xs,e_es) = unzip [(x,e) | Vdef((m,x),_,e) <- vdefs, m /= ""]
preallocate _ =
do p <- hallocateE undefined
return (Vheap p)
reallocate (Vheap p0,h) =
hupdateE p0 h
allocate h =
do p <- hallocateE h
return (Vheap p)
suspendExp:: Venv -> Exp -> HeapValue
suspendExp env (Lam (Vb(x,_)) e) = Hclos env' x e
where env' = thin env (delete x (freevarsExp e))
suspendExp env e = Hthunk env' e
where env' = thin env (freevarsExp e)
evalExp :: Menv -> Venv -> Exp -> Eval Value
evalExp globalEnv env (Var qv) =
let v = qlookup globalEnv env qv
in case v of
Vheap p ->
do z <- hlookupE p -- can fail due to black-holing
case z of
Hthunk env' e ->
do hremoveE p -- black-hole
w@(Vheap p') <- evalExp globalEnv env' e -- result is guaranteed to be boxed!
h <- hlookupE p'
hupdateE p h
return w
return pointer to or Hconstr
return Vimm or
evalExp globalEnv env (Lit l) = return (Vimm (evalLit l))
evalExp globalEnv env (Dcon (_,c)) =
do p <- hallocateE (Hconstr c [])
return (Vheap p)
evalExp globalEnv env (App e1 e2) = evalApp env e1 [e2]
where
evalApp :: Venv -> Exp -> [Exp] -> Eval Value
evalApp env (App e1 e2) es = evalApp env e1 (e2:es)
evalApp env (op @(Dcon (qdc@(m,c)))) es =
do vs <- suspendExps globalEnv env es
if isUtupleDc qdc then
return (Vutuple vs)
else
{- allocate a thunk -}
do p <- hallocateE (Hconstr c vs)
return (Vheap p)
evalApp env (op @ (Var(m,p))) es | m == primMname =
do vs <- evalExps globalEnv env es
case (p,vs) of
("raisezh",[exn]) -> raiseE exn
("catchzh",[body,handler,rws]) ->
catchE (apply body [rws])
(\exn -> apply handler [exn,rws])
_ -> evalPrimop p vs
evalApp env (External s _) es =
do vs <- evalExps globalEnv env es
evalExternal s vs
evalApp env (Appt e _) es = evalApp env e es
evalApp env (Lam (Tb _) e) es = evalApp env e es
evalApp env (Coerce _ e) es = evalApp env e es
evalApp env (Note _ e) es = evalApp env e es
evalApp env e es =
{- e must now evaluate to a closure -}
do vs <- suspendExps globalEnv env es
vop <- evalExp globalEnv env e
apply vop vs
apply :: Value -> [Value] -> Eval Value
apply vop [] = return vop
apply (Vheap p) (v:vs) =
do Hclos env' x b <- hlookupE p
v' <- evalExp globalEnv (eextend env' (x,v)) b
apply v' vs
evalExp globalEnv env (Appt e _) = evalExp globalEnv env e
evalExp globalEnv env (Lam (Vb(x,_)) e) =
do p <- hallocateE (Hclos env' x e)
return (Vheap p)
where env' = thin env (delete x (freevarsExp e))
evalExp globalEnv env (Lam _ e) = evalExp globalEnv env e
evalExp globalEnv env (Let vdef e) =
do env' <- evalVdef globalEnv env vdef
evalExp globalEnv env' e
where
evalVdef :: Menv -> Venv -> Vdefg -> Eval Venv
evalVdef globalEnv env (Nonrec(Vdef((m,x),t,e))) =
do v <- suspendExp globalEnv env e
return (eextend env (x,v))
evalVdef globalEnv env (Rec vdefs) =
do vs0 <- mapM preallocate xs
let env' = foldl eextend env (zip xs vs0)
vs <- suspendExps globalEnv env' es
mapM_ reallocate (zip vs0 vs)
return env'
where
(xs,es) = unzip [(x,e) | Vdef((_,x),_,e) <- vdefs]
preallocate _ =
do p <- hallocateE (Hconstr "UGH" [])
return (Vheap p)
reallocate (Vheap p0,Vheap p) =
do h <- hlookupE p
hupdateE p0 h
evalExp globalEnv env (Case e (x,_) alts) =
do z <- evalExp globalEnv env e
let env' = eextend env (x,z)
case z of
Vheap p ->
do h <- hlookupE p -- can fail due to black-holing
case h of
Hconstr dcon vs -> evalDcAlt env' dcon vs (reverse alts)
_ -> evalDefaultAlt env' alts
Vutuple vs ->
evalUtupleAlt env' vs (reverse alts)
Vimm pv ->
evalLitAlt env' pv (reverse alts)
where
evalDcAlt :: Venv -> Dcon -> [Value] -> [Alt] -> Eval Value
evalDcAlt env dcon vs alts =
f alts
where
f ((Acon (_,dcon') _ xs e):as) =
if dcon == dcon' then
evalExp globalEnv (foldl eextend env (zip (map fst xs) vs)) e
else f as
f [Adefault e] =
evalExp globalEnv env e
f _ = error "impossible Case-evalDcAlt"
evalUtupleAlt :: Venv -> [Value] -> [Alt] -> Eval Value
evalUtupleAlt env vs [Acon _ _ xs e] =
evalExp globalEnv (foldl eextend env (zip (map fst xs) vs)) e
evalLitAlt :: Venv -> PrimValue -> [Alt] -> Eval Value
evalLitAlt env pv alts =
f alts
where
f ((Alit lit e):as) =
let pv' = evalLit lit
in if pv == pv' then
evalExp globalEnv env e
else f as
f [Adefault e] =
evalExp globalEnv env e
f _ = error "impossible Case-evalLitAlt"
evalDefaultAlt :: Venv -> [Alt] -> Eval Value
evalDefaultAlt env [Adefault e] = evalExp globalEnv env e
evalExp globalEnv env (Coerce _ e) = evalExp globalEnv env e
evalExp globalEnv env (Note _ e) = evalExp globalEnv env e
evalExp globalEnv env (External s t) = evalExternal s []
evalExps :: Menv -> Venv -> [Exp] -> Eval [Value]
evalExps globalEnv env = mapM (evalExp globalEnv env)
suspendExp:: Menv -> Venv -> Exp -> Eval Value
suspendExp globalEnv env (Var qv) = return (qlookup globalEnv env qv)
suspendExp globalEnv env (Lit l) = return (Vimm (evalLit l))
suspendExp globalEnv env (Lam (Vb(x,_)) e) =
do p <- hallocateE (Hclos env' x e)
return (Vheap p)
where env' = thin env (delete x (freevarsExp e))
suspendExp globalEnv env (Lam _ e) = suspendExp globalEnv env e
suspendExp globalEnv env (Appt e _) = suspendExp globalEnv env e
suspendExp globalEnv env (Coerce _ e) = suspendExp globalEnv env e
suspendExp globalEnv env (Note _ e) = suspendExp globalEnv env e
suspendExp globalEnv env (External s _) = evalExternal s []
suspendExp globalEnv env e =
do p <- hallocateE (Hthunk env' e)
return (Vheap p)
where env' = thin env (freevarsExp e)
suspendExps :: Menv -> Venv -> [Exp] -> Eval [Value]
suspendExps globalEnv env = mapM (suspendExp globalEnv env)
mlookup :: Menv -> Venv -> Mname -> Venv
mlookup _ env "" = env
mlookup globalEnv _ m =
case elookup globalEnv m of
Just env' -> env'
Nothing -> error ("undefined module name: " ++ m)
qlookup :: Menv -> Venv -> (Mname,Var) -> Value
qlookup globalEnv env (m,k) =
case elookup (mlookup globalEnv env m) k of
Just v -> v
Nothing -> error ("undefined identifier: " ++ show m ++ "." ++ show k)
evalPrimop :: Var -> [Value] -> Eval Value
evalPrimop "zpzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = return (Vimm (PIntzh (i1+i2)))
evalPrimop "zmzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = return (Vimm (PIntzh (i1-i2)))
evalPrimop "ztzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = return (Vimm (PIntzh (i1*i2)))
evalPrimop "zgzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = mkBool (i1 > i2)
evalPrimop "remIntzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = return (Vimm (PIntzh (i1 `rem` i2)))
-- etc.
evalPrimop p vs = error ("undefined primop: " ++ p)
evalExternal :: String -> [Value] -> Eval Value
-- etc.
evalExternal s vs = error "evalExternal undefined for now" -- etc.,etc.
evalLit :: Lit -> PrimValue
evalLit l =
case l of
Lint i (Tcon(_,"Intzh")) -> PIntzh i
Lint i (Tcon(_,"Wordzh")) -> PWordzh i
Lint i (Tcon(_,"Addrzh")) -> PAddrzh i
Lint i (Tcon(_,"Charzh")) -> PCharzh i
Lrational r (Tcon(_,"Floatzh")) -> PFloatzh r
Lrational r (Tcon(_,"Doublezh")) -> PDoublezh r
Lchar c (Tcon(_,"Charzh")) -> PCharzh (toEnum (ord c))
Lstring s (Tcon(_,"Addrzh")) -> PAddrzh 0 -- should really be address of non-heap copy of C-format string s
Utilities
mkBool True =
do p <- hallocateE (Hconstr "ZdwTrue" [])
return (Vheap p)
mkBool False =
do p <- hallocateE (Hconstr "ZdwFalse" [])
return (Vheap p)
thin env vars = efilter env (`elem` vars)
{- Return the free non-external variables in an expression. -}
freevarsExp :: Exp -> [Var]
freevarsExp (Var ("",v)) = [v]
freevarsExp (Var qv) = []
freevarsExp (Dcon _) = []
freevarsExp (Lit _) = []
freevarsExp (App e1 e2) = freevarsExp e1 `union` freevarsExp e2
freevarsExp (Appt e t) = freevarsExp e
freevarsExp (Lam (Vb(v,_)) e) = delete v (freevarsExp e)
freevarsExp (Lam _ e) = freevarsExp e
freevarsExp (Let vdefg e) = freevarsVdefg vdefg `union` freevarsExp e
where freevarsVdefg (Rec vdefs) = (foldl union [] (map freevarsExp es)) \\ vs
where (vs,es) = unzip [(v,e) | Vdef((_,v),_,e) <- vdefs]
freevarsVdefg (Nonrec (Vdef (_,_,e))) = freevarsExp e
freevarsExp (Case e (v,_) as) = freevarsExp e `union` [v] `union` freevarsAlts as
where freevarsAlts alts = foldl union [] (map freevarsAlt alts)
freevarsAlt (Acon _ _ vbs e) = freevarsExp e \\ (map fst vbs)
freevarsAlt (Alit _ e) = freevarsExp e
freevarsAlt (Adefault e) = freevarsExp e
freevarsExp (Coerce _ e) = freevarsExp e
freevarsExp (Note _ e) = freevarsExp e
freevarsExp (External _ _) = []
| null | https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/utils/ext-core/Interp.hs | haskell | constructed value (note: no qualifier needed!)
function closure
unevaluated thunk
heap pointer (boxed)
immediate primitive value (unboxed)
unboxed tuples
values of vars
values of the (unboxed) primitive types
actually WORD_SIZE_IN_BITS-bit signed
actually WORD_SIZE_IN_BITS-bit unsigned
actually native pointer size
etc., etc.
modules
Nothing is said about garbage collection.
last cell allocated; environment of allocated cells
The evaluation monad manages the heap and the possiblity
of exceptions.
Main entry point
Environments:
Evaluating a module just fills an environment with suspensions for all
the external top-level values; it doesn't actually do any evaluation
or look anything up.
By the time we actually evaluate an expression, all external values from
all modules will be in globalEnv. So evaluation just maintains an environment
of non-external values (top-level or local). In particular, only non-external
values end up in closures (all other values are accessible from globalEnv.)
Throughout:
- globalEnv contains external values (all top-level) from all modules seen so far.
In evalModule:
- e_venv contains external values (all top-level) seen so far in current module
- l_venv contains non-external values (top-level or local)
seen so far in current module.
In evalExp:
- env contains non-external values (top-level or local) seen so far
in current expression.
can fail due to black-holing
black-hole
result is guaranteed to be boxed!
allocate a thunk
e must now evaluate to a closure
can fail due to black-holing
etc.
etc.
etc.,etc.
should really be address of non-heap copy of C-format string s
Return the free non-external variables in an expression. |
Interprets the subset of well - typed Core programs for which
( a ) All constructor and primop applications are saturated
( b ) All non - trivial expressions of unlifted kind ( ' # ' ) are
scrutinized in a Case expression .
This is by no means a " minimal " interpreter , in the sense that considerably
simpler machinary could be used to run programs and get the right answers .
However , it attempts to mirror the intended use of various Core constructs ,
particularly with respect to heap usage . So considerations such as unboxed
tuples , sharing , trimming , black - holing , etc . are all covered .
The only major omission is garbage collection .
Just a sampling of primitive types and operators are included .
Interprets the subset of well-typed Core programs for which
(a) All constructor and primop applications are saturated
(b) All non-trivial expressions of unlifted kind ('#') are
scrutinized in a Case expression.
This is by no means a "minimal" interpreter, in the sense that considerably
simpler machinary could be used to run programs and get the right answers.
However, it attempts to mirror the intended use of various Core constructs,
particularly with respect to heap usage. So considerations such as unboxed
tuples, sharing, trimming, black-holing, etc. are all covered.
The only major omission is garbage collection.
Just a sampling of primitive types and operators are included.
-}
module Interp where
import Core
import Printer
import Monad
import Env
import List
import Char
import Prims
data HeapValue =
deriving (Show)
type Ptr = Int
data Value =
deriving (Show)
actually 31 - bit unsigned
actually 32 - bit
actually 64 - bit
deriving (Eq,Show)
initialGlobalEnv :: Menv
initialGlobalEnv =
efromlist
[(primMname,efromlist [("realWorldzh",Vimm (PIntzh 0))])]
Heap management .
deriving (Show)
hallocate :: Heap -> HeapValue -> (Heap,Ptr)
hallocate (Heap last contents) v =
let next = last+1
in (Heap next (eextend contents (next,v)),next)
hupdate :: Heap -> Ptr -> HeapValue -> Heap
hupdate (Heap last contents) p v =
Heap last (eextend contents (p,v))
hlookup:: Heap -> Ptr -> HeapValue
hlookup (Heap _ contents) p =
case elookup contents p of
Just v -> v
Nothing -> error "Missing heap entry (black hole?)"
hremove :: Heap -> Ptr -> Heap
hremove (Heap last contents) p =
Heap last (eremove contents p)
hempty :: Heap
hempty = Heap 0 eempty
type Exn = Value
newtype Eval a = Eval (Heap -> (Heap,Either a Exn))
instance Monad Eval where
(Eval m) >>= k = Eval (
\h -> case m h of
(h',Left x) -> case k x of
Eval k' -> k' h'
(h',Right exn) -> (h',Right exn))
return x = Eval (\h -> (h,Left x))
hallocateE :: HeapValue -> Eval Ptr
hallocateE v = Eval (\ h ->
let (h',p) = hallocate h v
in (h', Left p))
hupdateE :: Ptr -> HeapValue -> Eval ()
hupdateE p v = Eval (\h -> (hupdate h p v,Left ()))
hlookupE :: Ptr -> Eval HeapValue
hlookupE p = Eval (\h -> (h,Left (hlookup h p)))
hremoveE :: Ptr -> Eval ()
hremoveE p = Eval (\h -> (hremove h p, Left ()))
raiseE :: Exn -> Eval a
raiseE exn = Eval (\h -> (h,Right exn))
catchE :: Eval a -> (Exn -> Eval a) -> Eval a
catchE (Eval m) f = Eval
(\h -> case m h of
(h',Left x) -> (h',Left x)
(h',Right exn) ->
case f exn of
Eval f' -> f' h')
runE :: Eval a -> a
runE (Eval f) =
case f hempty of
(_,Left v) -> v
(_,Right exn) -> error ("evaluation failed with uncaught exception: " ++ show exn)
evalProgram :: [Module] -> Value
evalProgram modules =
runE(
do globalEnv <- foldM evalModule initialGlobalEnv modules
Vutuple [_,v] <- evalExp globalEnv eempty (App (Var ("Main","main")) (Var (primMname,"realWorldzh")))
return v)
evalModule :: Menv -> Module -> Eval Menv
evalModule globalEnv (Module mn tdefs vdefgs) =
do (e_venv,l_venv) <- foldM evalVdef (eempty,eempty) vdefgs
return (eextend globalEnv (mn,e_venv))
where
evalVdef :: (Venv,Venv) -> Vdefg -> Eval (Venv,Venv)
evalVdef (e_env,l_env) (Nonrec(Vdef((m,x),t,e))) =
do p <- hallocateE (suspendExp l_env e)
let heaps =
if m == "" then
(e_env,eextend l_env (x,Vheap p))
else
(eextend e_env (x,Vheap p),l_env)
return heaps
evalVdef (e_env,l_env) (Rec vdefs) =
do l_vs0 <- mapM preallocate l_xs
let l_env' = foldl eextend l_env (zip l_xs l_vs0)
let l_hs = map (suspendExp l_env') l_es
mapM_ reallocate (zip l_vs0 l_hs)
let e_hs = map (suspendExp l_env') e_es
e_vs <- mapM allocate e_hs
let e_env' = foldl eextend e_env (zip e_xs e_vs)
return (e_env',l_env')
where
(l_xs,l_es) = unzip [(x,e) | Vdef(("",x),_,e) <- vdefs]
(e_xs,e_es) = unzip [(x,e) | Vdef((m,x),_,e) <- vdefs, m /= ""]
preallocate _ =
do p <- hallocateE undefined
return (Vheap p)
reallocate (Vheap p0,h) =
hupdateE p0 h
allocate h =
do p <- hallocateE h
return (Vheap p)
suspendExp:: Venv -> Exp -> HeapValue
suspendExp env (Lam (Vb(x,_)) e) = Hclos env' x e
where env' = thin env (delete x (freevarsExp e))
suspendExp env e = Hthunk env' e
where env' = thin env (freevarsExp e)
evalExp :: Menv -> Venv -> Exp -> Eval Value
evalExp globalEnv env (Var qv) =
let v = qlookup globalEnv env qv
in case v of
Vheap p ->
case z of
Hthunk env' e ->
h <- hlookupE p'
hupdateE p h
return w
return pointer to or Hconstr
return Vimm or
evalExp globalEnv env (Lit l) = return (Vimm (evalLit l))
evalExp globalEnv env (Dcon (_,c)) =
do p <- hallocateE (Hconstr c [])
return (Vheap p)
evalExp globalEnv env (App e1 e2) = evalApp env e1 [e2]
where
evalApp :: Venv -> Exp -> [Exp] -> Eval Value
evalApp env (App e1 e2) es = evalApp env e1 (e2:es)
evalApp env (op @(Dcon (qdc@(m,c)))) es =
do vs <- suspendExps globalEnv env es
if isUtupleDc qdc then
return (Vutuple vs)
else
do p <- hallocateE (Hconstr c vs)
return (Vheap p)
evalApp env (op @ (Var(m,p))) es | m == primMname =
do vs <- evalExps globalEnv env es
case (p,vs) of
("raisezh",[exn]) -> raiseE exn
("catchzh",[body,handler,rws]) ->
catchE (apply body [rws])
(\exn -> apply handler [exn,rws])
_ -> evalPrimop p vs
evalApp env (External s _) es =
do vs <- evalExps globalEnv env es
evalExternal s vs
evalApp env (Appt e _) es = evalApp env e es
evalApp env (Lam (Tb _) e) es = evalApp env e es
evalApp env (Coerce _ e) es = evalApp env e es
evalApp env (Note _ e) es = evalApp env e es
evalApp env e es =
do vs <- suspendExps globalEnv env es
vop <- evalExp globalEnv env e
apply vop vs
apply :: Value -> [Value] -> Eval Value
apply vop [] = return vop
apply (Vheap p) (v:vs) =
do Hclos env' x b <- hlookupE p
v' <- evalExp globalEnv (eextend env' (x,v)) b
apply v' vs
evalExp globalEnv env (Appt e _) = evalExp globalEnv env e
evalExp globalEnv env (Lam (Vb(x,_)) e) =
do p <- hallocateE (Hclos env' x e)
return (Vheap p)
where env' = thin env (delete x (freevarsExp e))
evalExp globalEnv env (Lam _ e) = evalExp globalEnv env e
evalExp globalEnv env (Let vdef e) =
do env' <- evalVdef globalEnv env vdef
evalExp globalEnv env' e
where
evalVdef :: Menv -> Venv -> Vdefg -> Eval Venv
evalVdef globalEnv env (Nonrec(Vdef((m,x),t,e))) =
do v <- suspendExp globalEnv env e
return (eextend env (x,v))
evalVdef globalEnv env (Rec vdefs) =
do vs0 <- mapM preallocate xs
let env' = foldl eextend env (zip xs vs0)
vs <- suspendExps globalEnv env' es
mapM_ reallocate (zip vs0 vs)
return env'
where
(xs,es) = unzip [(x,e) | Vdef((_,x),_,e) <- vdefs]
preallocate _ =
do p <- hallocateE (Hconstr "UGH" [])
return (Vheap p)
reallocate (Vheap p0,Vheap p) =
do h <- hlookupE p
hupdateE p0 h
evalExp globalEnv env (Case e (x,_) alts) =
do z <- evalExp globalEnv env e
let env' = eextend env (x,z)
case z of
Vheap p ->
case h of
Hconstr dcon vs -> evalDcAlt env' dcon vs (reverse alts)
_ -> evalDefaultAlt env' alts
Vutuple vs ->
evalUtupleAlt env' vs (reverse alts)
Vimm pv ->
evalLitAlt env' pv (reverse alts)
where
evalDcAlt :: Venv -> Dcon -> [Value] -> [Alt] -> Eval Value
evalDcAlt env dcon vs alts =
f alts
where
f ((Acon (_,dcon') _ xs e):as) =
if dcon == dcon' then
evalExp globalEnv (foldl eextend env (zip (map fst xs) vs)) e
else f as
f [Adefault e] =
evalExp globalEnv env e
f _ = error "impossible Case-evalDcAlt"
evalUtupleAlt :: Venv -> [Value] -> [Alt] -> Eval Value
evalUtupleAlt env vs [Acon _ _ xs e] =
evalExp globalEnv (foldl eextend env (zip (map fst xs) vs)) e
evalLitAlt :: Venv -> PrimValue -> [Alt] -> Eval Value
evalLitAlt env pv alts =
f alts
where
f ((Alit lit e):as) =
let pv' = evalLit lit
in if pv == pv' then
evalExp globalEnv env e
else f as
f [Adefault e] =
evalExp globalEnv env e
f _ = error "impossible Case-evalLitAlt"
evalDefaultAlt :: Venv -> [Alt] -> Eval Value
evalDefaultAlt env [Adefault e] = evalExp globalEnv env e
evalExp globalEnv env (Coerce _ e) = evalExp globalEnv env e
evalExp globalEnv env (Note _ e) = evalExp globalEnv env e
evalExp globalEnv env (External s t) = evalExternal s []
evalExps :: Menv -> Venv -> [Exp] -> Eval [Value]
evalExps globalEnv env = mapM (evalExp globalEnv env)
suspendExp:: Menv -> Venv -> Exp -> Eval Value
suspendExp globalEnv env (Var qv) = return (qlookup globalEnv env qv)
suspendExp globalEnv env (Lit l) = return (Vimm (evalLit l))
suspendExp globalEnv env (Lam (Vb(x,_)) e) =
do p <- hallocateE (Hclos env' x e)
return (Vheap p)
where env' = thin env (delete x (freevarsExp e))
suspendExp globalEnv env (Lam _ e) = suspendExp globalEnv env e
suspendExp globalEnv env (Appt e _) = suspendExp globalEnv env e
suspendExp globalEnv env (Coerce _ e) = suspendExp globalEnv env e
suspendExp globalEnv env (Note _ e) = suspendExp globalEnv env e
suspendExp globalEnv env (External s _) = evalExternal s []
suspendExp globalEnv env e =
do p <- hallocateE (Hthunk env' e)
return (Vheap p)
where env' = thin env (freevarsExp e)
suspendExps :: Menv -> Venv -> [Exp] -> Eval [Value]
suspendExps globalEnv env = mapM (suspendExp globalEnv env)
mlookup :: Menv -> Venv -> Mname -> Venv
mlookup _ env "" = env
mlookup globalEnv _ m =
case elookup globalEnv m of
Just env' -> env'
Nothing -> error ("undefined module name: " ++ m)
qlookup :: Menv -> Venv -> (Mname,Var) -> Value
qlookup globalEnv env (m,k) =
case elookup (mlookup globalEnv env m) k of
Just v -> v
Nothing -> error ("undefined identifier: " ++ show m ++ "." ++ show k)
evalPrimop :: Var -> [Value] -> Eval Value
evalPrimop "zpzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = return (Vimm (PIntzh (i1+i2)))
evalPrimop "zmzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = return (Vimm (PIntzh (i1-i2)))
evalPrimop "ztzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = return (Vimm (PIntzh (i1*i2)))
evalPrimop "zgzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = mkBool (i1 > i2)
evalPrimop "remIntzh" [Vimm (PIntzh i1),Vimm (PIntzh i2)] = return (Vimm (PIntzh (i1 `rem` i2)))
evalPrimop p vs = error ("undefined primop: " ++ p)
evalExternal :: String -> [Value] -> Eval Value
evalLit :: Lit -> PrimValue
evalLit l =
case l of
Lint i (Tcon(_,"Intzh")) -> PIntzh i
Lint i (Tcon(_,"Wordzh")) -> PWordzh i
Lint i (Tcon(_,"Addrzh")) -> PAddrzh i
Lint i (Tcon(_,"Charzh")) -> PCharzh i
Lrational r (Tcon(_,"Floatzh")) -> PFloatzh r
Lrational r (Tcon(_,"Doublezh")) -> PDoublezh r
Lchar c (Tcon(_,"Charzh")) -> PCharzh (toEnum (ord c))
Utilities
mkBool True =
do p <- hallocateE (Hconstr "ZdwTrue" [])
return (Vheap p)
mkBool False =
do p <- hallocateE (Hconstr "ZdwFalse" [])
return (Vheap p)
thin env vars = efilter env (`elem` vars)
freevarsExp :: Exp -> [Var]
freevarsExp (Var ("",v)) = [v]
freevarsExp (Var qv) = []
freevarsExp (Dcon _) = []
freevarsExp (Lit _) = []
freevarsExp (App e1 e2) = freevarsExp e1 `union` freevarsExp e2
freevarsExp (Appt e t) = freevarsExp e
freevarsExp (Lam (Vb(v,_)) e) = delete v (freevarsExp e)
freevarsExp (Lam _ e) = freevarsExp e
freevarsExp (Let vdefg e) = freevarsVdefg vdefg `union` freevarsExp e
where freevarsVdefg (Rec vdefs) = (foldl union [] (map freevarsExp es)) \\ vs
where (vs,es) = unzip [(v,e) | Vdef((_,v),_,e) <- vdefs]
freevarsVdefg (Nonrec (Vdef (_,_,e))) = freevarsExp e
freevarsExp (Case e (v,_) as) = freevarsExp e `union` [v] `union` freevarsAlts as
where freevarsAlts alts = foldl union [] (map freevarsAlt alts)
freevarsAlt (Acon _ _ vbs e) = freevarsExp e \\ (map fst vbs)
freevarsAlt (Alit _ e) = freevarsExp e
freevarsAlt (Adefault e) = freevarsExp e
freevarsExp (Coerce _ e) = freevarsExp e
freevarsExp (Note _ e) = freevarsExp e
freevarsExp (External _ _) = []
|
ac1bee5d7543279d51e7e2bc4d67b2ebfe73a6a80caff96c989ab02eca9b186f | AndrewMagerman/wizard-book-study | obj-harun.rkt | ;;#lang simply-scheme
obj.scm version 4.0 5/18/2000
;;; -- implementation of the object-oriented syntax
By , based on a handout from MIT
Revised for STk by - removed scm and procedure->macro
Utilities
MAKNAM : create a new symbol whose name is the concatenation of the
names of those in the symbol list SYMBOLS .
(define (maknam . symbols)
(string->symbol (apply string-append (map symbol->string symbols))))
ASK : send a message to an object
The dot in the first line of the definition of ASK , below , makes it
take a variable number of arguments . The first argument is associated
with the formal parameter OBJECT ; the second with MESSAGE ; any extra
; actual arguments are put in a list, and that list is associated with
the formal parameter ARGS . ( If there are only two actual args , then
; ARGS will be the empty list.)
APPLY takes two arguments , a procedure and a list , and applies the
; procedure to the things in the list, which are used as actual
; argument values.
(define (ask object message . args)
(let ((method (object message)))
(if (method? method)
(apply method args)
(error "No method " message " in class " (cadr method)))))
(define (no-method name)
(list 'no-method name))
(define (no-method? x)
(if (pair? x)
(eq? (car x) 'no-method)
#f))
(define (method? x)
(not (no-method? x)))
INSTANTIATE and INSTANTIATE - PARENT : Create an instance of a class
; The difference is that only INSTANTIATE initializes the new object
(define (instantiate class . arguments)
(let ((new-instance (apply (class 'instantiate) arguments)))
(ask new-instance 'initialize new-instance)
new-instance))
(define (instantiate-parent class . arguments)
(apply (class 'instantiate) arguments))
GET - METHOD : Send a message to several objects and return the first
;; method found (for multiple inheritance)
(define (get-method give-up-name message . objects)
(if (null? objects)
(no-method give-up-name)
(let ((method ((car objects) message)))
(if (method? method)
method
(apply get-method (cons give-up-name
(cons message (cdr objects)) ))))))
;; USUAL: Invoke a parent's method
;; Note: The 'send-usual-to-parent method is put in automatically by
;; define-class.
(define-macro (usual . args)
'(ask dispatch 'send-usual-to-parent . ,args))
;; DEFINE-CLASS: Create a new class.
; DEFINE-CLASS is a special form. When you type (define-class body...)
; it's as if you typed (make-definitions (quote body...)). In other
; words, the argument to DEFINE-CLASS isn't evaluated. This makes sense
; because the argument isn't Scheme syntax, but rather is the special
; object-oriented programming language we're defining.
; Make-definitions transforms the OOP notation into a standard Scheme
expression , then uses EVAL to evaluate the result . ( You 'll see
again in chapter 4 with the metacircular evaluator . )
When you define a class named THING , for example , two global Scheme
; variables are created. The variable THING has as its value the
; procedure that represents the class. This procedure is invoked by
INSTANTIATE to create instances of the class . A second variable ,
; THING-DEFINITION, has as its value the text of the Scheme expression
; that defines THING. This text is used only by SHOW-CLASS, the
; procedure that lets you examine the result of the OOP-to-Scheme
; translation process.
(define-macro (define-class . body) (make-definitions body))
(define (make-definitions form)
(let ((definition (translate form)))
(eval `(define ,(maknam (class-name form) '-definition) ',definition))
(eval definition)
(list 'quote (class-name form))))
(define (show-class name)
(eval (maknam name '-definition)) )
; TRANSLATE does all the work of DEFINE-CLASS.
; The backquote operator (`) works just like regular quote (') except
; that expressions proceeded by a comma are evaluated. Also, expressions
; proceeded by ",@" evaluate to lists; the lists are inserted into the
; text without the outermost level of parentheses.
(define (translate form)
(cond ((null? form) (error "Define-class: empty body"))
((not (null? (obj-filter form (lambda (x) (not (pair? x))))))
(error "Each argument to define-class must be a list"))
((not (null? (extra-clauses form)))
(error "Unrecognized clause in define-class:" (extra-clauses form)))
(else
`(define ,(class-name form)
(let ,(class-var-bindings form)
(lambda (class-message)
(cond
,@(class-variable-methods form)
((eq? class-message 'instantiate)
(lambda ,(instantiation-vars form)
(let ((self '())
,@(parent-let-list form)
,@(instance-vars-let-list form))
(define (dispatch message)
(cond
,(init-clause form)
,(usual-clause form)
,@(method-clauses form)
,@(local-variable-methods form)
,(else-clause form) ))
dispatch )))
(else (error "Bad message to class" class-message)) )))))))
(define *legal-clauses*
'(instance-vars class-vars method default-method parent initialize))
(define (extra-clauses form)
(obj-filter (cdr form)
(lambda (x) (null? (member (car x) *legal-clauses*)))))
(define class-name caar)
(define (class-var-bindings form)
(let ((classvar-clause (find-a-clause 'class-vars form)))
(if (null? classvar-clause)
'()
(cdr classvar-clause) )))
(define instantiation-vars cdar)
(define (parent-let-list form)
(let ((parent-clause (find-a-clause 'parent form)))
(if (null? parent-clause)
'()
(map (lambda (parent-and-args)
(list (maknam 'my- (car parent-and-args))
(cons 'instantiate-parent parent-and-args)))
(cdr parent-clause)))))
(define (instance-vars-let-list form)
(let ((instance-vars-clause (find-a-clause 'instance-vars form)))
(if (null? instance-vars-clause)
'()
(cdr instance-vars-clause))))
(define (init-clause form)
(define (parent-initialization form)
(let ((parent-clause (find-a-clause 'parent form)))
(if (null? parent-clause)
'()
(map
(lambda (parent-and-args)
`(ask ,(maknam 'my- (car parent-and-args)) 'initialize self) )
(cdr parent-clause) ))))
(define (my-initialization form)
(let ((init-clause (find-a-clause 'initialize form)))
(if (null? init-clause) '()
(cdr init-clause))))
(define (init-body form)
(append (parent-initialization form)
(my-initialization form) ))
`((eq? message 'initialize)
(lambda (value-for-self)
(set! self value-for-self)
,@(init-body form) )))
(define (variable-list var-type form)
(let ((clause (find-a-clause var-type form)))
(if (null? clause)
'()
(map car (cdr clause)) )))
(define (class-variable-methods form)
(cons `((eq? class-message 'class-name) (lambda () ',(class-name form)))
(map (lambda (variable)
`((eq? class-message ',variable) (lambda () ,variable)))
(variable-list 'class-vars form))))
(define (local-variable-methods form)
(cons `((eq? message 'class-name) (lambda () ',(class-name form)))
(map (lambda (variable)
`((eq? message ',variable) (lambda () ,variable)))
(append (cdr (car form))
(variable-list 'instance-vars form)
(variable-list 'class-vars form)))))
(define (method-clauses form)
(map
(lambda (method-defn)
(let ((this-message (car (cadr method-defn)))
(args (cdr (cadr method-defn)))
(body (cddr method-defn)))
`((eq? message ',this-message)
(lambda ,args ,@body))))
(obj-filter (cdr form) (lambda (x) (eq? (car x) 'method))) ))
(define (parent-list form)
(let ((parent-clause (find-a-clause 'parent form)))
(if (null? parent-clause)
'()
(map (lambda (class) (maknam 'my- class))
(map car (cdr parent-clause))))))
(define (usual-clause form)
(let ((parent-clause (find-a-clause 'parent form)))
(if (null? parent-clause)
`((eq? message 'send-usual-to-parent)
(error "Can't use USUAL without a parent." ',(class-name form)))
`((eq? message 'send-usual-to-parent)
(lambda (message . args)
(let ((method (get-method ',(class-name form)
message
,@(parent-list form))))
(if (method? method)
(apply method args)
(error "No USUAL method" message ',(class-name form)) )))))))
(define (else-clause form)
(let ((parent-clause (find-a-clause 'parent form))
(default-method (find-a-clause 'default-method form)))
(cond
((and (null? parent-clause) (null? default-method))
`(else (no-method ',(class-name form))))
((null? parent-clause)
`(else (lambda args ,@(cdr default-method))))
((null? default-method)
`(else (get-method ',(class-name form) message ,@(parent-list form))) )
(else
`(else (let ((method (get-method ',(class-name form)
message
,@(parent-list form))))
(if (method? method)
method
(lambda args ,@(cdr default-method)) )))))))
(define (find-a-clause clause-name form)
(let ((clauses (obj-filter (cdr form)
(lambda (x) (eq? (car x) clause-name)))))
(cond ((null? clauses) '())
((null? (cdr clauses)) (car clauses))
(else (error "Error in define-class: too many "
clause-name "clauses.")) )))
(define (obj-filter l pred)
(cond ((null? l) '())
((pred (car l))
(cons (car l) (obj-filter (cdr l) pred)))
(else (obj-filter (cdr l) pred))))
(provide "obj")
| null | https://raw.githubusercontent.com/AndrewMagerman/wizard-book-study/01f777f6d73967361eabcdacf6c6f69d73cc244d/missing_files/project_4/obj-harun.rkt | racket | #lang simply-scheme
-- implementation of the object-oriented syntax
the second with MESSAGE ; any extra
actual arguments are put in a list, and that list is associated with
ARGS will be the empty list.)
procedure to the things in the list, which are used as actual
argument values.
The difference is that only INSTANTIATE initializes the new object
method found (for multiple inheritance)
USUAL: Invoke a parent's method
Note: The 'send-usual-to-parent method is put in automatically by
define-class.
DEFINE-CLASS: Create a new class.
DEFINE-CLASS is a special form. When you type (define-class body...)
it's as if you typed (make-definitions (quote body...)). In other
words, the argument to DEFINE-CLASS isn't evaluated. This makes sense
because the argument isn't Scheme syntax, but rather is the special
object-oriented programming language we're defining.
Make-definitions transforms the OOP notation into a standard Scheme
variables are created. The variable THING has as its value the
procedure that represents the class. This procedure is invoked by
THING-DEFINITION, has as its value the text of the Scheme expression
that defines THING. This text is used only by SHOW-CLASS, the
procedure that lets you examine the result of the OOP-to-Scheme
translation process.
TRANSLATE does all the work of DEFINE-CLASS.
The backquote operator (`) works just like regular quote (') except
that expressions proceeded by a comma are evaluated. Also, expressions
proceeded by ",@" evaluate to lists; the lists are inserted into the
text without the outermost level of parentheses. | obj.scm version 4.0 5/18/2000
By , based on a handout from MIT
Revised for STk by - removed scm and procedure->macro
Utilities
MAKNAM : create a new symbol whose name is the concatenation of the
names of those in the symbol list SYMBOLS .
(define (maknam . symbols)
(string->symbol (apply string-append (map symbol->string symbols))))
ASK : send a message to an object
The dot in the first line of the definition of ASK , below , makes it
take a variable number of arguments . The first argument is associated
the formal parameter ARGS . ( If there are only two actual args , then
APPLY takes two arguments , a procedure and a list , and applies the
(define (ask object message . args)
(let ((method (object message)))
(if (method? method)
(apply method args)
(error "No method " message " in class " (cadr method)))))
(define (no-method name)
(list 'no-method name))
(define (no-method? x)
(if (pair? x)
(eq? (car x) 'no-method)
#f))
(define (method? x)
(not (no-method? x)))
INSTANTIATE and INSTANTIATE - PARENT : Create an instance of a class
(define (instantiate class . arguments)
(let ((new-instance (apply (class 'instantiate) arguments)))
(ask new-instance 'initialize new-instance)
new-instance))
(define (instantiate-parent class . arguments)
(apply (class 'instantiate) arguments))
GET - METHOD : Send a message to several objects and return the first
(define (get-method give-up-name message . objects)
(if (null? objects)
(no-method give-up-name)
(let ((method ((car objects) message)))
(if (method? method)
method
(apply get-method (cons give-up-name
(cons message (cdr objects)) ))))))
(define-macro (usual . args)
'(ask dispatch 'send-usual-to-parent . ,args))
expression , then uses EVAL to evaluate the result . ( You 'll see
again in chapter 4 with the metacircular evaluator . )
When you define a class named THING , for example , two global Scheme
INSTANTIATE to create instances of the class . A second variable ,
(define-macro (define-class . body) (make-definitions body))
(define (make-definitions form)
(let ((definition (translate form)))
(eval `(define ,(maknam (class-name form) '-definition) ',definition))
(eval definition)
(list 'quote (class-name form))))
(define (show-class name)
(eval (maknam name '-definition)) )
(define (translate form)
(cond ((null? form) (error "Define-class: empty body"))
((not (null? (obj-filter form (lambda (x) (not (pair? x))))))
(error "Each argument to define-class must be a list"))
((not (null? (extra-clauses form)))
(error "Unrecognized clause in define-class:" (extra-clauses form)))
(else
`(define ,(class-name form)
(let ,(class-var-bindings form)
(lambda (class-message)
(cond
,@(class-variable-methods form)
((eq? class-message 'instantiate)
(lambda ,(instantiation-vars form)
(let ((self '())
,@(parent-let-list form)
,@(instance-vars-let-list form))
(define (dispatch message)
(cond
,(init-clause form)
,(usual-clause form)
,@(method-clauses form)
,@(local-variable-methods form)
,(else-clause form) ))
dispatch )))
(else (error "Bad message to class" class-message)) )))))))
(define *legal-clauses*
'(instance-vars class-vars method default-method parent initialize))
(define (extra-clauses form)
(obj-filter (cdr form)
(lambda (x) (null? (member (car x) *legal-clauses*)))))
(define class-name caar)
(define (class-var-bindings form)
(let ((classvar-clause (find-a-clause 'class-vars form)))
(if (null? classvar-clause)
'()
(cdr classvar-clause) )))
(define instantiation-vars cdar)
(define (parent-let-list form)
(let ((parent-clause (find-a-clause 'parent form)))
(if (null? parent-clause)
'()
(map (lambda (parent-and-args)
(list (maknam 'my- (car parent-and-args))
(cons 'instantiate-parent parent-and-args)))
(cdr parent-clause)))))
(define (instance-vars-let-list form)
(let ((instance-vars-clause (find-a-clause 'instance-vars form)))
(if (null? instance-vars-clause)
'()
(cdr instance-vars-clause))))
(define (init-clause form)
(define (parent-initialization form)
(let ((parent-clause (find-a-clause 'parent form)))
(if (null? parent-clause)
'()
(map
(lambda (parent-and-args)
`(ask ,(maknam 'my- (car parent-and-args)) 'initialize self) )
(cdr parent-clause) ))))
(define (my-initialization form)
(let ((init-clause (find-a-clause 'initialize form)))
(if (null? init-clause) '()
(cdr init-clause))))
(define (init-body form)
(append (parent-initialization form)
(my-initialization form) ))
`((eq? message 'initialize)
(lambda (value-for-self)
(set! self value-for-self)
,@(init-body form) )))
(define (variable-list var-type form)
(let ((clause (find-a-clause var-type form)))
(if (null? clause)
'()
(map car (cdr clause)) )))
(define (class-variable-methods form)
(cons `((eq? class-message 'class-name) (lambda () ',(class-name form)))
(map (lambda (variable)
`((eq? class-message ',variable) (lambda () ,variable)))
(variable-list 'class-vars form))))
(define (local-variable-methods form)
(cons `((eq? message 'class-name) (lambda () ',(class-name form)))
(map (lambda (variable)
`((eq? message ',variable) (lambda () ,variable)))
(append (cdr (car form))
(variable-list 'instance-vars form)
(variable-list 'class-vars form)))))
(define (method-clauses form)
(map
(lambda (method-defn)
(let ((this-message (car (cadr method-defn)))
(args (cdr (cadr method-defn)))
(body (cddr method-defn)))
`((eq? message ',this-message)
(lambda ,args ,@body))))
(obj-filter (cdr form) (lambda (x) (eq? (car x) 'method))) ))
(define (parent-list form)
(let ((parent-clause (find-a-clause 'parent form)))
(if (null? parent-clause)
'()
(map (lambda (class) (maknam 'my- class))
(map car (cdr parent-clause))))))
(define (usual-clause form)
(let ((parent-clause (find-a-clause 'parent form)))
(if (null? parent-clause)
`((eq? message 'send-usual-to-parent)
(error "Can't use USUAL without a parent." ',(class-name form)))
`((eq? message 'send-usual-to-parent)
(lambda (message . args)
(let ((method (get-method ',(class-name form)
message
,@(parent-list form))))
(if (method? method)
(apply method args)
(error "No USUAL method" message ',(class-name form)) )))))))
(define (else-clause form)
(let ((parent-clause (find-a-clause 'parent form))
(default-method (find-a-clause 'default-method form)))
(cond
((and (null? parent-clause) (null? default-method))
`(else (no-method ',(class-name form))))
((null? parent-clause)
`(else (lambda args ,@(cdr default-method))))
((null? default-method)
`(else (get-method ',(class-name form) message ,@(parent-list form))) )
(else
`(else (let ((method (get-method ',(class-name form)
message
,@(parent-list form))))
(if (method? method)
method
(lambda args ,@(cdr default-method)) )))))))
(define (find-a-clause clause-name form)
(let ((clauses (obj-filter (cdr form)
(lambda (x) (eq? (car x) clause-name)))))
(cond ((null? clauses) '())
((null? (cdr clauses)) (car clauses))
(else (error "Error in define-class: too many "
clause-name "clauses.")) )))
(define (obj-filter l pred)
(cond ((null? l) '())
((pred (car l))
(cons (car l) (obj-filter (cdr l) pred)))
(else (obj-filter (cdr l) pred))))
(provide "obj")
|
23a07bea7fe3ed5ff343e26f457fe47aac9e85c2b75e9ab1f76918374d23fcc4 | roelvandijk/numerals | OJI.hs | |
[ @ISO639 - 1@ ] oj
[ @ISO639 - 2@ ] oji
[ @ISO639 - 3@ ] oji
[ @Native name@ ] ᐊᓂᔑᓈᐯᒧᐎᓐ ( )
[ @English name@ ] Ojibwe
[@ISO639-1@] oj
[@ISO639-2@] oji
[@ISO639-3@] oji
[@Native name@] ᐊᓂᔑᓈᐯᒧᐎᓐ (Anishinaabemowin)
[@English name@] Ojibwe
-}
module Text.Numeral.Language.OJI
( -- * Language entry
entry
-- * Conversions
, cardinal
-- * Structure
, struct
-- * Bounds
, bounds
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
import "base" Data.Function ( fix )
import qualified "containers" Data.Map as M ( fromList, lookup )
import "this" Text.Numeral
import "this" Text.Numeral.Entry
import "text" Data.Text ( Text )
--------------------------------------------------------------------------------
OJ
--------------------------------------------------------------------------------
entry :: Entry
entry = emptyEntry
{ entIso639_1 = Just "oj"
, entIso639_2 = ["oji"]
, entIso639_3 = Just "oji"
, entNativeNames = ["ᐊᓂᔑᓈᐯᒧᐎᓐ", "Anishinaabemowin"]
, entEnglishName = Just "Ojibwe"
, entCardinal = Just Conversion
{ toNumeral = cardinal
, toStructure = struct
}
}
cardinal :: (Integral a) => Inflection -> a -> Maybe Text
cardinal inf = cardinalRepr inf . struct
struct :: (Integral a) => a -> Exp
struct = checkPos
$ fix
$ findRule ( 1, lit )
[ ( 11, step 10 10 R L)
, ( 100, step 100 10 R L)
, (1000, step 1000 2 R L)
]
1999
bounds :: (Integral a) => (a, a)
bounds = (1, 1999)
cardinalRepr :: Inflection -> Exp -> Maybe Text
cardinalRepr = render defaultRepr
{ reprValue = \_ n -> M.lookup n syms
, reprAdd = Just $ \_ _ _ -> " shaa "
, reprMul = Just $ \_ _ _ -> ""
}
where
syms =
M.fromList
[ (0, const "kaagego" )
, (1, const "bezhik" )
, (2, const "niizh" )
, (3, forms "nswi" "nsim" "ns" )
, (4, forms "niiwin" "niim" "nii" )
, (5, forms "naanan" "naanmi" "naan" )
, (6, forms "ngodwaaswi" "ngodwaasmi" "ngodwaas" )
, (7, forms "niizhwaaswi" "niizhwaasmi" "niizhwaas")
, (8, forms "nshwaaswi" "nshwaasmi" "nshwaas" )
, (9, forms "zhaangswi" "zhaangsmi" "zhaangs" )
, (10, \c -> case c of
CtxMul {} -> "taana"
_ -> "mdaaswi"
)
, (100, \c -> case c of
CtxMul {} -> "waak"
_ -> "ngodwaak"
)
, (1000, const "mdaaswaak")
]
forms :: s -> s -> s -> Ctx Exp -> s
forms o t h = \c -> case c of
CtxMul _ (Lit 10) _ -> t
CtxMul _ (Lit 100) _ -> h
_ -> o
| null | https://raw.githubusercontent.com/roelvandijk/numerals/b1e4121e0824ac0646a3230bd311818e159ec127/src/Text/Numeral/Language/OJI.hs | haskell | * Language entry
* Conversions
* Structure
* Bounds
------------------------------------------------------------------------------
Imports
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------ | |
[ @ISO639 - 1@ ] oj
[ @ISO639 - 2@ ] oji
[ @ISO639 - 3@ ] oji
[ @Native name@ ] ᐊᓂᔑᓈᐯᒧᐎᓐ ( )
[ @English name@ ] Ojibwe
[@ISO639-1@] oj
[@ISO639-2@] oji
[@ISO639-3@] oji
[@Native name@] ᐊᓂᔑᓈᐯᒧᐎᓐ (Anishinaabemowin)
[@English name@] Ojibwe
-}
module Text.Numeral.Language.OJI
entry
, cardinal
, struct
, bounds
) where
import "base" Data.Function ( fix )
import qualified "containers" Data.Map as M ( fromList, lookup )
import "this" Text.Numeral
import "this" Text.Numeral.Entry
import "text" Data.Text ( Text )
OJ
entry :: Entry
entry = emptyEntry
{ entIso639_1 = Just "oj"
, entIso639_2 = ["oji"]
, entIso639_3 = Just "oji"
, entNativeNames = ["ᐊᓂᔑᓈᐯᒧᐎᓐ", "Anishinaabemowin"]
, entEnglishName = Just "Ojibwe"
, entCardinal = Just Conversion
{ toNumeral = cardinal
, toStructure = struct
}
}
cardinal :: (Integral a) => Inflection -> a -> Maybe Text
cardinal inf = cardinalRepr inf . struct
struct :: (Integral a) => a -> Exp
struct = checkPos
$ fix
$ findRule ( 1, lit )
[ ( 11, step 10 10 R L)
, ( 100, step 100 10 R L)
, (1000, step 1000 2 R L)
]
1999
bounds :: (Integral a) => (a, a)
bounds = (1, 1999)
cardinalRepr :: Inflection -> Exp -> Maybe Text
cardinalRepr = render defaultRepr
{ reprValue = \_ n -> M.lookup n syms
, reprAdd = Just $ \_ _ _ -> " shaa "
, reprMul = Just $ \_ _ _ -> ""
}
where
syms =
M.fromList
[ (0, const "kaagego" )
, (1, const "bezhik" )
, (2, const "niizh" )
, (3, forms "nswi" "nsim" "ns" )
, (4, forms "niiwin" "niim" "nii" )
, (5, forms "naanan" "naanmi" "naan" )
, (6, forms "ngodwaaswi" "ngodwaasmi" "ngodwaas" )
, (7, forms "niizhwaaswi" "niizhwaasmi" "niizhwaas")
, (8, forms "nshwaaswi" "nshwaasmi" "nshwaas" )
, (9, forms "zhaangswi" "zhaangsmi" "zhaangs" )
, (10, \c -> case c of
CtxMul {} -> "taana"
_ -> "mdaaswi"
)
, (100, \c -> case c of
CtxMul {} -> "waak"
_ -> "ngodwaak"
)
, (1000, const "mdaaswaak")
]
forms :: s -> s -> s -> Ctx Exp -> s
forms o t h = \c -> case c of
CtxMul _ (Lit 10) _ -> t
CtxMul _ (Lit 100) _ -> h
_ -> o
|
627d56c942e7213015d01aac0670fef7ba951b6735ba6fdcb005317999499a2a | danlarkin/subrosa | database.clj | (ns subrosa.database
(:refer-clojure :exclude [get])
(:import (java.util UUID)))
(defonce ^:dynamic db (ref {}))
(defn ensure-id [m]
(if (:id m)
m
(assoc m :id (str (UUID/randomUUID)))))
(defn add-index* [db table field-or-fields opts]
(update-in db [table :indices] assoc field-or-fields opts))
(defn add-index [table field-or-fields & {:as opts}]
(dosync
(alter db add-index* table field-or-fields opts)))
(defn get-indices* [db table]
(assoc (get-in db [table :indices]) :id {}))
(defn get-indices [table]
(dosync
(get-indices* @db table)))
(defn get*
([db table]
(set (vals (get-in db [table :data :id]))))
([db table column value]
(get-in db [table :data column value])))
(defn get
([table]
(get* @db table))
([table column value]
(get* @db table column value)))
(defn select-from-indices [db table m]
(into {} (for [[index opts] (get-indices* db table)]
[index {:opts opts
:data (if (coll? index)
(map m index)
(m index))}])))
(defn dissoc-if-empty [m ks]
(if (empty? (get-in m ks))
(update-in m (butlast ks) dissoc (last ks))
m))
(defn delete* [db table id]
(let [m (get* db table :id id)]
(update-in db [table] assoc
:data (reduce (fn [a [index {:keys [opts data]}]]
(if (:list opts)
(-> a
(update-in [index data] disj m)
(dissoc-if-empty [index data]))
(update-in a [index] dissoc data)))
(get-in db [table :data])
(select-from-indices db table (or m {}))))))
(defn delete [table id]
(dosync
(alter db delete* table id)))
(defn put* [db table m]
(update-in db [table] assoc
:data (reduce (fn [a [index {:keys [opts data]}]]
(if (:list opts)
(update-in a [index data] (comp set conj) m)
(update-in a [index] assoc data m)))
(get-in db [table :data])
(select-from-indices db table m))))
(defn put [table m]
(dosync
(let [m (ensure-id m)]
(alter db (fn [db]
(-> db
(delete* table (:id m))
(put* table m)))))))
| null | https://raw.githubusercontent.com/danlarkin/subrosa/b8e554ffc1b83572acbbb8f50704d3db44b3770f/src/subrosa/database.clj | clojure | (ns subrosa.database
(:refer-clojure :exclude [get])
(:import (java.util UUID)))
(defonce ^:dynamic db (ref {}))
(defn ensure-id [m]
(if (:id m)
m
(assoc m :id (str (UUID/randomUUID)))))
(defn add-index* [db table field-or-fields opts]
(update-in db [table :indices] assoc field-or-fields opts))
(defn add-index [table field-or-fields & {:as opts}]
(dosync
(alter db add-index* table field-or-fields opts)))
(defn get-indices* [db table]
(assoc (get-in db [table :indices]) :id {}))
(defn get-indices [table]
(dosync
(get-indices* @db table)))
(defn get*
([db table]
(set (vals (get-in db [table :data :id]))))
([db table column value]
(get-in db [table :data column value])))
(defn get
([table]
(get* @db table))
([table column value]
(get* @db table column value)))
(defn select-from-indices [db table m]
(into {} (for [[index opts] (get-indices* db table)]
[index {:opts opts
:data (if (coll? index)
(map m index)
(m index))}])))
(defn dissoc-if-empty [m ks]
(if (empty? (get-in m ks))
(update-in m (butlast ks) dissoc (last ks))
m))
(defn delete* [db table id]
(let [m (get* db table :id id)]
(update-in db [table] assoc
:data (reduce (fn [a [index {:keys [opts data]}]]
(if (:list opts)
(-> a
(update-in [index data] disj m)
(dissoc-if-empty [index data]))
(update-in a [index] dissoc data)))
(get-in db [table :data])
(select-from-indices db table (or m {}))))))
(defn delete [table id]
(dosync
(alter db delete* table id)))
(defn put* [db table m]
(update-in db [table] assoc
:data (reduce (fn [a [index {:keys [opts data]}]]
(if (:list opts)
(update-in a [index data] (comp set conj) m)
(update-in a [index] assoc data m)))
(get-in db [table :data])
(select-from-indices db table m))))
(defn put [table m]
(dosync
(let [m (ensure-id m)]
(alter db (fn [db]
(-> db
(delete* table (:id m))
(put* table m)))))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.