_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
|
---|---|---|---|---|---|---|---|---|
1899db247a0f29e5a7a06decc67127714fe90d669ca5df0ae63be8b5b311b86b | typelead/eta | T9951.hs | # LANGUAGE OverloadedLists #
# OPTIONS_GHC -fwarn - incomplete - patterns -fwarn - overlapping - patterns #
module T9951 where
f :: [a] -> ()
f x = case x of
[] -> ()
(_:_) -> ()
| null | https://raw.githubusercontent.com/typelead/eta/97ee2251bbc52294efbf60fa4342ce6f52c0d25c/tests/suite/pmcheck/compile/T9951.hs | haskell | # LANGUAGE OverloadedLists #
# OPTIONS_GHC -fwarn - incomplete - patterns -fwarn - overlapping - patterns #
module T9951 where
f :: [a] -> ()
f x = case x of
[] -> ()
(_:_) -> ()
|
|
997154dd15d9aeeeb5f6f19fbb7c134cebf9774773f543d0a93330c5ad8239a4 | skanev/playground | 21.scm | SICP exercise 1.21
;
; Use the smallest-divisor procedure to find the smallest divisor of each of
the following numbers : 199 , 1999 , 19999 .
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (square a)
(* a a))
(define (divides? a b)
(= (remainder b a) 0))
199
1999
7
| null | https://raw.githubusercontent.com/skanev/playground/d88e53a7f277b35041c2f709771a0b96f993b310/scheme/sicp/01/21.scm | scheme |
Use the smallest-divisor procedure to find the smallest divisor of each of | SICP exercise 1.21
the following numbers : 199 , 1999 , 19999 .
(define (smallest-divisor n)
(find-divisor n 2))
(define (find-divisor n test-divisor)
(cond ((> (square test-divisor) n) n)
((divides? test-divisor n) test-divisor)
(else (find-divisor n (+ test-divisor 1)))))
(define (square a)
(* a a))
(define (divides? a b)
(= (remainder b a) 0))
199
1999
7
|
f8f49026d21429ff171945e476a72af540069a4e43eaf0e5144497aa9b2a5dda | patrickgombert/erlang-koans | about_gen_fsms.erl | -module(about_gen_fsms).
-behaviour(gen_fsm).
-export([initial_state_is_set_in_init/0,
some_actions_will_not_trigger_a_state_change/0,
while_others_will_trigger_a_state_change/0,
go_ahead_and_grab_a_soda/0
]).
-export([init/1,
not_paid/3,
paid/3,
handle_event/3,
terminate/3
]).
initial_state_is_set_in_init() ->
{ok, FsmPid} = gen_fsm:start(?MODULE, 0, []),
Result = __ =:= gen_fsm:sync_send_event(FsmPid, {button, "Coke"}),
gen_fsm:send_all_state_event(FsmPid, stop),
Result.
some_actions_will_not_trigger_a_state_change() ->
{ok, FsmPid} = gen_fsm:start(?MODULE, 0, []),
Result = __ =:= gen_fsm:sync_send_event(FsmPid, {coin, 25}),
gen_fsm:send_all_state_event(FsmPid, stop),
Result.
while_others_will_trigger_a_state_change() ->
{ok, FsmPid} = gen_fsm:start(?MODULE, 0, []),
gen_fsm:sync_send_event(FsmPid, {coin, 100}),
gen_fsm:sync_send_event(FsmPid, {coin, 25}),
Result = __ =:= gen_fsm:sync_send_event(FsmPid, {coin, 25}),
gen_fsm:send_all_state_event(FsmPid, stop),
Result.
go_ahead_and_grab_a_soda() ->
{ok, FsmPid} = gen_fsm:start(?MODULE, 0, []),
gen_fsm:sync_send_event(FsmPid, {coin, 100}),
gen_fsm:sync_send_event(FsmPid, {coin, 25}),
Result = __ =:= gen_fsm:sync_send_event(FsmPid, {button, "Soda"}),
gen_fsm:send_all_state_event(FsmPid, stop),
Result.
gen fsm
init(_) ->
{ok, not_paid, {0, 125}}.
not_paid({button, _}, _From, {Cents, Cost}) ->
RemainingBalance = (Cost - Cents),
Message = "You still owe " ++ integer_to_list(RemainingBalance),
{reply, Message, not_paid, {Cents, Cost}};
not_paid({coin, Value}, _From, {Cents, Cost}) ->
NewCents = Cents + Value,
case NewCents >= Cost of
true -> {reply, "Make a selection", paid, {Cost - Cents, Cost}};
_ ->
Message = "You still owe " ++ integer_to_list(Cost - NewCents),
{reply, Message, not_paid, {NewCents, Cost}}
end.
paid({button, Selection}, _From, {Cents, Cost}) ->
{reply, "Vending a " ++ Selection, not_paid, {Cents, Cost}};
paid({coin, _Value}, _From, {Cents, Cost}) ->
{reply, "Please make a selection, refunding coin", paid, {Cents, Cost}}.
handle_event(stop, _StateName, StateData) ->
{stop, normal, StateData}.
terminate(_Reason, _StateName, _State) ->
ok.
| null | https://raw.githubusercontent.com/patrickgombert/erlang-koans/d80032d99b6ee3537e585ea02b743fe681fad8cf/src/about_gen_fsms.erl | erlang | -module(about_gen_fsms).
-behaviour(gen_fsm).
-export([initial_state_is_set_in_init/0,
some_actions_will_not_trigger_a_state_change/0,
while_others_will_trigger_a_state_change/0,
go_ahead_and_grab_a_soda/0
]).
-export([init/1,
not_paid/3,
paid/3,
handle_event/3,
terminate/3
]).
initial_state_is_set_in_init() ->
{ok, FsmPid} = gen_fsm:start(?MODULE, 0, []),
Result = __ =:= gen_fsm:sync_send_event(FsmPid, {button, "Coke"}),
gen_fsm:send_all_state_event(FsmPid, stop),
Result.
some_actions_will_not_trigger_a_state_change() ->
{ok, FsmPid} = gen_fsm:start(?MODULE, 0, []),
Result = __ =:= gen_fsm:sync_send_event(FsmPid, {coin, 25}),
gen_fsm:send_all_state_event(FsmPid, stop),
Result.
while_others_will_trigger_a_state_change() ->
{ok, FsmPid} = gen_fsm:start(?MODULE, 0, []),
gen_fsm:sync_send_event(FsmPid, {coin, 100}),
gen_fsm:sync_send_event(FsmPid, {coin, 25}),
Result = __ =:= gen_fsm:sync_send_event(FsmPid, {coin, 25}),
gen_fsm:send_all_state_event(FsmPid, stop),
Result.
go_ahead_and_grab_a_soda() ->
{ok, FsmPid} = gen_fsm:start(?MODULE, 0, []),
gen_fsm:sync_send_event(FsmPid, {coin, 100}),
gen_fsm:sync_send_event(FsmPid, {coin, 25}),
Result = __ =:= gen_fsm:sync_send_event(FsmPid, {button, "Soda"}),
gen_fsm:send_all_state_event(FsmPid, stop),
Result.
gen fsm
init(_) ->
{ok, not_paid, {0, 125}}.
not_paid({button, _}, _From, {Cents, Cost}) ->
RemainingBalance = (Cost - Cents),
Message = "You still owe " ++ integer_to_list(RemainingBalance),
{reply, Message, not_paid, {Cents, Cost}};
not_paid({coin, Value}, _From, {Cents, Cost}) ->
NewCents = Cents + Value,
case NewCents >= Cost of
true -> {reply, "Make a selection", paid, {Cost - Cents, Cost}};
_ ->
Message = "You still owe " ++ integer_to_list(Cost - NewCents),
{reply, Message, not_paid, {NewCents, Cost}}
end.
paid({button, Selection}, _From, {Cents, Cost}) ->
{reply, "Vending a " ++ Selection, not_paid, {Cents, Cost}};
paid({coin, _Value}, _From, {Cents, Cost}) ->
{reply, "Please make a selection, refunding coin", paid, {Cents, Cost}}.
handle_event(stop, _StateName, StateData) ->
{stop, normal, StateData}.
terminate(_Reason, _StateName, _State) ->
ok.
|
|
10397878ecef1d434a23f1050f63bfe116b30478133c1017bd008a35d49cfa53 | awalterschulze/the-little-typer-exercises | chapter8-1-zero-plus-n.rkt | #lang pie
Define a function called zero+n = n that states and proves that
0+n = n for all
(claim + (-> Nat Nat Nat))
(define +
(lambda (a b)
(rec-Nat a
b
(lambda (_ b+a-1)
(add1 b+a-1)))))
(claim zero+n=n
(Pi ((n Nat))
(= Nat (+ 0 n) n)))
(define zero+n=n
(lambda (n)
(same n)))
| null | https://raw.githubusercontent.com/awalterschulze/the-little-typer-exercises/91cad6c6d5c1733562aa952d8ca515addb2b301d/chapter8-1-zero-plus-n.rkt | racket | #lang pie
Define a function called zero+n = n that states and proves that
0+n = n for all
(claim + (-> Nat Nat Nat))
(define +
(lambda (a b)
(rec-Nat a
b
(lambda (_ b+a-1)
(add1 b+a-1)))))
(claim zero+n=n
(Pi ((n Nat))
(= Nat (+ 0 n) n)))
(define zero+n=n
(lambda (n)
(same n)))
|
|
786ad2b2188dd46084f3c6be5ac4a485d8ce425e533085a014fe6727c48f71d9 | jdormit/sicp-logic | db.clj | (ns sicp-logic.db)
(defprotocol FactDB
"The FactDB protocol specifies methods to store and retrieve
assertions (facts) and rules."
(fetch-assertions [db query frame]
"Fetches assertions that may match the given query and frame.")
(add-assertion [db assertion]
"Stores an assertion (a fact) in the database.")
(fetch-rules [db query frame]
"Fetches rules whose conditions may unify with the given query and frame")
(add-rule [db rule]
"Adds a new rule to the database"))
| null | https://raw.githubusercontent.com/jdormit/sicp-logic/56ae0fc344d3fce943dcc740a64d3eebc82062d1/src/sicp_logic/db.clj | clojure | (ns sicp-logic.db)
(defprotocol FactDB
"The FactDB protocol specifies methods to store and retrieve
assertions (facts) and rules."
(fetch-assertions [db query frame]
"Fetches assertions that may match the given query and frame.")
(add-assertion [db assertion]
"Stores an assertion (a fact) in the database.")
(fetch-rules [db query frame]
"Fetches rules whose conditions may unify with the given query and frame")
(add-rule [db rule]
"Adds a new rule to the database"))
|
|
c08741af70089c0420639a5149df6504e0fa309fa7793f7ef25442d580120303 | evilbinary/scheme-lib | dirs.scm | " dirs.scm " Directories .
Copyright 1998 , 2002
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
1 . Any copy made of this software must include this copyright notice
;in full.
;
2 . I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
3 . In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
(require 'filename)
(require 'line-i/o)
(require 'system)
(require 'filename)
;;@code{(require 'directory)}
;;@ftindex directory
@args
@0 returns a string containing the absolute file
;;name representing the current working directory. If this string
;;cannot be obtained, #f is returned.
;;
If @0 can not be supported by the platform , then # f is returned .
(define current-directory
(case (software-type)
( ( ) )
;;((macos thinkc) )
((ms-dos windows atarist os/2) (lambda () (system->line "cd")))
;;((nosve) )
((unix coherent plan9) (lambda () (system->line "pwd")))
;;((vms) )
(else #f)))
;;@body
;;Creates a sub-directory @1 of the current-directory. If
successful , @0 returns # t ; otherwise # f.
(define (make-directory name)
(eqv? 0 (system (string-append "mkdir \"" name "\""))))
(define (dir:lister dirname tmp)
(case (software-type)
((unix coherent plan9)
(zero? (system (string-append "ls '" dirname "' > " tmp))))
((ms-dos windows os/2 atarist)
(zero? (system (string-append "DIR /B \"" dirname "\" > " tmp))))
(else (slib:error (software-type) 'list?))))
@args proc directory
@var{proc } must be a procedure taking one argument .
;;@samp{Directory-For-Each} applies @var{proc} to the (string) name of
each file in @var{directory } . The dynamic order in which @var{proc } is
;;applied to the filenames is unspecified. The value returned by
;;@samp{directory-for-each} is unspecified.
;;
@args proc directory pred
;;Applies @var{proc} only to those filenames for which the procedure
;;@var{pred} returns a non-false value.
;;
@args proc directory match
;;Applies @var{proc} only to those filenames for which
;;@code{(filename:match?? @var{match})} would return a non-false value
;;(@pxref{Filenames, , , slib, SLIB}).
;;
;;@example
;;(require 'directory)
;;(directory-for-each print "." "[A-Z]*.scm")
@print { }
;;"Bev2slib.scm"
" "
;;@end example
(define (directory-for-each proc dirname . args)
(define selector
(cond ((null? args) identity)
((> (length args) 1)
(slib:error 'directory-for-each 'too-many-arguments (cdr args)))
((procedure? (car args)) (car args))
((string? (car args)) (filename:match?? (car args)))
(else
(slib:error 'directory-for-each 'filter? (car args)))))
(call-with-tmpnam
(lambda (tmp)
(and (dir:lister dirname tmp)
(file-exists? tmp)
(call-with-input-file tmp
(lambda (port)
(do ((filename (read-line port) (read-line port)))
((or (eof-object? filename) (equal? "" filename)))
(and (selector filename) (proc filename)))))))))
;;@body
@2 is a pathname whose last component is a ( wildcard ) pattern
;;(@pxref{Filenames, , , slib, SLIB}).
@1 must be a procedure taking one argument .
;;@samp{directory*-for-each} applies @var{proc} to the (string) name of
;;each file in the current directory. The dynamic order in which @var{proc} is
;;applied to the filenames is unspecified. The value returned by
;;@samp{directory*-for-each} is unspecified.
(define (directory*-for-each proc path-glob)
(define dir (pathname->vicinity path-glob))
(let ((glob (substring path-glob
(string-length dir)
(string-length path-glob))))
(directory-for-each proc
(if (equal? "" dir) "." dir)
glob)))
| null | https://raw.githubusercontent.com/evilbinary/scheme-lib/6df491c1f616929caa4e6569fa44e04df7a356a7/packages/slib/dirs.scm | scheme |
Permission to copy this software, to modify it, to redistribute it,
to distribute modified versions, and to use it for any purpose is
granted, subject to the following restrictions and understandings.
in full.
this software will be error-free, and I am under no obligation to
provide any services, by way of maintenance, update, or otherwise.
material, there shall be no use of my name in any advertising,
promotional, or sales literature without prior written consent in
each case.
@code{(require 'directory)}
@ftindex directory
name representing the current working directory. If this string
cannot be obtained, #f is returned.
((macos thinkc) )
((nosve) )
((vms) )
@body
Creates a sub-directory @1 of the current-directory. If
otherwise # f.
@samp{Directory-For-Each} applies @var{proc} to the (string) name of
applied to the filenames is unspecified. The value returned by
@samp{directory-for-each} is unspecified.
Applies @var{proc} only to those filenames for which the procedure
@var{pred} returns a non-false value.
Applies @var{proc} only to those filenames for which
@code{(filename:match?? @var{match})} would return a non-false value
(@pxref{Filenames, , , slib, SLIB}).
@example
(require 'directory)
(directory-for-each print "." "[A-Z]*.scm")
"Bev2slib.scm"
@end example
@body
(@pxref{Filenames, , , slib, SLIB}).
@samp{directory*-for-each} applies @var{proc} to the (string) name of
each file in the current directory. The dynamic order in which @var{proc} is
applied to the filenames is unspecified. The value returned by
@samp{directory*-for-each} is unspecified. | " dirs.scm " Directories .
Copyright 1998 , 2002
1 . Any copy made of this software must include this copyright notice
2 . I have made no warranty or representation that the operation of
3 . In conjunction with products arising from the use of this
(require 'filename)
(require 'line-i/o)
(require 'system)
(require 'filename)
@args
@0 returns a string containing the absolute file
If @0 can not be supported by the platform , then # f is returned .
(define current-directory
(case (software-type)
( ( ) )
((ms-dos windows atarist os/2) (lambda () (system->line "cd")))
((unix coherent plan9) (lambda () (system->line "pwd")))
(else #f)))
(define (make-directory name)
(eqv? 0 (system (string-append "mkdir \"" name "\""))))
(define (dir:lister dirname tmp)
(case (software-type)
((unix coherent plan9)
(zero? (system (string-append "ls '" dirname "' > " tmp))))
((ms-dos windows os/2 atarist)
(zero? (system (string-append "DIR /B \"" dirname "\" > " tmp))))
(else (slib:error (software-type) 'list?))))
@args proc directory
@var{proc } must be a procedure taking one argument .
each file in @var{directory } . The dynamic order in which @var{proc } is
@args proc directory pred
@args proc directory match
@print { }
" "
(define (directory-for-each proc dirname . args)
(define selector
(cond ((null? args) identity)
((> (length args) 1)
(slib:error 'directory-for-each 'too-many-arguments (cdr args)))
((procedure? (car args)) (car args))
((string? (car args)) (filename:match?? (car args)))
(else
(slib:error 'directory-for-each 'filter? (car args)))))
(call-with-tmpnam
(lambda (tmp)
(and (dir:lister dirname tmp)
(file-exists? tmp)
(call-with-input-file tmp
(lambda (port)
(do ((filename (read-line port) (read-line port)))
((or (eof-object? filename) (equal? "" filename)))
(and (selector filename) (proc filename)))))))))
@2 is a pathname whose last component is a ( wildcard ) pattern
@1 must be a procedure taking one argument .
(define (directory*-for-each proc path-glob)
(define dir (pathname->vicinity path-glob))
(let ((glob (substring path-glob
(string-length dir)
(string-length path-glob))))
(directory-for-each proc
(if (equal? "" dir) "." dir)
glob)))
|
f323bf835ed57942f9f5e4aca03e30ae66509146a645cd093044e48a22c27c66 | schibsted/spid-tech-docs | config.clj | (ns spid-docs.config
(:require [clojure.java.io :as io]
[spid-docs.load :refer [load-edn]]))
(defn config-exists? []
(io/resource "config.edn"))
(def get-config (memoize #(load-edn "config.edn"))) | null | https://raw.githubusercontent.com/schibsted/spid-tech-docs/ee6a4394e9732572e97fc3a55506b2d6b9a9fe2b/src/spid_docs/config.clj | clojure | (ns spid-docs.config
(:require [clojure.java.io :as io]
[spid-docs.load :refer [load-edn]]))
(defn config-exists? []
(io/resource "config.edn"))
(def get-config (memoize #(load-edn "config.edn"))) |
|
f581d39cd1278565bf825f2b4f405f350703f1fdf5be7b86fb4c7adf69534c1a | huangjs/cl | calendar.lisp | (in-package :cl-user)
(defpackage :hjs.util.time
(:use :cl :hjs.meta.macro :split-sequence :date)
(:export #:translate-japanese-year
#:parse-kanji-date
#:year
#:month
#:day
#:hour
#:minute
#:sec
#:time-string
#:date-string
#:weekday))
(in-package :hjs.util.time)
(defnewconstant +timezone-tokyo+ -9)
(defnewconstant +timezone-beijing+ -8)
(defun year (&optional (time (get-universal-time)))
(write-to-string (nth-value 5 (decode-universal-time time))))
(defun month (&optional (time (get-universal-time)))
(write-to-string (nth-value 4 (decode-universal-time time))))
(defun day (&optional (time (get-universal-time)))
(write-to-string (nth-value 3 (decode-universal-time time))))
(defun hour (&optional (time (get-universal-time)))
(write-to-string (nth-value 2 (decode-universal-time time))))
(defun minute (&optional (time (get-universal-time)))
(write-to-string (nth-value 1 (decode-universal-time time))))
(defun sec (&optional (time (get-universal-time)))
(write-to-string (nth-value 0 (decode-universal-time time))))
(defun time-string (&key (time (get-universal-time)) (timezone +timezone-tokyo+))
(with-date time timezone
(format nil "~a:~a:~a" hour minute second)))
(defun date-string (&key (time (get-universal-time)) (timezone +timezone-tokyo+))
(with-date time timezone
(format nil "~a/~a/~a" year month day-of-month)))
(defun weekday (&key (time (get-universal-time)) (timezone +timezone-tokyo+))
"Return weekday start from Monday as 0"
(with-date time timezone
day-of-week))
;;; FIXME: it's a hack
(defun translate-japanese-year (year)
"Translate a japanese year (number) to standard year."
(cond ((<= year 0)
(error "year must be a positive integer."))
((<= year 25)
(+ 1988 year))
((<= year 64)
(+ 1925 year))
(t
(error "year must be less than or equal to 64."))))
;;; fixme: not complete, just a hack...
(defun parse-kanji-date (datestring)
(destructuring-bind (month rest)
(split-sequence #\月 datestring)
(let ((date (subseq rest 0 (1- (length rest)))))
(concatenate 'string
(year)
"/"
month
"/"
date))))
| null | https://raw.githubusercontent.com/huangjs/cl/96158b3f82f82a6b7d53ef04b3b29c5c8de2dbf7/lib/mylib/calendar.lisp | lisp | FIXME: it's a hack
fixme: not complete, just a hack... | (in-package :cl-user)
(defpackage :hjs.util.time
(:use :cl :hjs.meta.macro :split-sequence :date)
(:export #:translate-japanese-year
#:parse-kanji-date
#:year
#:month
#:day
#:hour
#:minute
#:sec
#:time-string
#:date-string
#:weekday))
(in-package :hjs.util.time)
(defnewconstant +timezone-tokyo+ -9)
(defnewconstant +timezone-beijing+ -8)
(defun year (&optional (time (get-universal-time)))
(write-to-string (nth-value 5 (decode-universal-time time))))
(defun month (&optional (time (get-universal-time)))
(write-to-string (nth-value 4 (decode-universal-time time))))
(defun day (&optional (time (get-universal-time)))
(write-to-string (nth-value 3 (decode-universal-time time))))
(defun hour (&optional (time (get-universal-time)))
(write-to-string (nth-value 2 (decode-universal-time time))))
(defun minute (&optional (time (get-universal-time)))
(write-to-string (nth-value 1 (decode-universal-time time))))
(defun sec (&optional (time (get-universal-time)))
(write-to-string (nth-value 0 (decode-universal-time time))))
(defun time-string (&key (time (get-universal-time)) (timezone +timezone-tokyo+))
(with-date time timezone
(format nil "~a:~a:~a" hour minute second)))
(defun date-string (&key (time (get-universal-time)) (timezone +timezone-tokyo+))
(with-date time timezone
(format nil "~a/~a/~a" year month day-of-month)))
(defun weekday (&key (time (get-universal-time)) (timezone +timezone-tokyo+))
"Return weekday start from Monday as 0"
(with-date time timezone
day-of-week))
(defun translate-japanese-year (year)
"Translate a japanese year (number) to standard year."
(cond ((<= year 0)
(error "year must be a positive integer."))
((<= year 25)
(+ 1988 year))
((<= year 64)
(+ 1925 year))
(t
(error "year must be less than or equal to 64."))))
(defun parse-kanji-date (datestring)
(destructuring-bind (month rest)
(split-sequence #\月 datestring)
(let ((date (subseq rest 0 (1- (length rest)))))
(concatenate 'string
(year)
"/"
month
"/"
date))))
|
f92fbc3f2b46620a1056980a2e9c358a87a6be4712e8c60642fa59444d28e224 | manuel-serrano/bigloo | cfa2.scm | ;*=====================================================================*/
* serrano / prgm / project / bigloo / recette / cfa2.scm * /
;* ------------------------------------------------------------- */
* Author : * /
* Creation : Tue Apr 29 10:03:37 1997 * /
* Last change : Tue Apr 29 10:06:39 1997 ( serrano ) * /
;* ------------------------------------------------------------- */
* A module provinding bindings for the cfa tests . * /
;*=====================================================================*/
;*---------------------------------------------------------------------*/
;* The module */
;*---------------------------------------------------------------------*/
(module cfa2
(export cfa2))
;*---------------------------------------------------------------------*/
;* cfa2 ... */
;*---------------------------------------------------------------------*/
(define (cfa2 f)
(f 5))
| null | https://raw.githubusercontent.com/manuel-serrano/bigloo/eb650ed4429155f795a32465e009706bbf1b8d74/recette/cfa2.scm | scheme | *=====================================================================*/
* ------------------------------------------------------------- */
* ------------------------------------------------------------- */
*=====================================================================*/
*---------------------------------------------------------------------*/
* The module */
*---------------------------------------------------------------------*/
*---------------------------------------------------------------------*/
* cfa2 ... */
*---------------------------------------------------------------------*/ | * serrano / prgm / project / bigloo / recette / cfa2.scm * /
* Author : * /
* Creation : Tue Apr 29 10:03:37 1997 * /
* Last change : Tue Apr 29 10:06:39 1997 ( serrano ) * /
* A module provinding bindings for the cfa tests . * /
(module cfa2
(export cfa2))
(define (cfa2 f)
(f 5))
|
67bada7ade7d02d28f04d87402b67e8018a1b09991f99313fe4197876f2c1377 | deadpendency/deadpendency | IsRepoNotFoundRuleSpec.hs | module Effect.AssessDependencies.Backend.Rules.IsRepoNotFoundRuleSpec (spec) where
import Common.Model.Assessment.DependencyAssessmentFailure
import Common.Model.Assessment.DependencyAssessmentViolation
import Common.Model.Assessment.DependencyAssessmentWarning
import Common.Model.Git.Repo
import Common.Model.Git.RepoHost
import Common.Model.RepoConfig.Rules.RuleStatus
import CommonTest.Gen.General
import CommonTest.Gen.Model.Dependency
import CommonTest.Gen.Model.Git
import CommonTest.Gen.Model.RepoConfig
import Data.Maybe (fromJust)
import Data.Vector qualified as V
import Hedgehog.Gen qualified as Gen
import RG.Effect.AssessDependencies.Backend.Model.InternalDependencyAssessment
import RG.Effect.AssessDependencies.Backend.Rules.IsRepoNotFoundRule
import Test.Hspec
import Test.Hspec.Hedgehog
import Text.URI qualified as URI
spec :: Spec
spec = parallel $
context "is missing repo checking" $ do
it "is missing repo, produce warning" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceWarning
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ GitHub
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.singleton $ DependencyAssessmentWarning DAVRepoNotFound,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (This registryDetails)
result === expected
it "with repo will pass" $
hedgehog $ do
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
repoStats <- Gen.sample genDependencyRepoStats
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceWarning
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ GitHub
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (That repoStats)
result === expected
it "is missing repo, produce failure" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceFailure
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ GitHub
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.singleton $ DependencyAssessmentFailure DAVRepoNotFound
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (This registryDetails)
result === expected
it "is missing repo, disabled" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSDisabled
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ GitHub
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (This registryDetails)
result === expected
it "is missing non github repo" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceWarning
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ Bitbucket
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (This registryDetails)
result === expected
it "has an unknown repo" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceWarning
repo = RepoUnknown $ fromJust $ URI.mkURI "/"
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just repo) (This registryDetails)
result === expected
| null | https://raw.githubusercontent.com/deadpendency/deadpendency/170d6689658f81842168b90aa3d9e235d416c8bd/apps/report-generator/test/Effect/AssessDependencies/Backend/Rules/IsRepoNotFoundRuleSpec.hs | haskell | module Effect.AssessDependencies.Backend.Rules.IsRepoNotFoundRuleSpec (spec) where
import Common.Model.Assessment.DependencyAssessmentFailure
import Common.Model.Assessment.DependencyAssessmentViolation
import Common.Model.Assessment.DependencyAssessmentWarning
import Common.Model.Git.Repo
import Common.Model.Git.RepoHost
import Common.Model.RepoConfig.Rules.RuleStatus
import CommonTest.Gen.General
import CommonTest.Gen.Model.Dependency
import CommonTest.Gen.Model.Git
import CommonTest.Gen.Model.RepoConfig
import Data.Maybe (fromJust)
import Data.Vector qualified as V
import Hedgehog.Gen qualified as Gen
import RG.Effect.AssessDependencies.Backend.Model.InternalDependencyAssessment
import RG.Effect.AssessDependencies.Backend.Rules.IsRepoNotFoundRule
import Test.Hspec
import Test.Hspec.Hedgehog
import Text.URI qualified as URI
spec :: Spec
spec = parallel $
context "is missing repo checking" $ do
it "is missing repo, produce warning" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceWarning
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ GitHub
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.singleton $ DependencyAssessmentWarning DAVRepoNotFound,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (This registryDetails)
result === expected
it "with repo will pass" $
hedgehog $ do
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
repoStats <- Gen.sample genDependencyRepoStats
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceWarning
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ GitHub
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (That repoStats)
result === expected
it "is missing repo, produce failure" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceFailure
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ GitHub
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.singleton $ DependencyAssessmentFailure DAVRepoNotFound
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (This registryDetails)
result === expected
it "is missing repo, disabled" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSDisabled
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ GitHub
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (This registryDetails)
result === expected
it "is missing non github repo" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
qualifiedRepo <- Gen.sample genQualifiedRepo
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceWarning
massagedQualifiedRepo =
qualifiedRepo
& #_repoHost .~ Bitbucket
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just $ RepoQR massagedQualifiedRepo) (This registryDetails)
result === expected
it "has an unknown repo" $
hedgehog $ do
registryDetails <- Gen.sample genDependencyRegistryInfo
currentTime <- Gen.sample genUTCTime
rulesConfig <- Gen.sample genRulesConfig
let massagedRulesConfig =
rulesConfig
& #_repositoryNotFound .~ RSProduceWarning
repo = RepoUnknown $ fromJust $ URI.mkURI "/"
expected =
InternalDependencyAssessment
{ _idaDependencyAssessmentWarnings = V.empty,
_idaDependencyAssessmentFailures = V.empty
}
result = isRepoNotFoundRule currentTime massagedRulesConfig (Just repo) (This registryDetails)
result === expected
|
|
41d94bffe946ecdadccd729fe1298995f0118b3db367760a4075bdfe412106d5 | erdos/stencil | tree_postprocess.clj | (ns stencil.tree-postprocess
"Postprocessing an xml tree"
(:require [stencil.postprocess.table :refer :all]
[stencil.postprocess.whitespaces :refer :all]
[stencil.postprocess.ignored-tag :refer :all]
[stencil.postprocess.images :refer :all]
[stencil.postprocess.list-ref :refer :all]
[stencil.postprocess.fragments :refer :all]
[stencil.postprocess.html :refer :all]))
;; calls postprocess
(def postprocess
(comp
must be called last . replaces the Ignored attrubute values from ids to namespaces .
#'unmap-ignored-attr
;; hides rows/columns where markers are present
#'fix-tables
;; fixes xml:space attribute values where missing
#'fix-whitespaces
;; includes html() call results.
#'fix-html-chunks
#'fix-list-dirty-refs
#'replace-images
;; call this first. includes fragments and evaluates them too.
#'unpack-fragments))
| null | https://raw.githubusercontent.com/erdos/stencil/cd5d4f510e8f423b6bff7968ec7def3d138c390f/src/stencil/tree_postprocess.clj | clojure | calls postprocess
hides rows/columns where markers are present
fixes xml:space attribute values where missing
includes html() call results.
call this first. includes fragments and evaluates them too. | (ns stencil.tree-postprocess
"Postprocessing an xml tree"
(:require [stencil.postprocess.table :refer :all]
[stencil.postprocess.whitespaces :refer :all]
[stencil.postprocess.ignored-tag :refer :all]
[stencil.postprocess.images :refer :all]
[stencil.postprocess.list-ref :refer :all]
[stencil.postprocess.fragments :refer :all]
[stencil.postprocess.html :refer :all]))
(def postprocess
(comp
must be called last . replaces the Ignored attrubute values from ids to namespaces .
#'unmap-ignored-attr
#'fix-tables
#'fix-whitespaces
#'fix-html-chunks
#'fix-list-dirty-refs
#'replace-images
#'unpack-fragments))
|
2d42a7d053d873af2c465e979720b075fd798453dd7eccd34b81e17ac89688c5 | jacobobryant/platypub | platypub.clj | (ns com.platypub
(:require [com.biffweb :as biff]
[com.platypub.feat.auth :as auth]
[com.platypub.feat.home :as home]
[com.platypub.feat.lists :as lists]
[com.platypub.feat.items :as items]
[com.platypub.feat.sites :as sites]
[com.platypub.schema :refer [malli-opts]]
[com.platypub.util :as util]
[clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.string :as str]
[clojure.test :as test]
[clojure.tools.logging :as log]
[ring.middleware.anti-forgery :as anti-forgery]
[nrepl.cmdline :as nrepl-cmd]))
(def features
[auth/features
home/features
lists/features
items/features
sites/features])
(def routes [["" {:middleware [anti-forgery/wrap-anti-forgery
biff/wrap-anti-forgery-websockets
biff/wrap-render-rum]}
(map :routes features)]
(map :api-routes features)])
(def handler (-> (biff/reitit-handler {:routes routes})
(biff/wrap-inner-defaults {})))
(defn on-tx [sys tx]
(let [sys (biff/assoc-db sys)]
(doseq [{:keys [on-tx]} features
:when on-tx]
(on-tx sys tx))))
(def tasks (->> features
(mapcat :tasks)
(map #(update % :task comp biff/assoc-db))))
(def static-pages (apply biff/safe-merge (map :static features)))
(defn generate-assets! [sys]
(when (:com.platypub/enable-web sys)
(biff/export-rum static-pages "target/resources/public")
(biff/delete-old-files {:dir "target/resources/public"
:exts [".html"]})
(log/info :done)))
(defn on-save [sys]
(biff/eval-files! sys)
(generate-assets! sys)
;; Uncomment this if we add any real tests.
#_(test/run-all-tests #"com.platypub.test.*"))
(defn start []
(biff/start-system
{:com.platypub/chat-clients (atom #{})
:biff/after-refresh `start
:biff/handler #'handler
:biff/malli-opts #'malli-opts
:biff.beholder/on-save #'on-save
:biff.xtdb/on-tx #'on-tx
:biff.chime/tasks tasks
:biff/config "config.edn"
:biff/components [biff/use-config
biff/use-random-default-secrets
biff/use-xt
biff/use-tx-listener
(biff/use-when
:com.platypub/enable-web
biff/use-outer-default-middleware
biff/use-jetty)
(biff/use-when
:com.platypub/enable-worker
biff/use-chime)
(biff/use-when
(some-fn :com.platypub/enable-hawk ; for backwards compatibility
:com.platypub/enable-beholder)
biff/use-beholder)]})
(generate-assets! @biff/system)
(log/info "Go to" (:biff/base-url @biff/system)))
(defn -main [& args]
(start)
(apply nrepl-cmd/-main args))
| null | https://raw.githubusercontent.com/jacobobryant/platypub/71799b1b8f4e8fd1f93d7ce94b6ca952aa9709fa/src/com/platypub.clj | clojure | Uncomment this if we add any real tests.
for backwards compatibility | (ns com.platypub
(:require [com.biffweb :as biff]
[com.platypub.feat.auth :as auth]
[com.platypub.feat.home :as home]
[com.platypub.feat.lists :as lists]
[com.platypub.feat.items :as items]
[com.platypub.feat.sites :as sites]
[com.platypub.schema :refer [malli-opts]]
[com.platypub.util :as util]
[clojure.java.io :as io]
[clojure.java.shell :as shell]
[clojure.string :as str]
[clojure.test :as test]
[clojure.tools.logging :as log]
[ring.middleware.anti-forgery :as anti-forgery]
[nrepl.cmdline :as nrepl-cmd]))
(def features
[auth/features
home/features
lists/features
items/features
sites/features])
(def routes [["" {:middleware [anti-forgery/wrap-anti-forgery
biff/wrap-anti-forgery-websockets
biff/wrap-render-rum]}
(map :routes features)]
(map :api-routes features)])
(def handler (-> (biff/reitit-handler {:routes routes})
(biff/wrap-inner-defaults {})))
(defn on-tx [sys tx]
(let [sys (biff/assoc-db sys)]
(doseq [{:keys [on-tx]} features
:when on-tx]
(on-tx sys tx))))
(def tasks (->> features
(mapcat :tasks)
(map #(update % :task comp biff/assoc-db))))
(def static-pages (apply biff/safe-merge (map :static features)))
(defn generate-assets! [sys]
(when (:com.platypub/enable-web sys)
(biff/export-rum static-pages "target/resources/public")
(biff/delete-old-files {:dir "target/resources/public"
:exts [".html"]})
(log/info :done)))
(defn on-save [sys]
(biff/eval-files! sys)
(generate-assets! sys)
#_(test/run-all-tests #"com.platypub.test.*"))
(defn start []
(biff/start-system
{:com.platypub/chat-clients (atom #{})
:biff/after-refresh `start
:biff/handler #'handler
:biff/malli-opts #'malli-opts
:biff.beholder/on-save #'on-save
:biff.xtdb/on-tx #'on-tx
:biff.chime/tasks tasks
:biff/config "config.edn"
:biff/components [biff/use-config
biff/use-random-default-secrets
biff/use-xt
biff/use-tx-listener
(biff/use-when
:com.platypub/enable-web
biff/use-outer-default-middleware
biff/use-jetty)
(biff/use-when
:com.platypub/enable-worker
biff/use-chime)
(biff/use-when
:com.platypub/enable-beholder)
biff/use-beholder)]})
(generate-assets! @biff/system)
(log/info "Go to" (:biff/base-url @biff/system)))
(defn -main [& args]
(start)
(apply nrepl-cmd/-main args))
|
736ff52475b1577916c214b9d69f698953fcc43ed9e3d24b506260aa5cd408fc | rtoy/cmucl | morecoms.lisp | ;;; -*- Log: hemlock.log; Package: Hemlock -*-
;;;
;;; **********************************************************************
This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
;;;
(ext:file-comment
"$Header: src/hemlock/morecoms.lisp $")
;;;
;;; **********************************************************************
;;;
Written by and .
;;;
;;; Even more commands...
(in-package "HEMLOCK")
(defhvar "Region Query Size"
"A number-of-lines threshold that destructive, undoable region commands
should ask the user about when the indicated region is too big."
:value 30)
(defun check-region-query-size (region)
"Checks the number of lines in region against \"Region Query Size\" and
asks the user if the region crosses this threshold. If the user responds
negatively, then an editor error is signaled."
(let ((threshold (or (value region-query-size) 0)))
(if (and (plusp threshold)
(>= (count-lines region) threshold)
(not (prompt-for-y-or-n
:prompt "Region size exceeds \"Region Query Size\". Confirm: "
:must-exist t)))
(editor-error))))
;;;; Casing commands...
(defcommand "Uppercase Word" (p)
"Uppercase a word at point.
With prefix argument uppercase that many words."
"Uppercase p words at the point."
(filter-words p (current-point) #'string-upcase))
(defcommand "Lowercase Word" (p)
"Uppercase a word at point.
With prefix argument uppercase that many words."
"Uppercase p words at the point."
(filter-words p (current-point) #'string-downcase))
FILTER - WORDS implements " Uppercase Word " and " Lowercase Word " .
;;;
(defun filter-words (p point function)
(let ((arg (or p 1)))
(with-mark ((mark point))
(if (word-offset (if (minusp arg) mark point) arg)
(filter-region function (region mark point))
(editor-error "Not enough words.")))))
" Capitalize Word " is different than uppercasing and lowercasing because
the differences between Hemlock 's notion of what a word is and Common
;;; Lisp's notion are too annoying.
;;;
(defcommand "Capitalize Word" (p)
"Lowercase a word capitalizing the first character. With a prefix
argument, capitalize that many words. A negative argument capitalizes
words before the point, but leaves the point where it was."
"Capitalize p words at the point."
(let ((point (current-point))
(arg (or p 1)))
(with-mark ((start point :left-inserting)
(end point))
(when (minusp arg)
(unless (word-offset start arg) (editor-error "No previous word.")))
(do ((region (region start end))
(cnt (abs arg) (1- cnt)))
((zerop cnt) (move-mark point end))
(unless (find-attribute start :word-delimiter #'zerop)
(editor-error "No next word."))
(move-mark end start)
(find-attribute end :word-delimiter)
(loop
(when (mark= start end)
(move-mark point end)
(editor-error "No alphabetic characters in word."))
(when (alpha-char-p (next-character start)) (return))
(character-offset start 1))
(setf (next-character start) (char-upcase (next-character start)))
(mark-after start)
(filter-region #'string-downcase region)))))
(defcommand "Uppercase Region" (p)
"Uppercase words from point to mark."
"Uppercase words from point to mark."
(declare (ignore p))
(twiddle-region (current-region) #'string-upcase "Uppercase Region"))
(defcommand "Lowercase Region" (p)
"Lowercase words from point to mark."
"Lowercase words from point to mark."
(declare (ignore p))
(twiddle-region (current-region) #'string-downcase "Lowercase Region"))
;;; TWIDDLE-REGION implements "Uppercase Region" and "Lowercase Region".
;;;
(defun twiddle-region (region function name)
(let* (;; don't delete marks start and end since undo stuff will.
(start (copy-mark (region-start region) :left-inserting))
(end (copy-mark (region-end region) :left-inserting)))
(let* ((region (region start end))
(undo-region (copy-region region)))
(check-region-query-size region)
(filter-region function region)
(make-region-undo :twiddle name region undo-region))))
;;;; More stuff.
(defcommand "Delete Previous Character Expanding Tabs" (p)
"Delete the previous character.
When deleting a tab pretend it is the equivalent number of spaces.
With prefix argument, do it that many times."
"Delete the P previous characters, expanding tabs into spaces."
(let ((point (current-point))
(n (or p 1)))
(when (minusp n)
(editor-error "Delete Previous Character Expanding Tabs only accepts ~
positive arguments."))
;; Pre-calculate the number of characters that need to be deleted
;; and any remaining white space filling, allowing modification to
;; be avoided if there are not enough characters to delete.
(let ((errorp nil)
(del 0)
(fill 0))
(with-mark ((mark point))
(dotimes (i n)
(if (> fill 0)
(decf fill)
(let ((prev (previous-character mark)))
(cond ((and prev (char= prev #\tab))
(let ((pos (mark-column mark)))
(mark-before mark)
(incf fill (- pos (mark-column mark) 1)))
(incf del))
((mark-before mark)
(incf del))
(t
(setq errorp t)
(return)))))))
(cond ((and (not errorp) (kill-characters point (- del)))
(with-mark ((mark point :left-inserting))
(dotimes (i fill)
(insert-character mark #\space))))
(t
(editor-error "There were not ~D characters before point." n))))))
(defvar *scope-table*
(list (make-string-table :initial-contents
'(("Global" . :global)
("Buffer" . :buffer)
("Mode" . :mode)))))
(defun prompt-for-place (prompt help)
(multiple-value-bind (word val)
(prompt-for-keyword *scope-table* :prompt prompt
:help help :default "Global")
(declare (ignore word))
(case val
(:buffer
(values :buffer (prompt-for-buffer :help "Buffer to be local to."
:default (current-buffer))))
(:mode
(values :mode (prompt-for-keyword
(list *mode-names*)
:prompt "Mode: "
:help "Mode to be local to."
:default (buffer-major-mode (current-buffer)))))
(:global :global))))
(defcommand "Bind Key" (p)
"Bind a command to a key.
The command, key and place to make the binding are prompted for."
"Prompt for stuff to do a bind-key."
(declare (ignore p))
(multiple-value-call #'bind-key
(values (prompt-for-keyword
(list *command-names*)
:prompt "Command to bind: "
:help "Name of command to bind to a key."))
(values (prompt-for-key
:prompt "Bind to: " :must-exist nil
:help "Key to bind command to, confirm to complete."))
(prompt-for-place "Kind of binding: "
"The kind of binding to make.")))
(defcommand "Delete Key Binding" (p)
"Delete a key binding.
The key and place to remove the binding are prompted for."
"Prompt for stuff to do a delete-key-binding."
(declare (ignore p))
(let ((key (prompt-for-key
:prompt "Delete binding: " :must-exist nil
:help "Key to delete binding from.")))
(multiple-value-bind (kind where)
(prompt-for-place "Kind of binding: "
"The kind of binding to make.")
(unless (get-command key kind where)
(editor-error "No such binding: ~S" key))
(delete-key-binding key kind where))))
(defcommand "Set Variable" (p)
"Prompt for a Hemlock variable and a new value."
"Prompt for a Hemlock variable and a new value."
(declare (ignore p))
(multiple-value-bind (name var)
(prompt-for-variable
:prompt "Variable: "
:help "The name of a variable to set.")
(declare (ignore name))
(setf (variable-value var)
(handle-lisp-errors
(eval (prompt-for-expression
:prompt "Value: "
:help "Expression to evaluate for new value."))))))
(defcommand "Defhvar" (p)
"Define a hemlock variable in some location. If the named variable exists
currently, its documentation is propagated to the new instance, but this
never prompts for documentation."
"Define a hemlock variable in some location."
(declare (ignore p))
(let* ((name (nstring-capitalize (prompt-for-variable :must-exist nil)))
(var (string-to-variable name))
(doc (if (hemlock-bound-p var)
(variable-documentation var)
""))
(hooks (if (hemlock-bound-p var) (variable-hooks var)))
(val (prompt-for-expression :prompt "Variable value: "
:help "Value for the variable.")))
(multiple-value-bind
(kind where)
(prompt-for-place
"Kind of binding: "
"Whether the variable is global, mode, or buffer specific.")
(if (eq kind :global)
(defhvar name doc :value val :hooks hooks)
(defhvar name doc kind where :value val :hooks hooks)))))
(defcommand "List Buffers" (p)
"Show a list of all buffers.
If the buffer is modified then a * is displayed before the name. If there
is an associated file then it's name is displayed last. With prefix
argument, only list modified buffers."
"Display the names of all buffers in a with-random-typeout window."
(with-pop-up-display (s)
(do-strings (n b *buffer-names*)
(declare (simple-string n))
(unless (or (eq b *echo-area-buffer*)
(assoc b *random-typeout-buffers* :test #'eq))
(let ((modified (buffer-modified b))
(buffer-pathname (buffer-pathname b)))
(when (or (not p) modified)
(write-char (if modified #\* #\space) s)
(if buffer-pathname
(format s "~A ~25T~A~:[~68T~A~;~]~%"
(file-namestring buffer-pathname)
(directory-namestring buffer-pathname)
(string= (pathname-to-buffer-name buffer-pathname) n)
n)
(format s "~A~68T~D Line~:P~%"
n (count-lines (buffer-region b))))))))))
(defcommand "Select Random Typeout Buffer" (p)
"Select last random typeout buffer."
"Select last random typeout buffer."
(declare (ignore p))
(if *random-typeout-buffers*
(change-to-buffer (caar *random-typeout-buffers*))
(editor-error "There are no random typeout buffers.")))
(defcommand "Room" (p)
"Display stats on allocated storage."
"Run Room into a With-Random-Typeout window."
(declare (ignore p))
(with-pop-up-display (*standard-output*)
(room)))
This is used by the : edit - level modeline field which is defined in Main . Lisp .
;;;
(defvar *recursive-edit-count* 0)
(defun do-recursive-edit ()
"Does a recursive edit, wrapping []'s around the modeline of the current
window during its execution. The current window and buffer are saved
beforehand and restored afterward. If they have been deleted by the
time the edit is done then an editor-error is signalled."
(let* ((win (current-window))
(buf (current-buffer)))
(unwind-protect
(let ((*recursive-edit-count* (1+ *recursive-edit-count*)))
(update-modeline-field *echo-area-buffer* *echo-area-window*
(modeline-field :edit-level))
(recursive-edit))
(update-modeline-field *echo-area-buffer* *echo-area-window*
(modeline-field :edit-level))
(unless (and (memq win *window-list*) (memq buf *buffer-list*))
(editor-error "Old window or buffer has been deleted."))
(setf (current-window) win)
(unless (eq (window-buffer win) buf)
(setf (window-buffer win) buf))
(setf (current-buffer) buf))))
(defcommand "Exit Recursive Edit" (p)
"Exit a level of recursive edit. Signals an error when not in a
recursive edit."
"Exit a level of recursive edit. Signals an error when not in a
recursive edit."
(declare (ignore p))
(unless (in-recursive-edit) (editor-error "Not in a recursive edit!"))
(exit-recursive-edit ()))
(defcommand "Abort Recursive Edit" (p)
"Abort the current recursive edit. Signals an error when not in a
recursive edit."
"Abort the current recursive edit. Signals an error when not in a
recursive edit."
(declare (ignore p))
(unless (in-recursive-edit) (editor-error "Not in a recursive edit!"))
(abort-recursive-edit "Recursive edit aborted."))
TRANSPOSE REGIONS uses CURRENT - REGION to signal an error if the current
;;; region is not active and to get start2 and end2 in proper order. Delete1,
delete2 , and are necessary since we are possibly ROTATEF'ing the
locals end1 / start1 , start1 / start2 , and end1 / end2 , and we need to know which
;;; marks to dispose of at the end of all this stuff. When we actually get to
;;; swapping the regions, we must delete both up front if they both are to be
deleted since we do n't know what kind of marks are in start1 , start2 , end1 ,
;;; and end2, and the marks will be moving around unpredictably as we insert
text at them . We copy point into ipoint for insertion purposes since one
of our four marks is the point .
;;;
(defcommand "Transpose Regions" (p)
"Transpose two regions with endpoints defined by the mark stack and point.
To use: mark start of region1, mark end of region1, mark start of region2,
and place point at end of region2. Invoking this immediately following
one use will put the regions back, but you will have to activate the
current region."
"Transpose two regions with endpoints defined by the mark stack and point."
(declare (ignore p))
(unless (>= (ring-length (value buffer-mark-ring)) 3)
(editor-error "Need two marked regions to do Transpose Regions."))
(let* ((region (current-region))
(end2 (region-end region))
(start2 (region-start region))
(delete1 (pop-buffer-mark))
(end1 (pop-buffer-mark))
(delete2 end1)
(start1 (pop-buffer-mark))
(delete3 start1))
;;get marks in the right order, to simplify the code that follows
(unless (mark<= start1 end1) (rotatef start1 end1))
(unless (mark<= start1 start2)
(rotatef start1 start2)
(rotatef end1 end2))
;;order now guaranteed: <Buffer Start> start1 end1 start2 end2 <Buffer End>
(unless (mark<= end1 start2)
(editor-error "Can't transpose overlapping regions."))
(let* ((adjacent-p (mark= end1 start2))
(region1 (delete-and-save-region (region start1 end1)))
(region2 (unless adjacent-p
(delete-and-save-region (region start2 end2))))
(point (current-point)))
(with-mark ((ipoint point :left-inserting))
(let ((save-end2-loc (push-buffer-mark (copy-mark end2))))
(ninsert-region (move-mark ipoint end2) region1)
(push-buffer-mark (copy-mark ipoint))
(cond (adjacent-p
(push-buffer-mark (copy-mark start2))
(move-mark point save-end2-loc))
(t (push-buffer-mark (copy-mark end1))
(ninsert-region (move-mark ipoint end1) region2)
(move-mark point ipoint))))))
(delete-mark delete1)
(delete-mark delete2)
(delete-mark delete3)))
(defcommand "Goto Absolute Line" (p)
"Goes to the indicated line, if you counted them starting at the beginning
of the buffer with the number one. If a prefix argument is supplied, that
is the line numbe; otherwise, the user is prompted."
"Go to a user perceived line number."
(let ((p (or p (prompt-for-expression
:prompt "Line number: "
:help "Enter an absolute line number to goto."))))
(unless (and (integerp p) (plusp p))
(editor-error "Must supply a positive integer."))
(let ((point (current-point)))
(with-mark ((m point))
(unless (line-offset (buffer-start m) (1- p) 0)
(editor-error "Not enough lines in buffer."))
(move-mark point m)))))
;;;; Mouse Commands.
(defcommand "Do Nothing" (p)
"Do nothing.
With prefix argument, do it that many times."
"Do nothing p times."
(dotimes (i (or p 1)))
(setf (last-command-type) (last-command-type)))
(defun maybe-change-window (window)
(unless (eq window (current-window))
(when (or (eq window *echo-area-window*)
(eq (current-window) *echo-area-window*)
(member window *random-typeout-buffers*
:key #'(lambda (cons)
(hi::random-typeout-stream-window (cdr cons)))))
(supply-generic-pointer-up-function #'lisp::do-nothing)
(editor-error "I'm afraid I can't let you do that Dave."))
(setf (current-window) window)
(let ((buffer (window-buffer window)))
(unless (eq (current-buffer) buffer)
(setf (current-buffer) buffer)))))
(defcommand "Top Line to Here" (p)
"Move the top line to the line the mouse is on.
If in the first two columns then scroll continuously until the button is
released."
"Move the top line to the line the mouse is on."
(declare (ignore p))
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless y (editor-error))
(cond ((< x 2)
(loop
(when (listen-editor-input *editor-input*) (return))
(scroll-window window -1)
(redisplay)
(editor-finish-output window)))
(t
(scroll-window window (- y))))))
(defcommand "Here to Top of Window" (p)
"Move the line the mouse is on to the top of the window.
If in the first two columns then scroll continuously until the button is
released."
"Move the line the mouse is on to the top of the window."
(declare (ignore p))
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless y (editor-error))
(cond ((< x 2)
(loop
(when (listen-editor-input *editor-input*) (return))
(scroll-window window 1)
(redisplay)
(editor-finish-output window)))
(t
(scroll-window window y)))))
(defvar *generic-pointer-up-fun* nil
"This is the function for the \"Generic Pointer Up\" command that defines
its action. Other commands set this in preparation for this command's
invocation.")
;;;
(defun supply-generic-pointer-up-function (fun)
"This provides the action \"Generic Pointer Up\" command performs."
(check-type fun function)
(setf *generic-pointer-up-fun* fun))
(defcommand "Generic Pointer Up" (p)
"Other commands determine this command's action by supplying functions that
this command invokes. The following built-in commands supply the following
generic up actions:
\"Point to Here\"
When the position of the pointer is different than the current
point, the action pushes a buffer mark at point and moves point
to the pointer's position.
\"Bufed Goto and Quit\"
The action is a no-op."
"Invoke whatever is on *generic-pointer-up-fun*."
(declare (ignore p))
(unless *generic-pointer-up-fun*
(editor-error "No commands have supplied a \"Generic Pointer Up\" action."))
(funcall *generic-pointer-up-fun*))
(defcommand "Point to Here" (p)
"Move the point to the position of the mouse.
If in the modeline, move to the absolute position in the file indicated by
the position within the modeline, pushing the old position on the mark
stack. This supplies a function \"Generic Pointer Up\" invokes if it runs
without any intervening generic pointer up predecessors running. If the
position of the pointer is different than the current point when the user
invokes \"Generic Pointer Up\", then this function pushes a buffer mark at
point and moves point to the pointer's position. This allows the user to
mark off a region with the mouse."
"Move the point to the position of the mouse."
(declare (ignore p))
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless x (editor-error))
(maybe-change-window window)
(if y
(let ((m (cursorpos-to-mark x y window)))
(unless m (editor-error))
(move-mark (current-point) m))
(let* ((buffer (window-buffer window))
(region (buffer-region buffer))
(point (buffer-point buffer)))
(push-buffer-mark (copy-mark point))
(move-mark point (region-start region))
(line-offset point (round (* (1- (count-lines region)) x)
(1- (window-width window)))))))
(supply-generic-pointer-up-function #'point-to-here-up-action))
(defun point-to-here-up-action ()
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless x (editor-error))
(when y
(maybe-change-window window)
(let ((m (cursorpos-to-mark x y window)))
(unless m (editor-error))
(when (eq (line-buffer (mark-line (current-point)))
(line-buffer (mark-line m)))
(unless (mark= m (current-point))
(push-buffer-mark (copy-mark (current-point)) t)))
(move-mark (current-point) m)))))
(defcommand "Insert Kill Buffer" (p)
"Move current point to the mouse location and insert the kill buffer."
"Move current point to the mouse location and insert the kill buffer."
(declare (ignore p))
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless x (editor-error))
(maybe-change-window window)
(if y
(let ((m (cursorpos-to-mark x y window)))
(unless m (editor-error))
(move-mark (current-point) m)
(un-kill-command nil))
(editor-error "Can't insert kill buffer in modeline."))))
Page commands & stuff .
(defvar *goto-page-last-num* 0)
(defvar *goto-page-last-string* "")
(defcommand "Goto Page" (p)
"Go to an absolute page number (argument). If no argument, then go to
next page. A negative argument moves back that many pages if possible.
If argument is zero, prompt for string and goto page with substring
in title."
"Go to an absolute page number (argument). If no argument, then go to
next page. A negative argument moves back that many pages if possible.
If argument is zero, prompt for string and goto page with substring
in title."
(let ((point (current-point)))
(cond ((not p)
(page-offset point 1))
((zerop p)
(let* ((againp (eq (last-command-type) :goto-page-zero))
(name (prompt-for-string :prompt "Substring of page title: "
:default (if againp
*goto-page-last-string*
*parse-default*)))
(dir (page-directory (current-buffer)))
(i 1))
(declare (simple-string name))
(cond ((not againp)
(push-buffer-mark (copy-mark point)))
((string-equal name *goto-page-last-string*)
(setf dir (nthcdr *goto-page-last-num* dir))
(setf i (1+ *goto-page-last-num*))))
(loop
(when (null dir)
(editor-error "No page title contains ~S." name))
(when (search name (the simple-string (car dir))
:test #'char-equal)
(goto-page point i)
(setf (last-command-type) :goto-page-zero)
(setf *goto-page-last-num* i)
(setf *goto-page-last-string* name)
(return t))
(incf i)
(setf dir (cdr dir)))))
((minusp p)
(page-offset point p))
(t (goto-page point p)))
(line-start (move-mark (window-display-start (current-window)) point))))
(defun goto-page (mark i)
(with-mark ((m mark))
(buffer-start m)
(unless (page-offset m (1- i))
(editor-error "No page numbered ~D." i))
(move-mark mark m)))
(defcommand "View Page Directory" (p)
"Print a listing of the first non-blank line after each page mark
in a pop-up window."
"Print a listing of the first non-blank line after each page mark
in a pop-up window."
(declare (ignore p))
(let ((dir (page-directory (current-buffer))))
(declare (list dir))
(with-pop-up-display (s :height (1+ (the fixnum (length dir))))
(display-page-directory s dir))))
(defcommand "Insert Page Directory" (p)
"Insert a listing of the first non-blank line after each page mark at
the beginning of the buffer. A mark is dropped before going to the
beginning of the buffer. If an argument is supplied, insert the page
directory at point."
"Insert a listing of the first non-blank line after each page mark at
the beginning of the buffer."
(let ((point (current-point)))
(unless p
(push-buffer-mark (copy-mark point))
(buffer-start point))
(push-buffer-mark (copy-mark point))
(display-page-directory (make-hemlock-output-stream point :full)
(page-directory (current-buffer))))
(setf (last-command-type) :ephemerally-active))
(defun display-page-directory (stream directory)
"This writes the list of strings, directory, to stream, enumerating them
in a field of three characters. The number and string are separated by
two spaces, and the first line contains headings for the numbers and
strings columns."
(write-line "Page First Non-blank Line" stream)
(do ((dir directory (cdr dir))
(count 1 (1+ count)))
((null dir))
(declare (fixnum count))
(format stream "~3D " count)
(write-line (car dir) stream)))
(defun page-directory (buffer)
"Return a list of strings where each is the first non-blank line
following a :page-delimiter in buffer."
(with-mark ((m (buffer-point buffer)))
(buffer-start m)
(let ((end-of-buffer (buffer-end-mark buffer)) result)
(loop ;over pages.
for first non - blank line .
(cond ((not (blank-after-p m))
(let* ((str (line-string (mark-line m)))
(len (length str)))
(declare (simple-string str))
(push (if (and (> len 1)
(= (character-attribute :page-delimiter
(schar str 0))
1))
(subseq str 1)
str)
result))
(unless (page-offset m 1)
(return-from page-directory (nreverse result)))
(when (mark= m end-of-buffer)
(return-from page-directory (nreverse result)))
(return))
((not (line-offset m 1 0))
(return-from page-directory (nreverse result)))
((= (character-attribute :page-delimiter (next-character m))
1)
(push "" result)
(mark-after m)
(return))))))))
(defcommand "Previous Page" (p)
"Move to the beginning of the current page.
With prefix argument move that many pages."
"Move backward P pages."
(let ((point (current-point)))
(unless (page-offset point (- (or p 1)))
(editor-error "No such page."))
(line-start (move-mark (window-display-start (current-window)) point))))
(defcommand "Next Page" (p)
"Move to the beginning of the next page.
With prefix argument move that many pages."
"Move forward P pages."
(let ((point (current-point)))
(unless (page-offset point (or p 1))
(editor-error "No such page."))
(line-start (move-mark (window-display-start (current-window)) point))))
(defcommand "Mark Page" (p)
"Put point at beginning, mark at end of current page.
With prefix argument, mark the page that many pages after the current one."
"Mark the P'th page after the current one."
(let ((point (current-point)))
(if p
(unless (page-offset point (1+ p)) (editor-error "No such page."))
(page-offset point 1)) ;If this loses, we're at buffer-end.
(with-mark ((m point))
(unless (page-offset point -1)
(editor-error "No such page."))
(push-buffer-mark (copy-mark m) t)
(line-start (move-mark (window-display-start (current-window)) point)))))
(defun page-offset (mark n)
"Move mark past n :page-delimiters that are in the zero'th line position.
If a :page-delimiter is the immediately next character after mark in the
appropriate direction, then skip it before starting."
(cond ((plusp n)
(find-attribute mark :page-delimiter #'zerop)
(dotimes (i n mark)
(unless (next-character mark) (return nil))
(loop
(unless (find-attribute mark :page-delimiter)
(return-from page-offset nil))
(unless (mark-after mark)
(return (if (= i (1- n)) mark)))
(when (= (mark-charpos mark) 1) (return)))))
(t
(reverse-find-attribute mark :page-delimiter #'zerop)
(prog1
(dotimes (i (- n) mark)
(unless (previous-character mark) (return nil))
(loop
(unless (reverse-find-attribute mark :page-delimiter)
(return-from page-offset nil))
(mark-before mark)
(when (= (mark-charpos mark) 0) (return))))
(let ((buffer (line-buffer (mark-line mark))))
(unless (or (not buffer) (mark= mark (buffer-start-mark buffer)))
(mark-after mark)))))))
;;;; Counting some stuff
(defcommand "Count Lines Page" (p)
"Display number of lines in current page and position within page.
With prefix argument do on entire buffer."
"Count some lines, Man."
(let ((point (current-point)))
(if p
(let ((r (buffer-region (current-buffer))))
(count-lines-function "Buffer" (region-start r) point (region-end r)))
(with-mark ((m1 point)
(m2 point))
(unless (and (= (character-attribute :page-delimiter
(previous-character m1))
1)
(= (mark-charpos m1) 1))
(page-offset m1 -1))
(unless (and (= (character-attribute :page-delimiter
(next-character m2))
1)
(= (mark-charpos m2) 0))
(page-offset m2 1))
(count-lines-function "Page" m1 point m2)))))
(defun count-lines-function (msg start mark end)
(let ((before (1- (count-lines (region start mark))))
(after (count-lines (region mark end))))
(message "~A: ~D lines, ~D/~D" msg (+ before after) before after)))
(defcommand "Count Lines" (p)
"Display number of lines in the region."
"Display number of lines in the region."
(declare (ignore p))
(multiple-value-bind (region activep) (get-count-region)
(message "~:[After point~;Active region~]: ~A lines"
activep (count-lines region))))
(defcommand "Count Words" (p)
"Prints in the Echo Area the number of words in the region
between the point and the mark by using word-offset. The
argument is ignored."
"Prints Number of Words in the Region"
(declare (ignore p))
(multiple-value-bind (region activep) (get-count-region)
(let ((end-mark (region-end region)))
(with-mark ((beg-mark (region-start region)))
(let ((word-count 0))
(loop
(when (mark>= beg-mark end-mark)
(return))
(unless (word-offset beg-mark 1)
(return))
(incf word-count))
(message "~:[After point~;Active region~]: ~D Word~:P"
activep word-count))))))
GET - COUNT - REGION -- Internal Interface .
;;;
;;; Returns the active region or the region between point and end-of-buffer.
As a second value , it returns whether the region was active .
;;;
;;; Some searching commands use this routine.
;;;
(defun get-count-region ()
(if (region-active-p)
(values (current-region) t)
(values (region (current-point) (buffer-end-mark (current-buffer)))
nil)))
;;;; Some modes:
(defcommand "Fundamental Mode" (p)
"Put the current buffer into \"Fundamental\" mode."
"Put the current buffer into \"Fundamental\" mode."
(declare (ignore p))
(setf (buffer-major-mode (current-buffer)) "Fundamental"))
;;;
;;; Text mode.
;;;
(defmode "Text" :major-p t)
(defcommand "Text Mode" (p)
"Put the current buffer into \"Text\" mode."
"Put the current buffer into \"Text\" mode."
(declare (ignore p))
(setf (buffer-major-mode (current-buffer)) "Text"))
;;;
;;; Caps-lock mode.
;;;
(defmode "CAPS-LOCK")
(defcommand "Caps Lock Mode" (p)
"Simulate having a CAPS LOCK key. Toggle CAPS-LOCK mode. Zero or a
negative argument turns it off, while a positive argument turns it
on."
"Simulate having a CAPS LOCK key. Toggle CAPS-LOCK mode. Zero or a
negative argument turns it off, while a positive argument turns it
on."
(setf (buffer-minor-mode (current-buffer) "CAPS-LOCK")
(if p
(plusp p)
(not (buffer-minor-mode (current-buffer) "CAPS-LOCK")))))
(defcommand "Self Insert Caps Lock" (p)
"Insert the last character typed, or the argument number of them.
If the last character was an alphabetic character, then insert its
capital form."
"Insert the last character typed, or the argument number of them.
If the last character was an alphabetic character, then insert its
capital form."
(let ((char (char-upcase (ext:key-event-char *last-key-event-typed*))))
(if (and p (> p 1))
(insert-string (current-point) (make-string p :initial-element char))
(insert-character (current-point) char))))
| null | https://raw.githubusercontent.com/rtoy/cmucl/9b1abca53598f03a5b39ded4185471a5b8777dea/src/hemlock/morecoms.lisp | lisp | -*- Log: hemlock.log; Package: Hemlock -*-
**********************************************************************
**********************************************************************
Even more commands...
Casing commands...
Lisp's notion are too annoying.
TWIDDLE-REGION implements "Uppercase Region" and "Lowercase Region".
don't delete marks start and end since undo stuff will.
More stuff.
Pre-calculate the number of characters that need to be deleted
and any remaining white space filling, allowing modification to
be avoided if there are not enough characters to delete.
region is not active and to get start2 and end2 in proper order. Delete1,
marks to dispose of at the end of all this stuff. When we actually get to
swapping the regions, we must delete both up front if they both are to be
and end2, and the marks will be moving around unpredictably as we insert
get marks in the right order, to simplify the code that follows
order now guaranteed: <Buffer Start> start1 end1 start2 end2 <Buffer End>
otherwise, the user is prompted."
Mouse Commands.
over pages.
If this loses, we're at buffer-end.
Counting some stuff
Returns the active region or the region between point and end-of-buffer.
Some searching commands use this routine.
Some modes:
Text mode.
Caps-lock mode.
| This code was written as part of the CMU Common Lisp project at
Carnegie Mellon University , and has been placed in the public domain .
(ext:file-comment
"$Header: src/hemlock/morecoms.lisp $")
Written by and .
(in-package "HEMLOCK")
(defhvar "Region Query Size"
"A number-of-lines threshold that destructive, undoable region commands
should ask the user about when the indicated region is too big."
:value 30)
(defun check-region-query-size (region)
"Checks the number of lines in region against \"Region Query Size\" and
asks the user if the region crosses this threshold. If the user responds
negatively, then an editor error is signaled."
(let ((threshold (or (value region-query-size) 0)))
(if (and (plusp threshold)
(>= (count-lines region) threshold)
(not (prompt-for-y-or-n
:prompt "Region size exceeds \"Region Query Size\". Confirm: "
:must-exist t)))
(editor-error))))
(defcommand "Uppercase Word" (p)
"Uppercase a word at point.
With prefix argument uppercase that many words."
"Uppercase p words at the point."
(filter-words p (current-point) #'string-upcase))
(defcommand "Lowercase Word" (p)
"Uppercase a word at point.
With prefix argument uppercase that many words."
"Uppercase p words at the point."
(filter-words p (current-point) #'string-downcase))
FILTER - WORDS implements " Uppercase Word " and " Lowercase Word " .
(defun filter-words (p point function)
(let ((arg (or p 1)))
(with-mark ((mark point))
(if (word-offset (if (minusp arg) mark point) arg)
(filter-region function (region mark point))
(editor-error "Not enough words.")))))
" Capitalize Word " is different than uppercasing and lowercasing because
the differences between Hemlock 's notion of what a word is and Common
(defcommand "Capitalize Word" (p)
"Lowercase a word capitalizing the first character. With a prefix
argument, capitalize that many words. A negative argument capitalizes
words before the point, but leaves the point where it was."
"Capitalize p words at the point."
(let ((point (current-point))
(arg (or p 1)))
(with-mark ((start point :left-inserting)
(end point))
(when (minusp arg)
(unless (word-offset start arg) (editor-error "No previous word.")))
(do ((region (region start end))
(cnt (abs arg) (1- cnt)))
((zerop cnt) (move-mark point end))
(unless (find-attribute start :word-delimiter #'zerop)
(editor-error "No next word."))
(move-mark end start)
(find-attribute end :word-delimiter)
(loop
(when (mark= start end)
(move-mark point end)
(editor-error "No alphabetic characters in word."))
(when (alpha-char-p (next-character start)) (return))
(character-offset start 1))
(setf (next-character start) (char-upcase (next-character start)))
(mark-after start)
(filter-region #'string-downcase region)))))
(defcommand "Uppercase Region" (p)
"Uppercase words from point to mark."
"Uppercase words from point to mark."
(declare (ignore p))
(twiddle-region (current-region) #'string-upcase "Uppercase Region"))
(defcommand "Lowercase Region" (p)
"Lowercase words from point to mark."
"Lowercase words from point to mark."
(declare (ignore p))
(twiddle-region (current-region) #'string-downcase "Lowercase Region"))
(defun twiddle-region (region function name)
(start (copy-mark (region-start region) :left-inserting))
(end (copy-mark (region-end region) :left-inserting)))
(let* ((region (region start end))
(undo-region (copy-region region)))
(check-region-query-size region)
(filter-region function region)
(make-region-undo :twiddle name region undo-region))))
(defcommand "Delete Previous Character Expanding Tabs" (p)
"Delete the previous character.
When deleting a tab pretend it is the equivalent number of spaces.
With prefix argument, do it that many times."
"Delete the P previous characters, expanding tabs into spaces."
(let ((point (current-point))
(n (or p 1)))
(when (minusp n)
(editor-error "Delete Previous Character Expanding Tabs only accepts ~
positive arguments."))
(let ((errorp nil)
(del 0)
(fill 0))
(with-mark ((mark point))
(dotimes (i n)
(if (> fill 0)
(decf fill)
(let ((prev (previous-character mark)))
(cond ((and prev (char= prev #\tab))
(let ((pos (mark-column mark)))
(mark-before mark)
(incf fill (- pos (mark-column mark) 1)))
(incf del))
((mark-before mark)
(incf del))
(t
(setq errorp t)
(return)))))))
(cond ((and (not errorp) (kill-characters point (- del)))
(with-mark ((mark point :left-inserting))
(dotimes (i fill)
(insert-character mark #\space))))
(t
(editor-error "There were not ~D characters before point." n))))))
(defvar *scope-table*
(list (make-string-table :initial-contents
'(("Global" . :global)
("Buffer" . :buffer)
("Mode" . :mode)))))
(defun prompt-for-place (prompt help)
(multiple-value-bind (word val)
(prompt-for-keyword *scope-table* :prompt prompt
:help help :default "Global")
(declare (ignore word))
(case val
(:buffer
(values :buffer (prompt-for-buffer :help "Buffer to be local to."
:default (current-buffer))))
(:mode
(values :mode (prompt-for-keyword
(list *mode-names*)
:prompt "Mode: "
:help "Mode to be local to."
:default (buffer-major-mode (current-buffer)))))
(:global :global))))
(defcommand "Bind Key" (p)
"Bind a command to a key.
The command, key and place to make the binding are prompted for."
"Prompt for stuff to do a bind-key."
(declare (ignore p))
(multiple-value-call #'bind-key
(values (prompt-for-keyword
(list *command-names*)
:prompt "Command to bind: "
:help "Name of command to bind to a key."))
(values (prompt-for-key
:prompt "Bind to: " :must-exist nil
:help "Key to bind command to, confirm to complete."))
(prompt-for-place "Kind of binding: "
"The kind of binding to make.")))
(defcommand "Delete Key Binding" (p)
"Delete a key binding.
The key and place to remove the binding are prompted for."
"Prompt for stuff to do a delete-key-binding."
(declare (ignore p))
(let ((key (prompt-for-key
:prompt "Delete binding: " :must-exist nil
:help "Key to delete binding from.")))
(multiple-value-bind (kind where)
(prompt-for-place "Kind of binding: "
"The kind of binding to make.")
(unless (get-command key kind where)
(editor-error "No such binding: ~S" key))
(delete-key-binding key kind where))))
(defcommand "Set Variable" (p)
"Prompt for a Hemlock variable and a new value."
"Prompt for a Hemlock variable and a new value."
(declare (ignore p))
(multiple-value-bind (name var)
(prompt-for-variable
:prompt "Variable: "
:help "The name of a variable to set.")
(declare (ignore name))
(setf (variable-value var)
(handle-lisp-errors
(eval (prompt-for-expression
:prompt "Value: "
:help "Expression to evaluate for new value."))))))
(defcommand "Defhvar" (p)
"Define a hemlock variable in some location. If the named variable exists
currently, its documentation is propagated to the new instance, but this
never prompts for documentation."
"Define a hemlock variable in some location."
(declare (ignore p))
(let* ((name (nstring-capitalize (prompt-for-variable :must-exist nil)))
(var (string-to-variable name))
(doc (if (hemlock-bound-p var)
(variable-documentation var)
""))
(hooks (if (hemlock-bound-p var) (variable-hooks var)))
(val (prompt-for-expression :prompt "Variable value: "
:help "Value for the variable.")))
(multiple-value-bind
(kind where)
(prompt-for-place
"Kind of binding: "
"Whether the variable is global, mode, or buffer specific.")
(if (eq kind :global)
(defhvar name doc :value val :hooks hooks)
(defhvar name doc kind where :value val :hooks hooks)))))
(defcommand "List Buffers" (p)
"Show a list of all buffers.
If the buffer is modified then a * is displayed before the name. If there
is an associated file then it's name is displayed last. With prefix
argument, only list modified buffers."
"Display the names of all buffers in a with-random-typeout window."
(with-pop-up-display (s)
(do-strings (n b *buffer-names*)
(declare (simple-string n))
(unless (or (eq b *echo-area-buffer*)
(assoc b *random-typeout-buffers* :test #'eq))
(let ((modified (buffer-modified b))
(buffer-pathname (buffer-pathname b)))
(when (or (not p) modified)
(write-char (if modified #\* #\space) s)
(if buffer-pathname
(format s "~A ~25T~A~:[~68T~A~;~]~%"
(file-namestring buffer-pathname)
(directory-namestring buffer-pathname)
(string= (pathname-to-buffer-name buffer-pathname) n)
n)
(format s "~A~68T~D Line~:P~%"
n (count-lines (buffer-region b))))))))))
(defcommand "Select Random Typeout Buffer" (p)
"Select last random typeout buffer."
"Select last random typeout buffer."
(declare (ignore p))
(if *random-typeout-buffers*
(change-to-buffer (caar *random-typeout-buffers*))
(editor-error "There are no random typeout buffers.")))
(defcommand "Room" (p)
"Display stats on allocated storage."
"Run Room into a With-Random-Typeout window."
(declare (ignore p))
(with-pop-up-display (*standard-output*)
(room)))
This is used by the : edit - level modeline field which is defined in Main . Lisp .
(defvar *recursive-edit-count* 0)
(defun do-recursive-edit ()
"Does a recursive edit, wrapping []'s around the modeline of the current
window during its execution. The current window and buffer are saved
beforehand and restored afterward. If they have been deleted by the
time the edit is done then an editor-error is signalled."
(let* ((win (current-window))
(buf (current-buffer)))
(unwind-protect
(let ((*recursive-edit-count* (1+ *recursive-edit-count*)))
(update-modeline-field *echo-area-buffer* *echo-area-window*
(modeline-field :edit-level))
(recursive-edit))
(update-modeline-field *echo-area-buffer* *echo-area-window*
(modeline-field :edit-level))
(unless (and (memq win *window-list*) (memq buf *buffer-list*))
(editor-error "Old window or buffer has been deleted."))
(setf (current-window) win)
(unless (eq (window-buffer win) buf)
(setf (window-buffer win) buf))
(setf (current-buffer) buf))))
(defcommand "Exit Recursive Edit" (p)
"Exit a level of recursive edit. Signals an error when not in a
recursive edit."
"Exit a level of recursive edit. Signals an error when not in a
recursive edit."
(declare (ignore p))
(unless (in-recursive-edit) (editor-error "Not in a recursive edit!"))
(exit-recursive-edit ()))
(defcommand "Abort Recursive Edit" (p)
"Abort the current recursive edit. Signals an error when not in a
recursive edit."
"Abort the current recursive edit. Signals an error when not in a
recursive edit."
(declare (ignore p))
(unless (in-recursive-edit) (editor-error "Not in a recursive edit!"))
(abort-recursive-edit "Recursive edit aborted."))
TRANSPOSE REGIONS uses CURRENT - REGION to signal an error if the current
delete2 , and are necessary since we are possibly ROTATEF'ing the
locals end1 / start1 , start1 / start2 , and end1 / end2 , and we need to know which
deleted since we do n't know what kind of marks are in start1 , start2 , end1 ,
text at them . We copy point into ipoint for insertion purposes since one
of our four marks is the point .
(defcommand "Transpose Regions" (p)
"Transpose two regions with endpoints defined by the mark stack and point.
To use: mark start of region1, mark end of region1, mark start of region2,
and place point at end of region2. Invoking this immediately following
one use will put the regions back, but you will have to activate the
current region."
"Transpose two regions with endpoints defined by the mark stack and point."
(declare (ignore p))
(unless (>= (ring-length (value buffer-mark-ring)) 3)
(editor-error "Need two marked regions to do Transpose Regions."))
(let* ((region (current-region))
(end2 (region-end region))
(start2 (region-start region))
(delete1 (pop-buffer-mark))
(end1 (pop-buffer-mark))
(delete2 end1)
(start1 (pop-buffer-mark))
(delete3 start1))
(unless (mark<= start1 end1) (rotatef start1 end1))
(unless (mark<= start1 start2)
(rotatef start1 start2)
(rotatef end1 end2))
(unless (mark<= end1 start2)
(editor-error "Can't transpose overlapping regions."))
(let* ((adjacent-p (mark= end1 start2))
(region1 (delete-and-save-region (region start1 end1)))
(region2 (unless adjacent-p
(delete-and-save-region (region start2 end2))))
(point (current-point)))
(with-mark ((ipoint point :left-inserting))
(let ((save-end2-loc (push-buffer-mark (copy-mark end2))))
(ninsert-region (move-mark ipoint end2) region1)
(push-buffer-mark (copy-mark ipoint))
(cond (adjacent-p
(push-buffer-mark (copy-mark start2))
(move-mark point save-end2-loc))
(t (push-buffer-mark (copy-mark end1))
(ninsert-region (move-mark ipoint end1) region2)
(move-mark point ipoint))))))
(delete-mark delete1)
(delete-mark delete2)
(delete-mark delete3)))
(defcommand "Goto Absolute Line" (p)
"Goes to the indicated line, if you counted them starting at the beginning
of the buffer with the number one. If a prefix argument is supplied, that
"Go to a user perceived line number."
(let ((p (or p (prompt-for-expression
:prompt "Line number: "
:help "Enter an absolute line number to goto."))))
(unless (and (integerp p) (plusp p))
(editor-error "Must supply a positive integer."))
(let ((point (current-point)))
(with-mark ((m point))
(unless (line-offset (buffer-start m) (1- p) 0)
(editor-error "Not enough lines in buffer."))
(move-mark point m)))))
(defcommand "Do Nothing" (p)
"Do nothing.
With prefix argument, do it that many times."
"Do nothing p times."
(dotimes (i (or p 1)))
(setf (last-command-type) (last-command-type)))
(defun maybe-change-window (window)
(unless (eq window (current-window))
(when (or (eq window *echo-area-window*)
(eq (current-window) *echo-area-window*)
(member window *random-typeout-buffers*
:key #'(lambda (cons)
(hi::random-typeout-stream-window (cdr cons)))))
(supply-generic-pointer-up-function #'lisp::do-nothing)
(editor-error "I'm afraid I can't let you do that Dave."))
(setf (current-window) window)
(let ((buffer (window-buffer window)))
(unless (eq (current-buffer) buffer)
(setf (current-buffer) buffer)))))
(defcommand "Top Line to Here" (p)
"Move the top line to the line the mouse is on.
If in the first two columns then scroll continuously until the button is
released."
"Move the top line to the line the mouse is on."
(declare (ignore p))
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless y (editor-error))
(cond ((< x 2)
(loop
(when (listen-editor-input *editor-input*) (return))
(scroll-window window -1)
(redisplay)
(editor-finish-output window)))
(t
(scroll-window window (- y))))))
(defcommand "Here to Top of Window" (p)
"Move the line the mouse is on to the top of the window.
If in the first two columns then scroll continuously until the button is
released."
"Move the line the mouse is on to the top of the window."
(declare (ignore p))
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless y (editor-error))
(cond ((< x 2)
(loop
(when (listen-editor-input *editor-input*) (return))
(scroll-window window 1)
(redisplay)
(editor-finish-output window)))
(t
(scroll-window window y)))))
(defvar *generic-pointer-up-fun* nil
"This is the function for the \"Generic Pointer Up\" command that defines
its action. Other commands set this in preparation for this command's
invocation.")
(defun supply-generic-pointer-up-function (fun)
"This provides the action \"Generic Pointer Up\" command performs."
(check-type fun function)
(setf *generic-pointer-up-fun* fun))
(defcommand "Generic Pointer Up" (p)
"Other commands determine this command's action by supplying functions that
this command invokes. The following built-in commands supply the following
generic up actions:
\"Point to Here\"
When the position of the pointer is different than the current
point, the action pushes a buffer mark at point and moves point
to the pointer's position.
\"Bufed Goto and Quit\"
The action is a no-op."
"Invoke whatever is on *generic-pointer-up-fun*."
(declare (ignore p))
(unless *generic-pointer-up-fun*
(editor-error "No commands have supplied a \"Generic Pointer Up\" action."))
(funcall *generic-pointer-up-fun*))
(defcommand "Point to Here" (p)
"Move the point to the position of the mouse.
If in the modeline, move to the absolute position in the file indicated by
the position within the modeline, pushing the old position on the mark
stack. This supplies a function \"Generic Pointer Up\" invokes if it runs
without any intervening generic pointer up predecessors running. If the
position of the pointer is different than the current point when the user
invokes \"Generic Pointer Up\", then this function pushes a buffer mark at
point and moves point to the pointer's position. This allows the user to
mark off a region with the mouse."
"Move the point to the position of the mouse."
(declare (ignore p))
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless x (editor-error))
(maybe-change-window window)
(if y
(let ((m (cursorpos-to-mark x y window)))
(unless m (editor-error))
(move-mark (current-point) m))
(let* ((buffer (window-buffer window))
(region (buffer-region buffer))
(point (buffer-point buffer)))
(push-buffer-mark (copy-mark point))
(move-mark point (region-start region))
(line-offset point (round (* (1- (count-lines region)) x)
(1- (window-width window)))))))
(supply-generic-pointer-up-function #'point-to-here-up-action))
(defun point-to-here-up-action ()
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless x (editor-error))
(when y
(maybe-change-window window)
(let ((m (cursorpos-to-mark x y window)))
(unless m (editor-error))
(when (eq (line-buffer (mark-line (current-point)))
(line-buffer (mark-line m)))
(unless (mark= m (current-point))
(push-buffer-mark (copy-mark (current-point)) t)))
(move-mark (current-point) m)))))
(defcommand "Insert Kill Buffer" (p)
"Move current point to the mouse location and insert the kill buffer."
"Move current point to the mouse location and insert the kill buffer."
(declare (ignore p))
(multiple-value-bind (x y window)
(last-key-event-cursorpos)
(unless x (editor-error))
(maybe-change-window window)
(if y
(let ((m (cursorpos-to-mark x y window)))
(unless m (editor-error))
(move-mark (current-point) m)
(un-kill-command nil))
(editor-error "Can't insert kill buffer in modeline."))))
Page commands & stuff .
(defvar *goto-page-last-num* 0)
(defvar *goto-page-last-string* "")
(defcommand "Goto Page" (p)
"Go to an absolute page number (argument). If no argument, then go to
next page. A negative argument moves back that many pages if possible.
If argument is zero, prompt for string and goto page with substring
in title."
"Go to an absolute page number (argument). If no argument, then go to
next page. A negative argument moves back that many pages if possible.
If argument is zero, prompt for string and goto page with substring
in title."
(let ((point (current-point)))
(cond ((not p)
(page-offset point 1))
((zerop p)
(let* ((againp (eq (last-command-type) :goto-page-zero))
(name (prompt-for-string :prompt "Substring of page title: "
:default (if againp
*goto-page-last-string*
*parse-default*)))
(dir (page-directory (current-buffer)))
(i 1))
(declare (simple-string name))
(cond ((not againp)
(push-buffer-mark (copy-mark point)))
((string-equal name *goto-page-last-string*)
(setf dir (nthcdr *goto-page-last-num* dir))
(setf i (1+ *goto-page-last-num*))))
(loop
(when (null dir)
(editor-error "No page title contains ~S." name))
(when (search name (the simple-string (car dir))
:test #'char-equal)
(goto-page point i)
(setf (last-command-type) :goto-page-zero)
(setf *goto-page-last-num* i)
(setf *goto-page-last-string* name)
(return t))
(incf i)
(setf dir (cdr dir)))))
((minusp p)
(page-offset point p))
(t (goto-page point p)))
(line-start (move-mark (window-display-start (current-window)) point))))
(defun goto-page (mark i)
(with-mark ((m mark))
(buffer-start m)
(unless (page-offset m (1- i))
(editor-error "No page numbered ~D." i))
(move-mark mark m)))
(defcommand "View Page Directory" (p)
"Print a listing of the first non-blank line after each page mark
in a pop-up window."
"Print a listing of the first non-blank line after each page mark
in a pop-up window."
(declare (ignore p))
(let ((dir (page-directory (current-buffer))))
(declare (list dir))
(with-pop-up-display (s :height (1+ (the fixnum (length dir))))
(display-page-directory s dir))))
(defcommand "Insert Page Directory" (p)
"Insert a listing of the first non-blank line after each page mark at
the beginning of the buffer. A mark is dropped before going to the
beginning of the buffer. If an argument is supplied, insert the page
directory at point."
"Insert a listing of the first non-blank line after each page mark at
the beginning of the buffer."
(let ((point (current-point)))
(unless p
(push-buffer-mark (copy-mark point))
(buffer-start point))
(push-buffer-mark (copy-mark point))
(display-page-directory (make-hemlock-output-stream point :full)
(page-directory (current-buffer))))
(setf (last-command-type) :ephemerally-active))
(defun display-page-directory (stream directory)
"This writes the list of strings, directory, to stream, enumerating them
in a field of three characters. The number and string are separated by
two spaces, and the first line contains headings for the numbers and
strings columns."
(write-line "Page First Non-blank Line" stream)
(do ((dir directory (cdr dir))
(count 1 (1+ count)))
((null dir))
(declare (fixnum count))
(format stream "~3D " count)
(write-line (car dir) stream)))
(defun page-directory (buffer)
"Return a list of strings where each is the first non-blank line
following a :page-delimiter in buffer."
(with-mark ((m (buffer-point buffer)))
(buffer-start m)
(let ((end-of-buffer (buffer-end-mark buffer)) result)
for first non - blank line .
(cond ((not (blank-after-p m))
(let* ((str (line-string (mark-line m)))
(len (length str)))
(declare (simple-string str))
(push (if (and (> len 1)
(= (character-attribute :page-delimiter
(schar str 0))
1))
(subseq str 1)
str)
result))
(unless (page-offset m 1)
(return-from page-directory (nreverse result)))
(when (mark= m end-of-buffer)
(return-from page-directory (nreverse result)))
(return))
((not (line-offset m 1 0))
(return-from page-directory (nreverse result)))
((= (character-attribute :page-delimiter (next-character m))
1)
(push "" result)
(mark-after m)
(return))))))))
(defcommand "Previous Page" (p)
"Move to the beginning of the current page.
With prefix argument move that many pages."
"Move backward P pages."
(let ((point (current-point)))
(unless (page-offset point (- (or p 1)))
(editor-error "No such page."))
(line-start (move-mark (window-display-start (current-window)) point))))
(defcommand "Next Page" (p)
"Move to the beginning of the next page.
With prefix argument move that many pages."
"Move forward P pages."
(let ((point (current-point)))
(unless (page-offset point (or p 1))
(editor-error "No such page."))
(line-start (move-mark (window-display-start (current-window)) point))))
(defcommand "Mark Page" (p)
"Put point at beginning, mark at end of current page.
With prefix argument, mark the page that many pages after the current one."
"Mark the P'th page after the current one."
(let ((point (current-point)))
(if p
(unless (page-offset point (1+ p)) (editor-error "No such page."))
(with-mark ((m point))
(unless (page-offset point -1)
(editor-error "No such page."))
(push-buffer-mark (copy-mark m) t)
(line-start (move-mark (window-display-start (current-window)) point)))))
(defun page-offset (mark n)
"Move mark past n :page-delimiters that are in the zero'th line position.
If a :page-delimiter is the immediately next character after mark in the
appropriate direction, then skip it before starting."
(cond ((plusp n)
(find-attribute mark :page-delimiter #'zerop)
(dotimes (i n mark)
(unless (next-character mark) (return nil))
(loop
(unless (find-attribute mark :page-delimiter)
(return-from page-offset nil))
(unless (mark-after mark)
(return (if (= i (1- n)) mark)))
(when (= (mark-charpos mark) 1) (return)))))
(t
(reverse-find-attribute mark :page-delimiter #'zerop)
(prog1
(dotimes (i (- n) mark)
(unless (previous-character mark) (return nil))
(loop
(unless (reverse-find-attribute mark :page-delimiter)
(return-from page-offset nil))
(mark-before mark)
(when (= (mark-charpos mark) 0) (return))))
(let ((buffer (line-buffer (mark-line mark))))
(unless (or (not buffer) (mark= mark (buffer-start-mark buffer)))
(mark-after mark)))))))
(defcommand "Count Lines Page" (p)
"Display number of lines in current page and position within page.
With prefix argument do on entire buffer."
"Count some lines, Man."
(let ((point (current-point)))
(if p
(let ((r (buffer-region (current-buffer))))
(count-lines-function "Buffer" (region-start r) point (region-end r)))
(with-mark ((m1 point)
(m2 point))
(unless (and (= (character-attribute :page-delimiter
(previous-character m1))
1)
(= (mark-charpos m1) 1))
(page-offset m1 -1))
(unless (and (= (character-attribute :page-delimiter
(next-character m2))
1)
(= (mark-charpos m2) 0))
(page-offset m2 1))
(count-lines-function "Page" m1 point m2)))))
(defun count-lines-function (msg start mark end)
(let ((before (1- (count-lines (region start mark))))
(after (count-lines (region mark end))))
(message "~A: ~D lines, ~D/~D" msg (+ before after) before after)))
(defcommand "Count Lines" (p)
"Display number of lines in the region."
"Display number of lines in the region."
(declare (ignore p))
(multiple-value-bind (region activep) (get-count-region)
(message "~:[After point~;Active region~]: ~A lines"
activep (count-lines region))))
(defcommand "Count Words" (p)
"Prints in the Echo Area the number of words in the region
between the point and the mark by using word-offset. The
argument is ignored."
"Prints Number of Words in the Region"
(declare (ignore p))
(multiple-value-bind (region activep) (get-count-region)
(let ((end-mark (region-end region)))
(with-mark ((beg-mark (region-start region)))
(let ((word-count 0))
(loop
(when (mark>= beg-mark end-mark)
(return))
(unless (word-offset beg-mark 1)
(return))
(incf word-count))
(message "~:[After point~;Active region~]: ~D Word~:P"
activep word-count))))))
GET - COUNT - REGION -- Internal Interface .
As a second value , it returns whether the region was active .
(defun get-count-region ()
(if (region-active-p)
(values (current-region) t)
(values (region (current-point) (buffer-end-mark (current-buffer)))
nil)))
(defcommand "Fundamental Mode" (p)
"Put the current buffer into \"Fundamental\" mode."
"Put the current buffer into \"Fundamental\" mode."
(declare (ignore p))
(setf (buffer-major-mode (current-buffer)) "Fundamental"))
(defmode "Text" :major-p t)
(defcommand "Text Mode" (p)
"Put the current buffer into \"Text\" mode."
"Put the current buffer into \"Text\" mode."
(declare (ignore p))
(setf (buffer-major-mode (current-buffer)) "Text"))
(defmode "CAPS-LOCK")
(defcommand "Caps Lock Mode" (p)
"Simulate having a CAPS LOCK key. Toggle CAPS-LOCK mode. Zero or a
negative argument turns it off, while a positive argument turns it
on."
"Simulate having a CAPS LOCK key. Toggle CAPS-LOCK mode. Zero or a
negative argument turns it off, while a positive argument turns it
on."
(setf (buffer-minor-mode (current-buffer) "CAPS-LOCK")
(if p
(plusp p)
(not (buffer-minor-mode (current-buffer) "CAPS-LOCK")))))
(defcommand "Self Insert Caps Lock" (p)
"Insert the last character typed, or the argument number of them.
If the last character was an alphabetic character, then insert its
capital form."
"Insert the last character typed, or the argument number of them.
If the last character was an alphabetic character, then insert its
capital form."
(let ((char (char-upcase (ext:key-event-char *last-key-event-typed*))))
(if (and p (> p 1))
(insert-string (current-point) (make-string p :initial-element char))
(insert-character (current-point) char))))
|
cce3b5974a9e2ab5fa172cd782438a7ef19155b4f1fc46923c057aee5ede8c82 | Deducteam/zenon_modulo | printBox.ml |
copyright ( c ) 2013 - 2014 ,
all rights reserved .
redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
redistributions of source code must retain the above copyright notice , this
list of conditions and the following disclaimer . redistributions in binary
form must reproduce the above copyright notice , this list of conditions and the
following disclaimer in the documentation and/or other materials provided with
the distribution .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND
ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY ,
OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
copyright (c) 2013-2014, simon cruanes
all rights reserved.
redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. redistributions in binary
form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with
the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
* { 1 Pretty - Printing of Boxes }
type position = { x:int ; y: int }
let origin = {x=0; y=0;}
let _move pos x y = {x=pos.x + x; y=pos.y + y}
let _add pos1 pos2 = _move pos1 pos2.x pos2.y
let _minus pos1 pos2 = _move pos1 (- pos2.x) (- pos2.y)
let _move_x pos x = _move pos x 0
let _move_y pos y = _move pos 0 y
let _string_len = ref Bytes.length
let set_string_len f = _string_len := f
* { 2 Output : where to print to }
module Output = struct
type t = {
put_char : position -> char -> unit;
put_string : position -> string -> unit;
put_sub_string : position -> string -> int -> int -> unit;
flush : unit -> unit;
}
let put_char out pos c = out.put_char pos c
let put_string out pos s = out.put_string pos s
let put_sub_string out pos s s_i s_len = out.put_sub_string pos s s_i s_len
(** An internal buffer, suitable for writing efficiently, then
convertable into a list of lines *)
type buffer = {
mutable buf_lines : buf_line array;
mutable buf_len : int;
}
and buf_line = {
mutable bl_str : Bytes.t;
mutable bl_len : int;
}
let _make_line _ = {bl_str=Bytes.empty; bl_len=0}
let _ensure_lines buf i =
if i >= Array.length buf.buf_lines
then (
let lines' = Array.init (2 * i + 5) _make_line in
Array.blit buf.buf_lines 0 lines' 0 buf.buf_len;
buf.buf_lines <- lines';
)
let _ensure_line line i =
if i >= !_string_len line.bl_str
then (
let str' = Bytes.make (2 * i + 5) ' ' in
Bytes.blit line.bl_str 0 str' 0 line.bl_len;
line.bl_str <- str';
)
let _buf_put_char buf pos c =
_ensure_lines buf pos.y;
_ensure_line buf.buf_lines.(pos.y) pos.x;
buf.buf_len <- max buf.buf_len (pos.y+1);
let line = buf.buf_lines.(pos.y) in
Bytes.set line.bl_str pos.x c;
line.bl_len <- max line.bl_len (pos.x+1)
let _buf_put_sub_string buf pos s s_i s_len =
_ensure_lines buf pos.y;
_ensure_line buf.buf_lines.(pos.y) (pos.x + s_len);
buf.buf_len <- max buf.buf_len (pos.y+1);
let line = buf.buf_lines.(pos.y) in
String.blit s s_i line.bl_str pos.x s_len;
line.bl_len <- max line.bl_len (pos.x+s_len)
let _buf_put_string buf pos s =
_buf_put_sub_string buf pos s 0 (!_string_len (Bytes.unsafe_of_string s))
(* create a new buffer *)
let make_buffer () =
let buf = {
buf_lines = Array.init 16 _make_line;
buf_len = 0;
} in
let buf_out = {
put_char = _buf_put_char buf;
put_sub_string = _buf_put_sub_string buf;
put_string = _buf_put_string buf;
flush = (fun () -> ());
} in
buf, buf_out
let buf_to_lines ?(indent=0) buf =
let buffer = Buffer.create (5 + buf.buf_len * 32) in
for i = 0 to buf.buf_len - 1 do
for k = 1 to indent do Buffer.add_char buffer ' ' done;
let line = buf.buf_lines.(i) in
Buffer.add_substring buffer (Bytes.unsafe_to_string line.bl_str) 0 line.bl_len;
Buffer.add_char buffer '\n';
done;
Buffer.contents buffer
let buf_output ?(indent=0) oc buf =
for i = 0 to buf.buf_len - 1 do
for k = 1 to indent do output_char oc ' '; done;
let line = buf.buf_lines.(i) in
output oc line.bl_str 0 line.bl_len;
output_char oc '\n';
done
end
(* find [c] in [s], starting at offset [i] *)
let rec _find s c i =
if i >= String.length s then None
else if s.[i] = c then Some i
else _find s c (i+1)
let rec _lines s i k = match _find s '\n' i with
| None ->
if i<String.length s then k (String.sub s i (String.length s-i))
| Some j ->
let s' = String.sub s i (j-i) in
k s';
_lines s (j+1) k
module Box = struct
type grid_shape =
| GridNone
| GridBars
type 'a shape =
| Empty
| Text of string list (* list of lines *)
| Frame of 'a
| Pad of position * 'a (* vertical and horizontal padding *)
| Grid of grid_shape * 'a array array
| Tree of int * 'a * 'a array
type t = {
shape : t shape;
size : position lazy_t;
}
let size box = Lazy.force box.size
let shape b = b.shape
let _array_foldi f acc a =
let acc = ref acc in
Array.iteri (fun i x -> acc := f !acc i x) a;
!acc
let _dim_matrix m =
if Array.length m = 0 then {x=0;y=0}
else {y=Array.length m; x=Array.length m.(0); }
let _map_matrix f m =
Array.map (Array.map f) m
(* height of a line composed of boxes *)
let _height_line a =
_array_foldi
(fun h i box ->
let s = size box in
max h s.y
) 0 a
(* how large is the [i]-th column of [m]? *)
let _width_column m i =
let acc = ref 0 in
for j = 0 to Array.length m - 1 do
acc := max !acc (size m.(j).(i)).x
done;
!acc
(* width and height of a column as an array *)
let _dim_vertical_array a =
let w = ref 0 and h = ref 0 in
Array.iter
(fun b ->
let s = size b in
w := max !w s.x;
h := !h + s.y
) a;
{x= !w; y= !h;}
from a matrix [ m ] ( line , column ) , return two arrays [ lines ] and [ columns ] ,
with [ col.(i ) ] being the start offset of column [ i ] and
[ lines.(j ) ] being the start offset of line [ j ] .
Those arrays have one more slot to indicate the end position .
@param bars if true , leave space for bars between lines / columns
with [col.(i)] being the start offset of column [i] and
[lines.(j)] being the start offset of line [j].
Those arrays have one more slot to indicate the end position.
@param bars if true, leave space for bars between lines/columns *)
let _size_matrix ~bars m =
let dim = _dim_matrix m in
(* +1 is for keeping room for the vertical/horizontal line/column *)
let additional_space = if bars then 1 else 0 in
(* columns *)
let columns = Array.make (dim.x + 1) 0 in
for i = 0 to dim.x - 1 do
columns.(i+1) <- columns.(i) + (_width_column m i) + additional_space
done;
(* lines *)
let lines = Array.make (dim.y + 1) 0 in
for j = 1 to dim.y do
lines.(j) <- lines.(j-1) + (_height_line m.(j-1)) + additional_space
done;
(* no trailing bars, adjust *)
columns.(dim.x) <- columns.(dim.x) - additional_space;
lines.(dim.y) <- lines.(dim.y) - additional_space;
lines, columns
let _size = function
| Empty -> origin
| Text l ->
let width = List.fold_left
(fun acc line -> max acc (!_string_len (Bytes.unsafe_of_string line))) 0 l
in
{ x=width; y=List.length l; }
| Frame t ->
let {x;y} = size t in
{ x=x+2; y=y+2; }
| Pad (dim, b') ->
let {x;y} = size b' in
{ x=x+2*dim.x; y=y+2*dim.y; }
| Grid (style,m) ->
let bars = match style with
| GridBars -> true
| GridNone -> false
in
let dim = _dim_matrix m in
let lines, columns = _size_matrix ~bars m in
{ y=lines.(dim.y); x=columns.(dim.x)}
| Tree (indent, node, children) ->
let dim_children = _dim_vertical_array children in
let s = size node in
{ x=max s.x (dim_children.x+3+indent)
; y=s.y + dim_children.y
}
let _make shape =
{ shape; size=(lazy (_size shape)); }
end
let empty = Box._make Box.Empty
let line s =
assert (_find s '\n' 0 = None);
Box._make (Box.Text [s])
let text s =
let acc = ref [] in
_lines s 0 (fun x -> acc := x :: !acc);
Box._make (Box.Text (List.rev !acc))
let sprintf format =
let buffer = Buffer.create 64 in
Printf.kbprintf
(fun fmt -> text (Buffer.contents buffer))
buffer
format
let lines l =
assert (List.for_all (fun s -> _find s '\n' 0 = None) l);
Box._make (Box.Text l)
let int_ x = line (string_of_int x)
let float_ x = line (string_of_float x)
let bool_ x = line (string_of_bool x)
let frame b =
Box._make (Box.Frame b)
let pad' ~col ~lines b =
assert (col >=0 || lines >= 0);
if col=0 && lines=0
then b
else Box._make (Box.Pad ({x=col;y=lines}, b))
let pad b = pad' ~col:1 ~lines:1 b
let hpad col b = pad' ~col ~lines:0 b
let vpad lines b = pad' ~col:0 ~lines b
let grid ?(pad=fun b->b) ?(bars=true) m =
let m = Box._map_matrix pad m in
Box._make (Box.Grid ((if bars then Box.GridBars else Box.GridNone), m))
let init_grid ?bars ~line ~col f =
let m = Array.init line (fun j-> Array.init col (fun i -> f ~line:j ~col:i)) in
grid ?bars m
let vlist ?pad ?bars l =
let a = Array.of_list l in
grid ?pad ?bars (Array.map (fun line -> [| line |]) a)
let hlist ?pad ?bars l =
grid ?pad ?bars [| Array.of_list l |]
let hlist_map ?bars f l = hlist ?bars (List.map f l)
let vlist_map ?bars f l = vlist ?bars (List.map f l)
let grid_map ?bars f m = grid ?bars (Array.map (Array.map f) m)
let grid_text ?(pad=fun x->x) ?bars m =
grid_map ?bars (fun x -> pad (text x)) m
let transpose m =
let dim = Box._dim_matrix m in
Array.init dim.x
(fun i -> Array.init dim.y (fun j -> m.(j).(i)))
let tree ?(indent=1) node children =
let children =
List.filter
(function
| {Box.shape=Box.Empty; _} -> false
| _ -> true
) children
in
match children with
| [] -> node
| _::_ ->
let children = Array.of_list children in
Box._make (Box.Tree (indent, node, children))
let mk_tree ?indent f root =
let rec make x = match f x with
| b, [] -> b
| b, children -> tree ?indent b (List.map make children)
in
make root
* { 2 Rendering }
let _write_vline ~out pos n =
for j=0 to n-1 do
Output.put_char out (_move_y pos j) '|'
done
let _write_hline ~out pos n =
for i=0 to n-1 do
Output.put_char out (_move_x pos i) '-'
done
(* render given box on the output, starting with upper left corner
at the given position. [expected_size] is the size of the
available surrounding space. [offset] is the offset of the box
w.r.t the surrounding box *)
let rec _render ?(offset=origin) ?expected_size ~out b pos =
match Box.shape b with
| Box.Empty -> ()
| Box.Text l ->
List.iteri
(fun i line ->
Output.put_string out (_move_y pos i) line
) l
| Box.Frame b' ->
let {x;y} = Box.size b' in
Output.put_char out pos '+';
Output.put_char out (_move pos (x+1) (y+1)) '+';
Output.put_char out (_move pos 0 (y+1)) '+';
Output.put_char out (_move pos (x+1) 0) '+';
_write_hline ~out (_move_x pos 1) x;
_write_hline ~out (_move pos 1 (y+1)) x;
_write_vline ~out (_move_y pos 1) y;
_write_vline ~out (_move pos (x+1) 1) y;
_render ~out b' (_move pos 1 1)
| Box.Pad (dim, b') ->
let expected_size = Box.size b in
_render ~offset:(_add dim offset) ~expected_size ~out b' (_add pos dim)
| Box.Grid (style,m) ->
let dim = Box._dim_matrix m in
let bars = match style with
| Box.GridNone -> false
| Box.GridBars -> true
in
let lines, columns = Box._size_matrix ~bars m in
(* write boxes *)
for j = 0 to dim.y - 1 do
for i = 0 to dim.x - 1 do
let expected_size = {
x=columns.(i+1)-columns.(i);
y=lines.(j+1)-lines.(j);
} in
let pos' = _move pos (columns.(i)) (lines.(j)) in
_render ~expected_size ~out m.(j).(i) pos'
done;
done;
let len_hlines, len_vlines = match expected_size with
| None -> columns.(dim.x), lines.(dim.y)
| Some {x;y} -> x,y
in
(* write frame if needed *)
begin match style with
| Box.GridNone -> ()
| Box.GridBars ->
for j=1 to dim.y - 1 do
_write_hline ~out (_move pos (-offset.x) (lines.(j)-1)) len_hlines
done;
for i=1 to dim.x - 1 do
_write_vline ~out (_move pos (columns.(i)-1) (-offset.y)) len_vlines
done;
for j=1 to dim.y - 1 do
for i=1 to dim.x - 1 do
Output.put_char out (_move pos (columns.(i)-1) (lines.(j)-1)) '+'
done
done
end
| Box.Tree (indent, n, a) ->
_render ~out n pos;
(* star position for the children *)
let pos' = _move pos indent (Box.size n).y in
Output.put_char out (_move_x pos' ~-1) '`';
assert (Array.length a > 0);
let _ = Box._array_foldi
(fun pos' i b ->
Output.put_string out pos' "+- ";
if i<Array.length a-1
then (
_write_vline ~out (_move_y pos' 1) ((Box.size b).y-1)
);
_render ~out b (_move_x pos' 2);
_move_y pos' (Box.size b).y
) pos' a
in
()
let render out b =
_render ~out b origin
let to_string b =
let buf, out = Output.make_buffer () in
render out b;
Output.buf_to_lines buf
let output ?(indent=0) oc b =
let buf, out = Output.make_buffer () in
render out b;
Output.buf_output ~indent oc buf;
flush oc
* { 2 Simple Structural Interface }
type 'a ktree = unit -> [`Nil | `Node of 'a * 'a ktree list]
module Simple = struct
type t =
[ `Empty
| `Pad of t
| `Text of string
| `Vlist of t list
| `Hlist of t list
| `Table of t array array
| `Tree of t * t list
]
let rec to_box = function
| `Empty -> empty
| `Pad b -> pad (to_box b)
| `Text t -> text t
| `Vlist l -> vlist (List.map to_box l)
| `Hlist l -> hlist (List.map to_box l)
| `Table a -> grid (Box._map_matrix to_box a)
| `Tree (b,l) -> tree (to_box b) (List.map to_box l)
let rec of_ktree t = match t () with
| `Nil -> `Empty
| `Node (x, l) -> `Tree (x, List.map of_ktree l)
let rec map_ktree f t = match t () with
| `Nil -> `Empty
| `Node (x, l) -> `Tree (f x, List.map (map_ktree f) l)
let sprintf format =
let buffer = Buffer.create 64 in
Printf.kbprintf
(fun fmt -> `Text (Buffer.contents buffer))
buffer
format
let render out x = render out (to_box x)
let to_string x = to_string (to_box x)
let output ?indent out x = output ?indent out (to_box x)
end
| null | https://raw.githubusercontent.com/Deducteam/zenon_modulo/9534fbdca0d009a513cb40d9a5a2a98329835c63/printBox.ml | ocaml | * An internal buffer, suitable for writing efficiently, then
convertable into a list of lines
create a new buffer
find [c] in [s], starting at offset [i]
list of lines
vertical and horizontal padding
height of a line composed of boxes
how large is the [i]-th column of [m]?
width and height of a column as an array
+1 is for keeping room for the vertical/horizontal line/column
columns
lines
no trailing bars, adjust
render given box on the output, starting with upper left corner
at the given position. [expected_size] is the size of the
available surrounding space. [offset] is the offset of the box
w.r.t the surrounding box
write boxes
write frame if needed
star position for the children |
copyright ( c ) 2013 - 2014 ,
all rights reserved .
redistribution and use in source and binary forms , with or without
modification , are permitted provided that the following conditions are met :
redistributions of source code must retain the above copyright notice , this
list of conditions and the following disclaimer . redistributions in binary
form must reproduce the above copyright notice , this list of conditions and the
following disclaimer in the documentation and/or other materials provided with
the distribution .
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS " AS IS " AND
ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT LIMITED TO , THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
FOR ANY DIRECT , INDIRECT , INCIDENTAL , SPECIAL , EXEMPLARY , OR CONSEQUENTIAL
DAMAGES ( INCLUDING , BUT NOT LIMITED TO , PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES ; LOSS OF USE , DATA , OR PROFITS ; OR BUSINESS INTERRUPTION ) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY ,
OR TORT ( INCLUDING NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE , EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE .
copyright (c) 2013-2014, simon cruanes
all rights reserved.
redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer. redistributions in binary
form must reproduce the above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other materials provided with
the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*)
* { 1 Pretty - Printing of Boxes }
type position = { x:int ; y: int }
let origin = {x=0; y=0;}
let _move pos x y = {x=pos.x + x; y=pos.y + y}
let _add pos1 pos2 = _move pos1 pos2.x pos2.y
let _minus pos1 pos2 = _move pos1 (- pos2.x) (- pos2.y)
let _move_x pos x = _move pos x 0
let _move_y pos y = _move pos 0 y
let _string_len = ref Bytes.length
let set_string_len f = _string_len := f
* { 2 Output : where to print to }
module Output = struct
type t = {
put_char : position -> char -> unit;
put_string : position -> string -> unit;
put_sub_string : position -> string -> int -> int -> unit;
flush : unit -> unit;
}
let put_char out pos c = out.put_char pos c
let put_string out pos s = out.put_string pos s
let put_sub_string out pos s s_i s_len = out.put_sub_string pos s s_i s_len
type buffer = {
mutable buf_lines : buf_line array;
mutable buf_len : int;
}
and buf_line = {
mutable bl_str : Bytes.t;
mutable bl_len : int;
}
let _make_line _ = {bl_str=Bytes.empty; bl_len=0}
let _ensure_lines buf i =
if i >= Array.length buf.buf_lines
then (
let lines' = Array.init (2 * i + 5) _make_line in
Array.blit buf.buf_lines 0 lines' 0 buf.buf_len;
buf.buf_lines <- lines';
)
let _ensure_line line i =
if i >= !_string_len line.bl_str
then (
let str' = Bytes.make (2 * i + 5) ' ' in
Bytes.blit line.bl_str 0 str' 0 line.bl_len;
line.bl_str <- str';
)
let _buf_put_char buf pos c =
_ensure_lines buf pos.y;
_ensure_line buf.buf_lines.(pos.y) pos.x;
buf.buf_len <- max buf.buf_len (pos.y+1);
let line = buf.buf_lines.(pos.y) in
Bytes.set line.bl_str pos.x c;
line.bl_len <- max line.bl_len (pos.x+1)
let _buf_put_sub_string buf pos s s_i s_len =
_ensure_lines buf pos.y;
_ensure_line buf.buf_lines.(pos.y) (pos.x + s_len);
buf.buf_len <- max buf.buf_len (pos.y+1);
let line = buf.buf_lines.(pos.y) in
String.blit s s_i line.bl_str pos.x s_len;
line.bl_len <- max line.bl_len (pos.x+s_len)
let _buf_put_string buf pos s =
_buf_put_sub_string buf pos s 0 (!_string_len (Bytes.unsafe_of_string s))
let make_buffer () =
let buf = {
buf_lines = Array.init 16 _make_line;
buf_len = 0;
} in
let buf_out = {
put_char = _buf_put_char buf;
put_sub_string = _buf_put_sub_string buf;
put_string = _buf_put_string buf;
flush = (fun () -> ());
} in
buf, buf_out
let buf_to_lines ?(indent=0) buf =
let buffer = Buffer.create (5 + buf.buf_len * 32) in
for i = 0 to buf.buf_len - 1 do
for k = 1 to indent do Buffer.add_char buffer ' ' done;
let line = buf.buf_lines.(i) in
Buffer.add_substring buffer (Bytes.unsafe_to_string line.bl_str) 0 line.bl_len;
Buffer.add_char buffer '\n';
done;
Buffer.contents buffer
let buf_output ?(indent=0) oc buf =
for i = 0 to buf.buf_len - 1 do
for k = 1 to indent do output_char oc ' '; done;
let line = buf.buf_lines.(i) in
output oc line.bl_str 0 line.bl_len;
output_char oc '\n';
done
end
let rec _find s c i =
if i >= String.length s then None
else if s.[i] = c then Some i
else _find s c (i+1)
let rec _lines s i k = match _find s '\n' i with
| None ->
if i<String.length s then k (String.sub s i (String.length s-i))
| Some j ->
let s' = String.sub s i (j-i) in
k s';
_lines s (j+1) k
module Box = struct
type grid_shape =
| GridNone
| GridBars
type 'a shape =
| Empty
| Frame of 'a
| Grid of grid_shape * 'a array array
| Tree of int * 'a * 'a array
type t = {
shape : t shape;
size : position lazy_t;
}
let size box = Lazy.force box.size
let shape b = b.shape
let _array_foldi f acc a =
let acc = ref acc in
Array.iteri (fun i x -> acc := f !acc i x) a;
!acc
let _dim_matrix m =
if Array.length m = 0 then {x=0;y=0}
else {y=Array.length m; x=Array.length m.(0); }
let _map_matrix f m =
Array.map (Array.map f) m
let _height_line a =
_array_foldi
(fun h i box ->
let s = size box in
max h s.y
) 0 a
let _width_column m i =
let acc = ref 0 in
for j = 0 to Array.length m - 1 do
acc := max !acc (size m.(j).(i)).x
done;
!acc
let _dim_vertical_array a =
let w = ref 0 and h = ref 0 in
Array.iter
(fun b ->
let s = size b in
w := max !w s.x;
h := !h + s.y
) a;
{x= !w; y= !h;}
from a matrix [ m ] ( line , column ) , return two arrays [ lines ] and [ columns ] ,
with [ col.(i ) ] being the start offset of column [ i ] and
[ lines.(j ) ] being the start offset of line [ j ] .
Those arrays have one more slot to indicate the end position .
@param bars if true , leave space for bars between lines / columns
with [col.(i)] being the start offset of column [i] and
[lines.(j)] being the start offset of line [j].
Those arrays have one more slot to indicate the end position.
@param bars if true, leave space for bars between lines/columns *)
let _size_matrix ~bars m =
let dim = _dim_matrix m in
let additional_space = if bars then 1 else 0 in
let columns = Array.make (dim.x + 1) 0 in
for i = 0 to dim.x - 1 do
columns.(i+1) <- columns.(i) + (_width_column m i) + additional_space
done;
let lines = Array.make (dim.y + 1) 0 in
for j = 1 to dim.y do
lines.(j) <- lines.(j-1) + (_height_line m.(j-1)) + additional_space
done;
columns.(dim.x) <- columns.(dim.x) - additional_space;
lines.(dim.y) <- lines.(dim.y) - additional_space;
lines, columns
let _size = function
| Empty -> origin
| Text l ->
let width = List.fold_left
(fun acc line -> max acc (!_string_len (Bytes.unsafe_of_string line))) 0 l
in
{ x=width; y=List.length l; }
| Frame t ->
let {x;y} = size t in
{ x=x+2; y=y+2; }
| Pad (dim, b') ->
let {x;y} = size b' in
{ x=x+2*dim.x; y=y+2*dim.y; }
| Grid (style,m) ->
let bars = match style with
| GridBars -> true
| GridNone -> false
in
let dim = _dim_matrix m in
let lines, columns = _size_matrix ~bars m in
{ y=lines.(dim.y); x=columns.(dim.x)}
| Tree (indent, node, children) ->
let dim_children = _dim_vertical_array children in
let s = size node in
{ x=max s.x (dim_children.x+3+indent)
; y=s.y + dim_children.y
}
let _make shape =
{ shape; size=(lazy (_size shape)); }
end
let empty = Box._make Box.Empty
let line s =
assert (_find s '\n' 0 = None);
Box._make (Box.Text [s])
let text s =
let acc = ref [] in
_lines s 0 (fun x -> acc := x :: !acc);
Box._make (Box.Text (List.rev !acc))
let sprintf format =
let buffer = Buffer.create 64 in
Printf.kbprintf
(fun fmt -> text (Buffer.contents buffer))
buffer
format
let lines l =
assert (List.for_all (fun s -> _find s '\n' 0 = None) l);
Box._make (Box.Text l)
let int_ x = line (string_of_int x)
let float_ x = line (string_of_float x)
let bool_ x = line (string_of_bool x)
let frame b =
Box._make (Box.Frame b)
let pad' ~col ~lines b =
assert (col >=0 || lines >= 0);
if col=0 && lines=0
then b
else Box._make (Box.Pad ({x=col;y=lines}, b))
let pad b = pad' ~col:1 ~lines:1 b
let hpad col b = pad' ~col ~lines:0 b
let vpad lines b = pad' ~col:0 ~lines b
let grid ?(pad=fun b->b) ?(bars=true) m =
let m = Box._map_matrix pad m in
Box._make (Box.Grid ((if bars then Box.GridBars else Box.GridNone), m))
let init_grid ?bars ~line ~col f =
let m = Array.init line (fun j-> Array.init col (fun i -> f ~line:j ~col:i)) in
grid ?bars m
let vlist ?pad ?bars l =
let a = Array.of_list l in
grid ?pad ?bars (Array.map (fun line -> [| line |]) a)
let hlist ?pad ?bars l =
grid ?pad ?bars [| Array.of_list l |]
let hlist_map ?bars f l = hlist ?bars (List.map f l)
let vlist_map ?bars f l = vlist ?bars (List.map f l)
let grid_map ?bars f m = grid ?bars (Array.map (Array.map f) m)
let grid_text ?(pad=fun x->x) ?bars m =
grid_map ?bars (fun x -> pad (text x)) m
let transpose m =
let dim = Box._dim_matrix m in
Array.init dim.x
(fun i -> Array.init dim.y (fun j -> m.(j).(i)))
let tree ?(indent=1) node children =
let children =
List.filter
(function
| {Box.shape=Box.Empty; _} -> false
| _ -> true
) children
in
match children with
| [] -> node
| _::_ ->
let children = Array.of_list children in
Box._make (Box.Tree (indent, node, children))
let mk_tree ?indent f root =
let rec make x = match f x with
| b, [] -> b
| b, children -> tree ?indent b (List.map make children)
in
make root
* { 2 Rendering }
let _write_vline ~out pos n =
for j=0 to n-1 do
Output.put_char out (_move_y pos j) '|'
done
let _write_hline ~out pos n =
for i=0 to n-1 do
Output.put_char out (_move_x pos i) '-'
done
let rec _render ?(offset=origin) ?expected_size ~out b pos =
match Box.shape b with
| Box.Empty -> ()
| Box.Text l ->
List.iteri
(fun i line ->
Output.put_string out (_move_y pos i) line
) l
| Box.Frame b' ->
let {x;y} = Box.size b' in
Output.put_char out pos '+';
Output.put_char out (_move pos (x+1) (y+1)) '+';
Output.put_char out (_move pos 0 (y+1)) '+';
Output.put_char out (_move pos (x+1) 0) '+';
_write_hline ~out (_move_x pos 1) x;
_write_hline ~out (_move pos 1 (y+1)) x;
_write_vline ~out (_move_y pos 1) y;
_write_vline ~out (_move pos (x+1) 1) y;
_render ~out b' (_move pos 1 1)
| Box.Pad (dim, b') ->
let expected_size = Box.size b in
_render ~offset:(_add dim offset) ~expected_size ~out b' (_add pos dim)
| Box.Grid (style,m) ->
let dim = Box._dim_matrix m in
let bars = match style with
| Box.GridNone -> false
| Box.GridBars -> true
in
let lines, columns = Box._size_matrix ~bars m in
for j = 0 to dim.y - 1 do
for i = 0 to dim.x - 1 do
let expected_size = {
x=columns.(i+1)-columns.(i);
y=lines.(j+1)-lines.(j);
} in
let pos' = _move pos (columns.(i)) (lines.(j)) in
_render ~expected_size ~out m.(j).(i) pos'
done;
done;
let len_hlines, len_vlines = match expected_size with
| None -> columns.(dim.x), lines.(dim.y)
| Some {x;y} -> x,y
in
begin match style with
| Box.GridNone -> ()
| Box.GridBars ->
for j=1 to dim.y - 1 do
_write_hline ~out (_move pos (-offset.x) (lines.(j)-1)) len_hlines
done;
for i=1 to dim.x - 1 do
_write_vline ~out (_move pos (columns.(i)-1) (-offset.y)) len_vlines
done;
for j=1 to dim.y - 1 do
for i=1 to dim.x - 1 do
Output.put_char out (_move pos (columns.(i)-1) (lines.(j)-1)) '+'
done
done
end
| Box.Tree (indent, n, a) ->
_render ~out n pos;
let pos' = _move pos indent (Box.size n).y in
Output.put_char out (_move_x pos' ~-1) '`';
assert (Array.length a > 0);
let _ = Box._array_foldi
(fun pos' i b ->
Output.put_string out pos' "+- ";
if i<Array.length a-1
then (
_write_vline ~out (_move_y pos' 1) ((Box.size b).y-1)
);
_render ~out b (_move_x pos' 2);
_move_y pos' (Box.size b).y
) pos' a
in
()
let render out b =
_render ~out b origin
let to_string b =
let buf, out = Output.make_buffer () in
render out b;
Output.buf_to_lines buf
let output ?(indent=0) oc b =
let buf, out = Output.make_buffer () in
render out b;
Output.buf_output ~indent oc buf;
flush oc
* { 2 Simple Structural Interface }
type 'a ktree = unit -> [`Nil | `Node of 'a * 'a ktree list]
module Simple = struct
type t =
[ `Empty
| `Pad of t
| `Text of string
| `Vlist of t list
| `Hlist of t list
| `Table of t array array
| `Tree of t * t list
]
let rec to_box = function
| `Empty -> empty
| `Pad b -> pad (to_box b)
| `Text t -> text t
| `Vlist l -> vlist (List.map to_box l)
| `Hlist l -> hlist (List.map to_box l)
| `Table a -> grid (Box._map_matrix to_box a)
| `Tree (b,l) -> tree (to_box b) (List.map to_box l)
let rec of_ktree t = match t () with
| `Nil -> `Empty
| `Node (x, l) -> `Tree (x, List.map of_ktree l)
let rec map_ktree f t = match t () with
| `Nil -> `Empty
| `Node (x, l) -> `Tree (f x, List.map (map_ktree f) l)
let sprintf format =
let buffer = Buffer.create 64 in
Printf.kbprintf
(fun fmt -> `Text (Buffer.contents buffer))
buffer
format
let render out x = render out (to_box x)
let to_string x = to_string (to_box x)
let output ?indent out x = output ?indent out (to_box x)
end
|
eef17ddce691faed6d6d683993c7d1bf6053e2191ed027d538233c33bca9e0fb | juspay/atlas | Scheduler.hs | |
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Main
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Main
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Main where
import App.Scheduler
import Beckn.Prelude
main :: IO ()
main = runTransporterScheduler identity identity
| null | https://raw.githubusercontent.com/juspay/atlas/e64b227dc17887fb01c2554db21c08284d18a806/app/atlas-transport/server/Scheduler.hs | haskell | |
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Main
Copyright : ( C ) Juspay Technologies Pvt Ltd 2019 - 2022
License : Apache 2.0 ( see the file LICENSE )
Maintainer :
Stability : experimental
Portability : non - portable
Copyright 2022 Juspay Technologies Pvt Ltd
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 : Main
Copyright : (C) Juspay Technologies Pvt Ltd 2019-2022
License : Apache 2.0 (see the file LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable
-}
module Main where
import App.Scheduler
import Beckn.Prelude
main :: IO ()
main = runTransporterScheduler identity identity
|
|
c2185c18f5bbb3b042847042e1e7db7153cd0aa27dacfa89736d4df05a35e49a | clojure-interop/java-jdk | SSLPeerUnverifiedException.clj | (ns javax.net.ssl.SSLPeerUnverifiedException
"Indicates that the peer's identity has not been verified.
When the peer was not able to
identify itself (for example; no certificate, the particular
cipher suite being used does not support authentication, or no
peer authentication was established during SSL handshaking) this
exception is thrown."
(:refer-clojure :only [require comment defn ->])
(:import [javax.net.ssl SSLPeerUnverifiedException]))
(defn ->ssl-peer-unverified-exception
"Constructor.
Constructs an exception reporting that the SSL peer's
identity has not been verified.
reason - describes the problem. - `java.lang.String`"
(^SSLPeerUnverifiedException [^java.lang.String reason]
(new SSLPeerUnverifiedException reason)))
| null | https://raw.githubusercontent.com/clojure-interop/java-jdk/8d7a223e0f9a0965eb0332fad595cf7649d9d96e/javax.net/src/javax/net/ssl/SSLPeerUnverifiedException.clj | clojure | no certificate, the particular | (ns javax.net.ssl.SSLPeerUnverifiedException
"Indicates that the peer's identity has not been verified.
When the peer was not able to
cipher suite being used does not support authentication, or no
peer authentication was established during SSL handshaking) this
exception is thrown."
(:refer-clojure :only [require comment defn ->])
(:import [javax.net.ssl SSLPeerUnverifiedException]))
(defn ->ssl-peer-unverified-exception
"Constructor.
Constructs an exception reporting that the SSL peer's
identity has not been verified.
reason - describes the problem. - `java.lang.String`"
(^SSLPeerUnverifiedException [^java.lang.String reason]
(new SSLPeerUnverifiedException reason)))
|
68194984e32b8e88282444087ced07605cdba988a2db566838755836559ebecf | ChrisPenner/wc | MonoidBSFold.hs | module MonoidBSFold where
import Types
import Data.Traversable
import Data.Monoid
import Data.Char
import qualified Data.ByteString.Lazy.Char8 as BS
monoidBSFold :: [FilePath] -> IO [(FilePath, Counts)]
monoidBSFold paths = for paths $ \fp -> do
count <- monoidFoldFile <$> BS.readFile fp
return (fp, count)
monoidFoldFile :: BS.ByteString -> Counts
monoidFoldFile = BS.foldl' (\a b -> a <> countChar b) mempty
| null | https://raw.githubusercontent.com/ChrisPenner/wc/7a77329164c7b8e7f7d511539e75bce1a74651af/src/MonoidBSFold.hs | haskell | module MonoidBSFold where
import Types
import Data.Traversable
import Data.Monoid
import Data.Char
import qualified Data.ByteString.Lazy.Char8 as BS
monoidBSFold :: [FilePath] -> IO [(FilePath, Counts)]
monoidBSFold paths = for paths $ \fp -> do
count <- monoidFoldFile <$> BS.readFile fp
return (fp, count)
monoidFoldFile :: BS.ByteString -> Counts
monoidFoldFile = BS.foldl' (\a b -> a <> countChar b) mempty
|
|
c63af0822d92267554ee9075ed519ad5304a1a656549cf87e63d12debbe7daf0 | diprism/perpl | RecEq.hs | -- Constructs == functions for (types containing) recursive datatypes
module Transform.RecEq (replaceEqs) where
import Struct.Lib
import Util.Helpers
import Scope.Ctxt
import Scope.Free
import Data.List (intercalate)
import Data.Map (insert, (!), intersection, toList, fromList, member, size)
import Control.Monad.RWS
-- Do a comparison, generating comparison functions
-- for types containing recursive data when necessary
replaceEq :: [Term] -> EqM Term
replaceEq [] = error "Can't have == with 0 args"
replaceEq tms@(htm : _) =
compareTms tms
where
tp = typeof htm
n = length tms
eqName :: Type -> EqM TmName
eqName (TpData y _ _) =
return (TmN ("eq/" ++ show n ++ "/" ++ show y))
eqName (TpProd Multiplicative _) =
getEqs >>= \eqs ->
return (TmN ("eq/" ++ show n ++ "/product/" ++ show (size eqs)))
eqName tp = error ("eqName called on non-data, non-product type " ++ show tp)
xname :: [Int] -> TmVar
xname xis = TmV ('x' : intercalate "_" (map show xis))
xtm :: [Int] -> Type -> Term
xtm xis tp = TmVarL (xname xis) tp
-- Given [tm1, ..., tmn], returns conjuction of all: True == tm1 == ... == tmn
makeAnd [] = tmTrue
makeAnd (tm : []) = tm
makeAnd tms@(_ : _ : _) = TmEqs (tmTrue : tms)
makeEq :: TmName -> Type -> EqM ()
makeEq eqn tp =
let ps = [(xname [i], tp) | i <- [1..n]] in
-- Add stand-in def for now, so recursive calls work
addEq tp n eqn ps undefined >>
(case tp of
TpData y [] [] -> makeEqData y
TpProd Multiplicative tps -> makeEqProd tps
_ -> error ("makeEq got " ++ show tp ++ " (shouldn't happen)")) >>=
addEq tp n eqn ps
makeEqData :: TpName -> EqM Term
makeEqData y =
pure (!) <*> getData <*> pure y >>= \cs ->
pure (\cs -> TmCase (xtm [1] (TpData y [] [])) (y, [], []) cs tpBool) <*>
mapM (\(ci, Ctor cn as) ->
pure (Case cn [(xname [1, ci, ai], a) | (ai, a) <- zip [1..] as]) <*>
makeCase y cs as ci)
(zip [1..] cs)
makeCase y cs as ci = foldr
(\xi body ->
pure (\cs -> TmCase (xtm [xi] (TpData y [] [])) (y, [], []) cs tpBool) <*>
mapM (\(cj, Ctor cn as) ->
pure (Case cn [(xname [xi, cj, ai], a) | (ai, a) <- zip [1..] as]) <*>
if ci /= cj then pure tmFalse else body)
(zip [1..] cs))
(makeAnd <$> mapM (\(j, tp) -> compareTms [xtm [i, ci, j] tp | i <- [1..n]]) (zip [1..] as))
[2..n]
makeEqProd :: [Type] -> EqM Term
makeEqProd tps =
foldr
(\i body ->
let ps = [(xname [i, j], tp) | (j, tp) <- zip [1..] tps]
ptp = TpProd Multiplicative tps in
pure (TmElimMultiplicative (xtm [i] ptp) ps) <*> body <*> pure tpBool)
(makeAnd <$>
mapM (\(j, tp) -> compareTms [xtm [i, j] tp | i <- [1..n]]) (zip [1..] tps))
[1..n]
compareTms :: [Term] -> EqM Term
compareTms [] = error "compareTms [] (shouldn't happen)"
compareTms tms@(htm : _) =
let tp = typeof htm in
isFinite tp >>= \fin ->
if fin then
return (TmEqs tms)
else
isDefined tp >>= \def ->
eqName tp >>= \eqn ->
(if def then okay else makeEq eqn tp) >>
return (TmVarG GlDefine eqn [] [] [(tm, tp) | tm <- tms] tpBool)
isFinite :: Type -> EqM Bool
isFinite tp = getCtxt >>= \g -> return (not (isInfiniteType g tp))
isDefined :: Type -> EqM Bool
isDefined tp = member (tp, n) <$> getEqs
type EqM = RWS (Map TpName [Ctor]) () (Map (Type, Int) (TmName, [Param], Term))
getData :: EqM (Map TpName [Ctor])
getData = ask
getEqs :: EqM (Map (Type, Int) (TmName, [Param], Term))
getEqs = get
addEq :: Type -> Int -> TmName -> [Param] -> Term -> EqM ()
addEq tp n x ps tm = modify (insert (tp, n) (x, ps, tm))
getCtxt :: EqM Ctxt
getCtxt = getData >>= \ds -> return (emptyCtxt {tpNames = fmap (CtData [] []) ds})
replaceEqsh :: Term -> EqM Term
replaceEqsh (TmVarL x tp) =
pure (TmVarL x tp)
replaceEqsh (TmVarG gl x ts ps as tp) =
pure (TmVarG gl x ts ps) <*> mapArgsM replaceEqsh as <*> pure tp
replaceEqsh (TmLam x xtp tm tp) =
pure (TmLam x xtp) <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmApp tm1 tm2 tp2 tp) =
pure TmApp <*> replaceEqsh tm1 <*> replaceEqsh tm2 <*> pure tp2 <*> pure tp
replaceEqsh (TmLet x xtm xtp tm tp) =
pure (TmLet x) <*> replaceEqsh xtm <*> pure xtp <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmCase tm tpd cs rtp) =
pure TmCase <*> replaceEqsh tm <*> pure tpd <*> mapCasesM (\_ _ -> replaceEqsh) cs <*> pure rtp
replaceEqsh (TmAmb tms tp) =
pure TmAmb <*> mapM replaceEqsh tms <*> pure tp
replaceEqsh (TmFactor p tm tp) =
pure (TmFactor p) <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmProd am as) =
pure (TmProd am) <*> mapArgsM replaceEqsh as
replaceEqsh (TmElimMultiplicative xtm xps tm tp) =
pure TmElimMultiplicative <*> replaceEqsh xtm <*> pure xps <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmElimAdditive xtm xi xj xp tm tp) =
pure TmElimAdditive <*> replaceEqsh xtm <*> pure xi <*> pure xj <*> pure xp <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmEqs tms) = replaceEq tms
replaceEqsProg :: Prog -> EqM Prog
replaceEqsProg (ProgDefine x ps tm tp) =
pure (ProgDefine x ps) <*> replaceEqsh tm <*> pure tp
replaceEqsProg p = pure p
replaceEqsProgs :: Progs -> EqM Progs
replaceEqsProgs (Progs ps tm) =
pure Progs <*> mapM replaceEqsProg ps <*> replaceEqsh tm
replaceEqs :: Progs -> Progs
replaceEqs p =
let g = ctxtAddProgs p
r = fmap (\(CtData _ _ cs) -> cs) (tpNames g)
(Progs ps tm, s, ()) = runRWS (replaceEqsProgs p) r mempty
eqps = [ProgDefine x pms tm tpBool | ((y, i), (x, pms, tm)) <- toList s]
in
Progs (ps ++ eqps) tm
| null | https://raw.githubusercontent.com/diprism/perpl/347376cd8e3c4fdc9ad0d9fe79a684f9de33b455/src/Transform/RecEq.hs | haskell | Constructs == functions for (types containing) recursive datatypes
Do a comparison, generating comparison functions
for types containing recursive data when necessary
Given [tm1, ..., tmn], returns conjuction of all: True == tm1 == ... == tmn
Add stand-in def for now, so recursive calls work | module Transform.RecEq (replaceEqs) where
import Struct.Lib
import Util.Helpers
import Scope.Ctxt
import Scope.Free
import Data.List (intercalate)
import Data.Map (insert, (!), intersection, toList, fromList, member, size)
import Control.Monad.RWS
replaceEq :: [Term] -> EqM Term
replaceEq [] = error "Can't have == with 0 args"
replaceEq tms@(htm : _) =
compareTms tms
where
tp = typeof htm
n = length tms
eqName :: Type -> EqM TmName
eqName (TpData y _ _) =
return (TmN ("eq/" ++ show n ++ "/" ++ show y))
eqName (TpProd Multiplicative _) =
getEqs >>= \eqs ->
return (TmN ("eq/" ++ show n ++ "/product/" ++ show (size eqs)))
eqName tp = error ("eqName called on non-data, non-product type " ++ show tp)
xname :: [Int] -> TmVar
xname xis = TmV ('x' : intercalate "_" (map show xis))
xtm :: [Int] -> Type -> Term
xtm xis tp = TmVarL (xname xis) tp
makeAnd [] = tmTrue
makeAnd (tm : []) = tm
makeAnd tms@(_ : _ : _) = TmEqs (tmTrue : tms)
makeEq :: TmName -> Type -> EqM ()
makeEq eqn tp =
let ps = [(xname [i], tp) | i <- [1..n]] in
addEq tp n eqn ps undefined >>
(case tp of
TpData y [] [] -> makeEqData y
TpProd Multiplicative tps -> makeEqProd tps
_ -> error ("makeEq got " ++ show tp ++ " (shouldn't happen)")) >>=
addEq tp n eqn ps
makeEqData :: TpName -> EqM Term
makeEqData y =
pure (!) <*> getData <*> pure y >>= \cs ->
pure (\cs -> TmCase (xtm [1] (TpData y [] [])) (y, [], []) cs tpBool) <*>
mapM (\(ci, Ctor cn as) ->
pure (Case cn [(xname [1, ci, ai], a) | (ai, a) <- zip [1..] as]) <*>
makeCase y cs as ci)
(zip [1..] cs)
makeCase y cs as ci = foldr
(\xi body ->
pure (\cs -> TmCase (xtm [xi] (TpData y [] [])) (y, [], []) cs tpBool) <*>
mapM (\(cj, Ctor cn as) ->
pure (Case cn [(xname [xi, cj, ai], a) | (ai, a) <- zip [1..] as]) <*>
if ci /= cj then pure tmFalse else body)
(zip [1..] cs))
(makeAnd <$> mapM (\(j, tp) -> compareTms [xtm [i, ci, j] tp | i <- [1..n]]) (zip [1..] as))
[2..n]
makeEqProd :: [Type] -> EqM Term
makeEqProd tps =
foldr
(\i body ->
let ps = [(xname [i, j], tp) | (j, tp) <- zip [1..] tps]
ptp = TpProd Multiplicative tps in
pure (TmElimMultiplicative (xtm [i] ptp) ps) <*> body <*> pure tpBool)
(makeAnd <$>
mapM (\(j, tp) -> compareTms [xtm [i, j] tp | i <- [1..n]]) (zip [1..] tps))
[1..n]
compareTms :: [Term] -> EqM Term
compareTms [] = error "compareTms [] (shouldn't happen)"
compareTms tms@(htm : _) =
let tp = typeof htm in
isFinite tp >>= \fin ->
if fin then
return (TmEqs tms)
else
isDefined tp >>= \def ->
eqName tp >>= \eqn ->
(if def then okay else makeEq eqn tp) >>
return (TmVarG GlDefine eqn [] [] [(tm, tp) | tm <- tms] tpBool)
isFinite :: Type -> EqM Bool
isFinite tp = getCtxt >>= \g -> return (not (isInfiniteType g tp))
isDefined :: Type -> EqM Bool
isDefined tp = member (tp, n) <$> getEqs
type EqM = RWS (Map TpName [Ctor]) () (Map (Type, Int) (TmName, [Param], Term))
getData :: EqM (Map TpName [Ctor])
getData = ask
getEqs :: EqM (Map (Type, Int) (TmName, [Param], Term))
getEqs = get
addEq :: Type -> Int -> TmName -> [Param] -> Term -> EqM ()
addEq tp n x ps tm = modify (insert (tp, n) (x, ps, tm))
getCtxt :: EqM Ctxt
getCtxt = getData >>= \ds -> return (emptyCtxt {tpNames = fmap (CtData [] []) ds})
replaceEqsh :: Term -> EqM Term
replaceEqsh (TmVarL x tp) =
pure (TmVarL x tp)
replaceEqsh (TmVarG gl x ts ps as tp) =
pure (TmVarG gl x ts ps) <*> mapArgsM replaceEqsh as <*> pure tp
replaceEqsh (TmLam x xtp tm tp) =
pure (TmLam x xtp) <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmApp tm1 tm2 tp2 tp) =
pure TmApp <*> replaceEqsh tm1 <*> replaceEqsh tm2 <*> pure tp2 <*> pure tp
replaceEqsh (TmLet x xtm xtp tm tp) =
pure (TmLet x) <*> replaceEqsh xtm <*> pure xtp <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmCase tm tpd cs rtp) =
pure TmCase <*> replaceEqsh tm <*> pure tpd <*> mapCasesM (\_ _ -> replaceEqsh) cs <*> pure rtp
replaceEqsh (TmAmb tms tp) =
pure TmAmb <*> mapM replaceEqsh tms <*> pure tp
replaceEqsh (TmFactor p tm tp) =
pure (TmFactor p) <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmProd am as) =
pure (TmProd am) <*> mapArgsM replaceEqsh as
replaceEqsh (TmElimMultiplicative xtm xps tm tp) =
pure TmElimMultiplicative <*> replaceEqsh xtm <*> pure xps <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmElimAdditive xtm xi xj xp tm tp) =
pure TmElimAdditive <*> replaceEqsh xtm <*> pure xi <*> pure xj <*> pure xp <*> replaceEqsh tm <*> pure tp
replaceEqsh (TmEqs tms) = replaceEq tms
replaceEqsProg :: Prog -> EqM Prog
replaceEqsProg (ProgDefine x ps tm tp) =
pure (ProgDefine x ps) <*> replaceEqsh tm <*> pure tp
replaceEqsProg p = pure p
replaceEqsProgs :: Progs -> EqM Progs
replaceEqsProgs (Progs ps tm) =
pure Progs <*> mapM replaceEqsProg ps <*> replaceEqsh tm
replaceEqs :: Progs -> Progs
replaceEqs p =
let g = ctxtAddProgs p
r = fmap (\(CtData _ _ cs) -> cs) (tpNames g)
(Progs ps tm, s, ()) = runRWS (replaceEqsProgs p) r mempty
eqps = [ProgDefine x pms tm tpBool | ((y, i), (x, pms, tm)) <- toList s]
in
Progs (ps ++ eqps) tm
|
37bc9929fa6400fc9d5f558992e4a7da140721daa397fa73b82d50d3014c669f | well-typed-lightbulbs/ocaml-esp32 | dynlink_types.ml | #2 "otherlibs/dynlink/dynlink_types.ml"
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
and , Europe
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
Copyright 2017 - -2018 Jane Street Group LLC
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(** Types shared amongst the various parts of the dynlink code. *)
[@@@ocaml.warning "+a-4-30-40-41-42"]
type implem_state =
| Loaded
| Not_initialized
| Check_inited of int
type filename = string
type linking_error =
| Undefined_global of string
| Unavailable_primitive of string
| Uninitialized_global of string
type error =
| Not_a_bytecode_file of string
| Inconsistent_import of string
| Unavailable_unit of string
| Unsafe_file
| Linking_error of string * linking_error
| Corrupted_interface of string
| Cannot_open_dynamic_library of exn
| Library's_module_initializers_failed of exn
| Inconsistent_implementation of string
| Module_already_loaded of string
| Private_library_cannot_implement_interface of string
exception Error of error
let error_message = function
| Not_a_bytecode_file name ->
name ^ " is not an object file"
| Inconsistent_import name ->
"interface mismatch on " ^ name
| Unavailable_unit name ->
"no implementation available for " ^ name
| Unsafe_file ->
"this object file uses unsafe features"
| Linking_error (name, Undefined_global s) ->
"error while linking " ^ name ^ ".\n" ^
"Reference to undefined global `" ^ s ^ "'"
| Linking_error (name, Unavailable_primitive s) ->
"error while linking " ^ name ^ ".\n" ^
"The external function `" ^ s ^ "' is not available"
| Linking_error (name, Uninitialized_global s) ->
"error while linking " ^ name ^ ".\n" ^
"The module `" ^ s ^ "' is not yet initialized"
| Corrupted_interface name ->
"corrupted interface file " ^ name
| Cannot_open_dynamic_library exn ->
"error loading shared library: " ^ (Printexc.to_string exn)
| Inconsistent_implementation name ->
"implementation mismatch on " ^ name
| Library's_module_initializers_failed exn ->
"execution of module initializers in the shared library failed: "
^ (Printexc.to_string exn)
| Module_already_loaded name ->
"The module `" ^ name ^ "' is already loaded \
(either by the main program or a previously-dynlinked library)"
| Private_library_cannot_implement_interface name ->
"The interface `" ^ name ^ "' cannot be implemented by a \
library loaded privately"
let () =
Printexc.register_printer (function
| Error err ->
let msg = match err with
| Not_a_bytecode_file s -> Printf.sprintf "Not_a_bytecode_file %S" s
| Inconsistent_import s -> Printf.sprintf "Inconsistent_import %S" s
| Unavailable_unit s -> Printf.sprintf "Unavailable_unit %S" s
| Unsafe_file -> "Unsafe_file"
| Linking_error (s, Undefined_global s') ->
Printf.sprintf "Linking_error (%S, Dynlink.Undefined_global %S)"
s s'
| Linking_error (s, Unavailable_primitive s') ->
Printf.sprintf "Linking_error (%S, Dynlink.Unavailable_primitive %S)"
s s'
| Linking_error (s, Uninitialized_global s') ->
Printf.sprintf "Linking_error (%S, Dynlink.Uninitialized_global %S)"
s s'
| Corrupted_interface s ->
Printf.sprintf "Corrupted_interface %S" s
| Cannot_open_dynamic_library exn ->
Printf.sprintf "Cannot_open_dll %S" (Printexc.to_string exn)
| Inconsistent_implementation s ->
Printf.sprintf "Inconsistent_implementation %S" s
| Library's_module_initializers_failed exn ->
Printf.sprintf "Library's_module_initializers_failed %S"
(Printexc.to_string exn)
| Module_already_loaded name ->
Printf.sprintf "Module_already_loaded %S" name
| Private_library_cannot_implement_interface name ->
Printf.sprintf "Private_library_cannot_implement_interface %S" name
in
Some (Printf.sprintf "Dynlink.Error (Dynlink.%s)" msg)
| _ -> None)
| null | https://raw.githubusercontent.com/well-typed-lightbulbs/ocaml-esp32/c24fcbfbee0e3aa6bb71c9b467c60c6bac326cc7/otherlibs/dynlink/dynlink_types.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
* Types shared amongst the various parts of the dynlink code. | #2 "otherlibs/dynlink/dynlink_types.ml"
, projet Cristal , INRIA Rocquencourt
and , Europe
Copyright 1996 Institut National de Recherche en Informatique et
Copyright 2017 - -2018 Jane Street Group LLC
the GNU Lesser General Public License version 2.1 , with the
[@@@ocaml.warning "+a-4-30-40-41-42"]
type implem_state =
| Loaded
| Not_initialized
| Check_inited of int
type filename = string
type linking_error =
| Undefined_global of string
| Unavailable_primitive of string
| Uninitialized_global of string
type error =
| Not_a_bytecode_file of string
| Inconsistent_import of string
| Unavailable_unit of string
| Unsafe_file
| Linking_error of string * linking_error
| Corrupted_interface of string
| Cannot_open_dynamic_library of exn
| Library's_module_initializers_failed of exn
| Inconsistent_implementation of string
| Module_already_loaded of string
| Private_library_cannot_implement_interface of string
exception Error of error
let error_message = function
| Not_a_bytecode_file name ->
name ^ " is not an object file"
| Inconsistent_import name ->
"interface mismatch on " ^ name
| Unavailable_unit name ->
"no implementation available for " ^ name
| Unsafe_file ->
"this object file uses unsafe features"
| Linking_error (name, Undefined_global s) ->
"error while linking " ^ name ^ ".\n" ^
"Reference to undefined global `" ^ s ^ "'"
| Linking_error (name, Unavailable_primitive s) ->
"error while linking " ^ name ^ ".\n" ^
"The external function `" ^ s ^ "' is not available"
| Linking_error (name, Uninitialized_global s) ->
"error while linking " ^ name ^ ".\n" ^
"The module `" ^ s ^ "' is not yet initialized"
| Corrupted_interface name ->
"corrupted interface file " ^ name
| Cannot_open_dynamic_library exn ->
"error loading shared library: " ^ (Printexc.to_string exn)
| Inconsistent_implementation name ->
"implementation mismatch on " ^ name
| Library's_module_initializers_failed exn ->
"execution of module initializers in the shared library failed: "
^ (Printexc.to_string exn)
| Module_already_loaded name ->
"The module `" ^ name ^ "' is already loaded \
(either by the main program or a previously-dynlinked library)"
| Private_library_cannot_implement_interface name ->
"The interface `" ^ name ^ "' cannot be implemented by a \
library loaded privately"
let () =
Printexc.register_printer (function
| Error err ->
let msg = match err with
| Not_a_bytecode_file s -> Printf.sprintf "Not_a_bytecode_file %S" s
| Inconsistent_import s -> Printf.sprintf "Inconsistent_import %S" s
| Unavailable_unit s -> Printf.sprintf "Unavailable_unit %S" s
| Unsafe_file -> "Unsafe_file"
| Linking_error (s, Undefined_global s') ->
Printf.sprintf "Linking_error (%S, Dynlink.Undefined_global %S)"
s s'
| Linking_error (s, Unavailable_primitive s') ->
Printf.sprintf "Linking_error (%S, Dynlink.Unavailable_primitive %S)"
s s'
| Linking_error (s, Uninitialized_global s') ->
Printf.sprintf "Linking_error (%S, Dynlink.Uninitialized_global %S)"
s s'
| Corrupted_interface s ->
Printf.sprintf "Corrupted_interface %S" s
| Cannot_open_dynamic_library exn ->
Printf.sprintf "Cannot_open_dll %S" (Printexc.to_string exn)
| Inconsistent_implementation s ->
Printf.sprintf "Inconsistent_implementation %S" s
| Library's_module_initializers_failed exn ->
Printf.sprintf "Library's_module_initializers_failed %S"
(Printexc.to_string exn)
| Module_already_loaded name ->
Printf.sprintf "Module_already_loaded %S" name
| Private_library_cannot_implement_interface name ->
Printf.sprintf "Private_library_cannot_implement_interface %S" name
in
Some (Printf.sprintf "Dynlink.Error (Dynlink.%s)" msg)
| _ -> None)
|
4fbda2f70b01ddc50bcedf84aad8d74d8b4edfdcc6f5eabadef6f05c696e2797 | graninas/Functional-Design-and-Architecture | Device.hs | module Andromeda.Hardware.Device where
import Andromeda.Hardware.HDL
import Andromeda.Hardware.Parameter
import qualified Data.Map as M
data DeviceComponent = Sensor Measurement Guid
| Controller Guid
deriving (Read, Show, Eq)
newtype Device = DeviceImpl (M.Map ComponentIndex DeviceComponent)
deriving (Read, Show, Eq)
blankDevice :: Device
blankDevice = DeviceImpl M.empty
addSensor :: ComponentIndex -> Parameter -> ComponentDef -> Device -> Device
addSensor idx p c (DeviceImpl d) = DeviceImpl $ M.insert idx (Sensor (toMeasurement p) (componentGuid c)) d
addController :: ComponentIndex -> ComponentDef -> Device -> Device
addController idx c (DeviceImpl d) = DeviceImpl $ M.insert idx (Controller (componentGuid c)) d
getComponent :: ComponentIndex -> Device -> Maybe DeviceComponent
getComponent idx (DeviceImpl d) = undefined
updateComponent :: ComponentIndex -> DeviceComponent -> Device -> Maybe Device
updateComponent idx c d = undefined
setMeasurement :: ComponentIndex -> Measurement -> Device -> Maybe Device
setMeasurement = undefined
readMeasurement :: ComponentIndex -> Device -> Maybe Measurement
readMeasurement = undefined
| null | https://raw.githubusercontent.com/graninas/Functional-Design-and-Architecture/1736abc16d3e4917fc466010dcc182746af2fd0e/First-Edition/BookSamples/CH05/5.1.2%20HNDL/Andromeda/Hardware/Device.hs | haskell | module Andromeda.Hardware.Device where
import Andromeda.Hardware.HDL
import Andromeda.Hardware.Parameter
import qualified Data.Map as M
data DeviceComponent = Sensor Measurement Guid
| Controller Guid
deriving (Read, Show, Eq)
newtype Device = DeviceImpl (M.Map ComponentIndex DeviceComponent)
deriving (Read, Show, Eq)
blankDevice :: Device
blankDevice = DeviceImpl M.empty
addSensor :: ComponentIndex -> Parameter -> ComponentDef -> Device -> Device
addSensor idx p c (DeviceImpl d) = DeviceImpl $ M.insert idx (Sensor (toMeasurement p) (componentGuid c)) d
addController :: ComponentIndex -> ComponentDef -> Device -> Device
addController idx c (DeviceImpl d) = DeviceImpl $ M.insert idx (Controller (componentGuid c)) d
getComponent :: ComponentIndex -> Device -> Maybe DeviceComponent
getComponent idx (DeviceImpl d) = undefined
updateComponent :: ComponentIndex -> DeviceComponent -> Device -> Maybe Device
updateComponent idx c d = undefined
setMeasurement :: ComponentIndex -> Measurement -> Device -> Maybe Device
setMeasurement = undefined
readMeasurement :: ComponentIndex -> Device -> Maybe Measurement
readMeasurement = undefined
|
|
4464b5159e6296ff82a2c397d2aea924b40b8d8ddf1099f15203415b288cfaef | slipstream/SlipStreamServer | deployment_parameter_lifecycle_test.clj | (ns com.sixsq.slipstream.ssclj.resources.deployment-parameter-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer :all]
[com.sixsq.slipstream.ssclj.app.params :as p]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.deployment-parameter :as dp]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[peridot.core :refer :all]))
(use-fixtures :each ltu/with-test-server-fixture)
(def base-uri (str p/service-context (u/de-camelcase dp/resource-url)))
(def valid-entry
{:name "param1"
:nodeID "machine"
:deployment {:href "deployment/uuid"}
:acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "jane"
:type "USER"
:right "MODIFY"}]}})
(def valid-state-entry
{:name "ss:state"
:value "Provisioning"
:deployment {:href "deployment/uuid"}
:acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "jane"
:type "USER"
:right "MODIFY"}]}})
(def valid-complete-entry
{:name "complete"
:nodeID "machine"
:deployment {:href "deployment/uuid"}
:acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "jane"
:type "USER"
:right "MODIFY"}]}})
(deftest lifecycle
(let [session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "root ADMIN USER ANON")
session-jane (header session authn-info-header "jane USER ANON")
session-anon (header session authn-info-header "unknown ANON")]
;; admin user collection query should succeed but be empty (no records created yet)
(-> session-admin
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present "add")
(ltu/is-operation-absent "delete")
(ltu/is-operation-absent "edit"))
;; normal user collection query should succeed but be empty (no records created yet)
(-> session-jane
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-absent "add")
(ltu/is-operation-absent "delete")
(ltu/is-operation-absent "edit"))
;; anonymous credential collection query should not succeed
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 403))
;; create a deployment parameter as a admin user
(let [resp-test (-> session-admin
(request base-uri
:request-method :post
:body (json/write-str valid-entry))
(ltu/body->edn)
(ltu/is-status 201))
id-test (get-in resp-test [:response :body :resource-id])
location-test (str p/service-context (-> resp-test ltu/location))
test-uri (str p/service-context id-test)]
(-> session-jane
(request base-uri
:request-method :post
:body (json/write-str valid-entry))
(ltu/body->edn)
(ltu/is-status 403))
(is (= location-test test-uri))
;; admin should be able to see everyone's records. Deployment parameter href is predictable
(-> session-admin
(request test-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id "deployment-parameter/324c6138-0484-34b5-bf35-af3ad15815db")
(ltu/is-operation-present "delete")
(ltu/is-operation-present "edit"))
;; user allowed edits
(-> session-jane
(request test-uri
:request-method :put
:body (json/write-str valid-entry))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-anon
(request test-uri
:request-method :put
:body (json/write-str valid-entry))
(ltu/body->edn)
(ltu/is-status 403))
;; search
(-> session-admin
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200))
;;delete
(-> session-jane
(request test-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
;;record should be deleted
(-> session-admin
(request test-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 404))
(let [state-uri (-> session-admin
(request base-uri
:request-method :post
:body (json/write-str valid-state-entry))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
state-abs-uri (str p/service-context (u/de-camelcase state-uri))
complete-uri (-> session-admin
(request base-uri
:request-method :post
:body (json/write-str valid-complete-entry))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
abs-complete-uri (str p/service-context (u/de-camelcase complete-uri))]
(-> session-jane
(request abs-complete-uri
:request-method :put
:body (json/write-str {:value "Provisioning"}))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-jane
(request state-abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :value "Executing"))
(-> session-jane
(request abs-complete-uri
:request-method :put
:body (json/write-str {:value "Executing"}))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-jane
(request state-abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :value "SendingReports"))
;; complete same state is idempotent
(-> session-jane
(request abs-complete-uri
:request-method :put
:body (json/write-str {:value "Executing"}))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-jane
(request state-abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :value "SendingReports"))
(-> session-jane
(request abs-complete-uri
:request-method :put
:body (json/write-str {:value "SendingReports"}))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-jane
(request state-abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :value "Ready"))
;; user should see events created
(-> session-jane
(request (str p/service-context "event"))
(ltu/body->edn)
(ltu/is-count 5))
))))
(deftest bad-methods
(let [resource-uri (str p/service-context (u/new-resource-id dp/resource-name))]
(ltu/verify-405-status [[base-uri :options]
[base-uri :delete]
[resource-uri :options]
[resource-uri :post]])))
| null | https://raw.githubusercontent.com/slipstream/SlipStreamServer/3ee5c516877699746c61c48fc72779fe3d4e4652/cimi-resources/test/com/sixsq/slipstream/ssclj/resources/deployment_parameter_lifecycle_test.clj | clojure | admin user collection query should succeed but be empty (no records created yet)
normal user collection query should succeed but be empty (no records created yet)
anonymous credential collection query should not succeed
create a deployment parameter as a admin user
admin should be able to see everyone's records. Deployment parameter href is predictable
user allowed edits
search
delete
record should be deleted
complete same state is idempotent
user should see events created | (ns com.sixsq.slipstream.ssclj.resources.deployment-parameter-lifecycle-test
(:require
[clojure.data.json :as json]
[clojure.test :refer :all]
[com.sixsq.slipstream.ssclj.app.params :as p]
[com.sixsq.slipstream.ssclj.middleware.authn-info-header :refer [authn-info-header]]
[com.sixsq.slipstream.ssclj.resources.common.utils :as u]
[com.sixsq.slipstream.ssclj.resources.deployment-parameter :as dp]
[com.sixsq.slipstream.ssclj.resources.lifecycle-test-utils :as ltu]
[peridot.core :refer :all]))
(use-fixtures :each ltu/with-test-server-fixture)
(def base-uri (str p/service-context (u/de-camelcase dp/resource-url)))
(def valid-entry
{:name "param1"
:nodeID "machine"
:deployment {:href "deployment/uuid"}
:acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "jane"
:type "USER"
:right "MODIFY"}]}})
(def valid-state-entry
{:name "ss:state"
:value "Provisioning"
:deployment {:href "deployment/uuid"}
:acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "jane"
:type "USER"
:right "MODIFY"}]}})
(def valid-complete-entry
{:name "complete"
:nodeID "machine"
:deployment {:href "deployment/uuid"}
:acl {:owner {:principal "ADMIN"
:type "ROLE"}
:rules [{:principal "jane"
:type "USER"
:right "MODIFY"}]}})
(deftest lifecycle
(let [session (-> (ltu/ring-app)
session
(content-type "application/json"))
session-admin (header session authn-info-header "root ADMIN USER ANON")
session-jane (header session authn-info-header "jane USER ANON")
session-anon (header session authn-info-header "unknown ANON")]
(-> session-admin
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-present "add")
(ltu/is-operation-absent "delete")
(ltu/is-operation-absent "edit"))
(-> session-jane
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-count zero?)
(ltu/is-operation-absent "add")
(ltu/is-operation-absent "delete")
(ltu/is-operation-absent "edit"))
(-> session-anon
(request base-uri)
(ltu/body->edn)
(ltu/is-status 403))
(let [resp-test (-> session-admin
(request base-uri
:request-method :post
:body (json/write-str valid-entry))
(ltu/body->edn)
(ltu/is-status 201))
id-test (get-in resp-test [:response :body :resource-id])
location-test (str p/service-context (-> resp-test ltu/location))
test-uri (str p/service-context id-test)]
(-> session-jane
(request base-uri
:request-method :post
:body (json/write-str valid-entry))
(ltu/body->edn)
(ltu/is-status 403))
(is (= location-test test-uri))
(-> session-admin
(request test-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-id "deployment-parameter/324c6138-0484-34b5-bf35-af3ad15815db")
(ltu/is-operation-present "delete")
(ltu/is-operation-present "edit"))
(-> session-jane
(request test-uri
:request-method :put
:body (json/write-str valid-entry))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-anon
(request test-uri
:request-method :put
:body (json/write-str valid-entry))
(ltu/body->edn)
(ltu/is-status 403))
(-> session-admin
(request base-uri)
(ltu/body->edn)
(ltu/is-status 200))
(-> session-jane
(request test-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 200))
(-> session-admin
(request test-uri
:request-method :delete)
(ltu/body->edn)
(ltu/is-status 404))
(let [state-uri (-> session-admin
(request base-uri
:request-method :post
:body (json/write-str valid-state-entry))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
state-abs-uri (str p/service-context (u/de-camelcase state-uri))
complete-uri (-> session-admin
(request base-uri
:request-method :post
:body (json/write-str valid-complete-entry))
(ltu/body->edn)
(ltu/is-status 201)
(ltu/location))
abs-complete-uri (str p/service-context (u/de-camelcase complete-uri))]
(-> session-jane
(request abs-complete-uri
:request-method :put
:body (json/write-str {:value "Provisioning"}))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-jane
(request state-abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :value "Executing"))
(-> session-jane
(request abs-complete-uri
:request-method :put
:body (json/write-str {:value "Executing"}))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-jane
(request state-abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :value "SendingReports"))
(-> session-jane
(request abs-complete-uri
:request-method :put
:body (json/write-str {:value "Executing"}))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-jane
(request state-abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :value "SendingReports"))
(-> session-jane
(request abs-complete-uri
:request-method :put
:body (json/write-str {:value "SendingReports"}))
(ltu/body->edn)
(ltu/is-status 200))
(-> session-jane
(request state-abs-uri)
(ltu/body->edn)
(ltu/is-status 200)
(ltu/is-key-value :value "Ready"))
(-> session-jane
(request (str p/service-context "event"))
(ltu/body->edn)
(ltu/is-count 5))
))))
(deftest bad-methods
(let [resource-uri (str p/service-context (u/new-resource-id dp/resource-name))]
(ltu/verify-405-status [[base-uri :options]
[base-uri :delete]
[resource-uri :options]
[resource-uri :post]])))
|
763b747c42f91b23425f76d55ae85a97531b1bea89852cab6aa8e8dc8408f65e | nvim-treesitter/nvim-treesitter | indents.scm | [
(comp_body)
(state_statement)
(transition_statement)
(handler_body)
(consequence_body)
(global_single)
] @indent
"}" @indent_end
(comment) @auto
(string_literal) @auto
| null | https://raw.githubusercontent.com/nvim-treesitter/nvim-treesitter/41e013dd9a4d27d0154475318b59fd2ca59cbe3d/queries/slint/indents.scm | scheme | [
(comp_body)
(state_statement)
(transition_statement)
(handler_body)
(consequence_body)
(global_single)
] @indent
"}" @indent_end
(comment) @auto
(string_literal) @auto
|
|
6aebc94a87df39c981e1be2fd22db1250b6bf5b22b89821f974953f76e819ee1 | batterseapower/haskell-kata | Generics3.hs | # LANGUAGE TypeFamilies , EmptyDataDecls , ScopedTypeVariables , TypeOperators , FlexibleInstances , FlexibleContexts #
import Data.Monoid
-- Type family for evaluators on types
type family E a :: *
-- Tag for functor application: fundamental to our approach
infixr 9 :%
data f :% a
-- Tags for evalutor-style data declarations: such declarations contain "internal"
-- occurrences of E, so we can delay evaluation of their arguments
data P0T (f :: *)
type instance E (P0T f) = f
data P1T (f :: * -> *)
type instance E (P1T f :% a) = f a
data P2T (f :: * -> * -> *)
type instance E (P2T f :% a :% b) = f a b
data P3T (f :: * -> * -> * -> *)
type instance E (P3T f :% a :% b :% c) = f a b c
-- When applying legacy data types we have to manually force the arguments:
data FunT
type instance E (FunT :% a :% b) = E a -> E b
data Tup2T
type instance E (Tup2T :% a :% b) = (E a, E b)
data Tup3T
type instance E (Tup3T :% a :% b :% c) = (E a, E b, E c)
-- Evalutor-style versions of some type classes
class FunctorT f where
fmapT :: (E a -> E b) -> E (f :% a) -> E (f :% b)
class MonoidT a where
memptyT :: E a
mappendT :: E a -> E a -> E a
data AdditiveIntT
type instance E AdditiveIntT = Int
instance MonoidT AdditiveIntT where
memptyT = 0
mappendT = (+)
data MultiplicativeIntT
type instance E MultiplicativeIntT = Int
instance MonoidT MultiplicativeIntT where
memptyT = 1
mappendT = (*)
-- Make the default instance of Monoid be additive:
instance MonoidT (P0T Int) where
memptyT = memptyT :: E AdditiveIntT
mappendT = mappendT :: E AdditiveIntT -> E AdditiveIntT -> E AdditiveIntT
main = do
print (result :: E (P0T Int))
print (result :: E MultiplicativeIntT)
where
result :: forall a. (E a ~ Int, MonoidT a) => E a
result _ = memptyT `mappendT` 2 `mappendT` 3 | null | https://raw.githubusercontent.com/batterseapower/haskell-kata/49c0c5cf48f8e5549131c78d026e4f2aa73d8a7a/Generics3.hs | haskell | Type family for evaluators on types
Tag for functor application: fundamental to our approach
Tags for evalutor-style data declarations: such declarations contain "internal"
occurrences of E, so we can delay evaluation of their arguments
When applying legacy data types we have to manually force the arguments:
Evalutor-style versions of some type classes
Make the default instance of Monoid be additive: | # LANGUAGE TypeFamilies , EmptyDataDecls , ScopedTypeVariables , TypeOperators , FlexibleInstances , FlexibleContexts #
import Data.Monoid
type family E a :: *
infixr 9 :%
data f :% a
data P0T (f :: *)
type instance E (P0T f) = f
data P1T (f :: * -> *)
type instance E (P1T f :% a) = f a
data P2T (f :: * -> * -> *)
type instance E (P2T f :% a :% b) = f a b
data P3T (f :: * -> * -> * -> *)
type instance E (P3T f :% a :% b :% c) = f a b c
data FunT
type instance E (FunT :% a :% b) = E a -> E b
data Tup2T
type instance E (Tup2T :% a :% b) = (E a, E b)
data Tup3T
type instance E (Tup3T :% a :% b :% c) = (E a, E b, E c)
class FunctorT f where
fmapT :: (E a -> E b) -> E (f :% a) -> E (f :% b)
class MonoidT a where
memptyT :: E a
mappendT :: E a -> E a -> E a
data AdditiveIntT
type instance E AdditiveIntT = Int
instance MonoidT AdditiveIntT where
memptyT = 0
mappendT = (+)
data MultiplicativeIntT
type instance E MultiplicativeIntT = Int
instance MonoidT MultiplicativeIntT where
memptyT = 1
mappendT = (*)
instance MonoidT (P0T Int) where
memptyT = memptyT :: E AdditiveIntT
mappendT = mappendT :: E AdditiveIntT -> E AdditiveIntT -> E AdditiveIntT
main = do
print (result :: E (P0T Int))
print (result :: E MultiplicativeIntT)
where
result :: forall a. (E a ~ Int, MonoidT a) => E a
result _ = memptyT `mappendT` 2 `mappendT` 3 |
941ab67ccac39c9761bf5c8f7acf08f400d08ab76b7add87bf9d2e8ac57f50ff | clojure-interop/google-cloud-clients | PartitionOptions$Builder.clj | (ns com.google.cloud.spanner.PartitionOptions$Builder
"Builder for PartitionOptions instance."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.spanner PartitionOptions$Builder]))
(defn set-partition-size-bytes
"The desired data size for each partition generated. This is only a hint. The actual size of
each partition may be smaller or larger than this size request.
partition-size-bytes - configuration for size of the partitions returned - `long`
returns: `com.google.cloud.spanner.PartitionOptions$Builder`"
(^com.google.cloud.spanner.PartitionOptions$Builder [^PartitionOptions$Builder this ^Long partition-size-bytes]
(-> this (.setPartitionSizeBytes partition-size-bytes))))
(defn set-max-partitions
"max-partitions - `long`
returns: `com.google.cloud.spanner.PartitionOptions$Builder`"
(^com.google.cloud.spanner.PartitionOptions$Builder [^PartitionOptions$Builder this ^Long max-partitions]
(-> this (.setMaxPartitions max-partitions))))
(defn build
"returns: `com.google.cloud.spanner.PartitionOptions`"
(^com.google.cloud.spanner.PartitionOptions [^PartitionOptions$Builder this]
(-> this (.build))))
| null | https://raw.githubusercontent.com/clojure-interop/google-cloud-clients/80852d0496057c22f9cdc86d6f9ffc0fa3cd7904/com.google.cloud.spanner/src/com/google/cloud/spanner/PartitionOptions%24Builder.clj | clojure | (ns com.google.cloud.spanner.PartitionOptions$Builder
"Builder for PartitionOptions instance."
(:refer-clojure :only [require comment defn ->])
(:import [com.google.cloud.spanner PartitionOptions$Builder]))
(defn set-partition-size-bytes
"The desired data size for each partition generated. This is only a hint. The actual size of
each partition may be smaller or larger than this size request.
partition-size-bytes - configuration for size of the partitions returned - `long`
returns: `com.google.cloud.spanner.PartitionOptions$Builder`"
(^com.google.cloud.spanner.PartitionOptions$Builder [^PartitionOptions$Builder this ^Long partition-size-bytes]
(-> this (.setPartitionSizeBytes partition-size-bytes))))
(defn set-max-partitions
"max-partitions - `long`
returns: `com.google.cloud.spanner.PartitionOptions$Builder`"
(^com.google.cloud.spanner.PartitionOptions$Builder [^PartitionOptions$Builder this ^Long max-partitions]
(-> this (.setMaxPartitions max-partitions))))
(defn build
"returns: `com.google.cloud.spanner.PartitionOptions`"
(^com.google.cloud.spanner.PartitionOptions [^PartitionOptions$Builder this]
(-> this (.build))))
|
|
2af2190db86e08941a1e79343ad09a4fa0d260c38d7c5e7bda5775000c23dbe9 | bartavelle/language-puppet | EvaluateStatementSpec.hs | # LANGUAGE OverloadedLists #
module Interpreter.EvaluateStatementSpec where
import Helpers
import qualified Data.Text as Text
main :: IO ()
main = hspec spec
shouldNotify :: [Text] -> PValue -> Expectation
shouldNotify s expected = do
catalog <- case pureCatalog (Text.unlines s) of
Left rr -> fail rr
Right (x,_) -> pure x
let msg = catalog ^? at (RIdentifier "notify" "test")._Just.rattributes. ix "message"
msg `shouldBe` (Just expected)
spec :: Spec
spec = do
describe "evaluate statement" $ do
it "should evaluate simple variable assignment" $
[ "$a = 0" , "notify { 'test': message => \"a is ${a}\"}"] `shouldNotify` "a is 0"
it "should evaluate chained variables assignment" $
[ "$a = $b = 0" , "notify { 'test': message => \"b is ${b}\"}"] `shouldNotify` "b is 0"
| null | https://raw.githubusercontent.com/bartavelle/language-puppet/6af7458e094440816c8b9b7b387050612e87a70f/tests/Interpreter/EvaluateStatementSpec.hs | haskell | # LANGUAGE OverloadedLists #
module Interpreter.EvaluateStatementSpec where
import Helpers
import qualified Data.Text as Text
main :: IO ()
main = hspec spec
shouldNotify :: [Text] -> PValue -> Expectation
shouldNotify s expected = do
catalog <- case pureCatalog (Text.unlines s) of
Left rr -> fail rr
Right (x,_) -> pure x
let msg = catalog ^? at (RIdentifier "notify" "test")._Just.rattributes. ix "message"
msg `shouldBe` (Just expected)
spec :: Spec
spec = do
describe "evaluate statement" $ do
it "should evaluate simple variable assignment" $
[ "$a = 0" , "notify { 'test': message => \"a is ${a}\"}"] `shouldNotify` "a is 0"
it "should evaluate chained variables assignment" $
[ "$a = $b = 0" , "notify { 'test': message => \"b is ${b}\"}"] `shouldNotify` "b is 0"
|
|
99d4cf5cb91f573fb9fb6711666e3b8e0523c1e084a55fce010561e9ca3d4cd2 | frenetic-lang/ocaml-tdk | bdd.ml | open S
module Make(V:HashCmp) = struct
module C = struct
type t = bool
let hash x = if x then 1 else 0
let compare x y =
match x, y with
| true , false -> -1
| false, true -> 1
| _ , _ -> 0
let to_string x = if x then "true" else "false"
end
module R = struct
include C
let one = true
let zero = false
let sum x y = x || y
let prod x y = x && y
end
module B = Vcr.Make(V)(C)(R)
type t = B.t
type v = B.v
type r = B.r
let const = B.const
(* NOTE: This is done to ensure the unique representation of BDDs *)
let atom (v,c) t f = if c then B.atom (v, true) t f else B.atom (v, true) f t
let restrict = B.restrict
let peek = B.peek
let support = B.support
let sum = B.sum
let prod = B.prod
let map_r = B.map_r
let fold = B.fold
let destruct = B.destruct
let iter = B.iter
let equal = B.equal
let to_string = B.to_string
let to_dot = B.to_dot
let var v = atom (v, true) true false
let neg t = map_r (fun r -> not r) t
exception Short_circuit
let tautology t =
try
iter ~order:`Post
(fun r -> if not r then raise Short_circuit else ())
(fun _ _ _ -> ())
t;
true
with Short_circuit -> false
let falsehood t =
try
iter ~order:`Post
(fun r -> if r then raise Short_circuit else ())
(fun _ _ _ -> ())
t;
true
with Short_circuit -> false
end
| null | https://raw.githubusercontent.com/frenetic-lang/ocaml-tdk/175f25543c7fc7965eed8532fb012c19bfd8bf0f/lib/bdd.ml | ocaml | NOTE: This is done to ensure the unique representation of BDDs | open S
module Make(V:HashCmp) = struct
module C = struct
type t = bool
let hash x = if x then 1 else 0
let compare x y =
match x, y with
| true , false -> -1
| false, true -> 1
| _ , _ -> 0
let to_string x = if x then "true" else "false"
end
module R = struct
include C
let one = true
let zero = false
let sum x y = x || y
let prod x y = x && y
end
module B = Vcr.Make(V)(C)(R)
type t = B.t
type v = B.v
type r = B.r
let const = B.const
let atom (v,c) t f = if c then B.atom (v, true) t f else B.atom (v, true) f t
let restrict = B.restrict
let peek = B.peek
let support = B.support
let sum = B.sum
let prod = B.prod
let map_r = B.map_r
let fold = B.fold
let destruct = B.destruct
let iter = B.iter
let equal = B.equal
let to_string = B.to_string
let to_dot = B.to_dot
let var v = atom (v, true) true false
let neg t = map_r (fun r -> not r) t
exception Short_circuit
let tautology t =
try
iter ~order:`Post
(fun r -> if not r then raise Short_circuit else ())
(fun _ _ _ -> ())
t;
true
with Short_circuit -> false
let falsehood t =
try
iter ~order:`Post
(fun r -> if r then raise Short_circuit else ())
(fun _ _ _ -> ())
t;
true
with Short_circuit -> false
end
|
a6dc6877133c9aedce926c527599b8b982654d2fa30b75e962fe43cc819d8992 | modular-macros/ocaml-macros | nativeint.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Module [Nativeint]: processor-native integers *)
external neg: nativeint -> nativeint = "%nativeint_neg"
external add: nativeint -> nativeint -> nativeint = "%nativeint_add"
external sub: nativeint -> nativeint -> nativeint = "%nativeint_sub"
external mul: nativeint -> nativeint -> nativeint = "%nativeint_mul"
external div: nativeint -> nativeint -> nativeint = "%nativeint_div"
external rem: nativeint -> nativeint -> nativeint = "%nativeint_mod"
external logand: nativeint -> nativeint -> nativeint = "%nativeint_and"
external logor: nativeint -> nativeint -> nativeint = "%nativeint_or"
external logxor: nativeint -> nativeint -> nativeint = "%nativeint_xor"
external shift_left: nativeint -> int -> nativeint = "%nativeint_lsl"
external shift_right: nativeint -> int -> nativeint = "%nativeint_asr"
external shift_right_logical: nativeint -> int -> nativeint = "%nativeint_lsr"
external of_int: int -> nativeint = "%nativeint_of_int"
external to_int: nativeint -> int = "%nativeint_to_int"
external of_float : float -> nativeint
= "caml_nativeint_of_float" "caml_nativeint_of_float_unboxed"
[@@unboxed] [@@noalloc]
external to_float : nativeint -> float
= "caml_nativeint_to_float" "caml_nativeint_to_float_unboxed"
[@@unboxed] [@@noalloc]
external of_int32: int32 -> nativeint = "%nativeint_of_int32"
external to_int32: nativeint -> int32 = "%nativeint_to_int32"
let zero = 0n
let one = 1n
let minus_one = -1n
let succ n = add n 1n
let pred n = sub n 1n
let abs n = if n >= 0n then n else neg n
let size = Sys.word_size
let min_int = shift_left 1n (size - 1)
let max_int = sub min_int 1n
let lognot n = logxor n (-1n)
external format : string -> nativeint -> string = "caml_nativeint_format"
let to_string n = format "%d" n
external of_string: string -> nativeint = "caml_nativeint_of_string"
type t = nativeint
let compare (x: t) (y: t) = Pervasives.compare x y
let equal (x: t) (y: t) = compare x y = 0
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/stdlib/nativeint.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Module [Nativeint]: processor-native integers | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
external neg: nativeint -> nativeint = "%nativeint_neg"
external add: nativeint -> nativeint -> nativeint = "%nativeint_add"
external sub: nativeint -> nativeint -> nativeint = "%nativeint_sub"
external mul: nativeint -> nativeint -> nativeint = "%nativeint_mul"
external div: nativeint -> nativeint -> nativeint = "%nativeint_div"
external rem: nativeint -> nativeint -> nativeint = "%nativeint_mod"
external logand: nativeint -> nativeint -> nativeint = "%nativeint_and"
external logor: nativeint -> nativeint -> nativeint = "%nativeint_or"
external logxor: nativeint -> nativeint -> nativeint = "%nativeint_xor"
external shift_left: nativeint -> int -> nativeint = "%nativeint_lsl"
external shift_right: nativeint -> int -> nativeint = "%nativeint_asr"
external shift_right_logical: nativeint -> int -> nativeint = "%nativeint_lsr"
external of_int: int -> nativeint = "%nativeint_of_int"
external to_int: nativeint -> int = "%nativeint_to_int"
external of_float : float -> nativeint
= "caml_nativeint_of_float" "caml_nativeint_of_float_unboxed"
[@@unboxed] [@@noalloc]
external to_float : nativeint -> float
= "caml_nativeint_to_float" "caml_nativeint_to_float_unboxed"
[@@unboxed] [@@noalloc]
external of_int32: int32 -> nativeint = "%nativeint_of_int32"
external to_int32: nativeint -> int32 = "%nativeint_to_int32"
let zero = 0n
let one = 1n
let minus_one = -1n
let succ n = add n 1n
let pred n = sub n 1n
let abs n = if n >= 0n then n else neg n
let size = Sys.word_size
let min_int = shift_left 1n (size - 1)
let max_int = sub min_int 1n
let lognot n = logxor n (-1n)
external format : string -> nativeint -> string = "caml_nativeint_format"
let to_string n = format "%d" n
external of_string: string -> nativeint = "caml_nativeint_of_string"
type t = nativeint
let compare (x: t) (y: t) = Pervasives.compare x y
let equal (x: t) (y: t) = compare x y = 0
|
bbb15a3d434765da8485f614374fe1df02923c8cacec42fcc6f9bcfcc01af393 | UU-ComputerScience/uhc | Main.hs | --
The Great Computer Language Shootout
-- /
by , , and
--
import System.Environment
data F = F !Integer !Integer !Integer !Integer
main :: IO ()
main = loop 10 0 . flip take (str (F 1 0 0 1) ns) . read . head =<< getArgs
ns = [ F k (4*k+2) 0 (2*k+1) | k <- [1..] ]
loop :: Int -> Integer -> [Integer] -> IO ()
loop n s [] = putStrLn $ replicate n ' ' ++ "\t:" ++ show s
loop 0 s xs = putStrLn ("\t:"++show s) >> loop 10 s xs
loop n s (x:xs) = putStr (show x) >> loop (n-1) (s+1) xs
flr x (F q r s t) = (q*x + r) `div` (s*x + t)
comp1 (F q r s t) (F u v w x) = F (q*u+r*w) (q*v+r*x) (t*w) (t*x)
comp2 (F q r s t) (F u v w x) = F (q*u) (q*v+r*x) (s*u) (s*v+t*x)
str z (x:xs) | y == flr 4 z = y : str (comp1 (F 10 (-10*y) 0 1) z) (x:xs)
| otherwise = str (comp2 z x) xs where y = flr 3 z
| null | https://raw.githubusercontent.com/UU-ComputerScience/uhc/f2b94a90d26e2093d84044b3832a9a3e3c36b129/EHC/test/benchmark/nofib/imag/pidigits/Main.hs | haskell |
/
| The Great Computer Language Shootout
by , , and
import System.Environment
data F = F !Integer !Integer !Integer !Integer
main :: IO ()
main = loop 10 0 . flip take (str (F 1 0 0 1) ns) . read . head =<< getArgs
ns = [ F k (4*k+2) 0 (2*k+1) | k <- [1..] ]
loop :: Int -> Integer -> [Integer] -> IO ()
loop n s [] = putStrLn $ replicate n ' ' ++ "\t:" ++ show s
loop 0 s xs = putStrLn ("\t:"++show s) >> loop 10 s xs
loop n s (x:xs) = putStr (show x) >> loop (n-1) (s+1) xs
flr x (F q r s t) = (q*x + r) `div` (s*x + t)
comp1 (F q r s t) (F u v w x) = F (q*u+r*w) (q*v+r*x) (t*w) (t*x)
comp2 (F q r s t) (F u v w x) = F (q*u) (q*v+r*x) (s*u) (s*v+t*x)
str z (x:xs) | y == flr 4 z = y : str (comp1 (F 10 (-10*y) 0 1) z) (x:xs)
| otherwise = str (comp2 z x) xs where y = flr 3 z
|
ccaeeda50312d842090169dc61beba5a63500ca7a7a3940b70aa35ecd59d0cf7 | gafiatulin/codewars | Phonedir.hs | Phone Directory
--
module Codewars.G964.Phonedir(phone) where
import Data.Char(isDigit)
import Data.List(intercalate)
import Data.Maybe(listToMaybe, mapMaybe)
import Control.Applicative((<|>))
import Text.ParserCombinators.ReadP(readP_to_S, satisfy, get, many, char, many1, pfail, sepBy1, between)
data Person = Person { name :: String, pNumber :: String, address :: String}
instance Show Person where
show (Person n p a) = "Phone => " ++ p ++ ", " ++
"Name => " ++ n ++ ", " ++
"Address => " ++ a
addressChars = ['0'..'9'] ++ ['A'..'Z'] ++ ['a'..'z'] ++ ".-"
process = fmap record . listToMaybe . map fst . filter (null . snd) . readP_to_S phoneNameRest
where phoneNameRest = many get >>= \a -> nameOrPhone >>= \b -> many get >>= \c -> nameOrPhone >>= \d -> many get >>= \e -> return (if isDigit . head $ b then (b, d) else (d, b), unwords [a, c, e])
phoneNumber = char '+' >> sepBy1 (many1 digit) (char '-') >>= \ds -> if validPhone ds then return . intercalate "-" $ ds else pfail
validPhone x = length x == 4 && ((\(c, ns) -> all (<=2) c && ns == [3,3,4]) . splitAt 1 . map length $ x)
nameOrPhone = between (char '<') (char '>') (many1 get) <|> phoneNumber
digit = satisfy isDigit
record ((p, n), rest) = Person {name = n, pNumber = p, address = clean rest}
clean = unwords . filter (not . null) . map (filter (`elem` addressChars )) . words . map (\c -> if c == '_' then ' ' else c)
phone :: String -> String -> String
phone dr num = present . filter ((==num) . pNumber) . mapMaybe process . lines $ dr
where present [] = "Error => Not found: " ++ num
present [x] = show x
present (x:xs) = "Error => Too many people: " ++ num
| null | https://raw.githubusercontent.com/gafiatulin/codewars/535db608333e854be93ecfc165686a2162264fef/src/5%20kyu/Phonedir.hs | haskell | Phone Directory
module Codewars.G964.Phonedir(phone) where
import Data.Char(isDigit)
import Data.List(intercalate)
import Data.Maybe(listToMaybe, mapMaybe)
import Control.Applicative((<|>))
import Text.ParserCombinators.ReadP(readP_to_S, satisfy, get, many, char, many1, pfail, sepBy1, between)
data Person = Person { name :: String, pNumber :: String, address :: String}
instance Show Person where
show (Person n p a) = "Phone => " ++ p ++ ", " ++
"Name => " ++ n ++ ", " ++
"Address => " ++ a
addressChars = ['0'..'9'] ++ ['A'..'Z'] ++ ['a'..'z'] ++ ".-"
process = fmap record . listToMaybe . map fst . filter (null . snd) . readP_to_S phoneNameRest
where phoneNameRest = many get >>= \a -> nameOrPhone >>= \b -> many get >>= \c -> nameOrPhone >>= \d -> many get >>= \e -> return (if isDigit . head $ b then (b, d) else (d, b), unwords [a, c, e])
phoneNumber = char '+' >> sepBy1 (many1 digit) (char '-') >>= \ds -> if validPhone ds then return . intercalate "-" $ ds else pfail
validPhone x = length x == 4 && ((\(c, ns) -> all (<=2) c && ns == [3,3,4]) . splitAt 1 . map length $ x)
nameOrPhone = between (char '<') (char '>') (many1 get) <|> phoneNumber
digit = satisfy isDigit
record ((p, n), rest) = Person {name = n, pNumber = p, address = clean rest}
clean = unwords . filter (not . null) . map (filter (`elem` addressChars )) . words . map (\c -> if c == '_' then ' ' else c)
phone :: String -> String -> String
phone dr num = present . filter ((==num) . pNumber) . mapMaybe process . lines $ dr
where present [] = "Error => Not found: " ++ num
present [x] = show x
present (x:xs) = "Error => Too many people: " ++ num
|
|
e02f1d43800826506c2bfb399313f1c33fc622ef7a1909005e4f4801d801040a | ocaml-omake/omake | omake_env.ml |
module TargetElem = struct
type t = int * string * Omake_node_sig.node_kind
let compare (h1,s1,k1) (h2,s2,k2) =
if h1=h2 then
let p1 = String.compare s1 s2 in
if p1 = 0 then
compare k1 k2
else
p1
else
h1-h2
let intern ((s1,k1) as key) =
let h1 = Hashtbl.hash key in
(h1,s1,k1)
end
module TargetMap = Lm_map.Make(TargetElem)
(*
* Command lists have source arguments.
*)
type command_info =
{ command_env : t;
command_sources : Omake_node.Node.t list;
command_values : Omake_value_type.t list;
command_body : Omake_value_type.command list
}
(*
* An implicit rule with a body.
*
* In an implicit rule, we compile the targets/sources
* to wild patterns.
*)
and irule =
{ irule_loc : Lm_location.t;
irule_multiple : Omake_value_type.rule_multiple;
irule_targets : Lm_string_set.StringSet.t option;
irule_patterns : Lm_wild.in_patt list;
irule_locks : Omake_value_type.source_core Omake_value_type.source list;
irule_sources : Omake_value_type.source_core Omake_value_type.source list;
irule_scanners : Omake_value_type.source_core Omake_value_type.source list;
irule_values : Omake_value_type.t list;
irule_body : Omake_value_type.command list
}
(*
* An implicit dependency. There is no body, but
* it may have value dependencies.
*)
and inrule =
{ inrule_loc : Lm_location.t;
inrule_multiple : Omake_value_type.rule_multiple;
inrule_patterns : Lm_wild.in_patt list;
inrule_locks : Omake_value_type.source_core Omake_value_type.source list;
inrule_sources : Omake_value_type.source_core Omake_value_type.source list;
inrule_scanners : Omake_value_type.source_core Omake_value_type.source list;
inrule_values : Omake_value_type.t list
}
(*
* Explicit rules.
*)
and erule =
{ rule_loc : Lm_location.t;
rule_env : t;
rule_target : Omake_node.Node.t;
rule_effects : Omake_node.NodeSet.t;
rule_locks : Omake_node.NodeSet.t;
rule_sources : Omake_node.NodeSet.t;
rule_scanners : Omake_node.NodeSet.t;
rule_match : string option;
rule_multiple : Omake_value_type.rule_multiple;
rule_commands : command_info list
}
(*
* A listing of all the explicit rules.
*
* explicit_targets : the collapsed rules for each explicit target
* explicit_deps : the table of explicit rules that are just dependencies
* explicit_rules : the table of all individual explicit rules
* explicit_directories : the environment for each directory in the project
*)
and erule_info =
{ explicit_targets : erule Omake_node.NodeTable.t;
explicit_deps : (Omake_node.NodeSet.t * Omake_node.NodeSet.t * Omake_node.NodeSet.t) Omake_node.NodeTable.t; (* locks, sources, scanners *)
explicit_rules : erule Omake_node.NodeMTable.t;
explicit_directories : t Omake_node.DirTable.t
}
* An ordering rule .
* For now , this just defines an extra dependency
* of the form : patt1 - > patt2
* This means that if a file depends on patt1 ,
* then it also depends on patt2 .
* An ordering rule.
* For now, this just defines an extra dependency
* of the form: patt1 -> patt2
* This means that if a file depends on patt1,
* then it also depends on patt2.
*)
and orule =
{ orule_loc : Lm_location.t;
orule_name : Lm_symbol.t;
orule_pattern : Lm_wild.in_patt;
orule_sources : Omake_value_type.source_core list
}
and ordering_info = orule list
and srule =
{ srule_loc : Lm_location.t;
srule_static : bool;
srule_env : t;
srule_key : Omake_value_type.t;
srule_deps : Omake_node.NodeSet.t;
srule_vals : Omake_value_type.t list;
srule_exp : Omake_ir.exp
}
and static_info =
StaticRule of srule
| StaticValue of Omake_value_type.obj
* The environment contains three scopes :
* 1 . The dynamic scope
* 2 . The current object
* 3 . The static scope
* Lookup occurs in that order , unless the variables
* have been defined otherwise .
*
* Each function has its own static scope .
* The dynamic scope comes from the caller .
* The environment contains three scopes:
* 1. The dynamic scope
* 2. The current object
* 3. The static scope
* Lookup occurs in that order, unless the variables
* have been defined otherwise.
*
* Each function has its own static scope.
* The dynamic scope comes from the caller.
*)
and t =
{ venv_dynamic : Omake_value_type.env;
venv_this : Omake_value_type.obj;
venv_static : Omake_value_type.env;
venv_inner : venv_inner
}
and venv_inner =
{ venv_environ : string Lm_symbol.SymbolTable.t;
venv_dir : Omake_node.Dir.t;
venv_phony : Omake_node.NodeSet.t;
venv_implicit_deps : inrule list;
venv_implicit_rules : irule list;
venv_options : Omake_options.t;
venv_globals : venv_globals;
venv_mount : Omake_node.Mount.t;
venv_included_files : Omake_node.NodeSet.t
}
and venv_globals =
{ mutable venv_parent : (venv_globals * int) option;
(* after a venv_fork this is the pointer to the source; it is set back
to None when any of the versions is changed. The int is the version
of the parent.
*)
mutable venv_version : int;
(* increased after a change *)
mutable venv_mutex : Lm_thread.Mutex.t;
At present , the venv_parent / venv_version mechanism is only used to
accelerate target_is_buildable{_proper } . If a forked venv is still
identical to the original , this cache can be better updated in the
parent ( back propagation ) .
TODO : another candidate for back propagation is the file cache .
accelerate target_is_buildable{_proper}. If a forked venv is still
identical to the original, this cache can be better updated in the
parent (back propagation).
TODO: another candidate for back propagation is the file cache.
*)
(* Execution service *)
venv_exec : exec;
(* File cache *)
venv_cache : Omake_cache.t;
(* Mounting functions *)
venv_mount_info : Omake_node.mount_info;
(* Values from handles *)
venv_environments : t Lm_handle_table.t;
(* The set of files we have ever read *)
mutable venv_files : Omake_node.NodeSet.t;
(* Save the environment for each directory in the project *)
mutable venv_directories : t Omake_node.DirTable.t;
mutable venv_excluded_directories : Omake_node.DirSet.t;
(* All the phony targets we have ever generated *)
mutable venv_phonies : Omake_node.PreNodeSet.t;
(* Explicit rules are global *)
mutable venv_explicit_rules : erule list;
mutable venv_explicit_targets : erule Omake_node.NodeTable.t;
mutable venv_explicit_new : erule list;
(* Ordering rules *)
mutable venv_ordering_rules : orule list;
mutable venv_orders : Lm_string_set.StringSet.t;
(* Static rules *)
mutable venv_memo_rules : static_info Omake_value_util.ValueTable.t;
(* Cached values for files *)
mutable venv_ir_files : Omake_ir.t Omake_node.NodeTable.t;
mutable venv_object_files : Omake_value_type.obj Omake_node.NodeTable.t;
(* Cached values for static sections *)
mutable venv_static_values : Omake_value_type.obj Lm_symbol.SymbolTable.t Omake_node.NodeTable.t;
mutable venv_modified_values : Omake_value_type.obj Lm_symbol.SymbolTable.t Omake_node.NodeTable.t;
(* Cached values for the target_is_buildable function *)
This uses now a compression : we map directories to small integers
target_dir . This mapping is implemented by venv_target_dirs .
For every ( candidate ) target file we map the file name to two bitsets
( buildable , non_buildable ) enumerating the directories where the file
can be built or not be built .
target_dir. This mapping is implemented by venv_target_dirs.
For every (candidate) target file we map the file name to two bitsets
(buildable,non_buildable) enumerating the directories where the file
can be built or not be built.
*)
mutable venv_target_dirs : target_dir Omake_node.DirTable.t;
mutable venv_target_next_dir : target_dir;
mutable venv_target_is_buildable : (Lm_bitset.t * Lm_bitset.t) TargetMap.t;
mutable venv_target_is_buildable_proper : (Lm_bitset.t * Lm_bitset.t) TargetMap.t;
The state right after Pervasives is evaluated
mutable venv_pervasives_vars : Omake_ir.senv;
mutable venv_pervasives_obj : Omake_value_type.obj
}
and target_dir = int
(*
* Type of execution servers.
*)
and pid =
InternalPid of int
| ExternalPid of int
| ResultPid of int * t * Omake_value_type.t
and exec = (arg_command_line, pid, Omake_value_type.t) Omake_exec.Exec.t
(*
* Execution service.
*)
and arg_command_inst = (Omake_ir.exp, arg_pipe, Omake_value_type.t) Omake_command_type.poly_command_inst
and arg_command_line = (t, Omake_ir.exp, arg_pipe, Omake_value_type.t) Omake_command_type.poly_command_line
and string_command_inst = (Omake_ir.exp, string_pipe, Omake_value_type.t) Omake_command_type.poly_command_inst
and string_command_line = (t, Omake_ir.exp, string_pipe, Omake_value_type.t) Omake_command_type.poly_command_line
and apply = t -> Unix.file_descr -> Unix.file_descr -> Unix.file_descr -> (Lm_symbol.t * string) list -> Omake_value_type.t list -> int * t * Omake_value_type.t
and value_cmd = (unit, Omake_value_type.t list, Omake_value_type.t list) Omake_shell_type.poly_cmd
and value_apply = (Omake_value_type.t list, Omake_value_type.t list, apply) Omake_shell_type.poly_apply
and value_group = (unit, Omake_value_type.t list, Omake_value_type.t list, Omake_value_type.t list, apply) Omake_shell_type.poly_group
and value_pipe = (unit, Omake_value_type.t list, Omake_value_type.t list, Omake_value_type.t list, apply) Omake_shell_type.poly_pipe
and arg_cmd = (Omake_command_type.arg Omake_shell_type.cmd_exe, Omake_command_type.arg, Omake_command_type.arg) Omake_shell_type.poly_cmd
and arg_apply = (Omake_value_type.t, Omake_command_type.arg, apply) Omake_shell_type.poly_apply
and arg_group = (Omake_command_type.arg Omake_shell_type.cmd_exe, Omake_command_type.arg, Omake_value_type.t, Omake_command_type.arg, apply) Omake_shell_type.poly_group
and arg_pipe = (Omake_command_type.arg Omake_shell_type.cmd_exe, Omake_command_type.arg, Omake_value_type.t, Omake_command_type.arg, apply) Omake_shell_type.poly_pipe
and string_cmd = (Omake_shell_type.simple_exe, string, string) Omake_shell_type.poly_cmd
and string_apply = (Omake_value_type.t, string, apply) Omake_shell_type.poly_apply
and string_group = (Omake_shell_type.simple_exe, string, Omake_value_type.t, string, apply) Omake_shell_type.poly_group
and string_pipe = (Omake_shell_type.simple_exe, string, Omake_value_type.t, string, apply) Omake_shell_type.poly_pipe
(*
* Error during translation.
*)
exception Break of Lm_location.t * t
type prim_fun_data = t -> Omake_value_type.pos -> Lm_location.t ->
Omake_value_type.t list -> Omake_value_type.keyword_value list -> t * Omake_value_type.t
type venv_runtime =
{ venv_channels : Lm_channel.t Lm_int_handle_table.t;
mutable venv_primitives : prim_fun_data Lm_symbol.SymbolTable.t
}
(*
* Command line parsing.
*)
type lexer = string -> int -> int -> int option
type tok =
TokString of Omake_value_type.t
| TokToken of string
| TokGroup of tok list
* Inclusion scope is usually Pervasives ,
* but it may include everything in scope .
* Inclusion scope is usually Pervasives,
* but it may include everything in scope.
*)
type include_scope =
IncludePervasives
| IncludeAll
(*
* Full and partial applications.
*)
type partial_apply =
FullApply of t * Omake_value_type.t list * Omake_value_type.keyword_value list
| PartialApply of Omake_value_type.env * Omake_value_type.param_value list * Omake_value_type.keyword_param_value list * Omake_ir.param list * Omake_value_type.keyword_value list
let venv_runtime : venv_runtime =
{ venv_channels = Lm_int_handle_table.create ();
venv_primitives = Lm_symbol.SymbolTable.empty
}
* Now the stuff that is really global , not saved in venv .
* Now the stuff that is really global, not saved in venv.
*)
module IntCompare =
struct
type t = int
let compare = (-)
end;;
module IntTable = Lm_map.LmMake (IntCompare);;
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Access to the globals .
* This actually performs some computation in 0.9.9
* Access to the globals.
* This actually performs some computation in 0.9.9
*)
let venv_globals venv =
venv.venv_inner.venv_globals
let venv_get_mount_listing venv =
Omake_node.Mount.mount_listing venv.venv_inner.venv_mount
let venv_protect globals f =
Lm_thread.Mutex.lock globals.venv_mutex;
try
let r = f() in
Lm_thread.Mutex.unlock globals.venv_mutex;
r
with
| exn ->
Lm_thread.Mutex.unlock globals.venv_mutex;
raise exn
let venv_synch venv f =
let globals = venv_globals venv in
venv_protect
globals
(fun () ->
match globals.venv_parent with
| Some(pglobals, pversion) ->
venv_protect
pglobals
(fun () ->
if pversion = pglobals.venv_version then
f globals (Some pglobals)
else (
globals.venv_parent <- None;
f globals None
)
)
| None ->
f globals None
)
let venv_incr_version venv f =
(* At present, this function needs to be called when any change is done that
may affect target_is_buildable(_proper), i.e. the addition of implicit,
explicit or phony rules.
*)
let g = venv_globals venv in
venv_protect
g
(fun () ->
g.venv_version <- g.venv_version + 1;
g.venv_parent <- None;
f()
)
(*
* Map functions.
*)
let check_map_key = Omake_value_util.ValueCompare.check
let venv_map_empty = Omake_value_util.ValueTable.empty
let venv_map_add map pos v1 v2 =
Omake_value_util.ValueTable.add map (check_map_key pos v1) v2
let venv_map_remove map pos v1 =
Omake_value_util.ValueTable.remove map (check_map_key pos v1)
let venv_map_find map pos v =
try Omake_value_util.ValueTable.find map (check_map_key pos v) with
Not_found ->
raise (Omake_value_type.OmakeException (pos, UnboundValue v))
let venv_map_mem map pos v =
Omake_value_util.ValueTable.mem map (check_map_key pos v)
let venv_map_iter = Omake_value_util.ValueTable.iter
let venv_map_map = Omake_value_util.ValueTable.mapi
let venv_map_fold = Omake_value_util.ValueTable.fold
let venv_map_length = Omake_value_util.ValueTable.cardinal
(************************************************************************
* Printing.
*)
let rec pp_print_command buf command =
match command with
Omake_value_type.CommandSection (arg, _fv, e) ->
Format.fprintf buf "@[<hv 3>section %a@ %a@]" Omake_value_print.pp_print_value arg Omake_ir_print.pp_print_exp_list e
| CommandValue (_, _, v) ->
Omake_ir_print.pp_print_string_exp buf v
and pp_print_commands buf commands =
List.iter (fun command -> Format.fprintf buf "@ %a" pp_print_command command) commands
and pp_print_command_info buf info =
let { command_env = venv;
command_sources = sources;
command_body = commands;
_
} = info
in
Format.fprintf buf "@[<hv 0>@[<hv 3>{@ command_dir = %a;@ @[<b 3>command_sources =%a@]@ @[<b 3>command_body =%a@]@]@ }@]" (**)
Omake_node.pp_print_dir venv.venv_inner.venv_dir
Omake_node.pp_print_node_list sources
pp_print_commands commands
and pp_print_command_info_list buf infos =
List.iter (fun info -> Format.fprintf buf "@ %a" pp_print_command_info info) infos
and pp_print_rule buf erule =
let { rule_target = target;
rule_effects = effects;
rule_locks = locks;
rule_sources = sources;
rule_scanners = scanners;
rule_commands = commands;
_
} = erule
in
Format.fprintf buf "@[<hv 0>@[<hv 3>rule {";
Format.fprintf buf "@ target = %a" Omake_node.pp_print_node target;
Format.fprintf buf "@ @[<b 3>effects =%a@]" Omake_node.pp_print_node_set effects;
Format.fprintf buf "@ @[<b 3>locks =%a@]" Omake_node.pp_print_node_set locks;
Format.fprintf buf "@ @[<b 3>sources =%a@]" Omake_node.pp_print_node_set sources;
Format.fprintf buf "@ @[<b 3>scanners =%a@]" Omake_node.pp_print_node_set scanners;
Format.fprintf buf "@ @[<hv 3>commands =%a@]" pp_print_command_info_list commands;
Format.fprintf buf "@]@ }@]"
let pp_print_explicit_rules buf venv =
Format.fprintf buf "@[<hv 3>Explicit rules:";
List.iter (fun erule -> Format.fprintf buf "@ %a" pp_print_rule erule) venv.venv_inner.venv_globals.venv_explicit_rules;
Format.fprintf buf "@]"
(************************************************************************
* Pipeline printing.
*)
(*
* Token printing.
*)
let rec pp_print_tok buf tok =
match tok with
TokString v ->
Omake_value_print.pp_print_value buf v
| TokToken s ->
Format.fprintf buf "$%s" s
| TokGroup toks ->
Format.fprintf buf "(%a)" pp_print_tok_list toks
and pp_print_tok_list buf toks =
match toks with
[tok] ->
pp_print_tok buf tok
| tok :: toks ->
pp_print_tok buf tok;
Lm_printf.pp_print_char buf ' ';
pp_print_tok_list buf toks
| [] ->
()
let pp_print_simple_exe buf exe =
match exe with
Omake_shell_type.ExeString s ->
Lm_printf.pp_print_string buf s
| ExeQuote s ->
Format.fprintf buf "\\%s" s
| ExeNode node ->
Omake_node.pp_print_node buf node
(*
* Pipes based on strings.
*)
module PrintString =
struct
type arg_command = string
type arg_apply = Omake_value_type.t
type arg_other = string
type exe = Omake_shell_type.simple_exe
let pp_print_arg_command = Omake_command_type.pp_arg_data_string
let pp_print_arg_apply = Omake_value_print.pp_print_value
let pp_print_arg_other = Omake_command_type.pp_arg_data_string
let pp_print_exe = pp_print_simple_exe
end;;
module PrintStringPipe = Omake_shell_type.MakePrintPipe (PrintString);;
module PrintStringv =
struct
type argv = string_pipe
let pp_print_argv = PrintStringPipe.pp_print_pipe
end;;
module PrintStringCommand = Omake_command_type.MakePrintCommand (PrintStringv);;
let pp_print_string_pipe = PrintStringPipe.pp_print_pipe
let pp_print_string_command_inst = PrintStringCommand.pp_print_command_inst
let pp_print_string_command_line = PrintStringCommand.pp_print_command_line
let pp_print_string_command_lines = PrintStringCommand.pp_print_command_lines
(*
* Pipes based on arguments.
*)
module PrintArg =
struct
type arg_command = Omake_command_type.arg
type arg_apply = Omake_value_type.t
type arg_other = arg_command
type exe = arg_command Omake_shell_type.cmd_exe
let pp_print_arg_command = Omake_command_type.pp_print_arg
let pp_print_arg_apply = Omake_value_print.pp_print_simple_value
let pp_print_arg_other = pp_print_arg_command
let pp_print_exe buf exe =
match exe with
Omake_shell_type.CmdArg arg ->
pp_print_arg_command buf arg
| CmdNode node ->
Omake_node.pp_print_node buf node
end;;
module PrintArgPipe = Omake_shell_type.MakePrintPipe (PrintArg);;
module PrintArgv =
struct
type argv = arg_pipe
let pp_print_argv = PrintArgPipe.pp_print_pipe
end;;
module PrintArgCommand = Omake_command_type.MakePrintCommand (PrintArgv);;
let pp_print_arg_pipe = PrintArgPipe.pp_print_pipe
let pp_print_arg_command_inst = PrintArgCommand.pp_print_command_inst
let pp_print_arg_command_line = PrintArgCommand.pp_print_command_line
let pp_print_arg_command_lines = PrintArgCommand.pp_print_command_lines
(************************************************************************
* Utilities.
*)
(*
* Don't make command info if there are no commands.
*)
let make_command_info venv sources values body =
match values, body with
[], [] ->
[]
| _ ->
[{ command_env = venv;
command_sources = sources;
command_values = values;
command_body = body
}]
(*
* Check if the commands are trivial.
*)
let commands_are_trivial commands =
List.for_all (fun command -> command.command_body = []) commands
(*
* Multiple flags.
*)
let is_multiple_rule = function
Omake_value_type.RuleMultiple
| RuleScannerMultiple ->
true
| RuleSingle
| RuleScannerSingle ->
false
(* let is_scanner_rule = function *)
Omake_value_type . RuleScannerSingle
(* | RuleScannerMultiple -> *)
(* true *)
(* | RuleSingle *)
(* | RuleMultiple -> *)
(* false *)
let rule_kind = function
Omake_value_type.RuleScannerSingle
| RuleScannerMultiple ->
Omake_value_type.RuleScanner
| RuleSingle
| RuleMultiple ->
RuleNormal
(************************************************************************
* Handles.
*)
let venv_add_environment venv =
Lm_handle_table.add venv.venv_inner.venv_globals.venv_environments venv
module Pos= Omake_pos.Make (struct let name = "Omake_env" end)
let venv_find_environment venv pos hand =
try Lm_handle_table.find venv.venv_inner.venv_globals.venv_environments hand with
Not_found ->
let pos = Pos.string_pos "venv_find_environment" pos in
raise (Omake_value_type.OmakeException (pos, StringError "unbound environment"))
(************************************************************************
* Channels.
*)
(*
* Add a channel slot.
*)
let venv_add_index_channel index data =
let channels = venv_runtime.venv_channels in
let channel = Lm_int_handle_table.create_handle channels index in
Lm_channel.set_id data index;
Lm_int_handle_table.add channels channel data;
channel
let venv_add_channel _venv data =
let channels = venv_runtime.venv_channels in
let channel = Lm_int_handle_table.new_handle channels in
let index = Lm_int_handle_table.int_of_handle channel in
Lm_channel.set_id data index;
Lm_int_handle_table.add channels channel data;
channel
let add_channel file kind mode binary fd =
Lm_channel.create file kind mode binary (Some fd)
let venv_stdin = venv_add_index_channel 0 (add_channel "<stdin>" Lm_channel.PipeChannel Lm_channel.InChannel false Unix.stdin)
let venv_stdout = venv_add_index_channel 1 (add_channel "<stdout>" Lm_channel.PipeChannel Lm_channel.OutChannel false Unix.stdout)
let venv_stderr = venv_add_index_channel 2 (add_channel "<stderr>" Lm_channel.PipeChannel Lm_channel.OutChannel false Unix.stderr)
(*
* A formatting channel.
*)
let venv_add_formatter_channel _venv fmt =
let channels = venv_runtime.venv_channels in
let fd = Lm_channel.create "formatter" Lm_channel.FileChannel Lm_channel.OutChannel true None in
let channel = Lm_int_handle_table.new_handle channels in
let index = Lm_int_handle_table.int_of_handle channel in
let reader _s _off _len =
raise (Unix.Unix_error (Unix.EINVAL, "formatter-channel", ""))
in
let writer s off len =
Format.pp_print_string fmt (Bytes.to_string (Bytes.sub s off len));
len
in
Lm_channel.set_id fd index;
Lm_channel.set_io_functions fd reader writer;
Lm_int_handle_table.add channels channel fd;
channel
(*
* Get the channel.
*)
let venv_channel_data channel =
(* Standard channels are always available *)
if Lm_int_handle_table.int_of_handle channel <= 2 then
Lm_int_handle_table.find_any venv_runtime.venv_channels channel
else
Lm_int_handle_table.find venv_runtime.venv_channels channel
(*
* When a channel is closed, close the buffers too.
*)
let venv_close_channel _venv _pos channel =
try
let fd = venv_channel_data channel in
Lm_channel.close fd;
Lm_int_handle_table.remove venv_runtime.venv_channels channel
with
Not_found ->
(* Fail silently *)
()
(*
* Get the channel.
*)
let venv_find_channel _venv pos channel =
let pos = Pos.string_pos "venv_find_in_channel" pos in
try venv_channel_data channel with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringError "channel is closed"))
(*
* Finding by identifiers.
*)
let venv_find_channel_by_channel _venv pos fd =
let index, _, _, _ = Lm_channel.info fd in
try Lm_int_handle_table.find_value venv_runtime.venv_channels index fd with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringError "channel is closed"))
let venv_find_channel_by_id _venv pos index =
try Lm_int_handle_table.find_any_handle venv_runtime.venv_channels index with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringError "channel is closed"))
(************************************************************************
* Primitive values.
*)
(*
* Allocate a function primitive.
*)
let venv_add_prim_fun _venv name data =
venv_runtime.venv_primitives <- Lm_symbol.SymbolTable.add venv_runtime.venv_primitives name data;
name
let debug_scanner =
Lm_debug.create_debug (**)
{ debug_name = "scanner";
debug_description = "Display debugging information for scanner selection";
debug_value = false
}
let debug_implicit =
Lm_debug.create_debug (**)
{ debug_name = "implicit";
debug_description = "Display debugging information for implicit rule selection";
debug_value = false
}
(*
* Debug file database (.omc files).
*)
let debug_db = Lm_db.debug_db
(*
* Look up the primitive value if we haven't seen it already.
*)
let venv_apply_prim_fun name venv pos loc args =
let f =
try Lm_symbol.SymbolTable.find venv_runtime.venv_primitives name with
Not_found ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, UnboundVar name))
in
f venv pos loc args
(************************************************************************
* Target cache.
*
* To keep this up-to-date, entries are added for explicit targets,
* and the cache is flushed whenever an implicit rule is added.
*)
let lookup_target_dir_in g dir =
try
Omake_node.DirTable.find g.venv_target_dirs dir
with
| Not_found ->
let tdir = g.venv_target_next_dir in
g.venv_target_next_dir <- tdir+1;
let tab =
Omake_node.DirTable.add g.venv_target_dirs dir tdir in
g.venv_target_dirs <- tab;
tdir
let venv_lookup_target_dir venv dir =
venv_synch
venv
(fun globals pglobals_opt ->
match pglobals_opt with
| Some pglobals ->
let tdir = lookup_target_dir_in pglobals dir in
globals.venv_target_next_dir <- pglobals.venv_target_next_dir;
globals.venv_target_dirs <- pglobals.venv_target_dirs;
tdir
| None ->
lookup_target_dir_in globals dir
)
let squeeze_phony =
(* This is OK because whenever we add a phony target we flush the cache *)
function
| Omake_node_sig.NodePhony ->
Omake_node_sig.NodeNormal
| other ->
other
let venv_find_target_is_buildable_exn venv target_dir file node_kind =
let node_kind = squeeze_phony node_kind in
let g = venv_globals venv in
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
TargetMap.find ikey g.venv_target_is_buildable in
Lm_bitset.is_set bset target_dir || (
if not(Lm_bitset.is_set nonbset target_dir) then raise Not_found;
false
)
let venv_find_target_is_buildable_multi venv file node_kind =
let node_kind = squeeze_phony node_kind in
let g = venv_globals venv in
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
try
TargetMap.find ikey g.venv_target_is_buildable
with
| Not_found ->
(Lm_bitset.create(), Lm_bitset.create()) in
(fun target_dir ->
Lm_bitset.is_set bset target_dir || (
if not(Lm_bitset.is_set nonbset target_dir) then raise Not_found;
false
)
)
let venv_find_target_is_buildable_proper_exn venv target_dir file node_kind =
let node_kind = squeeze_phony node_kind in
let g = venv_globals venv in
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
TargetMap.find ikey g.venv_target_is_buildable_proper in
Lm_bitset.is_set bset target_dir || (
if not(Lm_bitset.is_set nonbset target_dir) then raise Not_found;
false
)
let add_target_to m target_dir file node_kind flag =
let node_kind = squeeze_phony node_kind in
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
try TargetMap.find ikey m
with Not_found -> (Lm_bitset.create(), Lm_bitset.create()) in
let (bset',nonbset') =
if flag then
(Lm_bitset.set bset target_dir, nonbset)
else
(bset, Lm_bitset.set nonbset target_dir) in
TargetMap.add ikey (bset',nonbset') m
let venv_add_target_is_buildable venv target_dir file node_kind flag =
let add g =
let tab =
add_target_to
g.venv_target_is_buildable target_dir file node_kind flag in
g.venv_target_is_buildable <- tab in
venv_synch
venv
(fun globals pglobals_opt ->
match pglobals_opt with
| Some pglobals ->
add pglobals;
globals.venv_target_is_buildable <-
pglobals.venv_target_is_buildable
| None ->
add globals
)
let venv_add_target_is_buildable_multi venv file node_kind tdirs_pos tdirs_neg =
let node_kind = squeeze_phony node_kind in
let add g =
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
try TargetMap.find ikey g.venv_target_is_buildable
with Not_found -> (Lm_bitset.create(), Lm_bitset.create()) in
let bset' = Lm_bitset.set_multiple bset tdirs_pos in
let nonbset' = Lm_bitset.set_multiple nonbset tdirs_neg in
let tab = TargetMap.add ikey (bset',nonbset') g.venv_target_is_buildable in
g.venv_target_is_buildable <- tab in
venv_synch
venv
(fun globals pglobals_opt ->
match pglobals_opt with
| Some pglobals ->
add pglobals;
globals.venv_target_is_buildable <-
pglobals.venv_target_is_buildable
| None ->
add globals
)
let venv_add_target_is_buildable_proper venv target_dir file node_kind flag =
let add g =
let tab =
add_target_to
g.venv_target_is_buildable_proper target_dir file node_kind flag in
g.venv_target_is_buildable_proper <- tab in
venv_synch
venv
(fun globals pglobals_opt ->
match pglobals_opt with
| Some pglobals ->
add pglobals;
globals.venv_target_is_buildable_proper <-
pglobals.venv_target_is_buildable_proper
| None ->
add globals
)
let venv_add_explicit_targets venv rules =
venv_incr_version
venv
(fun () ->
let globals = venv.venv_inner.venv_globals in
let { venv_target_is_buildable = cache;
venv_target_is_buildable_proper = cache_proper;
_
} = globals
in
let add cache erule =
let dir = Omake_node.Node.dir erule.rule_target in
let tdir = lookup_target_dir_in globals dir in
let file = Omake_node.Node.tail erule.rule_target in
let nkind = Omake_node.Node.kind erule.rule_target in
add_target_to cache tdir file nkind true in
let cache = List.fold_left add cache rules in
let cache_proper = List.fold_left add cache_proper rules in
globals.venv_target_is_buildable <- cache;
globals.venv_target_is_buildable_proper <- cache_proper
)
let venv_flush_target_cache venv =
venv_incr_version
venv
(fun () ->
let globals = venv.venv_inner.venv_globals in
globals.venv_target_is_buildable <- TargetMap.empty;
globals.venv_target_is_buildable_proper <- TargetMap.empty
)
(*
* Save explicit rules.
*)
let venv_save_explicit_rules venv _loc rules =
let globals = venv.venv_inner.venv_globals in
globals.venv_explicit_new <- List.rev_append rules globals.venv_explicit_new;
venv_add_explicit_targets venv rules
(*
* Add an explicit dependency.
*)
let venv_add_explicit_dep venv loc target source =
let erule =
{ rule_loc = loc;
rule_env = venv;
rule_target = target;
rule_effects = Omake_node.NodeSet.singleton target;
rule_sources = Omake_node.NodeSet.singleton source;
rule_locks = Omake_node.NodeSet.empty;
rule_scanners = Omake_node.NodeSet.empty;
rule_match = None;
rule_multiple = RuleSingle;
rule_commands = []
}
in
ignore (venv_save_explicit_rules venv loc [erule])
(*
* Phony names.
*)
let venv_add_phony venv loc names =
if names = [] then
venv
else
let inner = venv.venv_inner in
let { venv_dir = dir;
venv_phony = phony;
_
} = inner
in
let globals = venv_globals venv in
let phonies = globals.venv_phonies in
let phony, phonies =
List.fold_left (fun (phony, phonies) name ->
let name =
match name with
Omake_value_type.TargetNode _ ->
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, StringError ".PHONY arguments should be names"))
| TargetString s ->
s
in
let gnode = Omake_node.Node.create_phony_global name in
let dnode = Omake_node.Node.create_phony_dir dir name in
let phony = Omake_node.NodeSet.add phony dnode in
let phonies = Omake_node.PreNodeSet.add phonies (Omake_node.Node.dest gnode) in
let phonies = Omake_node.PreNodeSet.add phonies (Omake_node.Node.dest dnode) in
venv_add_explicit_dep venv loc gnode dnode;
phony, phonies) (phony, phonies) names
in
let inner = { inner with venv_phony = phony } in
let venv = { venv with venv_inner = inner } in
venv_incr_version venv (fun () -> ());
globals.venv_phonies <- phonies;
venv
(************************************************************************
* Static values.
*)
(*
* Static loading.
*)
module type StaticSig =
sig
type in_handle
type out_handle
(*
* Open a file. The Omake_node.Node.t is the name of the _source_ file,
* not the .omc file. We'll figure out where the .omc file
* goes on our own. Raises Not_found if the source file
* can't be found.
* The implementation will make sure all the locking/unlocking is done properly.
*)
val read : t -> Omake_node.Node.t -> (in_handle -> 'a) -> 'a
val rewrite : in_handle -> (out_handle -> 'a) -> 'a
* Fetch the two kinds of entries .
* Fetch the two kinds of entries.
*)
val find_ir : in_handle -> Omake_ir.t
val find_object : in_handle -> Omake_value_type.obj
val get_ir : out_handle -> Omake_ir.t
val get_object : out_handle -> Omake_value_type.obj
* Add the two kinds of entries .
* Add the two kinds of entries.
*)
val add_ir : out_handle -> Omake_ir.t -> unit
val add_object : out_handle -> Omake_value_type.obj -> unit
end
(*
* For static values, we access the db a bit more directly
*)
module type InternalStaticSig =
sig
include StaticSig
val write : t -> Omake_node.Node.t -> (out_handle -> 'a) -> 'a
val find_values : in_handle -> Omake_value_type.obj Lm_symbol.SymbolTable.t
val add_values : out_handle -> Omake_value_type.obj Lm_symbol.SymbolTable.t -> unit
end
module Static : InternalStaticSig =
struct
(*
* A .omc file.
*)
type handle =
{ db_file : Unix.file_descr option;
db_name : Omake_node.Node.t;
db_digest : string;
db_env : t;
db_flush_ir : bool;
db_flush_static : bool
}
type in_handle = handle
type out_handle = handle
(*
* Tags for the various kinds of entries.
*)
let ir_tag = 0, Lm_db.HostIndependent
let object_tag = 1, Lm_db.HostDependent
let values_tag = 2, Lm_db.HostDependent
(************************************************************************
* Operations.
*)
(*
* Open a file. The Omake_node.Node.t is the name of the _source_ file,
* not the .omc file. We'll figure out where the .omc file
* goes on our own.
*)
let create_mode mode venv source =
(* Get the source digest *)
let cache = venv.venv_inner.venv_globals.venv_cache in
let digest =
match Omake_cache.stat cache source with
Some (_,digest) ->
digest
| None ->
raise Not_found
in
* Open the result file . The lock_cache_file function
* will try to use the target directory first , and
* fall back to ~/.omake / cache if that is not writable .
* Open the result file. The lock_cache_file function
* will try to use the target directory first, and
* fall back to ~/.omake/cache if that is not writable.
*)
let source_name = Omake_node.Node.absname source in
let dir = Filename.dirname source_name in
let name = Filename.basename source_name in
let name =
if Filename.check_suffix name ".om" then
Filename.chop_suffix name ".om"
else
name
in
let name = name ^ ".omc" in
let target_fd =
try
let target_name, target_fd = Omake_state.get_cache_file dir name in
if !debug_db then
Lm_printf.eprintf "@[<v 3>Omake_db.create:@ %a --> %s@]@." Omake_node.pp_print_node source target_name;
Unix.set_close_on_exec target_fd;
Omake_state.lock_file target_fd mode;
Some target_fd
with
Unix.Unix_error _
| Failure _ ->
Lm_printf.eprintf "@[<v 3>OMake warning: could not create and/or lock a cache file for@ %s@]@." source_name;
None
in
{ db_file = target_fd;
db_name = source;
db_digest = digest;
db_env = venv;
db_flush_ir = Omake_options.opt_flush_include venv.venv_inner.venv_options;
db_flush_static = Omake_options.opt_flush_static venv.venv_inner.venv_options;
}
(*
* Restart with a write lock.
*)
let rewrite info f =
match info.db_file with
Some fd ->
ignore (Unix.lseek fd 0 Unix.SEEK_SET: int);
Omake_state.lock_file fd Unix.F_ULOCK;
Omake_state.lock_file fd Unix.F_LOCK;
let finish () =
ignore (Unix.lseek fd 0 Unix.SEEK_SET: int);
Omake_state.lock_file fd Unix.F_ULOCK;
Omake_state.lock_file fd Unix.F_RLOCK
in
begin try
let result = f info in
finish ();
result
with exn ->
finish ();
raise exn
end
| None ->
f info
(*
* Close the file.
*)
let close info =
match info with
{ db_file = Some fd; db_name = name ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.close: %a@." Omake_node.pp_print_node name;
Unix.close fd
| { db_file = None ; _} ->
()
let perform mode venv source f =
let info = create_mode mode venv source in
try
let result = f info in
close info;
result
with exn ->
close info;
raise exn
let read venv source f = perform Unix.F_RLOCK venv source f
let write venv source f = perform Unix.F_LOCK venv source f
* Add the three kinds of entries .
* Add the three kinds of entries.
*)
let add_ir info ir =
match info with
{ db_file = Some fd; db_name = name; db_digest = digest; db_env = _venv ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.add_ir: %a@." Omake_node.pp_print_node name;
Lm_db.add fd (Omake_node.Node.absname name) ir_tag Omake_magic.ir_magic digest ir
| { db_file = None ; _} ->
()
let add_object info obj =
match info with
{ db_file = Some fd; db_name = name; db_digest = digest; db_env = _venv ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.add_object: %a@." Omake_node.pp_print_node name;
Lm_db.add fd (Omake_node.Node.absname name) object_tag Omake_magic.obj_magic digest obj
| { db_file = None ; _} ->
()
let add_values info obj =
match info with
{ db_file = Some fd; db_name = name; db_digest = digest; db_env = _venv ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.add_values: %a@." Omake_node.pp_print_node name;
Lm_db.add fd (Omake_node.Node.absname name) values_tag Omake_magic.obj_magic digest obj
| { db_file = None ; _} ->
()
* Fetch the three kinds of entries .
* Fetch the three kinds of entries.
*)
let find_ir = function
{ db_file = Some fd; db_name = name; db_digest = digest; db_flush_ir = false ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.find_ir: finding: %a@." Omake_node.pp_print_node name;
let ir = Lm_db.find fd (Omake_node.Node.absname name) ir_tag Omake_magic.ir_magic digest in
if !debug_db then
Lm_printf.eprintf "Omake_db.find_ir: found: %a@." Omake_node.pp_print_node name;
ir
| { db_file = None ; _}
| { db_flush_ir = true ; _} ->
raise Not_found
let find_object = function
{ db_file = Some fd; db_name = name; db_digest = digest; db_flush_ir = false; db_flush_static = false ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.find_object: finding: %a@." Omake_node.pp_print_node name;
let obj = Lm_db.find fd (Omake_node.Node.absname name) object_tag Omake_magic.obj_magic digest in
if !debug_db then
Lm_printf.eprintf "Omake_db.find_object: found: %a@." Omake_node.pp_print_node name;
obj
| { db_file = None ; _}
| { db_flush_ir = true ;_}
| { db_flush_static = true ; _} ->
raise Not_found
let find_values = function
{ db_file = Some fd; db_name = name; db_digest = digest; db_flush_ir = false; db_flush_static = false ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.find_values: finding: %a@." Omake_node.pp_print_node name;
let obj = Lm_db.find fd (Omake_node.Node.absname name) values_tag Omake_magic.obj_magic digest in
if !debug_db then
Lm_printf.eprintf "Omake_db.find_values: found: %a@." Omake_node.pp_print_node name;
obj
| { db_file = None ; _}
| { db_flush_ir = true ; _}
| { db_flush_static = true ; _} ->
raise Not_found
let get_ir = find_ir
let get_object = find_object
end;;
(*
* Cached object files.
*)
let venv_find_ir_file_exn venv node =
Omake_node.NodeTable.find venv.venv_inner.venv_globals.venv_ir_files node
let venv_add_ir_file venv node obj =
let globals = venv.venv_inner.venv_globals in
globals.venv_ir_files <- Omake_node.NodeTable.add globals.venv_ir_files node obj
let venv_find_object_file_exn venv node =
Omake_node.NodeTable.find venv.venv_inner.venv_globals.venv_object_files node
let venv_add_object_file venv node obj =
let globals = venv.venv_inner.venv_globals in
globals.venv_object_files <- Omake_node.NodeTable.add globals.venv_object_files node obj
(************************************************************************
* Variables.
*)
(*
* Default empty object.
*)
let venv_empty_object = Lm_symbol.SymbolTable.empty
* For variables , try to look them up as 0 - arity functions first .
* For variables, try to look them up as 0-arity functions first.
*)
let venv_find_var_private_exn venv v =
Lm_symbol.SymbolTable.find venv.venv_static v
let venv_find_var_dynamic_exn venv v =
Lm_symbol.SymbolTable.find venv.venv_dynamic v
let venv_find_var_protected_exn venv v =
try Lm_symbol.SymbolTable.find venv.venv_this v with
Not_found ->
try Lm_symbol.SymbolTable.find venv.venv_dynamic v with
Not_found ->
try Lm_symbol.SymbolTable.find venv.venv_static v with
Not_found ->
ValString (Lm_symbol.SymbolTable.find venv.venv_inner.venv_environ v)
let venv_find_var_global_exn venv v =
try Lm_symbol.SymbolTable.find venv.venv_dynamic v with
Not_found ->
try Lm_symbol.SymbolTable.find venv.venv_this v with
Not_found ->
try Lm_symbol.SymbolTable.find venv.venv_static v with
Not_found ->
ValString (Lm_symbol.SymbolTable.find venv.venv_inner.venv_environ v)
let venv_find_var_exn venv v =
match v with
Omake_ir.VarPrivate (_, v) ->
venv_find_var_private_exn venv v
| VarThis (_, v) ->
venv_find_var_protected_exn venv v
| VarVirtual (_, v) ->
venv_find_var_dynamic_exn venv v
| VarGlobal (_, v) ->
venv_find_var_global_exn venv v
let venv_get_var venv pos v =
try venv_find_var_exn venv v with
Not_found ->
let pos = Pos.string_pos "venv_get_var" pos in
raise (Omake_value_type.OmakeException (pos, UnboundVarInfo v))
let venv_find_var venv pos loc v =
try venv_find_var_exn venv v with
Not_found ->
let pos = Pos.string_pos "venv_find_var" (Pos.loc_pos loc pos) in
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, UnboundVarInfo v))
let venv_find_object_or_empty venv v =
try
match venv_find_var_exn venv v with
ValObject obj ->
obj
| _ ->
venv_empty_object
with
Not_found ->
venv_empty_object
let venv_defined venv v =
let { venv_this = this;
venv_static = static;
venv_dynamic = dynamic;
_
} = venv
in
match v with
Omake_ir.VarPrivate (_, v) ->
Lm_symbol.SymbolTable.mem static v
| VarVirtual (_, v) ->
Lm_symbol.SymbolTable.mem dynamic v
| VarThis (_, v)
| VarGlobal (_, v) ->
Lm_symbol.SymbolTable.mem this v || Lm_symbol.SymbolTable.mem dynamic v || Lm_symbol.SymbolTable.mem static v
(*
* Adding to variable environment.
* Add to the current object and the static scope.
*)
let venv_add_var venv v s =
let { venv_this = this;
venv_static = static;
venv_dynamic = dynamic;
_
} = venv
in
match v with
Omake_ir.VarPrivate (_, v) ->
{ venv with venv_static = Lm_symbol.SymbolTable.add static v s }
| VarVirtual (_, v) ->
{ venv with venv_dynamic = Lm_symbol.SymbolTable.add dynamic v s }
| VarThis (_, v) ->
{ venv with venv_this = Lm_symbol.SymbolTable.add this v s;
venv_static = Lm_symbol.SymbolTable.add static v s
}
| VarGlobal (_, v) ->
{ venv with venv_dynamic = Lm_symbol.SymbolTable.add dynamic v s;
venv_static = Lm_symbol.SymbolTable.add static v s
}
(*
* Add the arguments given an environment.
*)
let rec venv_add_keyword_args pos venv keywords kargs =
match keywords, kargs with
(v1, v_info, opt_arg) :: keywords_tl, (v2, arg) :: kargs_tl ->
let i = Lm_symbol.compare v1 v2 in
if i = 0 then
venv_add_keyword_args pos (venv_add_var venv v_info arg) keywords_tl kargs_tl
else if i < 0 then
match opt_arg with
Some arg ->
venv_add_keyword_args pos (venv_add_var venv v_info arg) keywords_tl kargs
| None ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v1)))
else
raise (Omake_value_type.OmakeException (pos, StringVarError ("no such keyword", v2)))
| (v1, _, None) :: _, [] ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v1)))
| (_, v_info, Some arg) :: keywords_tl, [] ->
venv_add_keyword_args pos (venv_add_var venv v_info arg) keywords_tl kargs
| [], [] ->
venv
| [], (v2, _) :: _ ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("no such keyword", v2)))
let venv_add_args venv pos loc static params args keywords kargs =
let venv = { venv with venv_static = static } in
let venv = venv_add_keyword_args pos venv keywords kargs in
let len1 = List.length params in
let len2 = List.length args in
let () =
if len1 <> len2 then
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, ArityMismatch (ArityExact len1, len2)))
in
List.fold_left2 venv_add_var venv params args
(*
* Add the arguments to the given static environment.
*)
let venv_with_args venv pos loc params args keywords kargs =
venv_add_args venv pos loc venv.venv_static params args keywords kargs
* Curried - applications .
*
* XXX : this needs to be checked , and performance improved too .
*
* Here is the idea :
*
* - Given a normal arg
* + add the value to the env
* + if params = [ ] then call the function
* - Given a keyword arg
* + if the keyword is valid here , add it to the env , subtract from keywords
* + if not valid here , add to pending
* Curried-applications.
*
* XXX: this needs to be checked, and performance improved too.
*
* Here is the idea:
*
* - Given a normal arg
* + add the value to the env
* + if params = [] then call the function
* - Given a keyword arg
* + if the keyword is valid here, add it to the env, subtract from keywords
* + if not valid here, add to pending kargs
*)
let rec collect_merge_kargs pos rev_kargs kargs1 kargs2 =
match kargs1, kargs2 with
((v1, _) as karg1) :: kargs1_tl, ((v2, _) as karg2) :: kargs2_tl ->
let i = Lm_symbol.compare v1 v2 in
if i = 0 then
raise (Omake_value_type.OmakeException (pos, StringVarError ("duplicate keyword", v1)))
else if i < 0 then
collect_merge_kargs pos (karg1 :: rev_kargs) kargs1_tl kargs2
else
collect_merge_kargs pos (karg2 :: rev_kargs) kargs1 kargs2_tl
| [], kargs
| kargs, [] ->
List.rev_append rev_kargs kargs
let merge_kargs pos kargs1 kargs2 =
match kargs1, kargs2 with
[], kargs
| kargs, [] ->
kargs
| _ ->
collect_merge_kargs pos [] kargs1 kargs2
let add_partial_args venv args =
List.fold_left (fun venv (v, arg) ->
venv_add_var venv v arg) venv args
let rec apply_curry_args pos venv skipped_kargs params args =
match params, args with
[], _ ->
venv, args, List.rev skipped_kargs
| _, [] ->
raise (Omake_value_type.OmakeException (pos, ArityMismatch (ArityExact (List.length params), 0)))
| v :: params, arg :: args ->
apply_curry_args pos (venv_add_var venv v arg) skipped_kargs params args
let rec venv_add_curry_args pos venv params args keywords skipped_kargs kargs =
match keywords, kargs with
(v1, v_info, opt_arg) :: keywords_tl, ((v2, arg) as karg) :: kargs_tl ->
let i = Lm_symbol.compare v1 v2 in
if i = 0 then
venv_add_curry_args pos (venv_add_var venv v_info arg) params args keywords_tl skipped_kargs kargs_tl
else if i < 0 then
match opt_arg with
Some arg ->
venv_add_curry_args pos (venv_add_var venv v_info arg) params args keywords_tl skipped_kargs kargs
| None ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v1)));
else
venv_add_curry_args pos venv params args keywords (karg :: skipped_kargs) kargs_tl
| (v1, _, None) :: _, [] ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v1)))
| (_, v_info, Some arg) :: keywords_tl, [] ->
venv_add_curry_args pos (venv_add_var venv v_info arg) params args keywords_tl skipped_kargs kargs
| [], karg :: kargs_tl ->
venv_add_curry_args pos venv params args keywords (karg :: skipped_kargs) kargs_tl
| [], [] ->
apply_curry_args pos venv skipped_kargs params args
let venv_add_curry_args venv pos _loc static pargs params args keywords kargs1 kargs2 =
let venv = { venv with venv_static = static } in
let venv = add_partial_args venv pargs in
venv_add_curry_args pos venv params args keywords [] (merge_kargs pos kargs1 kargs2)
(*
* Also provide a form for partial applications.
*)
let rec add_partial_keywords pos venv = function
(v, _, None) :: _ ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v)))
| (_, v_info, Some arg) :: keywords_tl ->
add_partial_keywords pos (venv_add_var venv v_info arg) keywords_tl
| [] ->
venv
let rec apply_partial_args venv pos loc static env skipped_keywords keywords skipped_kargs params args =
match params, args with
[], _ ->
let venv = { venv with venv_static = static } in
let venv = add_partial_args venv env in
let venv = add_partial_keywords pos venv skipped_keywords in
let venv = add_partial_keywords pos venv keywords in
FullApply (venv, args, List.rev skipped_kargs)
| _, [] ->
PartialApply (static, env, List.rev_append skipped_keywords keywords, params, List.rev skipped_kargs)
| v :: params, arg :: args ->
apply_partial_args venv pos loc static ((v, arg) :: env) skipped_keywords keywords skipped_kargs params args
let rec venv_add_partial_args venv pos loc static env params args skipped_keywords keywords skipped_kargs kargs =
match keywords, kargs with
((v1, v_info, _) as key) :: keywords_tl, ((v2, arg) as karg) :: kargs_tl ->
let i = Lm_symbol.compare v1 v2 in
if i = 0 then
venv_add_partial_args venv pos loc static ((v_info, arg) :: env) params args skipped_keywords keywords_tl skipped_kargs kargs_tl
else if i < 0 then
venv_add_partial_args venv pos loc static env params args (key :: skipped_keywords) keywords_tl skipped_kargs kargs
else
venv_add_partial_args venv pos loc static env params args skipped_keywords keywords (karg :: skipped_kargs) kargs_tl
| key :: keywords_tl, [] ->
venv_add_partial_args venv pos loc static env params args (key :: skipped_keywords) keywords_tl skipped_kargs kargs
| [], karg :: kargs_tl ->
venv_add_partial_args venv pos loc static env params args skipped_keywords keywords (karg :: skipped_kargs) kargs_tl
| [], [] ->
apply_partial_args venv pos loc static env skipped_keywords keywords skipped_kargs params args
let venv_add_partial_args venv pos loc static pargs params args keywords kargs1 kargs2 =
venv_add_partial_args venv pos loc static pargs params args [] keywords [] (merge_kargs pos kargs1 kargs2)
let venv_with_partial_args venv env args =
let venv = { venv with venv_static = env } in
add_partial_args venv args
(*
* The system environment.
*)
let venv_environment venv =
venv.venv_inner.venv_environ
let venv_getenv venv v =
Lm_symbol.SymbolTable.find venv.venv_inner.venv_environ v
let venv_setenv venv v x =
{ venv with venv_inner = { venv.venv_inner with venv_environ = Lm_symbol.SymbolTable.add venv.venv_inner.venv_environ v x } }
let venv_unsetenv venv v =
{ venv with venv_inner = { venv.venv_inner with venv_environ = Lm_symbol.SymbolTable.remove venv.venv_inner.venv_environ v } }
let venv_defined_env venv v =
Lm_symbol.SymbolTable.mem venv.venv_inner.venv_environ v
let venv_options (venv : t) : Omake_options.t =
venv.venv_inner.venv_options
let venv_with_options venv (options : Omake_options.t) : t =
{ venv with venv_inner = { venv.venv_inner with venv_options = options } }
let venv_set_options_aux venv loc pos argv =
let argv = Array.of_list argv in
let add_unknown _options s =
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringStringError ("unknown option", s)))
in
let options_spec =
Lm_arg.StrictOptions, (**)
["Make options", Omake_options.options_spec;
"Output options", Omake_options.output_spec]
in
let options =
try Lm_arg.fold_argv argv options_spec venv.venv_inner.venv_options add_unknown
"Generic system builder" with
Lm_arg.BogusArg s ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringError s))
in
venv_with_options venv options
let venv_set_options venv loc pos argv =
venv_set_options_aux venv loc pos ("omake" :: argv)
(************************************************************************
* Manipulating static objects.
*)
(*
* Static values. Load the values from the file
* if necessary. Raises Not_found if the object has not already
* been loaded.
*)
let venv_find_static_object venv node v =
let globals = venv.venv_inner.venv_globals in
let static = globals.venv_static_values in
let table =
try Omake_node.NodeTable.find static node with
Not_found ->
(* Load it from the file *)
let table = Static.read venv node Static.find_values in
globals.venv_static_values <- Omake_node.NodeTable.add static node table;
table
in
Lm_symbol.SymbolTable.find table v
(*
* Define a static var.
* Save the object on the modified list so it will get
* written back to the file.
*)
let venv_add_static_object venv node key obj =
let globals = venv.venv_inner.venv_globals in
let { venv_static_values = static;
venv_modified_values = modified;
_
} = globals
in
let table =
try Omake_node.NodeTable.find static node with
Not_found ->
Lm_symbol.SymbolTable.empty
in
let table = Lm_symbol.SymbolTable.add table key obj in
globals.venv_static_values <- Omake_node.NodeTable.add static node table;
globals.venv_modified_values <- Omake_node.NodeTable.add modified node table
(*
* Inline the static variables into the current environment.
*)
let venv_include_static_object venv obj =
let { venv_dynamic = dynamic ; _} = venv in
let dynamic = Lm_symbol.SymbolTable.fold Lm_symbol.SymbolTable.add dynamic obj in
{ venv with venv_dynamic = dynamic }
(*
* Save the modified values.
*)
let venv_save_static_values venv =
let globals = venv.venv_inner.venv_globals in
Omake_node.NodeTable.iter (fun node table ->
try Static.write venv node (fun fd -> Static.add_values fd table)
with Not_found ->
()) globals.venv_modified_values;
globals.venv_modified_values <- Omake_node.NodeTable.empty
(************************************************************************
* Methods and objects.
*)
(*
* Create a path when fetching fields, so that we
* can hoist the exports from a method call.
*)
(* let raise_field_error mode pos loc v = *)
let print_error buf =
Format.fprintf buf " @[<v 3 > Accessing % s field : % a@ The variable was defined at the following location@ % a@ ] " ( \**\ )
(* mode *)
Lm_symbol.pp_print_symbol v
(* in *)
raise ( Omake_value_type . OmakeException ( pos , LazyError print_error ) )
(* let rec squash_path_info path info = *)
(* match path with *)
(* |Omake_value_type.PathVar _ -> *)
Omake_value_type . PathVar info
(* | PathField (path, _, _) -> *)
(* squash_path_info path info *)
(*
* When finding a value, also construct the path to
* the value.
*)
let venv_find_field_path_exn _venv path obj _pos v =
Omake_value_type.PathField (path, obj, v), Lm_symbol.SymbolTable.find obj v
let venv_find_field_path venv path obj pos v =
try venv_find_field_path_exn venv path obj pos v with
Not_found ->
let pos = Pos.string_pos "venv_find_field_path" pos in
raise (Omake_value_type.OmakeException (pos, UnboundFieldVar (obj, v)))
(*
* Simple finding.
*)
let venv_find_field_exn _venv obj _pos v =
Lm_symbol.SymbolTable.find obj v
let venv_find_field venv obj pos v =
try venv_find_field_exn venv obj pos v with
Not_found ->
let pos = Pos.string_pos "venv_find_field" pos in
raise (Omake_value_type.OmakeException (pos, UnboundFieldVar (obj, v)))
(*
* Super fields come from the class.
*)
let venv_find_super_field venv pos loc v1 v2 =
let table = Omake_value_util.venv_get_class venv.venv_this in
try
let obj = Lm_symbol.SymbolTable.find table v1 in
venv_find_field_exn venv obj pos v2
with
Not_found ->
let pos = Pos.string_pos "venv_find_super_field" (Pos.loc_pos loc pos) in
raise (Omake_value_type.OmakeException (pos, StringVarError ("unbound super var", v2)))
(*
* Add a field.
*)
let venv_add_field venv obj _pos v e =
venv, Lm_symbol.SymbolTable.add obj v e
(*
* Hacked versions bypass translation.
*)
let venv_add_field_internal = Lm_symbol.SymbolTable.add
let venv_defined_field_internal = Lm_symbol.SymbolTable.mem
let venv_find_field_internal_exn = Lm_symbol.SymbolTable.find
let venv_find_field_internal obj pos v =
try Lm_symbol.SymbolTable.find obj v with
Not_found ->
let pos = Pos.string_pos "venv_find_field_internal" pos in
raise (Omake_value_type.OmakeException (pos, UnboundFieldVar (obj, v)))
let venv_object_fold_internal = Lm_symbol.SymbolTable.fold
let venv_object_length = Lm_symbol.SymbolTable.cardinal
(*
* Test whether a field is defined.
*)
let venv_defined_field_exn _venv obj v =
Lm_symbol.SymbolTable.mem obj v
let venv_defined_field venv obj v =
try venv_defined_field_exn venv obj v with
Not_found ->
false
(*
* Add a class to an object.
*)
let venv_add_class obj v =
let table = Omake_value_util.venv_get_class obj in
let table = Lm_symbol.SymbolTable.add table v obj in
Lm_symbol.SymbolTable.add obj Omake_value_util.class_sym (ValClass table)
(*
* Execute a method in an object.
* If we are currently in the outermost object,
* push the dynamic scope.
*)
let venv_with_object venv this =
{ venv with venv_this = this }
(*
* Define a new object.
*)
let venv_define_object venv =
venv_with_object venv Lm_symbol.SymbolTable.empty
(*
* Add the class to the current object.
*)
let venv_instanceof obj s =
Lm_symbol.SymbolTable.mem (Omake_value_util.venv_get_class obj) s
(*
* Include the fields in the given class.
* Be careful to merge classnames.
*)
let venv_include_object_aux obj1 obj2 =
let table1 = Omake_value_util.venv_get_class obj1 in
let table2 = Omake_value_util.venv_get_class obj2 in
let table = Lm_symbol.SymbolTable.fold Lm_symbol.SymbolTable.add table1 table2 in
let obj1 = Lm_symbol.SymbolTable.fold Lm_symbol.SymbolTable.add obj1 obj2 in
Lm_symbol.SymbolTable.add obj1 Omake_value_util.class_sym (ValClass table)
let venv_include_object venv obj2 =
let obj = venv_include_object_aux venv.venv_this obj2 in
{ venv with venv_this = obj }
let venv_flatten_object venv obj2 =
let obj = venv_include_object_aux venv.venv_dynamic obj2 in
{ venv with venv_dynamic = obj }
(*
* Function scoping.
*)
let venv_empty_env =
Lm_symbol.SymbolTable.empty
let venv_get_env venv =
venv.venv_static
let venv_with_env venv env =
{ venv with venv_static = env }
(*
* The current object is always in the venv_this field.
*)
let venv_this venv =
venv.venv_this
let venv_current_object venv classnames =
let obj = venv.venv_this in
if classnames = [] then
obj
else
let table = Omake_value_util.venv_get_class obj in
let table = List.fold_left (fun table v -> Lm_symbol.SymbolTable.add table v obj) table classnames in
Lm_symbol.SymbolTable.add obj Omake_value_util.class_sym (ValClass table)
* ZZZ : this will go away in 0.9.9 .
* ZZZ: this will go away in 0.9.9.
*)
let rec filter_objects venv pos v objl = function
obj :: rev_objl ->
let objl =
try venv_find_field_exn venv obj pos v :: objl with
Not_found ->
objl
in
filter_objects venv pos v objl rev_objl
| [] ->
objl
let venv_current_objects venv pos v =
let { venv_this = this;
venv_dynamic = dynamic;
venv_static = static;
_
} = venv
in
let v, objl =
match v with
Omake_ir.VarPrivate (_, v) ->
v, [static]
| VarThis (_, v) ->
v, [static; dynamic; this]
| VarVirtual (_, v) ->
v, [dynamic]
| VarGlobal (_, v) ->
v, [static; this; dynamic]
in
filter_objects venv pos v [] objl
(************************************************************************
* Environment.
*)
(*
* Convert a filename to a node.
*)
let venv_intern venv phony_flag name =
let { venv_mount = mount;
venv_dir = dir;
_
} = venv.venv_inner
in
let globals = venv_globals venv in
let { venv_phonies = phonies;
venv_mount_info = mount_info;
_
} = globals
in
Omake_node.create_node_or_phony phonies mount_info mount phony_flag dir name
let venv_intern_target venv phony_flag target =
match target with
Omake_value_type.TargetNode node -> node
| TargetString name -> venv_intern venv phony_flag name
let venv_intern_cd_1 venv phony_flag dir pname =
let mount = venv.venv_inner.venv_mount in
let globals = venv_globals venv in
let { venv_phonies = phonies;
venv_mount_info = mount_info;
_
} = globals
in
Omake_node.create_node_or_phony_1 phonies mount_info mount phony_flag dir pname
let venv_intern_cd venv phony_flag dir name =
venv_intern_cd_1 venv phony_flag dir (Omake_node.parse_phony_name name)
let venv_intern_cd_node_kind venv phony_flag dir pname =
let globals = venv_globals venv in
let { venv_phonies = phonies;
_
} = globals
in
if Omake_node.node_will_be_phony phonies phony_flag dir pname then
Omake_node_sig.NodePhony
else
Omake_node_sig.NodeNormal
let venv_intern_rule_target venv multiple name =
let node =
match name with
Omake_value_type.TargetNode node ->
node
| TargetString name ->
venv_intern venv PhonyOK name
in
match multiple with
| Omake_value_type.RuleScannerSingle
| RuleScannerMultiple ->
Omake_node.Node.create_escape NodeScanner node
| RuleSingle
| RuleMultiple ->
node
let venv_intern_dir venv name =
Omake_node.Dir.chdir venv.venv_inner.venv_dir name
let venv_intern_list venv names =
( venv_intern venv ) names
let node_set_of_list nodes =
List.fold_left Omake_node.NodeSet.add Omake_node.NodeSet.empty nodes
let node_set_add_names venv phony_flag nodes names =
(* List.fold_left (fun nodes name -> *)
Omake_node.NodeSet.add nodes ( venv_intern venv phony_flag name ) ) nodes names
(* let node_set_of_names venv phony_flag names = *)
node_set_add_names venv phony_flag Omake_node.NodeSet.empty names
(*
* Convert back to a string.
*)
let venv_dirname venv dir =
if Omake_options.opt_absname venv.venv_inner.venv_options then
Omake_node.Dir.absname dir
else
Omake_node.Dir.name venv.venv_inner.venv_dir dir
let venv_nodename venv dir =
if Omake_options.opt_absname venv.venv_inner.venv_options then
Omake_node.Node.absname dir
else
Omake_node.Node.name venv.venv_inner.venv_dir dir
(*
* Add a mount point.
*)
let venv_mount venv options src dst =
let inner = venv.venv_inner in
let mount = Omake_node.Mount.mount inner.venv_mount options src dst in
let inner = { inner with venv_mount = mount } in
{ venv with venv_inner = inner }
(*
* A target is wild if it is a string with a wild char.
*)
let target_is_wild target =
match target with
Omake_value_type.TargetNode _ ->
false
| TargetString s ->
Lm_wild.is_wild s
let string_of_target venv target =
match target with
|Omake_value_type.TargetString s ->
s
| Omake_value_type.TargetNode node ->
venv_nodename venv node
(*
* Compile a wild pattern.
* It is an error if it isn't wild.
*)
let compile_wild_pattern _venv pos loc target =
match target with
| Omake_value_type.TargetString s when Lm_wild.is_wild s ->
if Lm_string_util.contains_any s Lm_filename_util.separators then
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringStringError ("filename pattern is a path", s)));
Lm_wild.compile_in s
| _ ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringTargetError ("patterns must be wildcards", target)))
(*
* Compile a source.
*)
let compile_source_core venv s =
match s with
| Omake_value_type.TargetNode node ->
Omake_value_type.SourceNode node
| TargetString s ->
if Lm_wild.is_wild s then
SourceWild (Lm_wild.compile_out s)
else
SourceNode (venv_intern venv PhonyOK s)
let compile_source venv (kind, s) =
kind, compile_source_core venv s
let compile_implicit3_target pos loc = function
|Omake_value_type.TargetString s ->
if Lm_string_util.contains_any s Lm_filename_util.separators then
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringStringError ("target of a 3-place rule is a path", s)));
s
| target ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringTargetError ("target of a 3-place rule is not a simple string", target)))
(*
* Perform a wild substitution on a source.
*)
let subst_source_core venv dir subst source =
match source with
| Omake_value_type.SourceWild wild ->
let s = Lm_wild.subst subst wild in
venv_intern_cd venv PhonyOK dir s
| SourceNode node ->
node
let subst_source venv dir subst (kind, source) =
Omake_node.Node.create_escape kind (subst_source_core venv dir subst source)
(*
* No wildcard matching.
*)
let intern_source venv (kind, source) =
let source =
match source with
| Omake_value_type.TargetNode node ->
node
| TargetString name ->
venv_intern venv PhonyOK name
in
Omake_node.Node.create_escape kind source
(************************************************************************
* Rules
*)
(*
* Symbols for directories.
*)
(* let wild_sym = Lm_symbol.add Lm_wild.wild_string *)
let explicit_target_sym = Lm_symbol.add "<EXPLICIT_TARGET>"
(*
* Don't save explicit rules.
*)
let venv_explicit_target venv target =
venv_add_var venv Omake_var.explicit_target_var (ValNode target)
(*
* Save explicit rules.
*)
let venv_save_explicit_rules venv loc erules =
(* Filter out the rules with a different target *)
let erules =
try
match venv_find_var_dynamic_exn venv explicit_target_sym with
ValNode target ->
let rules =
List.fold_left (fun rules erule ->
if Omake_node.Node.equal erule.rule_target target then
erule :: rules
else
rules) [] erules
in
let rules = List.rev rules in
let () =
if rules = [] then
let print_error buf =
Format.fprintf buf "@[<b 3>Computed rule for `%a' produced no useful rules:" Omake_node.pp_print_node target;
List.iter (fun erule ->
Format.fprintf buf "@ `%a'" Omake_node.pp_print_node erule.rule_target) erules;
Format.fprintf buf "@]"
in
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, LazyError print_error))
in
rules
| _ ->
erules
with
Not_found ->
erules
in
venv_save_explicit_rules venv loc erules
(*
* Add the wild target.
*)
let venv_add_wild_match venv v =
venv_add_var venv Omake_var.wild_var v
let command_add_wild venv wild command =
match command with
Omake_value_type.CommandSection _ ->
command
| CommandValue(loc, env, s) ->
let env = venv_get_env (venv_add_wild_match (venv_with_env venv env) wild) in
CommandValue(loc, env, s)
(*
* This is the standard way to add results of a pattern match.
*)
let venv_add_match_values venv args =
let venv, _ =
List.fold_left (fun (venv, i) arg ->
let v = Omake_var.create_numeric_var i in
let venv = venv_add_var venv v arg in
venv, succ i) (venv, 1) args
in
venv
let venv_add_match_args venv args =
let venv, _ =
List.fold_left (fun (venv, i) arg ->
let v = Omake_var.create_numeric_var i in
let venv = venv_add_var venv v (ValData arg) in
venv, succ i) (venv, 1) args
in
venv
let venv_add_match venv line args =
let args = List.map (fun s -> Omake_value_type.ValData s) args in
let venv, _ =
List.fold_left (fun (venv, i) arg ->
let v = Omake_var.create_numeric_var i in
let venv = venv_add_var venv v arg in
venv, succ i) (venv, 1) args
in
let venv = venv_add_var venv Omake_var.zero_var (Omake_value_type.ValData line) in
let venv = venv_add_var venv Omake_var.star_var (ValArray args) in
let venv = venv_add_var venv Omake_var.nf_var (ValInt (List.length args)) in
venv
(*
* Create an environment.
*)
let create_environ () =
let env = Unix.environment () in
let len = Array.length env in
let rec collect table i =
if i = len then
table
else
let s = env.(i) in
let j = String.index s '=' in
let name = String.sub s 0 j in
let name =
if Sys.os_type = "Win32" then
String.uppercase_ascii name
else
name
in
let v = Lm_symbol.add name in
let x = String.sub s (j + 1) (String.length s - j - 1) in
let table = Lm_symbol.SymbolTable.add table v x in
collect table (succ i)
in
collect Lm_symbol.SymbolTable.empty 0
let create options _dir exec cache =
let cwd = Omake_node.Dir.cwd () in
let env = create_environ () in
let mount_info =
{ Omake_node_sig.mount_file_exists = Omake_cache.exists cache;
mount_file_reset = (fun node -> ignore (Omake_cache.force_stat cache node));
mount_is_dir = Omake_cache.is_dir cache;
mount_digest = Omake_cache.stat cache;
mount_stat = Omake_cache.stat_unix cache
}
in
let globals =
{ venv_parent = None;
venv_version = 0;
venv_mutex = Lm_thread.Mutex.create "venv_globals";
venv_exec = exec;
venv_cache = cache;
venv_mount_info = mount_info;
venv_environments = Lm_handle_table.create ();
venv_files = Omake_node.NodeSet.empty;
venv_directories = Omake_node.DirTable.empty;
venv_excluded_directories = Omake_node.DirSet.empty;
venv_phonies = Omake_node.PreNodeSet.empty;
venv_explicit_rules = [];
venv_explicit_new = [];
venv_explicit_targets = Omake_node.NodeTable.empty;
venv_ordering_rules = [];
venv_orders = Lm_string_set.StringSet.empty;
venv_memo_rules = Omake_value_util.ValueTable.empty;
venv_pervasives_obj = Lm_symbol.SymbolTable.empty;
venv_pervasives_vars = Lm_symbol.SymbolTable.empty;
venv_ir_files = Omake_node.NodeTable.empty;
venv_object_files = Omake_node.NodeTable.empty;
venv_static_values = Omake_node.NodeTable.empty;
venv_modified_values = Omake_node.NodeTable.empty;
venv_target_dirs = Omake_node.DirTable.empty;
venv_target_next_dir = 0;
venv_target_is_buildable = TargetMap.empty;
venv_target_is_buildable_proper = TargetMap.empty
}
in
let inner =
{ venv_dir = cwd;
venv_environ = env;
venv_phony = Omake_node.NodeSet.empty;
venv_implicit_deps = [];
venv_implicit_rules = [];
venv_globals = globals;
venv_options = options;
venv_mount = Omake_node.Mount.empty;
venv_included_files = Omake_node.NodeSet.empty
}
in
let venv =
{ venv_this = Lm_symbol.SymbolTable.empty;
venv_dynamic = Lm_symbol.SymbolTable.empty;
venv_static = Lm_symbol.SymbolTable.empty;
venv_inner = inner
}
in
let venv = venv_add_phony venv (Lm_location.bogus_loc Omake_state.makeroot_name) [TargetString ".PHONY"] in
let venv = venv_add_var venv Omake_var.cwd_var (ValDir cwd) in
let venv = venv_add_var venv Omake_var.stdlib_var (ValDir Omake_node.Dir.lib) in
let venv = venv_add_var venv Omake_var.stdroot_var (ValNode (venv_intern_cd venv PhonyProhibited Omake_node.Dir.lib "OMakeroot")) in
let venv = venv_add_var venv Omake_var.ostype_var (ValString Sys.os_type) in
let venv = venv_add_wild_match venv (ValData Lm_wild.wild_string) in
let omakepath =
try
let path = Lm_string_util.split Lm_filename_util.pathsep (Lm_symbol.SymbolTable.find env Omake_symbol.omakepath_sym) in
List.map (fun s -> Omake_value_type.ValString s) path
with
Not_found ->
[ValString "."; ValDir Omake_node.Dir.lib]
in
let omakepath = Omake_value_type.ValArray omakepath in
let venv = venv_add_var venv Omake_var.omakepath_var omakepath in
let path =
try
let path = Lm_string_util.split Lm_filename_util.pathsep (Lm_symbol.SymbolTable.find env Omake_symbol.path_sym) in
Omake_value_type.ValArray (List.map (fun s -> Omake_value_type.ValData s) path)
with
Not_found ->
Lm_printf.eprintf "*** omake: PATH environment variable is not set!@.";
ValArray []
in
let venv = venv_add_var venv Omake_var.path_var path in
venv
(*
* Create a fresh environment from the pervasives.
* This is used for compiling objects.
*)
let venv_set_pervasives venv =
let globals = venv.venv_inner.venv_globals in
let obj = venv.venv_dynamic in
let loc = Lm_location.bogus_loc "Pervasives" in
let vars =
Lm_symbol.SymbolTable.fold (fun vars v _ ->
Lm_symbol.SymbolTable.add vars v (Omake_ir.VarVirtual (loc, v))) Lm_symbol.SymbolTable.empty obj
in
globals.venv_pervasives_obj <- venv.venv_dynamic;
globals.venv_pervasives_vars <- vars
let venv_get_pervasives venv node =
let { venv_inner = inner ; _} = venv in
let { venv_environ = env;
venv_options = options;
venv_globals = globals;
_
} = inner
in
let {
venv_pervasives_obj = obj;
_
} = globals
in
let inner =
{ venv_dir = Omake_node.Node.dir node;
venv_environ = env;
venv_phony = Omake_node.NodeSet.empty;
venv_implicit_deps = [];
venv_implicit_rules = [];
venv_globals = globals;
venv_options = options;
venv_mount = Omake_node.Mount.empty;
venv_included_files = Omake_node.NodeSet.empty
}
in
{ venv_this = Lm_symbol.SymbolTable.empty;
venv_dynamic = obj;
venv_static = Lm_symbol.SymbolTable.empty;
venv_inner = inner
}
(*
* Fork the environment, so that changes really have no effect on the old one.
* This is primarly used when a thread wants a private copy of the environment.
*)
let venv_fork venv =
let inner = venv.venv_inner in
let globals = inner.venv_globals in
let globals = { globals with
venv_parent = Some(globals, globals.venv_version);
venv_mutex = Lm_thread.Mutex.create "venv_globals";
venv_version = 0;
} in
let inner = { inner with venv_globals = globals } in
{ venv with venv_inner = inner }
let copy_var src_dynamic dst_dynamic v =
try
Lm_symbol.SymbolTable.add dst_dynamic v (Lm_symbol.SymbolTable.find src_dynamic v)
with
Not_found ->
Lm_symbol.SymbolTable.remove dst_dynamic v
let copy_vars dst_dynamic src_dynamic vars =
List.fold_left (copy_var src_dynamic) dst_dynamic vars
let copy_var_list =
Omake_symbol.[stdin_sym; stdout_sym; stderr_sym]
let venv_unfork venv_dst venv_src =
let { venv_dynamic = dst_dynamic;
venv_inner = dst_inner;
_
} = venv_dst
in
let { venv_dynamic = src_dynamic;
venv_inner = src_inner;
_
} = venv_src
in
let inner = { dst_inner with venv_globals = src_inner.venv_globals } in
let dst_dynamic = copy_vars dst_dynamic src_dynamic copy_var_list in
{ venv_dst with venv_dynamic = dst_dynamic;
venv_inner = inner
}
(*
* Get the scope of all variables.
*)
let venv_include_scope venv mode =
match mode with
IncludePervasives ->
venv.venv_inner.venv_globals.venv_pervasives_vars
| IncludeAll ->
let loc = Lm_location.bogus_loc "venv_include_scope" in
let { venv_this = this;
venv_dynamic = dynamic;
_
} = venv
in
let vars = Lm_symbol.SymbolTable.mapi (fun v _ -> Omake_ir.VarThis (loc, v)) this in
let vars = Lm_symbol.SymbolTable.fold
(fun vars v _ -> Lm_symbol.SymbolTable.add vars v (Omake_ir.VarGlobal (loc, v))) vars dynamic in
vars
(*
* Add an included file.
*)
let venv_is_included_file venv node =
Omake_node.NodeSet.mem venv.venv_inner.venv_included_files node
let venv_add_included_file venv node =
let inner = venv.venv_inner in
let inner = { inner with venv_included_files = Omake_node.NodeSet.add inner.venv_included_files node } in
{ venv with venv_inner = inner }
(*
* Global state.
*)
let venv_exec venv =
venv.venv_inner.venv_globals.venv_exec
let venv_cache venv =
venv.venv_inner.venv_globals.venv_cache
let venv_add_cache venv cache =
let inner = venv.venv_inner in
let globals = inner.venv_globals in
let globals = { globals with venv_cache = cache } in
let inner = { inner with venv_globals = globals } in
{ venv with venv_inner = inner }
* Change directories . Update the CWD var , and all a default
* rule for all the phonies .
* Change directories. Update the CWD var, and all a default
* rule for all the phonies.
*)
let venv_chdir_tmp venv dir =
{ venv with venv_inner = { venv.venv_inner with venv_dir = dir } }
let venv_chdir_dir venv loc dir =
let inner = venv.venv_inner in
let { venv_dir = cwd;
venv_phony = phony;
_
} = inner
in
if Omake_node.Dir.equal dir cwd then
venv
else
let venv = venv_add_var venv Omake_var.cwd_var (ValDir dir) in
let venv = venv_chdir_tmp venv dir in
let globals = venv_globals venv in
let phonies = globals.venv_phonies in
let phony, phonies =
Omake_node.NodeSet.fold (fun (phony, phonies) node ->
let node' = Omake_node.Node.create_phony_chdir node dir in
let phony = Omake_node.NodeSet.add phony node' in
let phonies = Omake_node.PreNodeSet.add phonies (Omake_node.Node.dest node') in
venv_add_explicit_dep venv loc node node';
phony, phonies) (Omake_node.NodeSet.empty, phonies) phony
in
let inner =
{ inner with venv_dir = dir;
venv_phony = phony
}
in
let venv = { venv with venv_inner = inner } in
globals.venv_phonies <- phonies;
venv
let venv_chdir venv loc dir =
let dir = Omake_node.Dir.chdir venv.venv_inner.venv_dir dir in
venv_chdir_dir venv loc dir
(*
* The public version does not mess whith the phonies.
*)
let venv_chdir_tmp venv dir =
let cwd = venv.venv_inner.venv_dir in
if Omake_node.Dir.equal dir cwd then
venv
else
let venv = venv_add_var venv Omake_var.cwd_var (ValDir dir) in
venv_chdir_tmp venv dir
(*
* Get the dir.
*)
let venv_dir venv =
venv.venv_inner.venv_dir
* When an OMakefile in a dir is read , save the venv
* to be used for targets that do not have nay explicit target rule .
* When an OMakefile in a dir is read, save the venv
* to be used for targets that do not have nay explicit target rule.
*)
let venv_add_dir venv =
let globals = venv.venv_inner.venv_globals in
globals.venv_directories <- Omake_node.DirTable.add globals.venv_directories venv.venv_inner.venv_dir venv
let venv_directories venv =
let globals = venv.venv_inner.venv_globals in
Omake_node.DirSet.fold Omake_node.DirTable.remove globals.venv_directories globals.venv_excluded_directories
let venv_add_explicit_dir venv dir =
let globals = venv.venv_inner.venv_globals in
globals.venv_directories <- Omake_node.DirTable.add globals.venv_directories dir venv;
globals.venv_excluded_directories <- Omake_node.DirSet.remove globals.venv_excluded_directories dir
let venv_remove_explicit_dir venv dir =
let globals = venv.venv_inner.venv_globals in
globals.venv_excluded_directories <- Omake_node.DirSet.add globals.venv_excluded_directories dir
let venv_find_target_dir_opt venv target =
let target_dir = Omake_node.Node.dir target in
if Omake_node.Dir.equal venv.venv_inner.venv_dir target_dir then
Some venv
else
try Some (Omake_node.DirTable.find venv.venv_inner.venv_globals.venv_directories target_dir) with
Not_found ->
None
(*
* When a file is read, remember it as a configuration file.
*)
let venv_add_file venv node =
let globals = venv.venv_inner.venv_globals in
globals.venv_files <- Omake_node.NodeSet.add globals.venv_files node;
venv
(*
* Get all the configuration files.
*)
let venv_files venv =
venv.venv_inner.venv_globals.venv_files
(*
* Add a null rule.
*)
let venv_add_implicit_deps venv pos loc multiple patterns locks sources scanners values =
let pos = Pos.string_pos "venv_add_implicit_deps" pos in
let patterns = List.map (compile_wild_pattern venv pos loc) patterns in
let locks = List.map (compile_source venv) locks in
let sources = List.map (compile_source venv) sources in
let scanners = List.map (compile_source venv) scanners in
let nrule =
{ inrule_loc = loc;
inrule_multiple = multiple;
inrule_patterns = patterns;
inrule_locks = locks;
inrule_sources = sources;
inrule_scanners = scanners;
inrule_values = values
}
in
let venv = { venv with venv_inner = { venv.venv_inner with venv_implicit_deps = nrule :: venv.venv_inner.venv_implicit_deps } } in
venv_flush_target_cache venv;
venv, []
(*
* Add an implicit rule.
*)
let venv_add_implicit_rule venv loc multiple targets patterns locks sources scanners values body =
let irule =
{ irule_loc = loc;
irule_multiple = multiple;
irule_targets = targets;
irule_patterns = patterns;
irule_locks = locks;
irule_sources = sources;
irule_scanners = scanners;
irule_values = values;
irule_body = body
}
in
let venv = { venv with venv_inner = { venv.venv_inner with venv_implicit_rules = irule :: venv.venv_inner.venv_implicit_rules } } in
venv_flush_target_cache venv;
venv, []
* Add an 2 - place implicit rule .
* Add an 2-place implicit rule.
*)
let venv_add_implicit2_rule venv pos loc multiple patterns locks sources scanners values body =
let pos = Pos.string_pos "venv_add_implicit2_rule" pos in
let patterns = List.map (compile_wild_pattern venv pos loc) patterns in
let locks = List.map (compile_source venv) locks in
let sources = List.map (compile_source venv) sources in
let scanners = List.map (compile_source venv) scanners in
if Lm_debug.debug debug_implicit then
Lm_printf.eprintf "@[<hv 3>venv_add_implicit2_rule:@ @[<b 3>patterns =%a@]@ @[<b 3>sources =%a@]@]@." (**)
Omake_value_print.pp_print_wild_list patterns
Omake_value_print.pp_print_source_list sources;
venv_add_implicit_rule venv loc multiple None patterns locks sources scanners values body
(*
* Add an explicit rule.
*)
let venv_add_explicit_rules venv pos loc multiple targets locks sources scanners values body =
let _pos = Pos.string_pos "venv_add_explicit_rules" pos in
let target_args = List.map (venv_intern_rule_target venv multiple) targets in
let lock_args = List.map (intern_source venv) locks in
let source_args = List.map (intern_source venv) sources in
let scanner_args = List.map (intern_source venv) scanners in
let effects = node_set_of_list target_args in
let locks = node_set_of_list lock_args in
let sources = node_set_of_list source_args in
let scanners = node_set_of_list scanner_args in
let commands = make_command_info venv source_args values body in
let add_target target =
{ rule_loc = loc;
rule_env = venv;
rule_target = target;
rule_effects = effects;
rule_locks = locks;
rule_sources = sources;
rule_scanners = scanners;
rule_match = None;
rule_multiple = multiple;
rule_commands = commands
}
in
let rules = List.map add_target target_args in
let names = List.map (fun erule -> erule.rule_target) rules in
venv_save_explicit_rules venv loc rules;
venv, names
* Add a 3 - place rule ( automatically implicit ) .
* Add a 3-place rule (automatically implicit).
*)
let venv_add_implicit3_rule venv pos loc multiple targets locks patterns sources scanners values body =
let pos = Pos.string_pos "venv_add_implicit3_rule" pos in
let patterns = List.map (compile_wild_pattern venv pos loc) patterns in
let locks = List.map (compile_source venv) locks in
let sources = List.map (compile_source venv) sources in
let scanners = List.map (compile_source venv) scanners in
let targets = List.map (compile_implicit3_target pos loc) targets in
let rec check_target target = function
pattern :: patterns ->
begin match Lm_wild.wild_match pattern target with
Some _ -> ()
| None -> check_target target patterns
end
| [] ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringStringError ("bad match", target)))
in
let () = List.iter (fun target -> check_target target patterns) targets in
if Lm_debug.debug debug_implicit then
Lm_printf.eprintf "@[<hv 3>venv_add_implicit3_rule:@ @[<b 3>targets =%a@] @[<b 3>patterns =%a@]@ @[<b 3>sources =%a@]@]@." (**)
Omake_node.pp_print_string_list targets
Omake_value_print.pp_print_wild_list patterns
Omake_value_print.pp_print_source_list sources;
venv_add_implicit_rule venv loc multiple (Some (Lm_string_set.StringSet.of_list targets)) patterns locks sources scanners values body
let rec is_implicit loc = function
[] -> false
| [target] -> target_is_wild target
| target :: targets ->
let imp1 = target_is_wild target in
let imp2 = is_implicit loc targets in
if imp1 <> imp2 then
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, (**)
StringError "Rule contains an illegal mixture of implicit (pattern) targets and explicit ones"))
else
imp1
* Figure out what to do based on all the parts .
* A 2 - place rule is implicit if the targets do not contain a % . 3 - place rules are always implicit .
* Figure out what to do based on all the parts.
* A 2-place rule is implicit if the targets do not contain a %. 3-place rules are always implicit.
*)
let venv_add_rule venv pos loc multiple targets patterns locks sources scanners values commands =
let pos = Pos.string_pos "venv_add_rule" pos in
try match targets, patterns, commands with
[], [], _ ->
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, StringError "invalid null rule"))
| _, [], [] ->
if is_implicit loc targets then
venv_add_implicit_deps venv pos loc multiple targets locks sources scanners values
else
venv_add_explicit_rules venv pos loc multiple targets locks sources scanners values commands
| _, [], _ ->
if is_implicit loc targets then
venv_add_implicit2_rule venv pos loc multiple targets locks sources scanners values commands
else
venv_add_explicit_rules venv pos loc multiple targets locks sources scanners values commands
| _ ->
if not (is_implicit loc patterns) then
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, StringError "3-place rule does not contain patterns"))
else
venv_add_implicit3_rule venv pos loc multiple targets locks patterns sources scanners values commands
with
Failure err ->
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, StringError err))
(*
* Flush the explicit list.
*)
let venv_explicit_flush venv =
let globals = venv.venv_inner.venv_globals in
let { venv_explicit_rules = erules;
venv_explicit_targets = targets;
venv_explicit_new = enew;
_
} = globals
in
if enew <> [] then
let targets, erules =
List.fold_left (fun (targets, erules) erule ->
let erules = erule :: erules in
let targets = Omake_node.NodeTable.add targets erule.rule_target erule in
targets, erules) (targets, erules) (List.rev enew)
in
globals.venv_explicit_new <- [];
globals.venv_explicit_rules <- erules;
globals.venv_explicit_targets <- targets
(*
* Check if an explicit rule exists.
*)
let venv_explicit_find venv pos target =
venv_explicit_flush venv;
try Omake_node.NodeTable.find venv.venv_inner.venv_globals.venv_explicit_targets target with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringNodeError ("explicit target not found", target)))
let venv_explicit_exists venv target =
venv_explicit_flush venv;
Omake_node.NodeTable.mem venv.venv_inner.venv_globals.venv_explicit_targets target
let multiple_add_error errors target loc1 loc2 =
let table = !errors in
let table =
if Omake_node.NodeMTable.mem table target then
table
else
Omake_node.NodeMTable.add table target loc1
in
errors := Omake_node.NodeMTable.add table target loc2
let multiple_print_error errors buf =
Format.fprintf buf "@[<v 3>Multiple ways to build the following targets";
Omake_node.NodeMTable.iter_all (fun target locs ->
let locs = List.sort Lm_location.compare locs in
Format.fprintf buf "@ @[<v 3>%a:" Omake_node.pp_print_node target;
List.iter (fun loc -> Format.fprintf buf "@ %a" Lm_location.pp_print_location loc) locs;
Format.fprintf buf "@]") errors;
Format.fprintf buf "@]"
let raise_multiple_error errors =
let _, loc = Omake_node.NodeMTable.choose errors in
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, LazyError (multiple_print_error errors)))
(*
* Get the explicit rules. Build a table indexed by target.
*)
let venv_explicit_rules venv =
let errors = ref Omake_node.NodeMTable.empty in
let add_target table target erule =
Omake_node.NodeTable.filter_add table target (fun entry ->
match entry with
Some erule' ->
(*
* For .PHONY targets, multiple is ignored.
* Otherwise, multiple must be the same for both targets.
*)
let multiple = is_multiple_rule erule.rule_multiple in
let multiple' = is_multiple_rule erule'.rule_multiple in
if Omake_node.Node.is_phony target
|| (multiple && multiple')
|| ((not multiple && not multiple')
&& (commands_are_trivial erule.rule_commands || commands_are_trivial erule'.rule_commands))
then
{ erule with rule_commands = erule'.rule_commands @ erule.rule_commands }
else begin
multiple_add_error errors target erule'.rule_loc erule.rule_loc;
erule'
end
| None ->
erule)
in
if not (Omake_node.NodeMTable.is_empty !errors) then
raise_multiple_error !errors
else
let add_deps table target locks sources scanners =
Omake_node.NodeTable.filter_add table target (function
Some (lock_deps, source_deps, scanner_deps) ->
Omake_node.NodeSet.union lock_deps locks, Omake_node.NodeSet.union source_deps sources, Omake_node.NodeSet.union scanner_deps scanners
| None ->
locks, sources, scanners)
in
let info =
{ explicit_targets = Omake_node.NodeTable.empty;
explicit_deps = Omake_node.NodeTable.empty;
explicit_rules = Omake_node.NodeMTable.empty;
explicit_directories = venv_directories venv
}
in
venv_explicit_flush venv;
List.fold_left (fun info erule ->
let { rule_target = target;
rule_locks = locks;
rule_sources = sources;
rule_scanners = scanners;
_
} = erule
in
let target_table = add_target info.explicit_targets target erule in
let dep_table = add_deps info.explicit_deps target locks sources scanners in
{ info with explicit_targets = target_table;
explicit_deps = dep_table;
explicit_rules = Omake_node.NodeMTable.add info.explicit_rules target erule
}) info (List.rev venv.venv_inner.venv_globals.venv_explicit_rules)
(*
* Find all the explicit dependencies listed through null
* rules.
*)
let venv_find_implicit_deps_inner venv target =
let target_dir = Omake_node.Node.dir target in
let target_name = Omake_node.Node.tail target in
let is_scanner =
match Omake_node.Node.kind target with
NodeScanner -> Omake_value_type.RuleScanner
| _ -> RuleNormal
in
List.fold_left (fun (lock_deps, source_deps, scanner_deps, value_deps) nrule ->
let { inrule_multiple = multiple;
inrule_patterns = patterns;
inrule_locks = locks;
inrule_sources = sources;
inrule_scanners = scanners;
inrule_values = values;
_
} = nrule
in
if rule_kind multiple = is_scanner then
let rec search patterns =
match patterns with
pattern :: patterns ->
(match Lm_wild.wild_match pattern target_name with
Some subst ->
let lock_deps =
List.fold_left (fun lock_deps source ->
let source = subst_source venv target_dir subst source in
Omake_node.NodeSet.add lock_deps source) lock_deps locks
in
let source_deps =
List.fold_left (fun names source ->
let source = subst_source venv target_dir subst source in
Omake_node.NodeSet.add names source) source_deps sources
in
let scanner_deps =
List.fold_left (fun scanner_deps source ->
let source = subst_source venv target_dir subst source in
Omake_node.NodeSet.add scanner_deps source) scanner_deps scanners
in
let value_deps = values @ value_deps in
lock_deps, source_deps, scanner_deps, value_deps
| None ->
search patterns)
| [] ->
lock_deps, source_deps, scanner_deps, value_deps
in
search patterns
else
lock_deps, source_deps, scanner_deps, value_deps) (**)
(Omake_node.NodeSet.empty, Omake_node.NodeSet.empty, Omake_node.NodeSet.empty, []) venv.venv_inner.venv_implicit_deps
let venv_find_implicit_deps venv target =
match venv_find_target_dir_opt venv target with
Some venv ->
venv_find_implicit_deps_inner venv target
| None ->
Omake_node.NodeSet.empty, Omake_node.NodeSet.empty, Omake_node.NodeSet.empty, []
(*
* Find the commands from implicit rules.
*)
let venv_find_implicit_rules_inner venv target =
let target_dir = Omake_node.Node.dir target in
let target_name = Omake_node.Node.tail target in
let is_scanner =
match Omake_node.Node.kind target with
NodeScanner -> Omake_value_type.RuleScanner
| _ -> RuleNormal
in
let _ =
if Lm_debug.debug debug_implicit then
Lm_printf.eprintf "Finding implicit rules for %s@." target_name
in
let rec patt_search = function
pattern :: patterns ->
begin match Lm_wild.wild_match pattern target_name with
None -> patt_search patterns
| (Some _) as subst -> subst
end
| [] ->
None
in
let rec collect matched = function
irule :: irules ->
let multiple = irule.irule_multiple in
if rule_kind multiple = is_scanner then
let subst =
if Lm_debug.debug debug_implicit then begin
Lm_printf.eprintf "@[<hv 3>venv_find_implicit_rules: considering implicit rule for@ target = %s:@ " target_name;
begin match irule.irule_targets with
Some targets ->
Lm_printf.eprintf "@[<b 3>3-place targets =%a@]@ " Omake_node.pp_print_string_list (Lm_string_set.StringSet.elements targets)
| None ->
()
end;
Lm_printf.eprintf "@[<b 3>patterns =%a@]@ @[<b 3>sources =%a@]@]@." (**)
Omake_value_print.pp_print_wild_list irule.irule_patterns
Omake_value_print.pp_print_source_list irule.irule_sources
end;
let matches =
match irule.irule_targets with
None -> true
| Some targets -> Lm_string_set.StringSet.mem targets target_name
in
if matches then
patt_search irule.irule_patterns
else
None
in
let matched =
match subst with
Some subst ->
let source_args = List.map (subst_source venv target_dir subst) irule.irule_sources in
let sources = node_set_of_list source_args in
let lock_args = List.map (subst_source venv target_dir subst) irule.irule_locks in
let locks = node_set_of_list lock_args in
let scanner_args = List.map (subst_source venv target_dir subst) irule.irule_scanners in
let scanners = node_set_of_list scanner_args in
let core = Lm_wild.core subst in
let core_val = Omake_value_type.ValData core in
let venv = venv_add_wild_match venv core_val in
let commands = List.map (command_add_wild venv core_val) irule.irule_body in
let commands = make_command_info venv source_args irule.irule_values commands in
let effects =
List.fold_left (fun effects pattern ->
let eff = Lm_wild.subst_in subst pattern in
let eff = venv_intern_rule_target venv multiple (TargetString eff) in
Omake_node.NodeSet.add effects eff) Omake_node.NodeSet.empty irule.irule_patterns
in
let erule =
{ rule_loc = irule.irule_loc;
rule_env = venv;
rule_target = target;
rule_match = Some core;
rule_effects = effects;
rule_locks = locks;
rule_sources = sources;
rule_scanners = scanners;
rule_multiple = multiple;
rule_commands = commands
}
in
if Lm_debug.debug debug_implicit then
Lm_printf.eprintf "@[<hv 3>Added implicit rule for %s:%a@]@." (**)
target_name pp_print_command_info_list commands;
erule :: matched
| None ->
matched
in
collect matched irules
else
collect matched irules
| [] ->
List.rev matched
in
collect [] venv.venv_inner.venv_implicit_rules
let venv_find_implicit_rules venv target =
match venv_find_target_dir_opt venv target with
Some venv ->
venv_find_implicit_rules_inner venv target
| None ->
[]
(************************************************************************
* Ordering rules.
*)
(*
* Add an order.
*)
let venv_add_orders venv loc targets =
let globals = venv.venv_inner.venv_globals in
let orders =
List.fold_left (fun orders target ->
let name =
match target with
| Omake_value_type.TargetNode _ ->
raise (Omake_value_type.OmakeException
(Pos.loc_exp_pos loc, StringTargetError (".ORDER should be a name", target)))
| TargetString s ->
s
in
Lm_string_set.StringSet.add orders name) globals.venv_orders targets
in
globals.venv_orders <- orders;
venv
(*
* Check for order.
*)
let venv_is_order venv name =
Lm_string_set.StringSet.mem venv.venv_inner.venv_globals.venv_orders name
(*
* Add an ordering rule.
*)
let venv_add_ordering_rule venv pos loc name pattern sources =
let pos = Pos.string_pos "venv_add_ordering_deps" pos in
let pattern = compile_wild_pattern venv pos loc pattern in
let sources = List.map (compile_source_core venv) sources in
let orule =
{ orule_loc = loc;
orule_name = name;
orule_pattern = pattern;
orule_sources = sources
}
in
let globals = venv.venv_inner.venv_globals in
globals.venv_ordering_rules <- orule :: globals.venv_ordering_rules;
venv
(*
* Get the ordering dependencies for a name.
*)
let venv_get_ordering_info venv name =
List.fold_left (fun orules orule ->
if Lm_symbol.eq orule.orule_name name then
orule :: orules
else
orules) [] venv.venv_inner.venv_globals.venv_ordering_rules
(*
* Get extra dependencies.
*)
let venv_get_ordering_deps venv orules deps =
let step deps =
Omake_node.NodeSet.fold (fun deps dep ->
let target_dir = Omake_node.Node.dir dep in
let target_str = Omake_node.Node.tail dep in
List.fold_left (fun deps orule ->
let { orule_pattern = pattern;
orule_sources = sources;
_
} = orule
in
match Lm_wild.wild_match pattern target_str with
Some subst ->
List.fold_left (fun deps source ->
let source = subst_source_core venv target_dir subst source in
Omake_node.NodeSet.add deps source) deps sources
| None ->
deps) deps orules) deps deps
in
let rec fixpoint deps =
let deps' = step deps in
if Omake_node.NodeSet.cardinal deps' = Omake_node.NodeSet.cardinal deps then
deps
else
fixpoint deps'
in
fixpoint deps
(************************************************************************
* Static rules.
*)
(*
* Each of the commands evaluates to an object.
*)
let venv_add_memo_rule venv _pos loc _multiple is_static key vars sources values body =
let source_args = List.map (intern_source venv) sources in
let sources = node_set_of_list source_args in
let srule =
{ srule_loc = loc;
srule_static = is_static;
srule_env = venv;
srule_key = key;
srule_deps = sources;
srule_vals = values;
srule_exp = body
}
in
let globals = venv_globals venv in
let venv =
List.fold_left (fun venv info ->
let _, v = Omake_ir_util.var_of_var_info info in
venv_add_var venv info (ValDelayed (ref (Omake_value_type.ValStaticApply (key, v))))) venv vars
in
globals.venv_memo_rules <- Omake_value_util.ValueTable.add globals.venv_memo_rules key (StaticRule srule);
venv
(*
* Force the evaluation.
*)
let venv_set_static_info venv key v =
let globals = venv_globals venv in
globals.venv_memo_rules <- Omake_value_util.ValueTable.add globals.venv_memo_rules key v
let venv_find_static_info venv pos key =
try Omake_value_util.ValueTable.find venv.venv_inner.venv_globals.venv_memo_rules key with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringValueError ("Static section not defined", key)))
(************************************************************************
* Return values.
*)
* Export an item from one environment to another .
* Export an item from one environment to another.
*)
let copy_var pos dst src v =
try Lm_symbol.SymbolTable.add dst v (Lm_symbol.SymbolTable.find src v) with
Not_found ->
raise (Omake_value_type.OmakeException (pos, UnboundVar v))
let export_item pos venv_dst venv_src = function
| Omake_ir.ExportVar (VarPrivate (_, v)) ->
{ venv_dst with venv_static = copy_var pos venv_dst.venv_static venv_src.venv_static v }
| ExportVar (VarThis (_, v)) ->
{ venv_dst with venv_this = copy_var pos venv_dst.venv_this venv_src.venv_this v }
| ExportVar (VarVirtual (_, v)) ->
{ venv_dst with venv_dynamic = copy_var pos venv_dst.venv_dynamic venv_src.venv_dynamic v }
| ExportVar (VarGlobal (_, v)) ->
(*
* For now, we don't know which scope to use, so we
* copy them all.
*)
let { venv_dynamic = dynamic_src;
venv_static = static_src;
venv_this = this_src;
_
} = venv_src
in
let { venv_dynamic = dynamic_dst;
venv_static = static_dst;
venv_this = this_dst;
_
} = venv_dst
in
let dynamic, found =
try Lm_symbol.SymbolTable.add dynamic_dst v (Lm_symbol.SymbolTable.find dynamic_src v), true with
Not_found ->
dynamic_dst, false
in
let static, found =
try Lm_symbol.SymbolTable.add static_dst v (Lm_symbol.SymbolTable.find static_src v), true with
Not_found ->
static_dst, found
in
let this, found =
try Lm_symbol.SymbolTable.add this_dst v (Lm_symbol.SymbolTable.find this_src v), true with
Not_found ->
this_dst, found
in
if not found then
raise (Omake_value_type.OmakeException (pos, UnboundVar v));
{ venv_dst with venv_dynamic = dynamic;
venv_static = static;
venv_this = this
}
| ExportRules ->
(*
* Export the implicit rules.
*)
let inner_src = venv_src.venv_inner in
let inner_dst =
{ venv_dst.venv_inner with
venv_implicit_deps = inner_src.venv_implicit_deps;
venv_implicit_rules = inner_src.venv_implicit_rules;
}
in
{ venv_dst with venv_inner = inner_dst }
| ExportPhonies ->
(*
* Export the phony vars.
*)
let inner_dst = { venv_dst.venv_inner with venv_phony = venv_src.venv_inner.venv_phony } in
{ venv_dst with venv_inner = inner_dst }
let export_list pos venv_dst venv_src vars =
List.fold_left (fun venv_dst v ->
export_item pos venv_dst venv_src v) venv_dst vars
* Exported environment does not include static values .
*
* We want to preserve pointer equality on venv2 to avoid giving unnecessary
* " these files are targeted separately , but appear as effects of a single rule "
* warnings .
* Exported environment does not include static values.
*
* We want to preserve pointer equality on venv2 to avoid giving unnecessary
* "these files are targeted separately, but appear as effects of a single rule"
* warnings.
*)
let venv_export_venv venv1 venv2 =
if venv1.venv_static == venv2.venv_static then
venv2
else
{ venv2 with venv_static = venv1.venv_static }
(*
* Add the exported result to the current environment.
*)
let add_exports venv_dst venv_src pos = function
|Omake_ir.ExportNone ->
venv_dst
| ExportAll ->
venv_export_venv venv_dst venv_src
| ExportList vars ->
export_list pos venv_dst venv_src vars
* venv_orig - environment before the function call .
* venv_dst - environment after " entering " the object namespace , before the function call
* venv_src - environment after the function call
*
* # venv_orig is here
* A.B.C.f(1 )
* # venv_dst is venv_orig with this = * # venv_src is venv when A.B.C.f returns
*
* 1 . export from venv_src into venv_dst
* 2 . take venv_orig.venv_this
* 3 . update along the path
* venv_orig - environment before the function call.
* venv_dst - environment after "entering" the object namespace, before the function call
* venv_src - environment after the function call
*
* # venv_orig is here
* A.B.C.f(1)
* # venv_dst is venv_orig with this = A.B.C
* # venv_src is venv when A.B.C.f returns
*
* 1. export from venv_src into venv_dst
* 2. take venv_orig.venv_this
* 3. update along the path A.B.C
*)
let rec hoist_path venv path obj =
match path with
| Omake_value_type.PathVar v ->
venv_add_var venv v (ValObject obj)
| PathField (path, parent_obj, v) ->
let obj = Lm_symbol.SymbolTable.add parent_obj v (ValObject obj) in
hoist_path venv path obj
let hoist_this venv_orig venv_obj path =
let venv = { venv_obj with venv_this = venv_orig.venv_this } in
hoist_path venv path venv_obj.venv_this
let add_path_exports venv_orig venv_dst venv_src pos path ( x : Omake_ir.export) =
match x with
| ExportNone ->
venv_orig
| ExportAll ->
hoist_this venv_orig (venv_export_venv venv_dst venv_src) path
| ExportList vars ->
hoist_this venv_orig (export_list pos venv_dst venv_src vars) path
(************************************************************************
* Squashing.
*)
let squash_prim_fun f =
f
let squash_object obj =
obj
| null | https://raw.githubusercontent.com/ocaml-omake/omake/26b39e82f81c912f8c0f9859328c9c24800e6ba8/src/env/omake_env.ml | ocaml |
* Command lists have source arguments.
* An implicit rule with a body.
*
* In an implicit rule, we compile the targets/sources
* to wild patterns.
* An implicit dependency. There is no body, but
* it may have value dependencies.
* Explicit rules.
* A listing of all the explicit rules.
*
* explicit_targets : the collapsed rules for each explicit target
* explicit_deps : the table of explicit rules that are just dependencies
* explicit_rules : the table of all individual explicit rules
* explicit_directories : the environment for each directory in the project
locks, sources, scanners
after a venv_fork this is the pointer to the source; it is set back
to None when any of the versions is changed. The int is the version
of the parent.
increased after a change
Execution service
File cache
Mounting functions
Values from handles
The set of files we have ever read
Save the environment for each directory in the project
All the phony targets we have ever generated
Explicit rules are global
Ordering rules
Static rules
Cached values for files
Cached values for static sections
Cached values for the target_is_buildable function
* Type of execution servers.
* Execution service.
* Error during translation.
* Command line parsing.
* Full and partial applications.
At present, this function needs to be called when any change is done that
may affect target_is_buildable(_proper), i.e. the addition of implicit,
explicit or phony rules.
* Map functions.
***********************************************************************
* Printing.
***********************************************************************
* Pipeline printing.
* Token printing.
* Pipes based on strings.
* Pipes based on arguments.
***********************************************************************
* Utilities.
* Don't make command info if there are no commands.
* Check if the commands are trivial.
* Multiple flags.
let is_scanner_rule = function
| RuleScannerMultiple ->
true
| RuleSingle
| RuleMultiple ->
false
***********************************************************************
* Handles.
***********************************************************************
* Channels.
* Add a channel slot.
* A formatting channel.
* Get the channel.
Standard channels are always available
* When a channel is closed, close the buffers too.
Fail silently
* Get the channel.
* Finding by identifiers.
***********************************************************************
* Primitive values.
* Allocate a function primitive.
* Debug file database (.omc files).
* Look up the primitive value if we haven't seen it already.
***********************************************************************
* Target cache.
*
* To keep this up-to-date, entries are added for explicit targets,
* and the cache is flushed whenever an implicit rule is added.
This is OK because whenever we add a phony target we flush the cache
* Save explicit rules.
* Add an explicit dependency.
* Phony names.
***********************************************************************
* Static values.
* Static loading.
* Open a file. The Omake_node.Node.t is the name of the _source_ file,
* not the .omc file. We'll figure out where the .omc file
* goes on our own. Raises Not_found if the source file
* can't be found.
* The implementation will make sure all the locking/unlocking is done properly.
* For static values, we access the db a bit more directly
* A .omc file.
* Tags for the various kinds of entries.
***********************************************************************
* Operations.
* Open a file. The Omake_node.Node.t is the name of the _source_ file,
* not the .omc file. We'll figure out where the .omc file
* goes on our own.
Get the source digest
* Restart with a write lock.
* Close the file.
* Cached object files.
***********************************************************************
* Variables.
* Default empty object.
* Adding to variable environment.
* Add to the current object and the static scope.
* Add the arguments given an environment.
* Add the arguments to the given static environment.
* Also provide a form for partial applications.
* The system environment.
***********************************************************************
* Manipulating static objects.
* Static values. Load the values from the file
* if necessary. Raises Not_found if the object has not already
* been loaded.
Load it from the file
* Define a static var.
* Save the object on the modified list so it will get
* written back to the file.
* Inline the static variables into the current environment.
* Save the modified values.
***********************************************************************
* Methods and objects.
* Create a path when fetching fields, so that we
* can hoist the exports from a method call.
let raise_field_error mode pos loc v =
mode
in
let rec squash_path_info path info =
match path with
|Omake_value_type.PathVar _ ->
| PathField (path, _, _) ->
squash_path_info path info
* When finding a value, also construct the path to
* the value.
* Simple finding.
* Super fields come from the class.
* Add a field.
* Hacked versions bypass translation.
* Test whether a field is defined.
* Add a class to an object.
* Execute a method in an object.
* If we are currently in the outermost object,
* push the dynamic scope.
* Define a new object.
* Add the class to the current object.
* Include the fields in the given class.
* Be careful to merge classnames.
* Function scoping.
* The current object is always in the venv_this field.
***********************************************************************
* Environment.
* Convert a filename to a node.
List.fold_left (fun nodes name ->
let node_set_of_names venv phony_flag names =
* Convert back to a string.
* Add a mount point.
* A target is wild if it is a string with a wild char.
* Compile a wild pattern.
* It is an error if it isn't wild.
* Compile a source.
* Perform a wild substitution on a source.
* No wildcard matching.
***********************************************************************
* Rules
* Symbols for directories.
let wild_sym = Lm_symbol.add Lm_wild.wild_string
* Don't save explicit rules.
* Save explicit rules.
Filter out the rules with a different target
* Add the wild target.
* This is the standard way to add results of a pattern match.
* Create an environment.
* Create a fresh environment from the pervasives.
* This is used for compiling objects.
* Fork the environment, so that changes really have no effect on the old one.
* This is primarly used when a thread wants a private copy of the environment.
* Get the scope of all variables.
* Add an included file.
* Global state.
* The public version does not mess whith the phonies.
* Get the dir.
* When a file is read, remember it as a configuration file.
* Get all the configuration files.
* Add a null rule.
* Add an implicit rule.
* Add an explicit rule.
* Flush the explicit list.
* Check if an explicit rule exists.
* Get the explicit rules. Build a table indexed by target.
* For .PHONY targets, multiple is ignored.
* Otherwise, multiple must be the same for both targets.
* Find all the explicit dependencies listed through null
* rules.
* Find the commands from implicit rules.
***********************************************************************
* Ordering rules.
* Add an order.
* Check for order.
* Add an ordering rule.
* Get the ordering dependencies for a name.
* Get extra dependencies.
***********************************************************************
* Static rules.
* Each of the commands evaluates to an object.
* Force the evaluation.
***********************************************************************
* Return values.
* For now, we don't know which scope to use, so we
* copy them all.
* Export the implicit rules.
* Export the phony vars.
* Add the exported result to the current environment.
***********************************************************************
* Squashing.
|
module TargetElem = struct
type t = int * string * Omake_node_sig.node_kind
let compare (h1,s1,k1) (h2,s2,k2) =
if h1=h2 then
let p1 = String.compare s1 s2 in
if p1 = 0 then
compare k1 k2
else
p1
else
h1-h2
let intern ((s1,k1) as key) =
let h1 = Hashtbl.hash key in
(h1,s1,k1)
end
module TargetMap = Lm_map.Make(TargetElem)
type command_info =
{ command_env : t;
command_sources : Omake_node.Node.t list;
command_values : Omake_value_type.t list;
command_body : Omake_value_type.command list
}
and irule =
{ irule_loc : Lm_location.t;
irule_multiple : Omake_value_type.rule_multiple;
irule_targets : Lm_string_set.StringSet.t option;
irule_patterns : Lm_wild.in_patt list;
irule_locks : Omake_value_type.source_core Omake_value_type.source list;
irule_sources : Omake_value_type.source_core Omake_value_type.source list;
irule_scanners : Omake_value_type.source_core Omake_value_type.source list;
irule_values : Omake_value_type.t list;
irule_body : Omake_value_type.command list
}
and inrule =
{ inrule_loc : Lm_location.t;
inrule_multiple : Omake_value_type.rule_multiple;
inrule_patterns : Lm_wild.in_patt list;
inrule_locks : Omake_value_type.source_core Omake_value_type.source list;
inrule_sources : Omake_value_type.source_core Omake_value_type.source list;
inrule_scanners : Omake_value_type.source_core Omake_value_type.source list;
inrule_values : Omake_value_type.t list
}
and erule =
{ rule_loc : Lm_location.t;
rule_env : t;
rule_target : Omake_node.Node.t;
rule_effects : Omake_node.NodeSet.t;
rule_locks : Omake_node.NodeSet.t;
rule_sources : Omake_node.NodeSet.t;
rule_scanners : Omake_node.NodeSet.t;
rule_match : string option;
rule_multiple : Omake_value_type.rule_multiple;
rule_commands : command_info list
}
and erule_info =
{ explicit_targets : erule Omake_node.NodeTable.t;
explicit_rules : erule Omake_node.NodeMTable.t;
explicit_directories : t Omake_node.DirTable.t
}
* An ordering rule .
* For now , this just defines an extra dependency
* of the form : patt1 - > patt2
* This means that if a file depends on patt1 ,
* then it also depends on patt2 .
* An ordering rule.
* For now, this just defines an extra dependency
* of the form: patt1 -> patt2
* This means that if a file depends on patt1,
* then it also depends on patt2.
*)
and orule =
{ orule_loc : Lm_location.t;
orule_name : Lm_symbol.t;
orule_pattern : Lm_wild.in_patt;
orule_sources : Omake_value_type.source_core list
}
and ordering_info = orule list
and srule =
{ srule_loc : Lm_location.t;
srule_static : bool;
srule_env : t;
srule_key : Omake_value_type.t;
srule_deps : Omake_node.NodeSet.t;
srule_vals : Omake_value_type.t list;
srule_exp : Omake_ir.exp
}
and static_info =
StaticRule of srule
| StaticValue of Omake_value_type.obj
* The environment contains three scopes :
* 1 . The dynamic scope
* 2 . The current object
* 3 . The static scope
* Lookup occurs in that order , unless the variables
* have been defined otherwise .
*
* Each function has its own static scope .
* The dynamic scope comes from the caller .
* The environment contains three scopes:
* 1. The dynamic scope
* 2. The current object
* 3. The static scope
* Lookup occurs in that order, unless the variables
* have been defined otherwise.
*
* Each function has its own static scope.
* The dynamic scope comes from the caller.
*)
and t =
{ venv_dynamic : Omake_value_type.env;
venv_this : Omake_value_type.obj;
venv_static : Omake_value_type.env;
venv_inner : venv_inner
}
and venv_inner =
{ venv_environ : string Lm_symbol.SymbolTable.t;
venv_dir : Omake_node.Dir.t;
venv_phony : Omake_node.NodeSet.t;
venv_implicit_deps : inrule list;
venv_implicit_rules : irule list;
venv_options : Omake_options.t;
venv_globals : venv_globals;
venv_mount : Omake_node.Mount.t;
venv_included_files : Omake_node.NodeSet.t
}
and venv_globals =
{ mutable venv_parent : (venv_globals * int) option;
mutable venv_version : int;
mutable venv_mutex : Lm_thread.Mutex.t;
At present , the venv_parent / venv_version mechanism is only used to
accelerate target_is_buildable{_proper } . If a forked venv is still
identical to the original , this cache can be better updated in the
parent ( back propagation ) .
TODO : another candidate for back propagation is the file cache .
accelerate target_is_buildable{_proper}. If a forked venv is still
identical to the original, this cache can be better updated in the
parent (back propagation).
TODO: another candidate for back propagation is the file cache.
*)
venv_exec : exec;
venv_cache : Omake_cache.t;
venv_mount_info : Omake_node.mount_info;
venv_environments : t Lm_handle_table.t;
mutable venv_files : Omake_node.NodeSet.t;
mutable venv_directories : t Omake_node.DirTable.t;
mutable venv_excluded_directories : Omake_node.DirSet.t;
mutable venv_phonies : Omake_node.PreNodeSet.t;
mutable venv_explicit_rules : erule list;
mutable venv_explicit_targets : erule Omake_node.NodeTable.t;
mutable venv_explicit_new : erule list;
mutable venv_ordering_rules : orule list;
mutable venv_orders : Lm_string_set.StringSet.t;
mutable venv_memo_rules : static_info Omake_value_util.ValueTable.t;
mutable venv_ir_files : Omake_ir.t Omake_node.NodeTable.t;
mutable venv_object_files : Omake_value_type.obj Omake_node.NodeTable.t;
mutable venv_static_values : Omake_value_type.obj Lm_symbol.SymbolTable.t Omake_node.NodeTable.t;
mutable venv_modified_values : Omake_value_type.obj Lm_symbol.SymbolTable.t Omake_node.NodeTable.t;
This uses now a compression : we map directories to small integers
target_dir . This mapping is implemented by venv_target_dirs .
For every ( candidate ) target file we map the file name to two bitsets
( buildable , non_buildable ) enumerating the directories where the file
can be built or not be built .
target_dir. This mapping is implemented by venv_target_dirs.
For every (candidate) target file we map the file name to two bitsets
(buildable,non_buildable) enumerating the directories where the file
can be built or not be built.
*)
mutable venv_target_dirs : target_dir Omake_node.DirTable.t;
mutable venv_target_next_dir : target_dir;
mutable venv_target_is_buildable : (Lm_bitset.t * Lm_bitset.t) TargetMap.t;
mutable venv_target_is_buildable_proper : (Lm_bitset.t * Lm_bitset.t) TargetMap.t;
The state right after Pervasives is evaluated
mutable venv_pervasives_vars : Omake_ir.senv;
mutable venv_pervasives_obj : Omake_value_type.obj
}
and target_dir = int
and pid =
InternalPid of int
| ExternalPid of int
| ResultPid of int * t * Omake_value_type.t
and exec = (arg_command_line, pid, Omake_value_type.t) Omake_exec.Exec.t
and arg_command_inst = (Omake_ir.exp, arg_pipe, Omake_value_type.t) Omake_command_type.poly_command_inst
and arg_command_line = (t, Omake_ir.exp, arg_pipe, Omake_value_type.t) Omake_command_type.poly_command_line
and string_command_inst = (Omake_ir.exp, string_pipe, Omake_value_type.t) Omake_command_type.poly_command_inst
and string_command_line = (t, Omake_ir.exp, string_pipe, Omake_value_type.t) Omake_command_type.poly_command_line
and apply = t -> Unix.file_descr -> Unix.file_descr -> Unix.file_descr -> (Lm_symbol.t * string) list -> Omake_value_type.t list -> int * t * Omake_value_type.t
and value_cmd = (unit, Omake_value_type.t list, Omake_value_type.t list) Omake_shell_type.poly_cmd
and value_apply = (Omake_value_type.t list, Omake_value_type.t list, apply) Omake_shell_type.poly_apply
and value_group = (unit, Omake_value_type.t list, Omake_value_type.t list, Omake_value_type.t list, apply) Omake_shell_type.poly_group
and value_pipe = (unit, Omake_value_type.t list, Omake_value_type.t list, Omake_value_type.t list, apply) Omake_shell_type.poly_pipe
and arg_cmd = (Omake_command_type.arg Omake_shell_type.cmd_exe, Omake_command_type.arg, Omake_command_type.arg) Omake_shell_type.poly_cmd
and arg_apply = (Omake_value_type.t, Omake_command_type.arg, apply) Omake_shell_type.poly_apply
and arg_group = (Omake_command_type.arg Omake_shell_type.cmd_exe, Omake_command_type.arg, Omake_value_type.t, Omake_command_type.arg, apply) Omake_shell_type.poly_group
and arg_pipe = (Omake_command_type.arg Omake_shell_type.cmd_exe, Omake_command_type.arg, Omake_value_type.t, Omake_command_type.arg, apply) Omake_shell_type.poly_pipe
and string_cmd = (Omake_shell_type.simple_exe, string, string) Omake_shell_type.poly_cmd
and string_apply = (Omake_value_type.t, string, apply) Omake_shell_type.poly_apply
and string_group = (Omake_shell_type.simple_exe, string, Omake_value_type.t, string, apply) Omake_shell_type.poly_group
and string_pipe = (Omake_shell_type.simple_exe, string, Omake_value_type.t, string, apply) Omake_shell_type.poly_pipe
exception Break of Lm_location.t * t
type prim_fun_data = t -> Omake_value_type.pos -> Lm_location.t ->
Omake_value_type.t list -> Omake_value_type.keyword_value list -> t * Omake_value_type.t
type venv_runtime =
{ venv_channels : Lm_channel.t Lm_int_handle_table.t;
mutable venv_primitives : prim_fun_data Lm_symbol.SymbolTable.t
}
type lexer = string -> int -> int -> int option
type tok =
TokString of Omake_value_type.t
| TokToken of string
| TokGroup of tok list
* Inclusion scope is usually Pervasives ,
* but it may include everything in scope .
* Inclusion scope is usually Pervasives,
* but it may include everything in scope.
*)
type include_scope =
IncludePervasives
| IncludeAll
type partial_apply =
FullApply of t * Omake_value_type.t list * Omake_value_type.keyword_value list
| PartialApply of Omake_value_type.env * Omake_value_type.param_value list * Omake_value_type.keyword_param_value list * Omake_ir.param list * Omake_value_type.keyword_value list
let venv_runtime : venv_runtime =
{ venv_channels = Lm_int_handle_table.create ();
venv_primitives = Lm_symbol.SymbolTable.empty
}
* Now the stuff that is really global , not saved in venv .
* Now the stuff that is really global, not saved in venv.
*)
module IntCompare =
struct
type t = int
let compare = (-)
end;;
module IntTable = Lm_map.LmMake (IntCompare);;
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Access to the globals .
* This actually performs some computation in 0.9.9
* Access to the globals.
* This actually performs some computation in 0.9.9
*)
let venv_globals venv =
venv.venv_inner.venv_globals
let venv_get_mount_listing venv =
Omake_node.Mount.mount_listing venv.venv_inner.venv_mount
let venv_protect globals f =
Lm_thread.Mutex.lock globals.venv_mutex;
try
let r = f() in
Lm_thread.Mutex.unlock globals.venv_mutex;
r
with
| exn ->
Lm_thread.Mutex.unlock globals.venv_mutex;
raise exn
let venv_synch venv f =
let globals = venv_globals venv in
venv_protect
globals
(fun () ->
match globals.venv_parent with
| Some(pglobals, pversion) ->
venv_protect
pglobals
(fun () ->
if pversion = pglobals.venv_version then
f globals (Some pglobals)
else (
globals.venv_parent <- None;
f globals None
)
)
| None ->
f globals None
)
let venv_incr_version venv f =
let g = venv_globals venv in
venv_protect
g
(fun () ->
g.venv_version <- g.venv_version + 1;
g.venv_parent <- None;
f()
)
let check_map_key = Omake_value_util.ValueCompare.check
let venv_map_empty = Omake_value_util.ValueTable.empty
let venv_map_add map pos v1 v2 =
Omake_value_util.ValueTable.add map (check_map_key pos v1) v2
let venv_map_remove map pos v1 =
Omake_value_util.ValueTable.remove map (check_map_key pos v1)
let venv_map_find map pos v =
try Omake_value_util.ValueTable.find map (check_map_key pos v) with
Not_found ->
raise (Omake_value_type.OmakeException (pos, UnboundValue v))
let venv_map_mem map pos v =
Omake_value_util.ValueTable.mem map (check_map_key pos v)
let venv_map_iter = Omake_value_util.ValueTable.iter
let venv_map_map = Omake_value_util.ValueTable.mapi
let venv_map_fold = Omake_value_util.ValueTable.fold
let venv_map_length = Omake_value_util.ValueTable.cardinal
let rec pp_print_command buf command =
match command with
Omake_value_type.CommandSection (arg, _fv, e) ->
Format.fprintf buf "@[<hv 3>section %a@ %a@]" Omake_value_print.pp_print_value arg Omake_ir_print.pp_print_exp_list e
| CommandValue (_, _, v) ->
Omake_ir_print.pp_print_string_exp buf v
and pp_print_commands buf commands =
List.iter (fun command -> Format.fprintf buf "@ %a" pp_print_command command) commands
and pp_print_command_info buf info =
let { command_env = venv;
command_sources = sources;
command_body = commands;
_
} = info
in
Omake_node.pp_print_dir venv.venv_inner.venv_dir
Omake_node.pp_print_node_list sources
pp_print_commands commands
and pp_print_command_info_list buf infos =
List.iter (fun info -> Format.fprintf buf "@ %a" pp_print_command_info info) infos
and pp_print_rule buf erule =
let { rule_target = target;
rule_effects = effects;
rule_locks = locks;
rule_sources = sources;
rule_scanners = scanners;
rule_commands = commands;
_
} = erule
in
Format.fprintf buf "@[<hv 0>@[<hv 3>rule {";
Format.fprintf buf "@ target = %a" Omake_node.pp_print_node target;
Format.fprintf buf "@ @[<b 3>effects =%a@]" Omake_node.pp_print_node_set effects;
Format.fprintf buf "@ @[<b 3>locks =%a@]" Omake_node.pp_print_node_set locks;
Format.fprintf buf "@ @[<b 3>sources =%a@]" Omake_node.pp_print_node_set sources;
Format.fprintf buf "@ @[<b 3>scanners =%a@]" Omake_node.pp_print_node_set scanners;
Format.fprintf buf "@ @[<hv 3>commands =%a@]" pp_print_command_info_list commands;
Format.fprintf buf "@]@ }@]"
let pp_print_explicit_rules buf venv =
Format.fprintf buf "@[<hv 3>Explicit rules:";
List.iter (fun erule -> Format.fprintf buf "@ %a" pp_print_rule erule) venv.venv_inner.venv_globals.venv_explicit_rules;
Format.fprintf buf "@]"
let rec pp_print_tok buf tok =
match tok with
TokString v ->
Omake_value_print.pp_print_value buf v
| TokToken s ->
Format.fprintf buf "$%s" s
| TokGroup toks ->
Format.fprintf buf "(%a)" pp_print_tok_list toks
and pp_print_tok_list buf toks =
match toks with
[tok] ->
pp_print_tok buf tok
| tok :: toks ->
pp_print_tok buf tok;
Lm_printf.pp_print_char buf ' ';
pp_print_tok_list buf toks
| [] ->
()
let pp_print_simple_exe buf exe =
match exe with
Omake_shell_type.ExeString s ->
Lm_printf.pp_print_string buf s
| ExeQuote s ->
Format.fprintf buf "\\%s" s
| ExeNode node ->
Omake_node.pp_print_node buf node
module PrintString =
struct
type arg_command = string
type arg_apply = Omake_value_type.t
type arg_other = string
type exe = Omake_shell_type.simple_exe
let pp_print_arg_command = Omake_command_type.pp_arg_data_string
let pp_print_arg_apply = Omake_value_print.pp_print_value
let pp_print_arg_other = Omake_command_type.pp_arg_data_string
let pp_print_exe = pp_print_simple_exe
end;;
module PrintStringPipe = Omake_shell_type.MakePrintPipe (PrintString);;
module PrintStringv =
struct
type argv = string_pipe
let pp_print_argv = PrintStringPipe.pp_print_pipe
end;;
module PrintStringCommand = Omake_command_type.MakePrintCommand (PrintStringv);;
let pp_print_string_pipe = PrintStringPipe.pp_print_pipe
let pp_print_string_command_inst = PrintStringCommand.pp_print_command_inst
let pp_print_string_command_line = PrintStringCommand.pp_print_command_line
let pp_print_string_command_lines = PrintStringCommand.pp_print_command_lines
module PrintArg =
struct
type arg_command = Omake_command_type.arg
type arg_apply = Omake_value_type.t
type arg_other = arg_command
type exe = arg_command Omake_shell_type.cmd_exe
let pp_print_arg_command = Omake_command_type.pp_print_arg
let pp_print_arg_apply = Omake_value_print.pp_print_simple_value
let pp_print_arg_other = pp_print_arg_command
let pp_print_exe buf exe =
match exe with
Omake_shell_type.CmdArg arg ->
pp_print_arg_command buf arg
| CmdNode node ->
Omake_node.pp_print_node buf node
end;;
module PrintArgPipe = Omake_shell_type.MakePrintPipe (PrintArg);;
module PrintArgv =
struct
type argv = arg_pipe
let pp_print_argv = PrintArgPipe.pp_print_pipe
end;;
module PrintArgCommand = Omake_command_type.MakePrintCommand (PrintArgv);;
let pp_print_arg_pipe = PrintArgPipe.pp_print_pipe
let pp_print_arg_command_inst = PrintArgCommand.pp_print_command_inst
let pp_print_arg_command_line = PrintArgCommand.pp_print_command_line
let pp_print_arg_command_lines = PrintArgCommand.pp_print_command_lines
let make_command_info venv sources values body =
match values, body with
[], [] ->
[]
| _ ->
[{ command_env = venv;
command_sources = sources;
command_values = values;
command_body = body
}]
let commands_are_trivial commands =
List.for_all (fun command -> command.command_body = []) commands
let is_multiple_rule = function
Omake_value_type.RuleMultiple
| RuleScannerMultiple ->
true
| RuleSingle
| RuleScannerSingle ->
false
Omake_value_type . RuleScannerSingle
let rule_kind = function
Omake_value_type.RuleScannerSingle
| RuleScannerMultiple ->
Omake_value_type.RuleScanner
| RuleSingle
| RuleMultiple ->
RuleNormal
let venv_add_environment venv =
Lm_handle_table.add venv.venv_inner.venv_globals.venv_environments venv
module Pos= Omake_pos.Make (struct let name = "Omake_env" end)
let venv_find_environment venv pos hand =
try Lm_handle_table.find venv.venv_inner.venv_globals.venv_environments hand with
Not_found ->
let pos = Pos.string_pos "venv_find_environment" pos in
raise (Omake_value_type.OmakeException (pos, StringError "unbound environment"))
let venv_add_index_channel index data =
let channels = venv_runtime.venv_channels in
let channel = Lm_int_handle_table.create_handle channels index in
Lm_channel.set_id data index;
Lm_int_handle_table.add channels channel data;
channel
let venv_add_channel _venv data =
let channels = venv_runtime.venv_channels in
let channel = Lm_int_handle_table.new_handle channels in
let index = Lm_int_handle_table.int_of_handle channel in
Lm_channel.set_id data index;
Lm_int_handle_table.add channels channel data;
channel
let add_channel file kind mode binary fd =
Lm_channel.create file kind mode binary (Some fd)
let venv_stdin = venv_add_index_channel 0 (add_channel "<stdin>" Lm_channel.PipeChannel Lm_channel.InChannel false Unix.stdin)
let venv_stdout = venv_add_index_channel 1 (add_channel "<stdout>" Lm_channel.PipeChannel Lm_channel.OutChannel false Unix.stdout)
let venv_stderr = venv_add_index_channel 2 (add_channel "<stderr>" Lm_channel.PipeChannel Lm_channel.OutChannel false Unix.stderr)
let venv_add_formatter_channel _venv fmt =
let channels = venv_runtime.venv_channels in
let fd = Lm_channel.create "formatter" Lm_channel.FileChannel Lm_channel.OutChannel true None in
let channel = Lm_int_handle_table.new_handle channels in
let index = Lm_int_handle_table.int_of_handle channel in
let reader _s _off _len =
raise (Unix.Unix_error (Unix.EINVAL, "formatter-channel", ""))
in
let writer s off len =
Format.pp_print_string fmt (Bytes.to_string (Bytes.sub s off len));
len
in
Lm_channel.set_id fd index;
Lm_channel.set_io_functions fd reader writer;
Lm_int_handle_table.add channels channel fd;
channel
let venv_channel_data channel =
if Lm_int_handle_table.int_of_handle channel <= 2 then
Lm_int_handle_table.find_any venv_runtime.venv_channels channel
else
Lm_int_handle_table.find venv_runtime.venv_channels channel
let venv_close_channel _venv _pos channel =
try
let fd = venv_channel_data channel in
Lm_channel.close fd;
Lm_int_handle_table.remove venv_runtime.venv_channels channel
with
Not_found ->
()
let venv_find_channel _venv pos channel =
let pos = Pos.string_pos "venv_find_in_channel" pos in
try venv_channel_data channel with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringError "channel is closed"))
let venv_find_channel_by_channel _venv pos fd =
let index, _, _, _ = Lm_channel.info fd in
try Lm_int_handle_table.find_value venv_runtime.venv_channels index fd with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringError "channel is closed"))
let venv_find_channel_by_id _venv pos index =
try Lm_int_handle_table.find_any_handle venv_runtime.venv_channels index with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringError "channel is closed"))
let venv_add_prim_fun _venv name data =
venv_runtime.venv_primitives <- Lm_symbol.SymbolTable.add venv_runtime.venv_primitives name data;
name
let debug_scanner =
{ debug_name = "scanner";
debug_description = "Display debugging information for scanner selection";
debug_value = false
}
let debug_implicit =
{ debug_name = "implicit";
debug_description = "Display debugging information for implicit rule selection";
debug_value = false
}
let debug_db = Lm_db.debug_db
let venv_apply_prim_fun name venv pos loc args =
let f =
try Lm_symbol.SymbolTable.find venv_runtime.venv_primitives name with
Not_found ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, UnboundVar name))
in
f venv pos loc args
let lookup_target_dir_in g dir =
try
Omake_node.DirTable.find g.venv_target_dirs dir
with
| Not_found ->
let tdir = g.venv_target_next_dir in
g.venv_target_next_dir <- tdir+1;
let tab =
Omake_node.DirTable.add g.venv_target_dirs dir tdir in
g.venv_target_dirs <- tab;
tdir
let venv_lookup_target_dir venv dir =
venv_synch
venv
(fun globals pglobals_opt ->
match pglobals_opt with
| Some pglobals ->
let tdir = lookup_target_dir_in pglobals dir in
globals.venv_target_next_dir <- pglobals.venv_target_next_dir;
globals.venv_target_dirs <- pglobals.venv_target_dirs;
tdir
| None ->
lookup_target_dir_in globals dir
)
let squeeze_phony =
function
| Omake_node_sig.NodePhony ->
Omake_node_sig.NodeNormal
| other ->
other
let venv_find_target_is_buildable_exn venv target_dir file node_kind =
let node_kind = squeeze_phony node_kind in
let g = venv_globals venv in
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
TargetMap.find ikey g.venv_target_is_buildable in
Lm_bitset.is_set bset target_dir || (
if not(Lm_bitset.is_set nonbset target_dir) then raise Not_found;
false
)
let venv_find_target_is_buildable_multi venv file node_kind =
let node_kind = squeeze_phony node_kind in
let g = venv_globals venv in
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
try
TargetMap.find ikey g.venv_target_is_buildable
with
| Not_found ->
(Lm_bitset.create(), Lm_bitset.create()) in
(fun target_dir ->
Lm_bitset.is_set bset target_dir || (
if not(Lm_bitset.is_set nonbset target_dir) then raise Not_found;
false
)
)
let venv_find_target_is_buildable_proper_exn venv target_dir file node_kind =
let node_kind = squeeze_phony node_kind in
let g = venv_globals venv in
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
TargetMap.find ikey g.venv_target_is_buildable_proper in
Lm_bitset.is_set bset target_dir || (
if not(Lm_bitset.is_set nonbset target_dir) then raise Not_found;
false
)
let add_target_to m target_dir file node_kind flag =
let node_kind = squeeze_phony node_kind in
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
try TargetMap.find ikey m
with Not_found -> (Lm_bitset.create(), Lm_bitset.create()) in
let (bset',nonbset') =
if flag then
(Lm_bitset.set bset target_dir, nonbset)
else
(bset, Lm_bitset.set nonbset target_dir) in
TargetMap.add ikey (bset',nonbset') m
let venv_add_target_is_buildable venv target_dir file node_kind flag =
let add g =
let tab =
add_target_to
g.venv_target_is_buildable target_dir file node_kind flag in
g.venv_target_is_buildable <- tab in
venv_synch
venv
(fun globals pglobals_opt ->
match pglobals_opt with
| Some pglobals ->
add pglobals;
globals.venv_target_is_buildable <-
pglobals.venv_target_is_buildable
| None ->
add globals
)
let venv_add_target_is_buildable_multi venv file node_kind tdirs_pos tdirs_neg =
let node_kind = squeeze_phony node_kind in
let add g =
let ikey = TargetElem.intern (file,node_kind) in
let (bset,nonbset) =
try TargetMap.find ikey g.venv_target_is_buildable
with Not_found -> (Lm_bitset.create(), Lm_bitset.create()) in
let bset' = Lm_bitset.set_multiple bset tdirs_pos in
let nonbset' = Lm_bitset.set_multiple nonbset tdirs_neg in
let tab = TargetMap.add ikey (bset',nonbset') g.venv_target_is_buildable in
g.venv_target_is_buildable <- tab in
venv_synch
venv
(fun globals pglobals_opt ->
match pglobals_opt with
| Some pglobals ->
add pglobals;
globals.venv_target_is_buildable <-
pglobals.venv_target_is_buildable
| None ->
add globals
)
let venv_add_target_is_buildable_proper venv target_dir file node_kind flag =
let add g =
let tab =
add_target_to
g.venv_target_is_buildable_proper target_dir file node_kind flag in
g.venv_target_is_buildable_proper <- tab in
venv_synch
venv
(fun globals pglobals_opt ->
match pglobals_opt with
| Some pglobals ->
add pglobals;
globals.venv_target_is_buildable_proper <-
pglobals.venv_target_is_buildable_proper
| None ->
add globals
)
let venv_add_explicit_targets venv rules =
venv_incr_version
venv
(fun () ->
let globals = venv.venv_inner.venv_globals in
let { venv_target_is_buildable = cache;
venv_target_is_buildable_proper = cache_proper;
_
} = globals
in
let add cache erule =
let dir = Omake_node.Node.dir erule.rule_target in
let tdir = lookup_target_dir_in globals dir in
let file = Omake_node.Node.tail erule.rule_target in
let nkind = Omake_node.Node.kind erule.rule_target in
add_target_to cache tdir file nkind true in
let cache = List.fold_left add cache rules in
let cache_proper = List.fold_left add cache_proper rules in
globals.venv_target_is_buildable <- cache;
globals.venv_target_is_buildable_proper <- cache_proper
)
let venv_flush_target_cache venv =
venv_incr_version
venv
(fun () ->
let globals = venv.venv_inner.venv_globals in
globals.venv_target_is_buildable <- TargetMap.empty;
globals.venv_target_is_buildable_proper <- TargetMap.empty
)
let venv_save_explicit_rules venv _loc rules =
let globals = venv.venv_inner.venv_globals in
globals.venv_explicit_new <- List.rev_append rules globals.venv_explicit_new;
venv_add_explicit_targets venv rules
let venv_add_explicit_dep venv loc target source =
let erule =
{ rule_loc = loc;
rule_env = venv;
rule_target = target;
rule_effects = Omake_node.NodeSet.singleton target;
rule_sources = Omake_node.NodeSet.singleton source;
rule_locks = Omake_node.NodeSet.empty;
rule_scanners = Omake_node.NodeSet.empty;
rule_match = None;
rule_multiple = RuleSingle;
rule_commands = []
}
in
ignore (venv_save_explicit_rules venv loc [erule])
let venv_add_phony venv loc names =
if names = [] then
venv
else
let inner = venv.venv_inner in
let { venv_dir = dir;
venv_phony = phony;
_
} = inner
in
let globals = venv_globals venv in
let phonies = globals.venv_phonies in
let phony, phonies =
List.fold_left (fun (phony, phonies) name ->
let name =
match name with
Omake_value_type.TargetNode _ ->
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, StringError ".PHONY arguments should be names"))
| TargetString s ->
s
in
let gnode = Omake_node.Node.create_phony_global name in
let dnode = Omake_node.Node.create_phony_dir dir name in
let phony = Omake_node.NodeSet.add phony dnode in
let phonies = Omake_node.PreNodeSet.add phonies (Omake_node.Node.dest gnode) in
let phonies = Omake_node.PreNodeSet.add phonies (Omake_node.Node.dest dnode) in
venv_add_explicit_dep venv loc gnode dnode;
phony, phonies) (phony, phonies) names
in
let inner = { inner with venv_phony = phony } in
let venv = { venv with venv_inner = inner } in
venv_incr_version venv (fun () -> ());
globals.venv_phonies <- phonies;
venv
module type StaticSig =
sig
type in_handle
type out_handle
val read : t -> Omake_node.Node.t -> (in_handle -> 'a) -> 'a
val rewrite : in_handle -> (out_handle -> 'a) -> 'a
* Fetch the two kinds of entries .
* Fetch the two kinds of entries.
*)
val find_ir : in_handle -> Omake_ir.t
val find_object : in_handle -> Omake_value_type.obj
val get_ir : out_handle -> Omake_ir.t
val get_object : out_handle -> Omake_value_type.obj
* Add the two kinds of entries .
* Add the two kinds of entries.
*)
val add_ir : out_handle -> Omake_ir.t -> unit
val add_object : out_handle -> Omake_value_type.obj -> unit
end
module type InternalStaticSig =
sig
include StaticSig
val write : t -> Omake_node.Node.t -> (out_handle -> 'a) -> 'a
val find_values : in_handle -> Omake_value_type.obj Lm_symbol.SymbolTable.t
val add_values : out_handle -> Omake_value_type.obj Lm_symbol.SymbolTable.t -> unit
end
module Static : InternalStaticSig =
struct
type handle =
{ db_file : Unix.file_descr option;
db_name : Omake_node.Node.t;
db_digest : string;
db_env : t;
db_flush_ir : bool;
db_flush_static : bool
}
type in_handle = handle
type out_handle = handle
let ir_tag = 0, Lm_db.HostIndependent
let object_tag = 1, Lm_db.HostDependent
let values_tag = 2, Lm_db.HostDependent
let create_mode mode venv source =
let cache = venv.venv_inner.venv_globals.venv_cache in
let digest =
match Omake_cache.stat cache source with
Some (_,digest) ->
digest
| None ->
raise Not_found
in
* Open the result file . The lock_cache_file function
* will try to use the target directory first , and
* fall back to ~/.omake / cache if that is not writable .
* Open the result file. The lock_cache_file function
* will try to use the target directory first, and
* fall back to ~/.omake/cache if that is not writable.
*)
let source_name = Omake_node.Node.absname source in
let dir = Filename.dirname source_name in
let name = Filename.basename source_name in
let name =
if Filename.check_suffix name ".om" then
Filename.chop_suffix name ".om"
else
name
in
let name = name ^ ".omc" in
let target_fd =
try
let target_name, target_fd = Omake_state.get_cache_file dir name in
if !debug_db then
Lm_printf.eprintf "@[<v 3>Omake_db.create:@ %a --> %s@]@." Omake_node.pp_print_node source target_name;
Unix.set_close_on_exec target_fd;
Omake_state.lock_file target_fd mode;
Some target_fd
with
Unix.Unix_error _
| Failure _ ->
Lm_printf.eprintf "@[<v 3>OMake warning: could not create and/or lock a cache file for@ %s@]@." source_name;
None
in
{ db_file = target_fd;
db_name = source;
db_digest = digest;
db_env = venv;
db_flush_ir = Omake_options.opt_flush_include venv.venv_inner.venv_options;
db_flush_static = Omake_options.opt_flush_static venv.venv_inner.venv_options;
}
let rewrite info f =
match info.db_file with
Some fd ->
ignore (Unix.lseek fd 0 Unix.SEEK_SET: int);
Omake_state.lock_file fd Unix.F_ULOCK;
Omake_state.lock_file fd Unix.F_LOCK;
let finish () =
ignore (Unix.lseek fd 0 Unix.SEEK_SET: int);
Omake_state.lock_file fd Unix.F_ULOCK;
Omake_state.lock_file fd Unix.F_RLOCK
in
begin try
let result = f info in
finish ();
result
with exn ->
finish ();
raise exn
end
| None ->
f info
let close info =
match info with
{ db_file = Some fd; db_name = name ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.close: %a@." Omake_node.pp_print_node name;
Unix.close fd
| { db_file = None ; _} ->
()
let perform mode venv source f =
let info = create_mode mode venv source in
try
let result = f info in
close info;
result
with exn ->
close info;
raise exn
let read venv source f = perform Unix.F_RLOCK venv source f
let write venv source f = perform Unix.F_LOCK venv source f
* Add the three kinds of entries .
* Add the three kinds of entries.
*)
let add_ir info ir =
match info with
{ db_file = Some fd; db_name = name; db_digest = digest; db_env = _venv ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.add_ir: %a@." Omake_node.pp_print_node name;
Lm_db.add fd (Omake_node.Node.absname name) ir_tag Omake_magic.ir_magic digest ir
| { db_file = None ; _} ->
()
let add_object info obj =
match info with
{ db_file = Some fd; db_name = name; db_digest = digest; db_env = _venv ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.add_object: %a@." Omake_node.pp_print_node name;
Lm_db.add fd (Omake_node.Node.absname name) object_tag Omake_magic.obj_magic digest obj
| { db_file = None ; _} ->
()
let add_values info obj =
match info with
{ db_file = Some fd; db_name = name; db_digest = digest; db_env = _venv ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.add_values: %a@." Omake_node.pp_print_node name;
Lm_db.add fd (Omake_node.Node.absname name) values_tag Omake_magic.obj_magic digest obj
| { db_file = None ; _} ->
()
* Fetch the three kinds of entries .
* Fetch the three kinds of entries.
*)
let find_ir = function
{ db_file = Some fd; db_name = name; db_digest = digest; db_flush_ir = false ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.find_ir: finding: %a@." Omake_node.pp_print_node name;
let ir = Lm_db.find fd (Omake_node.Node.absname name) ir_tag Omake_magic.ir_magic digest in
if !debug_db then
Lm_printf.eprintf "Omake_db.find_ir: found: %a@." Omake_node.pp_print_node name;
ir
| { db_file = None ; _}
| { db_flush_ir = true ; _} ->
raise Not_found
let find_object = function
{ db_file = Some fd; db_name = name; db_digest = digest; db_flush_ir = false; db_flush_static = false ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.find_object: finding: %a@." Omake_node.pp_print_node name;
let obj = Lm_db.find fd (Omake_node.Node.absname name) object_tag Omake_magic.obj_magic digest in
if !debug_db then
Lm_printf.eprintf "Omake_db.find_object: found: %a@." Omake_node.pp_print_node name;
obj
| { db_file = None ; _}
| { db_flush_ir = true ;_}
| { db_flush_static = true ; _} ->
raise Not_found
let find_values = function
{ db_file = Some fd; db_name = name; db_digest = digest; db_flush_ir = false; db_flush_static = false ; _} ->
if !debug_db then
Lm_printf.eprintf "Omake_db.find_values: finding: %a@." Omake_node.pp_print_node name;
let obj = Lm_db.find fd (Omake_node.Node.absname name) values_tag Omake_magic.obj_magic digest in
if !debug_db then
Lm_printf.eprintf "Omake_db.find_values: found: %a@." Omake_node.pp_print_node name;
obj
| { db_file = None ; _}
| { db_flush_ir = true ; _}
| { db_flush_static = true ; _} ->
raise Not_found
let get_ir = find_ir
let get_object = find_object
end;;
let venv_find_ir_file_exn venv node =
Omake_node.NodeTable.find venv.venv_inner.venv_globals.venv_ir_files node
let venv_add_ir_file venv node obj =
let globals = venv.venv_inner.venv_globals in
globals.venv_ir_files <- Omake_node.NodeTable.add globals.venv_ir_files node obj
let venv_find_object_file_exn venv node =
Omake_node.NodeTable.find venv.venv_inner.venv_globals.venv_object_files node
let venv_add_object_file venv node obj =
let globals = venv.venv_inner.venv_globals in
globals.venv_object_files <- Omake_node.NodeTable.add globals.venv_object_files node obj
let venv_empty_object = Lm_symbol.SymbolTable.empty
* For variables , try to look them up as 0 - arity functions first .
* For variables, try to look them up as 0-arity functions first.
*)
let venv_find_var_private_exn venv v =
Lm_symbol.SymbolTable.find venv.venv_static v
let venv_find_var_dynamic_exn venv v =
Lm_symbol.SymbolTable.find venv.venv_dynamic v
let venv_find_var_protected_exn venv v =
try Lm_symbol.SymbolTable.find venv.venv_this v with
Not_found ->
try Lm_symbol.SymbolTable.find venv.venv_dynamic v with
Not_found ->
try Lm_symbol.SymbolTable.find venv.venv_static v with
Not_found ->
ValString (Lm_symbol.SymbolTable.find venv.venv_inner.venv_environ v)
let venv_find_var_global_exn venv v =
try Lm_symbol.SymbolTable.find venv.venv_dynamic v with
Not_found ->
try Lm_symbol.SymbolTable.find venv.venv_this v with
Not_found ->
try Lm_symbol.SymbolTable.find venv.venv_static v with
Not_found ->
ValString (Lm_symbol.SymbolTable.find venv.venv_inner.venv_environ v)
let venv_find_var_exn venv v =
match v with
Omake_ir.VarPrivate (_, v) ->
venv_find_var_private_exn venv v
| VarThis (_, v) ->
venv_find_var_protected_exn venv v
| VarVirtual (_, v) ->
venv_find_var_dynamic_exn venv v
| VarGlobal (_, v) ->
venv_find_var_global_exn venv v
let venv_get_var venv pos v =
try venv_find_var_exn venv v with
Not_found ->
let pos = Pos.string_pos "venv_get_var" pos in
raise (Omake_value_type.OmakeException (pos, UnboundVarInfo v))
let venv_find_var venv pos loc v =
try venv_find_var_exn venv v with
Not_found ->
let pos = Pos.string_pos "venv_find_var" (Pos.loc_pos loc pos) in
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, UnboundVarInfo v))
let venv_find_object_or_empty venv v =
try
match venv_find_var_exn venv v with
ValObject obj ->
obj
| _ ->
venv_empty_object
with
Not_found ->
venv_empty_object
let venv_defined venv v =
let { venv_this = this;
venv_static = static;
venv_dynamic = dynamic;
_
} = venv
in
match v with
Omake_ir.VarPrivate (_, v) ->
Lm_symbol.SymbolTable.mem static v
| VarVirtual (_, v) ->
Lm_symbol.SymbolTable.mem dynamic v
| VarThis (_, v)
| VarGlobal (_, v) ->
Lm_symbol.SymbolTable.mem this v || Lm_symbol.SymbolTable.mem dynamic v || Lm_symbol.SymbolTable.mem static v
let venv_add_var venv v s =
let { venv_this = this;
venv_static = static;
venv_dynamic = dynamic;
_
} = venv
in
match v with
Omake_ir.VarPrivate (_, v) ->
{ venv with venv_static = Lm_symbol.SymbolTable.add static v s }
| VarVirtual (_, v) ->
{ venv with venv_dynamic = Lm_symbol.SymbolTable.add dynamic v s }
| VarThis (_, v) ->
{ venv with venv_this = Lm_symbol.SymbolTable.add this v s;
venv_static = Lm_symbol.SymbolTable.add static v s
}
| VarGlobal (_, v) ->
{ venv with venv_dynamic = Lm_symbol.SymbolTable.add dynamic v s;
venv_static = Lm_symbol.SymbolTable.add static v s
}
let rec venv_add_keyword_args pos venv keywords kargs =
match keywords, kargs with
(v1, v_info, opt_arg) :: keywords_tl, (v2, arg) :: kargs_tl ->
let i = Lm_symbol.compare v1 v2 in
if i = 0 then
venv_add_keyword_args pos (venv_add_var venv v_info arg) keywords_tl kargs_tl
else if i < 0 then
match opt_arg with
Some arg ->
venv_add_keyword_args pos (venv_add_var venv v_info arg) keywords_tl kargs
| None ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v1)))
else
raise (Omake_value_type.OmakeException (pos, StringVarError ("no such keyword", v2)))
| (v1, _, None) :: _, [] ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v1)))
| (_, v_info, Some arg) :: keywords_tl, [] ->
venv_add_keyword_args pos (venv_add_var venv v_info arg) keywords_tl kargs
| [], [] ->
venv
| [], (v2, _) :: _ ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("no such keyword", v2)))
let venv_add_args venv pos loc static params args keywords kargs =
let venv = { venv with venv_static = static } in
let venv = venv_add_keyword_args pos venv keywords kargs in
let len1 = List.length params in
let len2 = List.length args in
let () =
if len1 <> len2 then
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, ArityMismatch (ArityExact len1, len2)))
in
List.fold_left2 venv_add_var venv params args
let venv_with_args venv pos loc params args keywords kargs =
venv_add_args venv pos loc venv.venv_static params args keywords kargs
* Curried - applications .
*
* XXX : this needs to be checked , and performance improved too .
*
* Here is the idea :
*
* - Given a normal arg
* + add the value to the env
* + if params = [ ] then call the function
* - Given a keyword arg
* + if the keyword is valid here , add it to the env , subtract from keywords
* + if not valid here , add to pending
* Curried-applications.
*
* XXX: this needs to be checked, and performance improved too.
*
* Here is the idea:
*
* - Given a normal arg
* + add the value to the env
* + if params = [] then call the function
* - Given a keyword arg
* + if the keyword is valid here, add it to the env, subtract from keywords
* + if not valid here, add to pending kargs
*)
let rec collect_merge_kargs pos rev_kargs kargs1 kargs2 =
match kargs1, kargs2 with
((v1, _) as karg1) :: kargs1_tl, ((v2, _) as karg2) :: kargs2_tl ->
let i = Lm_symbol.compare v1 v2 in
if i = 0 then
raise (Omake_value_type.OmakeException (pos, StringVarError ("duplicate keyword", v1)))
else if i < 0 then
collect_merge_kargs pos (karg1 :: rev_kargs) kargs1_tl kargs2
else
collect_merge_kargs pos (karg2 :: rev_kargs) kargs1 kargs2_tl
| [], kargs
| kargs, [] ->
List.rev_append rev_kargs kargs
let merge_kargs pos kargs1 kargs2 =
match kargs1, kargs2 with
[], kargs
| kargs, [] ->
kargs
| _ ->
collect_merge_kargs pos [] kargs1 kargs2
let add_partial_args venv args =
List.fold_left (fun venv (v, arg) ->
venv_add_var venv v arg) venv args
let rec apply_curry_args pos venv skipped_kargs params args =
match params, args with
[], _ ->
venv, args, List.rev skipped_kargs
| _, [] ->
raise (Omake_value_type.OmakeException (pos, ArityMismatch (ArityExact (List.length params), 0)))
| v :: params, arg :: args ->
apply_curry_args pos (venv_add_var venv v arg) skipped_kargs params args
let rec venv_add_curry_args pos venv params args keywords skipped_kargs kargs =
match keywords, kargs with
(v1, v_info, opt_arg) :: keywords_tl, ((v2, arg) as karg) :: kargs_tl ->
let i = Lm_symbol.compare v1 v2 in
if i = 0 then
venv_add_curry_args pos (venv_add_var venv v_info arg) params args keywords_tl skipped_kargs kargs_tl
else if i < 0 then
match opt_arg with
Some arg ->
venv_add_curry_args pos (venv_add_var venv v_info arg) params args keywords_tl skipped_kargs kargs
| None ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v1)));
else
venv_add_curry_args pos venv params args keywords (karg :: skipped_kargs) kargs_tl
| (v1, _, None) :: _, [] ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v1)))
| (_, v_info, Some arg) :: keywords_tl, [] ->
venv_add_curry_args pos (venv_add_var venv v_info arg) params args keywords_tl skipped_kargs kargs
| [], karg :: kargs_tl ->
venv_add_curry_args pos venv params args keywords (karg :: skipped_kargs) kargs_tl
| [], [] ->
apply_curry_args pos venv skipped_kargs params args
let venv_add_curry_args venv pos _loc static pargs params args keywords kargs1 kargs2 =
let venv = { venv with venv_static = static } in
let venv = add_partial_args venv pargs in
venv_add_curry_args pos venv params args keywords [] (merge_kargs pos kargs1 kargs2)
let rec add_partial_keywords pos venv = function
(v, _, None) :: _ ->
raise (Omake_value_type.OmakeException (pos, StringVarError ("keyword argument is required", v)))
| (_, v_info, Some arg) :: keywords_tl ->
add_partial_keywords pos (venv_add_var venv v_info arg) keywords_tl
| [] ->
venv
let rec apply_partial_args venv pos loc static env skipped_keywords keywords skipped_kargs params args =
match params, args with
[], _ ->
let venv = { venv with venv_static = static } in
let venv = add_partial_args venv env in
let venv = add_partial_keywords pos venv skipped_keywords in
let venv = add_partial_keywords pos venv keywords in
FullApply (venv, args, List.rev skipped_kargs)
| _, [] ->
PartialApply (static, env, List.rev_append skipped_keywords keywords, params, List.rev skipped_kargs)
| v :: params, arg :: args ->
apply_partial_args venv pos loc static ((v, arg) :: env) skipped_keywords keywords skipped_kargs params args
let rec venv_add_partial_args venv pos loc static env params args skipped_keywords keywords skipped_kargs kargs =
match keywords, kargs with
((v1, v_info, _) as key) :: keywords_tl, ((v2, arg) as karg) :: kargs_tl ->
let i = Lm_symbol.compare v1 v2 in
if i = 0 then
venv_add_partial_args venv pos loc static ((v_info, arg) :: env) params args skipped_keywords keywords_tl skipped_kargs kargs_tl
else if i < 0 then
venv_add_partial_args venv pos loc static env params args (key :: skipped_keywords) keywords_tl skipped_kargs kargs
else
venv_add_partial_args venv pos loc static env params args skipped_keywords keywords (karg :: skipped_kargs) kargs_tl
| key :: keywords_tl, [] ->
venv_add_partial_args venv pos loc static env params args (key :: skipped_keywords) keywords_tl skipped_kargs kargs
| [], karg :: kargs_tl ->
venv_add_partial_args venv pos loc static env params args skipped_keywords keywords (karg :: skipped_kargs) kargs_tl
| [], [] ->
apply_partial_args venv pos loc static env skipped_keywords keywords skipped_kargs params args
let venv_add_partial_args venv pos loc static pargs params args keywords kargs1 kargs2 =
venv_add_partial_args venv pos loc static pargs params args [] keywords [] (merge_kargs pos kargs1 kargs2)
let venv_with_partial_args venv env args =
let venv = { venv with venv_static = env } in
add_partial_args venv args
let venv_environment venv =
venv.venv_inner.venv_environ
let venv_getenv venv v =
Lm_symbol.SymbolTable.find venv.venv_inner.venv_environ v
let venv_setenv venv v x =
{ venv with venv_inner = { venv.venv_inner with venv_environ = Lm_symbol.SymbolTable.add venv.venv_inner.venv_environ v x } }
let venv_unsetenv venv v =
{ venv with venv_inner = { venv.venv_inner with venv_environ = Lm_symbol.SymbolTable.remove venv.venv_inner.venv_environ v } }
let venv_defined_env venv v =
Lm_symbol.SymbolTable.mem venv.venv_inner.venv_environ v
let venv_options (venv : t) : Omake_options.t =
venv.venv_inner.venv_options
let venv_with_options venv (options : Omake_options.t) : t =
{ venv with venv_inner = { venv.venv_inner with venv_options = options } }
let venv_set_options_aux venv loc pos argv =
let argv = Array.of_list argv in
let add_unknown _options s =
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringStringError ("unknown option", s)))
in
let options_spec =
["Make options", Omake_options.options_spec;
"Output options", Omake_options.output_spec]
in
let options =
try Lm_arg.fold_argv argv options_spec venv.venv_inner.venv_options add_unknown
"Generic system builder" with
Lm_arg.BogusArg s ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringError s))
in
venv_with_options venv options
let venv_set_options venv loc pos argv =
venv_set_options_aux venv loc pos ("omake" :: argv)
let venv_find_static_object venv node v =
let globals = venv.venv_inner.venv_globals in
let static = globals.venv_static_values in
let table =
try Omake_node.NodeTable.find static node with
Not_found ->
let table = Static.read venv node Static.find_values in
globals.venv_static_values <- Omake_node.NodeTable.add static node table;
table
in
Lm_symbol.SymbolTable.find table v
let venv_add_static_object venv node key obj =
let globals = venv.venv_inner.venv_globals in
let { venv_static_values = static;
venv_modified_values = modified;
_
} = globals
in
let table =
try Omake_node.NodeTable.find static node with
Not_found ->
Lm_symbol.SymbolTable.empty
in
let table = Lm_symbol.SymbolTable.add table key obj in
globals.venv_static_values <- Omake_node.NodeTable.add static node table;
globals.venv_modified_values <- Omake_node.NodeTable.add modified node table
let venv_include_static_object venv obj =
let { venv_dynamic = dynamic ; _} = venv in
let dynamic = Lm_symbol.SymbolTable.fold Lm_symbol.SymbolTable.add dynamic obj in
{ venv with venv_dynamic = dynamic }
let venv_save_static_values venv =
let globals = venv.venv_inner.venv_globals in
Omake_node.NodeTable.iter (fun node table ->
try Static.write venv node (fun fd -> Static.add_values fd table)
with Not_found ->
()) globals.venv_modified_values;
globals.venv_modified_values <- Omake_node.NodeTable.empty
let print_error buf =
Format.fprintf buf " @[<v 3 > Accessing % s field : % a@ The variable was defined at the following location@ % a@ ] " ( \**\ )
Lm_symbol.pp_print_symbol v
raise ( Omake_value_type . OmakeException ( pos , LazyError print_error ) )
Omake_value_type . PathVar info
let venv_find_field_path_exn _venv path obj _pos v =
Omake_value_type.PathField (path, obj, v), Lm_symbol.SymbolTable.find obj v
let venv_find_field_path venv path obj pos v =
try venv_find_field_path_exn venv path obj pos v with
Not_found ->
let pos = Pos.string_pos "venv_find_field_path" pos in
raise (Omake_value_type.OmakeException (pos, UnboundFieldVar (obj, v)))
let venv_find_field_exn _venv obj _pos v =
Lm_symbol.SymbolTable.find obj v
let venv_find_field venv obj pos v =
try venv_find_field_exn venv obj pos v with
Not_found ->
let pos = Pos.string_pos "venv_find_field" pos in
raise (Omake_value_type.OmakeException (pos, UnboundFieldVar (obj, v)))
let venv_find_super_field venv pos loc v1 v2 =
let table = Omake_value_util.venv_get_class venv.venv_this in
try
let obj = Lm_symbol.SymbolTable.find table v1 in
venv_find_field_exn venv obj pos v2
with
Not_found ->
let pos = Pos.string_pos "venv_find_super_field" (Pos.loc_pos loc pos) in
raise (Omake_value_type.OmakeException (pos, StringVarError ("unbound super var", v2)))
let venv_add_field venv obj _pos v e =
venv, Lm_symbol.SymbolTable.add obj v e
let venv_add_field_internal = Lm_symbol.SymbolTable.add
let venv_defined_field_internal = Lm_symbol.SymbolTable.mem
let venv_find_field_internal_exn = Lm_symbol.SymbolTable.find
let venv_find_field_internal obj pos v =
try Lm_symbol.SymbolTable.find obj v with
Not_found ->
let pos = Pos.string_pos "venv_find_field_internal" pos in
raise (Omake_value_type.OmakeException (pos, UnboundFieldVar (obj, v)))
let venv_object_fold_internal = Lm_symbol.SymbolTable.fold
let venv_object_length = Lm_symbol.SymbolTable.cardinal
let venv_defined_field_exn _venv obj v =
Lm_symbol.SymbolTable.mem obj v
let venv_defined_field venv obj v =
try venv_defined_field_exn venv obj v with
Not_found ->
false
let venv_add_class obj v =
let table = Omake_value_util.venv_get_class obj in
let table = Lm_symbol.SymbolTable.add table v obj in
Lm_symbol.SymbolTable.add obj Omake_value_util.class_sym (ValClass table)
let venv_with_object venv this =
{ venv with venv_this = this }
let venv_define_object venv =
venv_with_object venv Lm_symbol.SymbolTable.empty
let venv_instanceof obj s =
Lm_symbol.SymbolTable.mem (Omake_value_util.venv_get_class obj) s
let venv_include_object_aux obj1 obj2 =
let table1 = Omake_value_util.venv_get_class obj1 in
let table2 = Omake_value_util.venv_get_class obj2 in
let table = Lm_symbol.SymbolTable.fold Lm_symbol.SymbolTable.add table1 table2 in
let obj1 = Lm_symbol.SymbolTable.fold Lm_symbol.SymbolTable.add obj1 obj2 in
Lm_symbol.SymbolTable.add obj1 Omake_value_util.class_sym (ValClass table)
let venv_include_object venv obj2 =
let obj = venv_include_object_aux venv.venv_this obj2 in
{ venv with venv_this = obj }
let venv_flatten_object venv obj2 =
let obj = venv_include_object_aux venv.venv_dynamic obj2 in
{ venv with venv_dynamic = obj }
let venv_empty_env =
Lm_symbol.SymbolTable.empty
let venv_get_env venv =
venv.venv_static
let venv_with_env venv env =
{ venv with venv_static = env }
let venv_this venv =
venv.venv_this
let venv_current_object venv classnames =
let obj = venv.venv_this in
if classnames = [] then
obj
else
let table = Omake_value_util.venv_get_class obj in
let table = List.fold_left (fun table v -> Lm_symbol.SymbolTable.add table v obj) table classnames in
Lm_symbol.SymbolTable.add obj Omake_value_util.class_sym (ValClass table)
* ZZZ : this will go away in 0.9.9 .
* ZZZ: this will go away in 0.9.9.
*)
let rec filter_objects venv pos v objl = function
obj :: rev_objl ->
let objl =
try venv_find_field_exn venv obj pos v :: objl with
Not_found ->
objl
in
filter_objects venv pos v objl rev_objl
| [] ->
objl
let venv_current_objects venv pos v =
let { venv_this = this;
venv_dynamic = dynamic;
venv_static = static;
_
} = venv
in
let v, objl =
match v with
Omake_ir.VarPrivate (_, v) ->
v, [static]
| VarThis (_, v) ->
v, [static; dynamic; this]
| VarVirtual (_, v) ->
v, [dynamic]
| VarGlobal (_, v) ->
v, [static; this; dynamic]
in
filter_objects venv pos v [] objl
let venv_intern venv phony_flag name =
let { venv_mount = mount;
venv_dir = dir;
_
} = venv.venv_inner
in
let globals = venv_globals venv in
let { venv_phonies = phonies;
venv_mount_info = mount_info;
_
} = globals
in
Omake_node.create_node_or_phony phonies mount_info mount phony_flag dir name
let venv_intern_target venv phony_flag target =
match target with
Omake_value_type.TargetNode node -> node
| TargetString name -> venv_intern venv phony_flag name
let venv_intern_cd_1 venv phony_flag dir pname =
let mount = venv.venv_inner.venv_mount in
let globals = venv_globals venv in
let { venv_phonies = phonies;
venv_mount_info = mount_info;
_
} = globals
in
Omake_node.create_node_or_phony_1 phonies mount_info mount phony_flag dir pname
let venv_intern_cd venv phony_flag dir name =
venv_intern_cd_1 venv phony_flag dir (Omake_node.parse_phony_name name)
let venv_intern_cd_node_kind venv phony_flag dir pname =
let globals = venv_globals venv in
let { venv_phonies = phonies;
_
} = globals
in
if Omake_node.node_will_be_phony phonies phony_flag dir pname then
Omake_node_sig.NodePhony
else
Omake_node_sig.NodeNormal
let venv_intern_rule_target venv multiple name =
let node =
match name with
Omake_value_type.TargetNode node ->
node
| TargetString name ->
venv_intern venv PhonyOK name
in
match multiple with
| Omake_value_type.RuleScannerSingle
| RuleScannerMultiple ->
Omake_node.Node.create_escape NodeScanner node
| RuleSingle
| RuleMultiple ->
node
let venv_intern_dir venv name =
Omake_node.Dir.chdir venv.venv_inner.venv_dir name
let venv_intern_list venv names =
( venv_intern venv ) names
let node_set_of_list nodes =
List.fold_left Omake_node.NodeSet.add Omake_node.NodeSet.empty nodes
let node_set_add_names venv phony_flag nodes names =
Omake_node.NodeSet.add nodes ( venv_intern venv phony_flag name ) ) nodes names
node_set_add_names venv phony_flag Omake_node.NodeSet.empty names
let venv_dirname venv dir =
if Omake_options.opt_absname venv.venv_inner.venv_options then
Omake_node.Dir.absname dir
else
Omake_node.Dir.name venv.venv_inner.venv_dir dir
let venv_nodename venv dir =
if Omake_options.opt_absname venv.venv_inner.venv_options then
Omake_node.Node.absname dir
else
Omake_node.Node.name venv.venv_inner.venv_dir dir
let venv_mount venv options src dst =
let inner = venv.venv_inner in
let mount = Omake_node.Mount.mount inner.venv_mount options src dst in
let inner = { inner with venv_mount = mount } in
{ venv with venv_inner = inner }
let target_is_wild target =
match target with
Omake_value_type.TargetNode _ ->
false
| TargetString s ->
Lm_wild.is_wild s
let string_of_target venv target =
match target with
|Omake_value_type.TargetString s ->
s
| Omake_value_type.TargetNode node ->
venv_nodename venv node
let compile_wild_pattern _venv pos loc target =
match target with
| Omake_value_type.TargetString s when Lm_wild.is_wild s ->
if Lm_string_util.contains_any s Lm_filename_util.separators then
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringStringError ("filename pattern is a path", s)));
Lm_wild.compile_in s
| _ ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringTargetError ("patterns must be wildcards", target)))
let compile_source_core venv s =
match s with
| Omake_value_type.TargetNode node ->
Omake_value_type.SourceNode node
| TargetString s ->
if Lm_wild.is_wild s then
SourceWild (Lm_wild.compile_out s)
else
SourceNode (venv_intern venv PhonyOK s)
let compile_source venv (kind, s) =
kind, compile_source_core venv s
let compile_implicit3_target pos loc = function
|Omake_value_type.TargetString s ->
if Lm_string_util.contains_any s Lm_filename_util.separators then
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringStringError ("target of a 3-place rule is a path", s)));
s
| target ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringTargetError ("target of a 3-place rule is not a simple string", target)))
let subst_source_core venv dir subst source =
match source with
| Omake_value_type.SourceWild wild ->
let s = Lm_wild.subst subst wild in
venv_intern_cd venv PhonyOK dir s
| SourceNode node ->
node
let subst_source venv dir subst (kind, source) =
Omake_node.Node.create_escape kind (subst_source_core venv dir subst source)
let intern_source venv (kind, source) =
let source =
match source with
| Omake_value_type.TargetNode node ->
node
| TargetString name ->
venv_intern venv PhonyOK name
in
Omake_node.Node.create_escape kind source
let explicit_target_sym = Lm_symbol.add "<EXPLICIT_TARGET>"
let venv_explicit_target venv target =
venv_add_var venv Omake_var.explicit_target_var (ValNode target)
let venv_save_explicit_rules venv loc erules =
let erules =
try
match venv_find_var_dynamic_exn venv explicit_target_sym with
ValNode target ->
let rules =
List.fold_left (fun rules erule ->
if Omake_node.Node.equal erule.rule_target target then
erule :: rules
else
rules) [] erules
in
let rules = List.rev rules in
let () =
if rules = [] then
let print_error buf =
Format.fprintf buf "@[<b 3>Computed rule for `%a' produced no useful rules:" Omake_node.pp_print_node target;
List.iter (fun erule ->
Format.fprintf buf "@ `%a'" Omake_node.pp_print_node erule.rule_target) erules;
Format.fprintf buf "@]"
in
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, LazyError print_error))
in
rules
| _ ->
erules
with
Not_found ->
erules
in
venv_save_explicit_rules venv loc erules
let venv_add_wild_match venv v =
venv_add_var venv Omake_var.wild_var v
let command_add_wild venv wild command =
match command with
Omake_value_type.CommandSection _ ->
command
| CommandValue(loc, env, s) ->
let env = venv_get_env (venv_add_wild_match (venv_with_env venv env) wild) in
CommandValue(loc, env, s)
let venv_add_match_values venv args =
let venv, _ =
List.fold_left (fun (venv, i) arg ->
let v = Omake_var.create_numeric_var i in
let venv = venv_add_var venv v arg in
venv, succ i) (venv, 1) args
in
venv
let venv_add_match_args venv args =
let venv, _ =
List.fold_left (fun (venv, i) arg ->
let v = Omake_var.create_numeric_var i in
let venv = venv_add_var venv v (ValData arg) in
venv, succ i) (venv, 1) args
in
venv
let venv_add_match venv line args =
let args = List.map (fun s -> Omake_value_type.ValData s) args in
let venv, _ =
List.fold_left (fun (venv, i) arg ->
let v = Omake_var.create_numeric_var i in
let venv = venv_add_var venv v arg in
venv, succ i) (venv, 1) args
in
let venv = venv_add_var venv Omake_var.zero_var (Omake_value_type.ValData line) in
let venv = venv_add_var venv Omake_var.star_var (ValArray args) in
let venv = venv_add_var venv Omake_var.nf_var (ValInt (List.length args)) in
venv
let create_environ () =
let env = Unix.environment () in
let len = Array.length env in
let rec collect table i =
if i = len then
table
else
let s = env.(i) in
let j = String.index s '=' in
let name = String.sub s 0 j in
let name =
if Sys.os_type = "Win32" then
String.uppercase_ascii name
else
name
in
let v = Lm_symbol.add name in
let x = String.sub s (j + 1) (String.length s - j - 1) in
let table = Lm_symbol.SymbolTable.add table v x in
collect table (succ i)
in
collect Lm_symbol.SymbolTable.empty 0
let create options _dir exec cache =
let cwd = Omake_node.Dir.cwd () in
let env = create_environ () in
let mount_info =
{ Omake_node_sig.mount_file_exists = Omake_cache.exists cache;
mount_file_reset = (fun node -> ignore (Omake_cache.force_stat cache node));
mount_is_dir = Omake_cache.is_dir cache;
mount_digest = Omake_cache.stat cache;
mount_stat = Omake_cache.stat_unix cache
}
in
let globals =
{ venv_parent = None;
venv_version = 0;
venv_mutex = Lm_thread.Mutex.create "venv_globals";
venv_exec = exec;
venv_cache = cache;
venv_mount_info = mount_info;
venv_environments = Lm_handle_table.create ();
venv_files = Omake_node.NodeSet.empty;
venv_directories = Omake_node.DirTable.empty;
venv_excluded_directories = Omake_node.DirSet.empty;
venv_phonies = Omake_node.PreNodeSet.empty;
venv_explicit_rules = [];
venv_explicit_new = [];
venv_explicit_targets = Omake_node.NodeTable.empty;
venv_ordering_rules = [];
venv_orders = Lm_string_set.StringSet.empty;
venv_memo_rules = Omake_value_util.ValueTable.empty;
venv_pervasives_obj = Lm_symbol.SymbolTable.empty;
venv_pervasives_vars = Lm_symbol.SymbolTable.empty;
venv_ir_files = Omake_node.NodeTable.empty;
venv_object_files = Omake_node.NodeTable.empty;
venv_static_values = Omake_node.NodeTable.empty;
venv_modified_values = Omake_node.NodeTable.empty;
venv_target_dirs = Omake_node.DirTable.empty;
venv_target_next_dir = 0;
venv_target_is_buildable = TargetMap.empty;
venv_target_is_buildable_proper = TargetMap.empty
}
in
let inner =
{ venv_dir = cwd;
venv_environ = env;
venv_phony = Omake_node.NodeSet.empty;
venv_implicit_deps = [];
venv_implicit_rules = [];
venv_globals = globals;
venv_options = options;
venv_mount = Omake_node.Mount.empty;
venv_included_files = Omake_node.NodeSet.empty
}
in
let venv =
{ venv_this = Lm_symbol.SymbolTable.empty;
venv_dynamic = Lm_symbol.SymbolTable.empty;
venv_static = Lm_symbol.SymbolTable.empty;
venv_inner = inner
}
in
let venv = venv_add_phony venv (Lm_location.bogus_loc Omake_state.makeroot_name) [TargetString ".PHONY"] in
let venv = venv_add_var venv Omake_var.cwd_var (ValDir cwd) in
let venv = venv_add_var venv Omake_var.stdlib_var (ValDir Omake_node.Dir.lib) in
let venv = venv_add_var venv Omake_var.stdroot_var (ValNode (venv_intern_cd venv PhonyProhibited Omake_node.Dir.lib "OMakeroot")) in
let venv = venv_add_var venv Omake_var.ostype_var (ValString Sys.os_type) in
let venv = venv_add_wild_match venv (ValData Lm_wild.wild_string) in
let omakepath =
try
let path = Lm_string_util.split Lm_filename_util.pathsep (Lm_symbol.SymbolTable.find env Omake_symbol.omakepath_sym) in
List.map (fun s -> Omake_value_type.ValString s) path
with
Not_found ->
[ValString "."; ValDir Omake_node.Dir.lib]
in
let omakepath = Omake_value_type.ValArray omakepath in
let venv = venv_add_var venv Omake_var.omakepath_var omakepath in
let path =
try
let path = Lm_string_util.split Lm_filename_util.pathsep (Lm_symbol.SymbolTable.find env Omake_symbol.path_sym) in
Omake_value_type.ValArray (List.map (fun s -> Omake_value_type.ValData s) path)
with
Not_found ->
Lm_printf.eprintf "*** omake: PATH environment variable is not set!@.";
ValArray []
in
let venv = venv_add_var venv Omake_var.path_var path in
venv
let venv_set_pervasives venv =
let globals = venv.venv_inner.venv_globals in
let obj = venv.venv_dynamic in
let loc = Lm_location.bogus_loc "Pervasives" in
let vars =
Lm_symbol.SymbolTable.fold (fun vars v _ ->
Lm_symbol.SymbolTable.add vars v (Omake_ir.VarVirtual (loc, v))) Lm_symbol.SymbolTable.empty obj
in
globals.venv_pervasives_obj <- venv.venv_dynamic;
globals.venv_pervasives_vars <- vars
let venv_get_pervasives venv node =
let { venv_inner = inner ; _} = venv in
let { venv_environ = env;
venv_options = options;
venv_globals = globals;
_
} = inner
in
let {
venv_pervasives_obj = obj;
_
} = globals
in
let inner =
{ venv_dir = Omake_node.Node.dir node;
venv_environ = env;
venv_phony = Omake_node.NodeSet.empty;
venv_implicit_deps = [];
venv_implicit_rules = [];
venv_globals = globals;
venv_options = options;
venv_mount = Omake_node.Mount.empty;
venv_included_files = Omake_node.NodeSet.empty
}
in
{ venv_this = Lm_symbol.SymbolTable.empty;
venv_dynamic = obj;
venv_static = Lm_symbol.SymbolTable.empty;
venv_inner = inner
}
let venv_fork venv =
let inner = venv.venv_inner in
let globals = inner.venv_globals in
let globals = { globals with
venv_parent = Some(globals, globals.venv_version);
venv_mutex = Lm_thread.Mutex.create "venv_globals";
venv_version = 0;
} in
let inner = { inner with venv_globals = globals } in
{ venv with venv_inner = inner }
let copy_var src_dynamic dst_dynamic v =
try
Lm_symbol.SymbolTable.add dst_dynamic v (Lm_symbol.SymbolTable.find src_dynamic v)
with
Not_found ->
Lm_symbol.SymbolTable.remove dst_dynamic v
let copy_vars dst_dynamic src_dynamic vars =
List.fold_left (copy_var src_dynamic) dst_dynamic vars
let copy_var_list =
Omake_symbol.[stdin_sym; stdout_sym; stderr_sym]
let venv_unfork venv_dst venv_src =
let { venv_dynamic = dst_dynamic;
venv_inner = dst_inner;
_
} = venv_dst
in
let { venv_dynamic = src_dynamic;
venv_inner = src_inner;
_
} = venv_src
in
let inner = { dst_inner with venv_globals = src_inner.venv_globals } in
let dst_dynamic = copy_vars dst_dynamic src_dynamic copy_var_list in
{ venv_dst with venv_dynamic = dst_dynamic;
venv_inner = inner
}
let venv_include_scope venv mode =
match mode with
IncludePervasives ->
venv.venv_inner.venv_globals.venv_pervasives_vars
| IncludeAll ->
let loc = Lm_location.bogus_loc "venv_include_scope" in
let { venv_this = this;
venv_dynamic = dynamic;
_
} = venv
in
let vars = Lm_symbol.SymbolTable.mapi (fun v _ -> Omake_ir.VarThis (loc, v)) this in
let vars = Lm_symbol.SymbolTable.fold
(fun vars v _ -> Lm_symbol.SymbolTable.add vars v (Omake_ir.VarGlobal (loc, v))) vars dynamic in
vars
let venv_is_included_file venv node =
Omake_node.NodeSet.mem venv.venv_inner.venv_included_files node
let venv_add_included_file venv node =
let inner = venv.venv_inner in
let inner = { inner with venv_included_files = Omake_node.NodeSet.add inner.venv_included_files node } in
{ venv with venv_inner = inner }
let venv_exec venv =
venv.venv_inner.venv_globals.venv_exec
let venv_cache venv =
venv.venv_inner.venv_globals.venv_cache
let venv_add_cache venv cache =
let inner = venv.venv_inner in
let globals = inner.venv_globals in
let globals = { globals with venv_cache = cache } in
let inner = { inner with venv_globals = globals } in
{ venv with venv_inner = inner }
* Change directories . Update the CWD var , and all a default
* rule for all the phonies .
* Change directories. Update the CWD var, and all a default
* rule for all the phonies.
*)
let venv_chdir_tmp venv dir =
{ venv with venv_inner = { venv.venv_inner with venv_dir = dir } }
let venv_chdir_dir venv loc dir =
let inner = venv.venv_inner in
let { venv_dir = cwd;
venv_phony = phony;
_
} = inner
in
if Omake_node.Dir.equal dir cwd then
venv
else
let venv = venv_add_var venv Omake_var.cwd_var (ValDir dir) in
let venv = venv_chdir_tmp venv dir in
let globals = venv_globals venv in
let phonies = globals.venv_phonies in
let phony, phonies =
Omake_node.NodeSet.fold (fun (phony, phonies) node ->
let node' = Omake_node.Node.create_phony_chdir node dir in
let phony = Omake_node.NodeSet.add phony node' in
let phonies = Omake_node.PreNodeSet.add phonies (Omake_node.Node.dest node') in
venv_add_explicit_dep venv loc node node';
phony, phonies) (Omake_node.NodeSet.empty, phonies) phony
in
let inner =
{ inner with venv_dir = dir;
venv_phony = phony
}
in
let venv = { venv with venv_inner = inner } in
globals.venv_phonies <- phonies;
venv
let venv_chdir venv loc dir =
let dir = Omake_node.Dir.chdir venv.venv_inner.venv_dir dir in
venv_chdir_dir venv loc dir
let venv_chdir_tmp venv dir =
let cwd = venv.venv_inner.venv_dir in
if Omake_node.Dir.equal dir cwd then
venv
else
let venv = venv_add_var venv Omake_var.cwd_var (ValDir dir) in
venv_chdir_tmp venv dir
let venv_dir venv =
venv.venv_inner.venv_dir
* When an OMakefile in a dir is read , save the venv
* to be used for targets that do not have nay explicit target rule .
* When an OMakefile in a dir is read, save the venv
* to be used for targets that do not have nay explicit target rule.
*)
let venv_add_dir venv =
let globals = venv.venv_inner.venv_globals in
globals.venv_directories <- Omake_node.DirTable.add globals.venv_directories venv.venv_inner.venv_dir venv
let venv_directories venv =
let globals = venv.venv_inner.venv_globals in
Omake_node.DirSet.fold Omake_node.DirTable.remove globals.venv_directories globals.venv_excluded_directories
let venv_add_explicit_dir venv dir =
let globals = venv.venv_inner.venv_globals in
globals.venv_directories <- Omake_node.DirTable.add globals.venv_directories dir venv;
globals.venv_excluded_directories <- Omake_node.DirSet.remove globals.venv_excluded_directories dir
let venv_remove_explicit_dir venv dir =
let globals = venv.venv_inner.venv_globals in
globals.venv_excluded_directories <- Omake_node.DirSet.add globals.venv_excluded_directories dir
let venv_find_target_dir_opt venv target =
let target_dir = Omake_node.Node.dir target in
if Omake_node.Dir.equal venv.venv_inner.venv_dir target_dir then
Some venv
else
try Some (Omake_node.DirTable.find venv.venv_inner.venv_globals.venv_directories target_dir) with
Not_found ->
None
let venv_add_file venv node =
let globals = venv.venv_inner.venv_globals in
globals.venv_files <- Omake_node.NodeSet.add globals.venv_files node;
venv
let venv_files venv =
venv.venv_inner.venv_globals.venv_files
let venv_add_implicit_deps venv pos loc multiple patterns locks sources scanners values =
let pos = Pos.string_pos "venv_add_implicit_deps" pos in
let patterns = List.map (compile_wild_pattern venv pos loc) patterns in
let locks = List.map (compile_source venv) locks in
let sources = List.map (compile_source venv) sources in
let scanners = List.map (compile_source venv) scanners in
let nrule =
{ inrule_loc = loc;
inrule_multiple = multiple;
inrule_patterns = patterns;
inrule_locks = locks;
inrule_sources = sources;
inrule_scanners = scanners;
inrule_values = values
}
in
let venv = { venv with venv_inner = { venv.venv_inner with venv_implicit_deps = nrule :: venv.venv_inner.venv_implicit_deps } } in
venv_flush_target_cache venv;
venv, []
let venv_add_implicit_rule venv loc multiple targets patterns locks sources scanners values body =
let irule =
{ irule_loc = loc;
irule_multiple = multiple;
irule_targets = targets;
irule_patterns = patterns;
irule_locks = locks;
irule_sources = sources;
irule_scanners = scanners;
irule_values = values;
irule_body = body
}
in
let venv = { venv with venv_inner = { venv.venv_inner with venv_implicit_rules = irule :: venv.venv_inner.venv_implicit_rules } } in
venv_flush_target_cache venv;
venv, []
* Add an 2 - place implicit rule .
* Add an 2-place implicit rule.
*)
let venv_add_implicit2_rule venv pos loc multiple patterns locks sources scanners values body =
let pos = Pos.string_pos "venv_add_implicit2_rule" pos in
let patterns = List.map (compile_wild_pattern venv pos loc) patterns in
let locks = List.map (compile_source venv) locks in
let sources = List.map (compile_source venv) sources in
let scanners = List.map (compile_source venv) scanners in
if Lm_debug.debug debug_implicit then
Omake_value_print.pp_print_wild_list patterns
Omake_value_print.pp_print_source_list sources;
venv_add_implicit_rule venv loc multiple None patterns locks sources scanners values body
let venv_add_explicit_rules venv pos loc multiple targets locks sources scanners values body =
let _pos = Pos.string_pos "venv_add_explicit_rules" pos in
let target_args = List.map (venv_intern_rule_target venv multiple) targets in
let lock_args = List.map (intern_source venv) locks in
let source_args = List.map (intern_source venv) sources in
let scanner_args = List.map (intern_source venv) scanners in
let effects = node_set_of_list target_args in
let locks = node_set_of_list lock_args in
let sources = node_set_of_list source_args in
let scanners = node_set_of_list scanner_args in
let commands = make_command_info venv source_args values body in
let add_target target =
{ rule_loc = loc;
rule_env = venv;
rule_target = target;
rule_effects = effects;
rule_locks = locks;
rule_sources = sources;
rule_scanners = scanners;
rule_match = None;
rule_multiple = multiple;
rule_commands = commands
}
in
let rules = List.map add_target target_args in
let names = List.map (fun erule -> erule.rule_target) rules in
venv_save_explicit_rules venv loc rules;
venv, names
* Add a 3 - place rule ( automatically implicit ) .
* Add a 3-place rule (automatically implicit).
*)
let venv_add_implicit3_rule venv pos loc multiple targets locks patterns sources scanners values body =
let pos = Pos.string_pos "venv_add_implicit3_rule" pos in
let patterns = List.map (compile_wild_pattern venv pos loc) patterns in
let locks = List.map (compile_source venv) locks in
let sources = List.map (compile_source venv) sources in
let scanners = List.map (compile_source venv) scanners in
let targets = List.map (compile_implicit3_target pos loc) targets in
let rec check_target target = function
pattern :: patterns ->
begin match Lm_wild.wild_match pattern target with
Some _ -> ()
| None -> check_target target patterns
end
| [] ->
raise (Omake_value_type.OmakeException (Pos.loc_pos loc pos, StringStringError ("bad match", target)))
in
let () = List.iter (fun target -> check_target target patterns) targets in
if Lm_debug.debug debug_implicit then
Omake_node.pp_print_string_list targets
Omake_value_print.pp_print_wild_list patterns
Omake_value_print.pp_print_source_list sources;
venv_add_implicit_rule venv loc multiple (Some (Lm_string_set.StringSet.of_list targets)) patterns locks sources scanners values body
let rec is_implicit loc = function
[] -> false
| [target] -> target_is_wild target
| target :: targets ->
let imp1 = target_is_wild target in
let imp2 = is_implicit loc targets in
if imp1 <> imp2 then
StringError "Rule contains an illegal mixture of implicit (pattern) targets and explicit ones"))
else
imp1
* Figure out what to do based on all the parts .
* A 2 - place rule is implicit if the targets do not contain a % . 3 - place rules are always implicit .
* Figure out what to do based on all the parts.
* A 2-place rule is implicit if the targets do not contain a %. 3-place rules are always implicit.
*)
let venv_add_rule venv pos loc multiple targets patterns locks sources scanners values commands =
let pos = Pos.string_pos "venv_add_rule" pos in
try match targets, patterns, commands with
[], [], _ ->
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, StringError "invalid null rule"))
| _, [], [] ->
if is_implicit loc targets then
venv_add_implicit_deps venv pos loc multiple targets locks sources scanners values
else
venv_add_explicit_rules venv pos loc multiple targets locks sources scanners values commands
| _, [], _ ->
if is_implicit loc targets then
venv_add_implicit2_rule venv pos loc multiple targets locks sources scanners values commands
else
venv_add_explicit_rules venv pos loc multiple targets locks sources scanners values commands
| _ ->
if not (is_implicit loc patterns) then
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, StringError "3-place rule does not contain patterns"))
else
venv_add_implicit3_rule venv pos loc multiple targets locks patterns sources scanners values commands
with
Failure err ->
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, StringError err))
let venv_explicit_flush venv =
let globals = venv.venv_inner.venv_globals in
let { venv_explicit_rules = erules;
venv_explicit_targets = targets;
venv_explicit_new = enew;
_
} = globals
in
if enew <> [] then
let targets, erules =
List.fold_left (fun (targets, erules) erule ->
let erules = erule :: erules in
let targets = Omake_node.NodeTable.add targets erule.rule_target erule in
targets, erules) (targets, erules) (List.rev enew)
in
globals.venv_explicit_new <- [];
globals.venv_explicit_rules <- erules;
globals.venv_explicit_targets <- targets
let venv_explicit_find venv pos target =
venv_explicit_flush venv;
try Omake_node.NodeTable.find venv.venv_inner.venv_globals.venv_explicit_targets target with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringNodeError ("explicit target not found", target)))
let venv_explicit_exists venv target =
venv_explicit_flush venv;
Omake_node.NodeTable.mem venv.venv_inner.venv_globals.venv_explicit_targets target
let multiple_add_error errors target loc1 loc2 =
let table = !errors in
let table =
if Omake_node.NodeMTable.mem table target then
table
else
Omake_node.NodeMTable.add table target loc1
in
errors := Omake_node.NodeMTable.add table target loc2
let multiple_print_error errors buf =
Format.fprintf buf "@[<v 3>Multiple ways to build the following targets";
Omake_node.NodeMTable.iter_all (fun target locs ->
let locs = List.sort Lm_location.compare locs in
Format.fprintf buf "@ @[<v 3>%a:" Omake_node.pp_print_node target;
List.iter (fun loc -> Format.fprintf buf "@ %a" Lm_location.pp_print_location loc) locs;
Format.fprintf buf "@]") errors;
Format.fprintf buf "@]"
let raise_multiple_error errors =
let _, loc = Omake_node.NodeMTable.choose errors in
raise (Omake_value_type.OmakeException (Pos.loc_exp_pos loc, LazyError (multiple_print_error errors)))
let venv_explicit_rules venv =
let errors = ref Omake_node.NodeMTable.empty in
let add_target table target erule =
Omake_node.NodeTable.filter_add table target (fun entry ->
match entry with
Some erule' ->
let multiple = is_multiple_rule erule.rule_multiple in
let multiple' = is_multiple_rule erule'.rule_multiple in
if Omake_node.Node.is_phony target
|| (multiple && multiple')
|| ((not multiple && not multiple')
&& (commands_are_trivial erule.rule_commands || commands_are_trivial erule'.rule_commands))
then
{ erule with rule_commands = erule'.rule_commands @ erule.rule_commands }
else begin
multiple_add_error errors target erule'.rule_loc erule.rule_loc;
erule'
end
| None ->
erule)
in
if not (Omake_node.NodeMTable.is_empty !errors) then
raise_multiple_error !errors
else
let add_deps table target locks sources scanners =
Omake_node.NodeTable.filter_add table target (function
Some (lock_deps, source_deps, scanner_deps) ->
Omake_node.NodeSet.union lock_deps locks, Omake_node.NodeSet.union source_deps sources, Omake_node.NodeSet.union scanner_deps scanners
| None ->
locks, sources, scanners)
in
let info =
{ explicit_targets = Omake_node.NodeTable.empty;
explicit_deps = Omake_node.NodeTable.empty;
explicit_rules = Omake_node.NodeMTable.empty;
explicit_directories = venv_directories venv
}
in
venv_explicit_flush venv;
List.fold_left (fun info erule ->
let { rule_target = target;
rule_locks = locks;
rule_sources = sources;
rule_scanners = scanners;
_
} = erule
in
let target_table = add_target info.explicit_targets target erule in
let dep_table = add_deps info.explicit_deps target locks sources scanners in
{ info with explicit_targets = target_table;
explicit_deps = dep_table;
explicit_rules = Omake_node.NodeMTable.add info.explicit_rules target erule
}) info (List.rev venv.venv_inner.venv_globals.venv_explicit_rules)
let venv_find_implicit_deps_inner venv target =
let target_dir = Omake_node.Node.dir target in
let target_name = Omake_node.Node.tail target in
let is_scanner =
match Omake_node.Node.kind target with
NodeScanner -> Omake_value_type.RuleScanner
| _ -> RuleNormal
in
List.fold_left (fun (lock_deps, source_deps, scanner_deps, value_deps) nrule ->
let { inrule_multiple = multiple;
inrule_patterns = patterns;
inrule_locks = locks;
inrule_sources = sources;
inrule_scanners = scanners;
inrule_values = values;
_
} = nrule
in
if rule_kind multiple = is_scanner then
let rec search patterns =
match patterns with
pattern :: patterns ->
(match Lm_wild.wild_match pattern target_name with
Some subst ->
let lock_deps =
List.fold_left (fun lock_deps source ->
let source = subst_source venv target_dir subst source in
Omake_node.NodeSet.add lock_deps source) lock_deps locks
in
let source_deps =
List.fold_left (fun names source ->
let source = subst_source venv target_dir subst source in
Omake_node.NodeSet.add names source) source_deps sources
in
let scanner_deps =
List.fold_left (fun scanner_deps source ->
let source = subst_source venv target_dir subst source in
Omake_node.NodeSet.add scanner_deps source) scanner_deps scanners
in
let value_deps = values @ value_deps in
lock_deps, source_deps, scanner_deps, value_deps
| None ->
search patterns)
| [] ->
lock_deps, source_deps, scanner_deps, value_deps
in
search patterns
else
(Omake_node.NodeSet.empty, Omake_node.NodeSet.empty, Omake_node.NodeSet.empty, []) venv.venv_inner.venv_implicit_deps
let venv_find_implicit_deps venv target =
match venv_find_target_dir_opt venv target with
Some venv ->
venv_find_implicit_deps_inner venv target
| None ->
Omake_node.NodeSet.empty, Omake_node.NodeSet.empty, Omake_node.NodeSet.empty, []
let venv_find_implicit_rules_inner venv target =
let target_dir = Omake_node.Node.dir target in
let target_name = Omake_node.Node.tail target in
let is_scanner =
match Omake_node.Node.kind target with
NodeScanner -> Omake_value_type.RuleScanner
| _ -> RuleNormal
in
let _ =
if Lm_debug.debug debug_implicit then
Lm_printf.eprintf "Finding implicit rules for %s@." target_name
in
let rec patt_search = function
pattern :: patterns ->
begin match Lm_wild.wild_match pattern target_name with
None -> patt_search patterns
| (Some _) as subst -> subst
end
| [] ->
None
in
let rec collect matched = function
irule :: irules ->
let multiple = irule.irule_multiple in
if rule_kind multiple = is_scanner then
let subst =
if Lm_debug.debug debug_implicit then begin
Lm_printf.eprintf "@[<hv 3>venv_find_implicit_rules: considering implicit rule for@ target = %s:@ " target_name;
begin match irule.irule_targets with
Some targets ->
Lm_printf.eprintf "@[<b 3>3-place targets =%a@]@ " Omake_node.pp_print_string_list (Lm_string_set.StringSet.elements targets)
| None ->
()
end;
Omake_value_print.pp_print_wild_list irule.irule_patterns
Omake_value_print.pp_print_source_list irule.irule_sources
end;
let matches =
match irule.irule_targets with
None -> true
| Some targets -> Lm_string_set.StringSet.mem targets target_name
in
if matches then
patt_search irule.irule_patterns
else
None
in
let matched =
match subst with
Some subst ->
let source_args = List.map (subst_source venv target_dir subst) irule.irule_sources in
let sources = node_set_of_list source_args in
let lock_args = List.map (subst_source venv target_dir subst) irule.irule_locks in
let locks = node_set_of_list lock_args in
let scanner_args = List.map (subst_source venv target_dir subst) irule.irule_scanners in
let scanners = node_set_of_list scanner_args in
let core = Lm_wild.core subst in
let core_val = Omake_value_type.ValData core in
let venv = venv_add_wild_match venv core_val in
let commands = List.map (command_add_wild venv core_val) irule.irule_body in
let commands = make_command_info venv source_args irule.irule_values commands in
let effects =
List.fold_left (fun effects pattern ->
let eff = Lm_wild.subst_in subst pattern in
let eff = venv_intern_rule_target venv multiple (TargetString eff) in
Omake_node.NodeSet.add effects eff) Omake_node.NodeSet.empty irule.irule_patterns
in
let erule =
{ rule_loc = irule.irule_loc;
rule_env = venv;
rule_target = target;
rule_match = Some core;
rule_effects = effects;
rule_locks = locks;
rule_sources = sources;
rule_scanners = scanners;
rule_multiple = multiple;
rule_commands = commands
}
in
if Lm_debug.debug debug_implicit then
target_name pp_print_command_info_list commands;
erule :: matched
| None ->
matched
in
collect matched irules
else
collect matched irules
| [] ->
List.rev matched
in
collect [] venv.venv_inner.venv_implicit_rules
let venv_find_implicit_rules venv target =
match venv_find_target_dir_opt venv target with
Some venv ->
venv_find_implicit_rules_inner venv target
| None ->
[]
let venv_add_orders venv loc targets =
let globals = venv.venv_inner.venv_globals in
let orders =
List.fold_left (fun orders target ->
let name =
match target with
| Omake_value_type.TargetNode _ ->
raise (Omake_value_type.OmakeException
(Pos.loc_exp_pos loc, StringTargetError (".ORDER should be a name", target)))
| TargetString s ->
s
in
Lm_string_set.StringSet.add orders name) globals.venv_orders targets
in
globals.venv_orders <- orders;
venv
let venv_is_order venv name =
Lm_string_set.StringSet.mem venv.venv_inner.venv_globals.venv_orders name
let venv_add_ordering_rule venv pos loc name pattern sources =
let pos = Pos.string_pos "venv_add_ordering_deps" pos in
let pattern = compile_wild_pattern venv pos loc pattern in
let sources = List.map (compile_source_core venv) sources in
let orule =
{ orule_loc = loc;
orule_name = name;
orule_pattern = pattern;
orule_sources = sources
}
in
let globals = venv.venv_inner.venv_globals in
globals.venv_ordering_rules <- orule :: globals.venv_ordering_rules;
venv
let venv_get_ordering_info venv name =
List.fold_left (fun orules orule ->
if Lm_symbol.eq orule.orule_name name then
orule :: orules
else
orules) [] venv.venv_inner.venv_globals.venv_ordering_rules
let venv_get_ordering_deps venv orules deps =
let step deps =
Omake_node.NodeSet.fold (fun deps dep ->
let target_dir = Omake_node.Node.dir dep in
let target_str = Omake_node.Node.tail dep in
List.fold_left (fun deps orule ->
let { orule_pattern = pattern;
orule_sources = sources;
_
} = orule
in
match Lm_wild.wild_match pattern target_str with
Some subst ->
List.fold_left (fun deps source ->
let source = subst_source_core venv target_dir subst source in
Omake_node.NodeSet.add deps source) deps sources
| None ->
deps) deps orules) deps deps
in
let rec fixpoint deps =
let deps' = step deps in
if Omake_node.NodeSet.cardinal deps' = Omake_node.NodeSet.cardinal deps then
deps
else
fixpoint deps'
in
fixpoint deps
let venv_add_memo_rule venv _pos loc _multiple is_static key vars sources values body =
let source_args = List.map (intern_source venv) sources in
let sources = node_set_of_list source_args in
let srule =
{ srule_loc = loc;
srule_static = is_static;
srule_env = venv;
srule_key = key;
srule_deps = sources;
srule_vals = values;
srule_exp = body
}
in
let globals = venv_globals venv in
let venv =
List.fold_left (fun venv info ->
let _, v = Omake_ir_util.var_of_var_info info in
venv_add_var venv info (ValDelayed (ref (Omake_value_type.ValStaticApply (key, v))))) venv vars
in
globals.venv_memo_rules <- Omake_value_util.ValueTable.add globals.venv_memo_rules key (StaticRule srule);
venv
let venv_set_static_info venv key v =
let globals = venv_globals venv in
globals.venv_memo_rules <- Omake_value_util.ValueTable.add globals.venv_memo_rules key v
let venv_find_static_info venv pos key =
try Omake_value_util.ValueTable.find venv.venv_inner.venv_globals.venv_memo_rules key with
Not_found ->
raise (Omake_value_type.OmakeException (pos, StringValueError ("Static section not defined", key)))
* Export an item from one environment to another .
* Export an item from one environment to another.
*)
let copy_var pos dst src v =
try Lm_symbol.SymbolTable.add dst v (Lm_symbol.SymbolTable.find src v) with
Not_found ->
raise (Omake_value_type.OmakeException (pos, UnboundVar v))
let export_item pos venv_dst venv_src = function
| Omake_ir.ExportVar (VarPrivate (_, v)) ->
{ venv_dst with venv_static = copy_var pos venv_dst.venv_static venv_src.venv_static v }
| ExportVar (VarThis (_, v)) ->
{ venv_dst with venv_this = copy_var pos venv_dst.venv_this venv_src.venv_this v }
| ExportVar (VarVirtual (_, v)) ->
{ venv_dst with venv_dynamic = copy_var pos venv_dst.venv_dynamic venv_src.venv_dynamic v }
| ExportVar (VarGlobal (_, v)) ->
let { venv_dynamic = dynamic_src;
venv_static = static_src;
venv_this = this_src;
_
} = venv_src
in
let { venv_dynamic = dynamic_dst;
venv_static = static_dst;
venv_this = this_dst;
_
} = venv_dst
in
let dynamic, found =
try Lm_symbol.SymbolTable.add dynamic_dst v (Lm_symbol.SymbolTable.find dynamic_src v), true with
Not_found ->
dynamic_dst, false
in
let static, found =
try Lm_symbol.SymbolTable.add static_dst v (Lm_symbol.SymbolTable.find static_src v), true with
Not_found ->
static_dst, found
in
let this, found =
try Lm_symbol.SymbolTable.add this_dst v (Lm_symbol.SymbolTable.find this_src v), true with
Not_found ->
this_dst, found
in
if not found then
raise (Omake_value_type.OmakeException (pos, UnboundVar v));
{ venv_dst with venv_dynamic = dynamic;
venv_static = static;
venv_this = this
}
| ExportRules ->
let inner_src = venv_src.venv_inner in
let inner_dst =
{ venv_dst.venv_inner with
venv_implicit_deps = inner_src.venv_implicit_deps;
venv_implicit_rules = inner_src.venv_implicit_rules;
}
in
{ venv_dst with venv_inner = inner_dst }
| ExportPhonies ->
let inner_dst = { venv_dst.venv_inner with venv_phony = venv_src.venv_inner.venv_phony } in
{ venv_dst with venv_inner = inner_dst }
let export_list pos venv_dst venv_src vars =
List.fold_left (fun venv_dst v ->
export_item pos venv_dst venv_src v) venv_dst vars
* Exported environment does not include static values .
*
* We want to preserve pointer equality on venv2 to avoid giving unnecessary
* " these files are targeted separately , but appear as effects of a single rule "
* warnings .
* Exported environment does not include static values.
*
* We want to preserve pointer equality on venv2 to avoid giving unnecessary
* "these files are targeted separately, but appear as effects of a single rule"
* warnings.
*)
let venv_export_venv venv1 venv2 =
if venv1.venv_static == venv2.venv_static then
venv2
else
{ venv2 with venv_static = venv1.venv_static }
let add_exports venv_dst venv_src pos = function
|Omake_ir.ExportNone ->
venv_dst
| ExportAll ->
venv_export_venv venv_dst venv_src
| ExportList vars ->
export_list pos venv_dst venv_src vars
* venv_orig - environment before the function call .
* venv_dst - environment after " entering " the object namespace , before the function call
* venv_src - environment after the function call
*
* # venv_orig is here
* A.B.C.f(1 )
* # venv_dst is venv_orig with this = * # venv_src is venv when A.B.C.f returns
*
* 1 . export from venv_src into venv_dst
* 2 . take venv_orig.venv_this
* 3 . update along the path
* venv_orig - environment before the function call.
* venv_dst - environment after "entering" the object namespace, before the function call
* venv_src - environment after the function call
*
* # venv_orig is here
* A.B.C.f(1)
* # venv_dst is venv_orig with this = A.B.C
* # venv_src is venv when A.B.C.f returns
*
* 1. export from venv_src into venv_dst
* 2. take venv_orig.venv_this
* 3. update along the path A.B.C
*)
let rec hoist_path venv path obj =
match path with
| Omake_value_type.PathVar v ->
venv_add_var venv v (ValObject obj)
| PathField (path, parent_obj, v) ->
let obj = Lm_symbol.SymbolTable.add parent_obj v (ValObject obj) in
hoist_path venv path obj
let hoist_this venv_orig venv_obj path =
let venv = { venv_obj with venv_this = venv_orig.venv_this } in
hoist_path venv path venv_obj.venv_this
let add_path_exports venv_orig venv_dst venv_src pos path ( x : Omake_ir.export) =
match x with
| ExportNone ->
venv_orig
| ExportAll ->
hoist_this venv_orig (venv_export_venv venv_dst venv_src) path
| ExportList vars ->
hoist_this venv_orig (export_list pos venv_dst venv_src vars) path
let squash_prim_fun f =
f
let squash_object obj =
obj
|
20f77952838958146a1786d1a958bf489f91c14634652f246cc15e53ce14d59d | theleoborges/imminent | core.clj | (require '[imminent.core :as immi]
'[imminent.executors :as executors]
'[imminent.util.monad :as monad])
(def repl-out *out*)
(defn prn-to-repl [& args]
(binding [*out* repl-out]
(apply prn args)))
(comment
(def ma (const-future 10))
(defn fmb [n]
(const-future (* 2 n)))
(bind ma fmb)
)
(comment
(binding [executors/*executor* executors/blocking-executor])
(def f1 (future (fn []
(Thread/sleep 5000)
(prn-to-repl (.getId (Thread/currentThread)))
"3")))
(def f2 (map f1 (fn [x]
(prn-to-repl (.getId (Thread/currentThread)))
(read-string x))))
(def f3 (filter f2 (fn [x]
(prn-to-repl (.getId (Thread/currentThread)))
(even? x))))
)
(comment
(def p (promise))
(def f (->future p))
(complete p (success 10))
(on-success f (fn [v]
(prn-to-repl "got stuff" v)))
)
(comment
(def p1 (promise))
(def f1 (->future p1))
(complete p1 (success 10))
@f1
(on-success f1 (fn [v]
(prn "hmm")
(prn-to-repl "got stuff" v)))
(on-failure f1 (fn [v]
(prn "hmm")
(prn-to-repl "got stuff" v)))
(def f2 (failed-future (Exception. "")))
(on-success f2 (fn [v]
(prn "hmm")
(prn-to-repl "got stuff on succ" v)))
(on-failure f2 (fn [v]
(prn "hmm")
(prn-to-repl "got stuff" v)))
)
(comment
(let [tasks [(immi/const-future 10)
(immi/const-future 20)
(immi/const-future 30)]]
(-> (immi/sequence tasks)
(immi/map (fn [xs]
(prn-to-repl xs)))))
)
(comment
(binding [executors/*executor* executors/blocking-executor]
(monad/fold-m future-monad
(fn [a mb]
((:bind future-monad) mb (fn [b]
(const-future (conj a b)))))
[]
[(const-future 20) (const-future 30)]))
(binding [executors/*executor* executors/blocking-executor]
(monad/fold-m future-monad
(fn [a mb]
((:bind future-monad) mb (fn [b]
(prn "got" b)
(const-future (conj a b)))))
[]
[(const-future 20) (failed-future (Exception. "error")) (const-future 30)]))
(binding [executors/*executor* executors/blocking-executor]
(reduce + 0 [(const-future 20) (const-future 30)]))
(binding [executors/*executor* executors/blocking-executor]
(reduce + 0 [(const-future 20) (failed-future (Exception. "error")) (const-future 30)]))
)
(comment
(def sleepy (future (fn []
(Thread/sleep 5000)
(prn-to-repl "awaking...")
57)))
(prn-to-repl @(await sleepy))
(prn-to-repl "finished")
(binding [executors/*executor* executors/blocking-executor]
(map const-future [1 2 3]))
(def ^:dynamic *myvalue* "leo")
(binding [*myvalue* "enif"]
(prn-to-repl "value is " *myvalue*)
(let [tasks (repeat 3 (fn []
(Thread/sleep 1000)
(prn-to-repl "id " (.getId (Thread/currentThread)))
(prn-to-repl "the name i have is " *myvalue*)))
conveyed (clojure.core/map #'clojure.core/binding-conveyor-fn tasks)
fs (clojure.core/map future-call conveyed)]
(prn-to-repl "doing...")
(await (sequence fs))
(prn-to-repl "done")))
)
(comment
;; README examples...
(require '[imminent.core :as immi] :reload)
(def future-result
(->> (repeat 3 (fn []
(Thread/sleep 1000)
creates 3 " expensive " computations
(map immi/future) ;; dispatches the computations in parallel
(immi/reduce + 0))) ;; reduces over the futures
(immi/map future-result prn)
(prn "I don't block and can go about my business while I wait...")
(def result (imminent.core.Success. 10))
100
# imminent.core . Success{:v 100 }
(def result (imminent.core.Failure. "Oops!"))
(* 10 @result) ;; ClassCastException java.lang.String cannot be cast to java.lang.Number
(immi/map result #(* 10 %)) ;; #imminent.core.Failure{:e "Oops!"}
(immi/map-failure result (fn [e] (prn "the error is" e))) ;; "the error is" "Oops!"
# < Future@37c26da0 : # imminent.core . Success{:v 10 } >
(immi/future (fn []
(Thread/sleep 1000)
;; doing something important...
"done.")) ;; #<Future@79d009ff: :imminent.core/unresolved>
(-> (immi/const-future 10)
(immi/map #(* % %)))
# < Future@34edb5aa : # imminent.core . Success{:v 100 } >
(-> (immi/const-future 10)
(immi/filter odd?))
;; #<Future@1c6b016: #imminent.core.Failure{:e #<NoSuchElementException java.util.NoSuchElementException: Failed predicate>}>
(-> (immi/const-future 10)
(immi/bind (fn [n] (immi/const-future (* n n)))))
# < Future@3603dd0a : # imminent.core . Success{:v 100 } >
(-> (immi/const-future 10)
(immi/flatmap (fn [n] (immi/const-future (* n n)))))
# < Future@2385558 : # imminent.core . Success{:v 100 } >
(defn f-double [n]
;; expensive computation here...
(immi/const-future (* n 2)))
(defn f-square [n]
;; expensive computation here...
(immi/const-future (* n n)))
(defn f-range [n]
;; expensive computation here...
(immi/const-future (range n)))
(prefer-method print-method clojure.lang.IDeref clojure.lang.IRecord)
(def x (immi/flatmap (immi/const-future 1)
(fn [m]
(immi/flatmap (f-double m)
(fn [n]
(immi/flatmap (f-square n)
f-range))))))
x ;; #<Future@42f92dbc: #<Success@7529b3fd: (0 1 2 3)>>
(def x (immi/mdo [a (immi/const-future 1)
b (f-double a)
o (f-square b)]
(f-range o)))
x ;; #<Future@76150f6f: #<Success@60a87cf9: (0 1 2 3)>>
(-> [(immi/const-future 10) (immi/const-future 20) (immi/const-future 30)]
immi/sequence)
# < Future@32afbbca : # imminent.core . Success{:v [ 10 20 30 ] } >
(-> [(immi/const-future 10) (immi/failed-future "Oops") (immi/const-future 30)]
immi/sequence)
;; #<Future@254acc8e: #imminent.core.Failure{:e "Oops"}>
(->> [(immi/const-future 10) (immi/const-future 20) (immi/const-future 30)]
(immi/reduce + 0))
# < Future@36783858 : # imminent.core . Success{:v 60 } >
(def f (fn [n] (immi/future (fn []
(* n n)))))
(immi/map-future f [1 2 3])
# < Future@69176437 : # imminent.core . Success{:v [ 1 4 9 ] } >
(def result (->> (repeat 3 (fn []
(Thread/sleep 1000)
10))
(map immi/future)
(immi/reduce + 0)))
(immi/await result)
(immi/await (immi/future (fn []
(Thread/sleep 5000)))
waits for 500 ms at most
(binding [executors/*executor* executors/blocking-executor]
(-> (immi/future (fn []
(Thread/sleep 5000)
41))
(immi/map inc))) ;; Automatically blocks here, without the need for `await`
# < Future@ac1c71d : # imminent.core . Success{:v 42 } >
(-> (immi/const-future 42)
(immi/on-complete prn))
(-> (immi/const-future 42)
(immi/on-complete #(match [%]
[{Success v}] (prn "success: " v)
[{Failure e}] (prn "failure: " e))))
" success : " 42
# imminent.core . Success{:v 42 }
(-> (immi/const-future 42)
(immi/on-success prn))
42
(-> (immi/failed-future "Error")
(immi/on-failure prn))
;; "Error"
(def plus (immi/curry + 4))
(defn int-f [n]
(immi/future (do (Thread/sleep 2000)
n)))
(time
(-> (immi/bind
(int-f 10)
(fn [a] (immi/bind
(int-f 20)
(fn [b] (immi/bind
(int-f 30)
(fn [c] (immi/pure immi/m-ctx (+ a b c))))))))
immi/await
immi/dderef))
;; "Elapsed time: 6002.731 msecs"
(time
(-> (immi/mdo [a (int-f 10)
b (int-f 20)
c (int-f 30)]
(immi/pure immi/m-ctx (+ a b c)))
immi/await
immi/dderef))
" Elapsed time : 6002.39 msecs "
(time
(-> (immi/<*> (immi/map (int-f 10) plus)
(int-f 20)
(int-f 30))
(immi/await 10000)
immi/dderef))
" Elapsed time : 2001.509 msecs "
(require '[imminent.util.applicative :as ap] :reload)
(time (-> ((immi/alift +) (int-f 10) (int-f 20) (int-f 30))
(immi/await 10000)
immi/dderef))
" Elapsed time : 2003.663 msecs "
(time
(-> (immi/sequence [(int-f 10) (int-f 20) (int-f 30) (int-f 40)])
(immi/map #(apply + %))
(immi/await 10000)
immi/dderef))
(->> (repeat 3 (fn []
(Thread/sleep 1000)
10))
creates 3 " expensive " computations
(map immi/blocking-future-call)
;; dispatches the computations in parallel,
;; indicating they might block
(immi/reduce + 0))
# < Future@1d4ed70 : # < Success@34dda2f6 : 30 > >
;; amb
(defmacro sleepy-future [ms & body]
`(immi/future
(Thread/sleep ~ms)
~@body))
(macroexpand ')
(-> (immi/amb (sleepy-future 100 10)
(sleepy-future 100 10)
(sleepy-future 10 20)
(sleepy-future 100 10))
(immi/await 200)
deref)
# object[imminent.result . Success 0x6e6bdd39 { : status : ready , : 20 } ]
(-> (immi/amb (sleepy-future 100 10)
(sleepy-future 100 10)
(immi/failed-future (Exception.))
(sleepy-future 100 10))
(immi/await 200)
deref)
# object[imminent.result . Failure 0x2139777b { ... : val # error{:cause nil , : via [ { : type java.lang . Exception , : message nil } ] ... } ... }
(-> (immi/sequence [(int-f 10) (int-f 20) (int-f 30) (int-f 40)])
(immi/map #(apply + %))
(immi/await 10000)
immi/dderef)
)
(comment
;; blocking futures
(def result (atom nil))
(dispatch-blocking (fn []
(reset! result 178)))
(binding [*executor* blocking-executor]
(dispatch-blocking (fn []
(reset! result 400))))
(def f1 )
(def f2 (immi/map f1 (fn [x]
(prn-to-repl (.getId (Thread/currentThread)))
(read-string x))))
(def f3 (immi/filter f2 (fn [x]
(prn-to-repl (.getId (Thread/currentThread)))
(even? x))))
(import '[java.util.concurrent
Executor ForkJoinPool ForkJoinPool$ManagedBlocker ForkJoinTask])
(def ex (java.util.concurrent.ForkJoinPool. 2))
(defn factorial [n]
(reduce *' (range 2 (inc n))))
(binding [executors/*executor* ex]
(time
doing some expensive IO
(Thread/sleep 10000))
doing some expensive IO
(Thread/sleep 10000))
doing some expensive IO
(Thread/sleep 10000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
]]
(-> tasks
immi/sequence
immi/await
)
nil)))
~ 20 secs
~ 27 secs
parallelism - 2
;; size - 2
(binding [executors/*executor* ex]
(time
doing some expensive IO
(Thread/sleep 10000))
doing some expensive IO
(Thread/sleep 10000))
doing some expensive IO
(Thread/sleep 10000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
]]
(-> tasks
immi/sequence
immi/await)
nil)))
~ 10 secs
~ 15 secs
parallelism - 2
;; size - 4
(time
(factorial 100000))
(dotimes [_ 5]
(time
(dotimes [_ 1]
(factorial 100000))))
)
| null | https://raw.githubusercontent.com/theleoborges/imminent/9429072dc2b46d2e23cb64992e40faa682c7eb47/examples/core.clj | clojure | README examples...
dispatches the computations in parallel
reduces over the futures
ClassCastException java.lang.String cannot be cast to java.lang.Number
#imminent.core.Failure{:e "Oops!"}
"the error is" "Oops!"
doing something important...
#<Future@79d009ff: :imminent.core/unresolved>
#<Future@1c6b016: #imminent.core.Failure{:e #<NoSuchElementException java.util.NoSuchElementException: Failed predicate>}>
expensive computation here...
expensive computation here...
expensive computation here...
#<Future@42f92dbc: #<Success@7529b3fd: (0 1 2 3)>>
#<Future@76150f6f: #<Success@60a87cf9: (0 1 2 3)>>
#<Future@254acc8e: #imminent.core.Failure{:e "Oops"}>
Automatically blocks here, without the need for `await`
"Error"
"Elapsed time: 6002.731 msecs"
dispatches the computations in parallel,
indicating they might block
amb
blocking futures
size - 2
size - 4 | (require '[imminent.core :as immi]
'[imminent.executors :as executors]
'[imminent.util.monad :as monad])
(def repl-out *out*)
(defn prn-to-repl [& args]
(binding [*out* repl-out]
(apply prn args)))
(comment
(def ma (const-future 10))
(defn fmb [n]
(const-future (* 2 n)))
(bind ma fmb)
)
(comment
(binding [executors/*executor* executors/blocking-executor])
(def f1 (future (fn []
(Thread/sleep 5000)
(prn-to-repl (.getId (Thread/currentThread)))
"3")))
(def f2 (map f1 (fn [x]
(prn-to-repl (.getId (Thread/currentThread)))
(read-string x))))
(def f3 (filter f2 (fn [x]
(prn-to-repl (.getId (Thread/currentThread)))
(even? x))))
)
(comment
(def p (promise))
(def f (->future p))
(complete p (success 10))
(on-success f (fn [v]
(prn-to-repl "got stuff" v)))
)
(comment
(def p1 (promise))
(def f1 (->future p1))
(complete p1 (success 10))
@f1
(on-success f1 (fn [v]
(prn "hmm")
(prn-to-repl "got stuff" v)))
(on-failure f1 (fn [v]
(prn "hmm")
(prn-to-repl "got stuff" v)))
(def f2 (failed-future (Exception. "")))
(on-success f2 (fn [v]
(prn "hmm")
(prn-to-repl "got stuff on succ" v)))
(on-failure f2 (fn [v]
(prn "hmm")
(prn-to-repl "got stuff" v)))
)
(comment
(let [tasks [(immi/const-future 10)
(immi/const-future 20)
(immi/const-future 30)]]
(-> (immi/sequence tasks)
(immi/map (fn [xs]
(prn-to-repl xs)))))
)
(comment
(binding [executors/*executor* executors/blocking-executor]
(monad/fold-m future-monad
(fn [a mb]
((:bind future-monad) mb (fn [b]
(const-future (conj a b)))))
[]
[(const-future 20) (const-future 30)]))
(binding [executors/*executor* executors/blocking-executor]
(monad/fold-m future-monad
(fn [a mb]
((:bind future-monad) mb (fn [b]
(prn "got" b)
(const-future (conj a b)))))
[]
[(const-future 20) (failed-future (Exception. "error")) (const-future 30)]))
(binding [executors/*executor* executors/blocking-executor]
(reduce + 0 [(const-future 20) (const-future 30)]))
(binding [executors/*executor* executors/blocking-executor]
(reduce + 0 [(const-future 20) (failed-future (Exception. "error")) (const-future 30)]))
)
(comment
(def sleepy (future (fn []
(Thread/sleep 5000)
(prn-to-repl "awaking...")
57)))
(prn-to-repl @(await sleepy))
(prn-to-repl "finished")
(binding [executors/*executor* executors/blocking-executor]
(map const-future [1 2 3]))
(def ^:dynamic *myvalue* "leo")
(binding [*myvalue* "enif"]
(prn-to-repl "value is " *myvalue*)
(let [tasks (repeat 3 (fn []
(Thread/sleep 1000)
(prn-to-repl "id " (.getId (Thread/currentThread)))
(prn-to-repl "the name i have is " *myvalue*)))
conveyed (clojure.core/map #'clojure.core/binding-conveyor-fn tasks)
fs (clojure.core/map future-call conveyed)]
(prn-to-repl "doing...")
(await (sequence fs))
(prn-to-repl "done")))
)
(comment
(require '[imminent.core :as immi] :reload)
(def future-result
(->> (repeat 3 (fn []
(Thread/sleep 1000)
creates 3 " expensive " computations
(immi/map future-result prn)
(prn "I don't block and can go about my business while I wait...")
(def result (imminent.core.Success. 10))
100
# imminent.core . Success{:v 100 }
(def result (imminent.core.Failure. "Oops!"))
# < Future@37c26da0 : # imminent.core . Success{:v 10 } >
(immi/future (fn []
(Thread/sleep 1000)
(-> (immi/const-future 10)
(immi/map #(* % %)))
# < Future@34edb5aa : # imminent.core . Success{:v 100 } >
(-> (immi/const-future 10)
(immi/filter odd?))
(-> (immi/const-future 10)
(immi/bind (fn [n] (immi/const-future (* n n)))))
# < Future@3603dd0a : # imminent.core . Success{:v 100 } >
(-> (immi/const-future 10)
(immi/flatmap (fn [n] (immi/const-future (* n n)))))
# < Future@2385558 : # imminent.core . Success{:v 100 } >
(defn f-double [n]
(immi/const-future (* n 2)))
(defn f-square [n]
(immi/const-future (* n n)))
(defn f-range [n]
(immi/const-future (range n)))
(prefer-method print-method clojure.lang.IDeref clojure.lang.IRecord)
(def x (immi/flatmap (immi/const-future 1)
(fn [m]
(immi/flatmap (f-double m)
(fn [n]
(immi/flatmap (f-square n)
f-range))))))
(def x (immi/mdo [a (immi/const-future 1)
b (f-double a)
o (f-square b)]
(f-range o)))
(-> [(immi/const-future 10) (immi/const-future 20) (immi/const-future 30)]
immi/sequence)
# < Future@32afbbca : # imminent.core . Success{:v [ 10 20 30 ] } >
(-> [(immi/const-future 10) (immi/failed-future "Oops") (immi/const-future 30)]
immi/sequence)
(->> [(immi/const-future 10) (immi/const-future 20) (immi/const-future 30)]
(immi/reduce + 0))
# < Future@36783858 : # imminent.core . Success{:v 60 } >
(def f (fn [n] (immi/future (fn []
(* n n)))))
(immi/map-future f [1 2 3])
# < Future@69176437 : # imminent.core . Success{:v [ 1 4 9 ] } >
(def result (->> (repeat 3 (fn []
(Thread/sleep 1000)
10))
(map immi/future)
(immi/reduce + 0)))
(immi/await result)
(immi/await (immi/future (fn []
(Thread/sleep 5000)))
waits for 500 ms at most
(binding [executors/*executor* executors/blocking-executor]
(-> (immi/future (fn []
(Thread/sleep 5000)
41))
# < Future@ac1c71d : # imminent.core . Success{:v 42 } >
(-> (immi/const-future 42)
(immi/on-complete prn))
(-> (immi/const-future 42)
(immi/on-complete #(match [%]
[{Success v}] (prn "success: " v)
[{Failure e}] (prn "failure: " e))))
" success : " 42
# imminent.core . Success{:v 42 }
(-> (immi/const-future 42)
(immi/on-success prn))
42
(-> (immi/failed-future "Error")
(immi/on-failure prn))
(def plus (immi/curry + 4))
(defn int-f [n]
(immi/future (do (Thread/sleep 2000)
n)))
(time
(-> (immi/bind
(int-f 10)
(fn [a] (immi/bind
(int-f 20)
(fn [b] (immi/bind
(int-f 30)
(fn [c] (immi/pure immi/m-ctx (+ a b c))))))))
immi/await
immi/dderef))
(time
(-> (immi/mdo [a (int-f 10)
b (int-f 20)
c (int-f 30)]
(immi/pure immi/m-ctx (+ a b c)))
immi/await
immi/dderef))
" Elapsed time : 6002.39 msecs "
(time
(-> (immi/<*> (immi/map (int-f 10) plus)
(int-f 20)
(int-f 30))
(immi/await 10000)
immi/dderef))
" Elapsed time : 2001.509 msecs "
(require '[imminent.util.applicative :as ap] :reload)
(time (-> ((immi/alift +) (int-f 10) (int-f 20) (int-f 30))
(immi/await 10000)
immi/dderef))
" Elapsed time : 2003.663 msecs "
(time
(-> (immi/sequence [(int-f 10) (int-f 20) (int-f 30) (int-f 40)])
(immi/map #(apply + %))
(immi/await 10000)
immi/dderef))
(->> (repeat 3 (fn []
(Thread/sleep 1000)
10))
creates 3 " expensive " computations
(map immi/blocking-future-call)
(immi/reduce + 0))
# < Future@1d4ed70 : # < Success@34dda2f6 : 30 > >
(defmacro sleepy-future [ms & body]
`(immi/future
(Thread/sleep ~ms)
~@body))
(macroexpand ')
(-> (immi/amb (sleepy-future 100 10)
(sleepy-future 100 10)
(sleepy-future 10 20)
(sleepy-future 100 10))
(immi/await 200)
deref)
# object[imminent.result . Success 0x6e6bdd39 { : status : ready , : 20 } ]
(-> (immi/amb (sleepy-future 100 10)
(sleepy-future 100 10)
(immi/failed-future (Exception.))
(sleepy-future 100 10))
(immi/await 200)
deref)
# object[imminent.result . Failure 0x2139777b { ... : val # error{:cause nil , : via [ { : type java.lang . Exception , : message nil } ] ... } ... }
(-> (immi/sequence [(int-f 10) (int-f 20) (int-f 30) (int-f 40)])
(immi/map #(apply + %))
(immi/await 10000)
immi/dderef)
)
(comment
(def result (atom nil))
(dispatch-blocking (fn []
(reset! result 178)))
(binding [*executor* blocking-executor]
(dispatch-blocking (fn []
(reset! result 400))))
(def f1 )
(def f2 (immi/map f1 (fn [x]
(prn-to-repl (.getId (Thread/currentThread)))
(read-string x))))
(def f3 (immi/filter f2 (fn [x]
(prn-to-repl (.getId (Thread/currentThread)))
(even? x))))
(import '[java.util.concurrent
Executor ForkJoinPool ForkJoinPool$ManagedBlocker ForkJoinTask])
(def ex (java.util.concurrent.ForkJoinPool. 2))
(defn factorial [n]
(reduce *' (range 2 (inc n))))
(binding [executors/*executor* ex]
(time
doing some expensive IO
(Thread/sleep 10000))
doing some expensive IO
(Thread/sleep 10000))
doing some expensive IO
(Thread/sleep 10000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
]]
(-> tasks
immi/sequence
immi/await
)
nil)))
~ 20 secs
~ 27 secs
parallelism - 2
(binding [executors/*executor* ex]
(time
doing some expensive IO
(Thread/sleep 10000))
doing some expensive IO
(Thread/sleep 10000))
doing some expensive IO
(Thread/sleep 10000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
(immi/future (factorial 100000))
]]
(-> tasks
immi/sequence
immi/await)
nil)))
~ 10 secs
~ 15 secs
parallelism - 2
(time
(factorial 100000))
(dotimes [_ 5]
(time
(dotimes [_ 1]
(factorial 100000))))
)
|
bcd901fa2a3421aeff0ad7370b0ae841f2953cd43597c2e4b18ed4c770d51ce9 | reborg/clojure-essential-reference | 1.clj | (require '[clojure.repl :refer [source]])
(require '[clojure.string :as s])
< 1 >
< 2 >
with-out-str ; <3>
< 4 >
println)
( DEFN SOME ? ; < 5 >
;; "RETURNS TRUE IF X IS NOT NIL, FALSE OTHERWISE."
{ : TAG BOOLEAN
: ADDED " 1.6 "
;; :STATIC TRUE}
;; [X] (NOT (NIL? X))) | null | https://raw.githubusercontent.com/reborg/clojure-essential-reference/c37fa19d45dd52b2995a191e3e96f0ebdc3f6d69/StringsandRegularExpressions/lower-case%2Cupper-case%2Ccapitalize/1.clj | clojure | <3>
< 5 >
"RETURNS TRUE IF X IS NOT NIL, FALSE OTHERWISE."
:STATIC TRUE}
[X] (NOT (NIL? X))) | (require '[clojure.repl :refer [source]])
(require '[clojure.string :as s])
< 1 >
< 2 >
< 4 >
println)
{ : TAG BOOLEAN
: ADDED " 1.6 " |
9c29e4ea071a09746116f64e89bacf83da242c5b19288c3a7264b64b487c0b9f | spectrum-finance/cardano-dex-backend | Process.hs | module Spectrum.Executor.PoolTracker.Process
( PoolTracker(..)
, mkPoolTracker
) where
import qualified Streamly.Prelude as S
import Streamly.Prelude
( IsStream )
import Control.Monad.IO.Class
( MonadIO )
import Control.Monad.Trans.Control
( MonadBaseControl )
import Control.Monad.Catch
( MonadThrow )
import Spectrum.Executor.Data.State
( Confirmed, Unconfirmed )
import Spectrum.Executor.Topic
( ReadTopic(..) )
import Spectrum.Executor.Data.PoolState
( NewPool(..), DiscardedPool(..) )
import Spectrum.Executor.PoolTracker.Persistence.Pools
( Pools(..) )
newtype PoolTracker s m = PoolTracker
{ run :: s m ()
}
mkPoolTracker
:: ( IsStream s
, Monad (s m)
, MonadIO m
, MonadBaseControl IO m
, MonadThrow m
)
=> Pools m
-> ReadTopic s m (NewPool Confirmed)
-> ReadTopic s m (NewPool Unconfirmed)
-> ReadTopic s m DiscardedPool
-> PoolTracker s m
mkPoolTracker pools conf unconf discarded =
PoolTracker $
S.parallel (trackConfirmedPoolUpdates pools conf) $
S.parallel (trackUnconfirmedPoolUpdates pools unconf) $
handlePoolRollbacks pools discarded
trackConfirmedPoolUpdates
:: (IsStream s, Monad (s m), Monad m)
=> Pools m
-> ReadTopic s m (NewPool Confirmed)
-> s m ()
trackConfirmedPoolUpdates Pools{..} ReadTopic{..} = do
NewPool pool <- upstream
S.fromEffect $ putConfirmed pool
trackUnconfirmedPoolUpdates
:: (IsStream s, Monad (s m), Monad m)
=> Pools m
-> ReadTopic s m (NewPool Unconfirmed)
-> s m ()
trackUnconfirmedPoolUpdates Pools{..} ReadTopic{..} = do
NewPool pool <- upstream
S.fromEffect $ putUnconfirmed pool
handlePoolRollbacks
:: (IsStream s, Monad (s m), Monad m)
=> Pools m
-> ReadTopic s m DiscardedPool
-> s m ()
handlePoolRollbacks Pools{..} ReadTopic{..} = do
DiscardedPool pid sid <- upstream
S.fromEffect $ invalidate pid sid
| null | https://raw.githubusercontent.com/spectrum-finance/cardano-dex-backend/47528f6a43124ab4f6849521d61dbb3fad476c19/amm-executor/src/Spectrum/Executor/PoolTracker/Process.hs | haskell | module Spectrum.Executor.PoolTracker.Process
( PoolTracker(..)
, mkPoolTracker
) where
import qualified Streamly.Prelude as S
import Streamly.Prelude
( IsStream )
import Control.Monad.IO.Class
( MonadIO )
import Control.Monad.Trans.Control
( MonadBaseControl )
import Control.Monad.Catch
( MonadThrow )
import Spectrum.Executor.Data.State
( Confirmed, Unconfirmed )
import Spectrum.Executor.Topic
( ReadTopic(..) )
import Spectrum.Executor.Data.PoolState
( NewPool(..), DiscardedPool(..) )
import Spectrum.Executor.PoolTracker.Persistence.Pools
( Pools(..) )
newtype PoolTracker s m = PoolTracker
{ run :: s m ()
}
mkPoolTracker
:: ( IsStream s
, Monad (s m)
, MonadIO m
, MonadBaseControl IO m
, MonadThrow m
)
=> Pools m
-> ReadTopic s m (NewPool Confirmed)
-> ReadTopic s m (NewPool Unconfirmed)
-> ReadTopic s m DiscardedPool
-> PoolTracker s m
mkPoolTracker pools conf unconf discarded =
PoolTracker $
S.parallel (trackConfirmedPoolUpdates pools conf) $
S.parallel (trackUnconfirmedPoolUpdates pools unconf) $
handlePoolRollbacks pools discarded
trackConfirmedPoolUpdates
:: (IsStream s, Monad (s m), Monad m)
=> Pools m
-> ReadTopic s m (NewPool Confirmed)
-> s m ()
trackConfirmedPoolUpdates Pools{..} ReadTopic{..} = do
NewPool pool <- upstream
S.fromEffect $ putConfirmed pool
trackUnconfirmedPoolUpdates
:: (IsStream s, Monad (s m), Monad m)
=> Pools m
-> ReadTopic s m (NewPool Unconfirmed)
-> s m ()
trackUnconfirmedPoolUpdates Pools{..} ReadTopic{..} = do
NewPool pool <- upstream
S.fromEffect $ putUnconfirmed pool
handlePoolRollbacks
:: (IsStream s, Monad (s m), Monad m)
=> Pools m
-> ReadTopic s m DiscardedPool
-> s m ()
handlePoolRollbacks Pools{..} ReadTopic{..} = do
DiscardedPool pid sid <- upstream
S.fromEffect $ invalidate pid sid
|
|
a42ee8d3127418269c108b61191c643904468fdc19fc5813d52cd4bee5043cc7 | koto-bank/lbge | image-loader.lisp | (in-package :lbge.image)
(defparameter *loaders* (list))
(defmacro register-loader (extension loader-name)
`(setf *loaders* (acons (string-upcase ,extension) ,loader-name *loaders*)))
(defun load-image (path)
"Takes path to an image and returns `image` structure.
If the image format is unsupported throws error."
(let ((extension (string-upcase (pathname-type path))))
(assert (assoc extension *loaders* :test #'string=) nil
"Failed to find loader for file type ~S (file ~S)" extension path)
(funcall (cdr (assoc extension *loaders* :test #'string=)) path)))
(register-loader "TGA" 'load-tga)
(register-loader "PNG" 'load-png)
| null | https://raw.githubusercontent.com/koto-bank/lbge/6be4b3212ea87288b1ee2a655e9a1bb30a74dd27/src/image-loader/image-loader.lisp | lisp | (in-package :lbge.image)
(defparameter *loaders* (list))
(defmacro register-loader (extension loader-name)
`(setf *loaders* (acons (string-upcase ,extension) ,loader-name *loaders*)))
(defun load-image (path)
"Takes path to an image and returns `image` structure.
If the image format is unsupported throws error."
(let ((extension (string-upcase (pathname-type path))))
(assert (assoc extension *loaders* :test #'string=) nil
"Failed to find loader for file type ~S (file ~S)" extension path)
(funcall (cdr (assoc extension *loaders* :test #'string=)) path)))
(register-loader "TGA" 'load-tga)
(register-loader "PNG" 'load-png)
|
|
b5a1d3ac6599c4106c2fbf045d2de53e69ab969fd9e04fb64f1c0c69adca43a9 | monadbobo/ocaml-core | fn.ml | let const c = (); fun _ -> c
external ignore : _ -> unit = "%ignore" (* this has the same behavior as [Pervasives.ignore] *)
let non f = (); fun x -> not (f x)
let forever f =
let rec forever () =
f ();
forever ()
in
try forever ()
with e -> e
external id : 'a -> 'a = "%identity"
let ( |! ) x y = y x
(* The typical use case for these functions is to pass in functional arguments and get
functions as a result. For this reason, we tell the compiler where to insert
breakpoints in the argument-passing scheme. *)
let compose f g = (); fun x -> f (g x)
let flip f = (); fun x y -> f y x
| null | https://raw.githubusercontent.com/monadbobo/ocaml-core/9c1c06e7a1af7e15b6019a325d7dbdbd4cdb4020/base/core/lib/fn.ml | ocaml | this has the same behavior as [Pervasives.ignore]
The typical use case for these functions is to pass in functional arguments and get
functions as a result. For this reason, we tell the compiler where to insert
breakpoints in the argument-passing scheme. | let const c = (); fun _ -> c
let non f = (); fun x -> not (f x)
let forever f =
let rec forever () =
f ();
forever ()
in
try forever ()
with e -> e
external id : 'a -> 'a = "%identity"
let ( |! ) x y = y x
let compose f g = (); fun x -> f (g x)
let flip f = (); fun x y -> f y x
|
364684a2168a4be3bf0b8dd4425d6add3fca9b14b297635f0a573a08b2d0c125 | SamB/coq | subtac_pretyping.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 *)
(************************************************************************)
$ Id$
open Global
open Pp
open Util
open Names
open Sign
open Evd
open Term
open Termops
open Reductionops
open Environ
open Type_errors
open Typeops
open Libnames
open Classops
open List
open Recordops
open Evarutil
open Pretype_errors
open Rawterm
open Evarconv
open Pattern
open Dyn
open Subtac_coercion
open Subtac_utils
open Coqlib
open Printer
open Subtac_errors
open Eterm
module Pretyping = Subtac_pretyping_F.SubtacPretyping_F(Subtac_coercion.Coercion)
open Pretyping
let _ = Pretyping.allow_anonymous_refs := true
type recursion_info = {
arg_name: name;
arg_type: types; (* A *)
args_after : rel_context;
wf_relation: constr; (* R : A -> A -> Prop *)
wf_proof: constr; (* : well_founded R *)
f_type: types; (* f: A -> Set *)
Type with argument and wf proof product first
}
let my_print_rec_info env t =
str "Name: " ++ Nameops.pr_name t.arg_name ++ spc () ++
str "Arg type: " ++ my_print_constr env t.arg_type ++ spc () ++
str "Wf relation: " ++ my_print_constr env t.wf_relation ++ spc () ++
str "Wf proof: " ++ my_print_constr env t.wf_proof ++ spc () ++
str "Abbreviated Type: " ++ my_print_constr env t.f_type ++ spc () ++
str "Full type: " ++ my_print_constr env t.f_fulltype
(* trace (str "pretype for " ++ (my_print_rawconstr env c) ++ *)
str " and " + + my_print_tycon env + +
(* str " in environment: " ++ my_print_env env); *)
let merge_evms x y =
Evd.fold (fun ev evi evm -> Evd.add evm ev evi) x y
let interp env isevars c tycon =
let j = pretype tycon env isevars ([],[]) c in
let _ = isevars := Evarutil.nf_evar_defs !isevars in
let evd,_ = consider_remaining_unif_problems env !isevars in
(* let unevd = undefined_evars evd in *)
let unevd' = Typeclasses.resolve_typeclasses ~onlyargs:true ~fail:false env evd in
let evm = evars_of unevd' in
isevars := unevd';
nf_evar evm j.uj_val, nf_evar evm j.uj_type
let find_with_index x l =
let rec aux i = function
(y, _, _) as t :: tl -> if x = y then i, t else aux (succ i) tl
| [] -> raise Not_found
in aux 0 l
let list_split_at index l =
let rec aux i acc = function
hd :: tl when i = index -> (List.rev acc), tl
| hd :: tl -> aux (succ i) (hd :: acc) tl
| [] -> failwith "list_split_at: Invalid argument"
in aux 0 [] l
open Vernacexpr
let coqintern_constr evd env : Topconstr.constr_expr -> Rawterm.rawconstr = Constrintern.intern_constr (evars_of evd) env
let coqintern_type evd env : Topconstr.constr_expr -> Rawterm.rawconstr = Constrintern.intern_type (evars_of evd) env
let env_with_binders env isevars l =
let rec aux ((env, rels) as acc) = function
Topconstr.LocalRawDef ((loc, name), def) :: tl ->
let rawdef = coqintern_constr !isevars env def in
let coqdef, deftyp = interp env isevars rawdef empty_tycon in
let reldecl = (name, Some coqdef, deftyp) in
aux (push_rel reldecl env, reldecl :: rels) tl
| Topconstr.LocalRawAssum (bl, k, typ) :: tl ->
let rawtyp = coqintern_type !isevars env typ in
let coqtyp, typtyp = interp env isevars rawtyp empty_tycon in
let acc =
List.fold_left (fun (env, rels) (loc, name) ->
let reldecl = (name, None, coqtyp) in
(push_rel reldecl env,
reldecl :: rels))
(env, rels) bl
in aux acc tl
| [] -> acc
in aux (env, []) l
let subtac_process env isevars id bl c tycon =
let c = Command.abstract_constr_expr c bl in
let tycon =
match tycon with
None -> empty_tycon
| Some t ->
let t = Command.generalize_constr_expr t bl in
let t = coqintern_type !isevars env t in
let coqt, ttyp = interp env isevars t empty_tycon in
mk_tycon coqt
in
let c = coqintern_constr !isevars env c in
let imps = Implicit_quantifiers.implicits_of_rawterm c in
let coqc, ctyp = interp env isevars c tycon in
let evm = non_instanciated_map env isevars (evars_of !isevars) in
let ty = nf_isevar !isevars (match tycon with Some (None, c) -> c | _ -> ctyp) in
evm, coqc, ty, imps
open Subtac_obligations
let subtac_proof kind env isevars id bl c tycon =
let evm, coqc, coqt, imps = subtac_process env isevars id bl c tycon in
let evm' = Subtac_utils.evars_of_term evm Evd.empty coqc in
let evm' = Subtac_utils.evars_of_term evm evm' coqt in
let evars, def, ty = Eterm.eterm_obligations env id !isevars evm' 0 coqc coqt in
add_definition id def ty ~implicits:imps ~kind:kind evars
| null | https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/contrib/subtac/subtac_pretyping.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
A
R : A -> A -> Prop
: well_founded R
f: A -> Set
trace (str "pretype for " ++ (my_print_rawconstr env c) ++
str " in environment: " ++ my_print_env env);
let unevd = undefined_evars evd in | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
$ Id$
open Global
open Pp
open Util
open Names
open Sign
open Evd
open Term
open Termops
open Reductionops
open Environ
open Type_errors
open Typeops
open Libnames
open Classops
open List
open Recordops
open Evarutil
open Pretype_errors
open Rawterm
open Evarconv
open Pattern
open Dyn
open Subtac_coercion
open Subtac_utils
open Coqlib
open Printer
open Subtac_errors
open Eterm
module Pretyping = Subtac_pretyping_F.SubtacPretyping_F(Subtac_coercion.Coercion)
open Pretyping
let _ = Pretyping.allow_anonymous_refs := true
type recursion_info = {
arg_name: name;
args_after : rel_context;
Type with argument and wf proof product first
}
let my_print_rec_info env t =
str "Name: " ++ Nameops.pr_name t.arg_name ++ spc () ++
str "Arg type: " ++ my_print_constr env t.arg_type ++ spc () ++
str "Wf relation: " ++ my_print_constr env t.wf_relation ++ spc () ++
str "Wf proof: " ++ my_print_constr env t.wf_proof ++ spc () ++
str "Abbreviated Type: " ++ my_print_constr env t.f_type ++ spc () ++
str "Full type: " ++ my_print_constr env t.f_fulltype
str " and " + + my_print_tycon env + +
let merge_evms x y =
Evd.fold (fun ev evi evm -> Evd.add evm ev evi) x y
let interp env isevars c tycon =
let j = pretype tycon env isevars ([],[]) c in
let _ = isevars := Evarutil.nf_evar_defs !isevars in
let evd,_ = consider_remaining_unif_problems env !isevars in
let unevd' = Typeclasses.resolve_typeclasses ~onlyargs:true ~fail:false env evd in
let evm = evars_of unevd' in
isevars := unevd';
nf_evar evm j.uj_val, nf_evar evm j.uj_type
let find_with_index x l =
let rec aux i = function
(y, _, _) as t :: tl -> if x = y then i, t else aux (succ i) tl
| [] -> raise Not_found
in aux 0 l
let list_split_at index l =
let rec aux i acc = function
hd :: tl when i = index -> (List.rev acc), tl
| hd :: tl -> aux (succ i) (hd :: acc) tl
| [] -> failwith "list_split_at: Invalid argument"
in aux 0 [] l
open Vernacexpr
let coqintern_constr evd env : Topconstr.constr_expr -> Rawterm.rawconstr = Constrintern.intern_constr (evars_of evd) env
let coqintern_type evd env : Topconstr.constr_expr -> Rawterm.rawconstr = Constrintern.intern_type (evars_of evd) env
let env_with_binders env isevars l =
let rec aux ((env, rels) as acc) = function
Topconstr.LocalRawDef ((loc, name), def) :: tl ->
let rawdef = coqintern_constr !isevars env def in
let coqdef, deftyp = interp env isevars rawdef empty_tycon in
let reldecl = (name, Some coqdef, deftyp) in
aux (push_rel reldecl env, reldecl :: rels) tl
| Topconstr.LocalRawAssum (bl, k, typ) :: tl ->
let rawtyp = coqintern_type !isevars env typ in
let coqtyp, typtyp = interp env isevars rawtyp empty_tycon in
let acc =
List.fold_left (fun (env, rels) (loc, name) ->
let reldecl = (name, None, coqtyp) in
(push_rel reldecl env,
reldecl :: rels))
(env, rels) bl
in aux acc tl
| [] -> acc
in aux (env, []) l
let subtac_process env isevars id bl c tycon =
let c = Command.abstract_constr_expr c bl in
let tycon =
match tycon with
None -> empty_tycon
| Some t ->
let t = Command.generalize_constr_expr t bl in
let t = coqintern_type !isevars env t in
let coqt, ttyp = interp env isevars t empty_tycon in
mk_tycon coqt
in
let c = coqintern_constr !isevars env c in
let imps = Implicit_quantifiers.implicits_of_rawterm c in
let coqc, ctyp = interp env isevars c tycon in
let evm = non_instanciated_map env isevars (evars_of !isevars) in
let ty = nf_isevar !isevars (match tycon with Some (None, c) -> c | _ -> ctyp) in
evm, coqc, ty, imps
open Subtac_obligations
let subtac_proof kind env isevars id bl c tycon =
let evm, coqc, coqt, imps = subtac_process env isevars id bl c tycon in
let evm' = Subtac_utils.evars_of_term evm Evd.empty coqc in
let evm' = Subtac_utils.evars_of_term evm evm' coqt in
let evars, def, ty = Eterm.eterm_obligations env id !isevars evm' 0 coqc coqt in
add_definition id def ty ~implicits:imps ~kind:kind evars
|
29c088ebf76c02c58d44dab3d3bf56d789bef2145242bccc0115a3da6940f5bb | cnuernber/dtype-next | neanderthal_test.clj | (ns tech.v3.libs.neanderthal-test
(:require [uncomplicate.neanderthal.core :as n-core]
[uncomplicate.neanderthal.native :as n-native]
[tech.v3.tensor :as dtt]
[tech.v3.datatype.functional :as dfn]
[tech.v3.datatype :as dtype]
[clojure.test :refer [deftest is]]
[tech.v3.libs.neanderthal]
[tech.v3.datatype]))
(deftest basic-neanderthal-test
(let [a (n-native/dge 3 3 (range 9))]
(is (dfn/equals (dtt/ensure-tensor a)
(-> (dtt/->tensor (partition 3 (range 9)))
(dtt/transpose [1 0]))))
(let [second-row (second (n-core/rows a))]
(is (dfn/equals (dtt/ensure-tensor second-row)
[1 4 7])))))
(deftest basic-neanderthal-test-row-major
(let [b (n-native/dge 3 3 (range 9) {:layout :row})]
(is (dfn/equals (dtt/ensure-tensor b)
(dtt/->tensor (partition 3 (range 9)))))
(let [second-row (second (n-core/rows b))]
(is (dfn/equals (dtt/ensure-tensor second-row)
[3 4 5])))))
(deftest single-col-row-matrix
(is (dfn/equals (dtt/ensure-tensor (n-native/dge 1 3 (range 3) {:layout :row}))
(dtt/->tensor (range 3))))
(is (dfn/equals (dtt/ensure-tensor (n-native/dge 1 3 (range 3) {:layout :column}))
(dtt/->tensor (range 3))))
(is (dfn/equals (dtt/ensure-tensor (n-native/dge 3 1 (range 3) {:layout :row}))
(dtt/->tensor (range 3))))
(is (dfn/equals (dtt/ensure-tensor (n-native/dge 3 1 (range 3) {:layout :column}))
(dtt/->tensor (range 3)))))
| null | https://raw.githubusercontent.com/cnuernber/dtype-next/2470025455a4425f910b3fad1a9313106a5c56a6/neanderthal/tech/v3/libs/neanderthal_test.clj | clojure | (ns tech.v3.libs.neanderthal-test
(:require [uncomplicate.neanderthal.core :as n-core]
[uncomplicate.neanderthal.native :as n-native]
[tech.v3.tensor :as dtt]
[tech.v3.datatype.functional :as dfn]
[tech.v3.datatype :as dtype]
[clojure.test :refer [deftest is]]
[tech.v3.libs.neanderthal]
[tech.v3.datatype]))
(deftest basic-neanderthal-test
(let [a (n-native/dge 3 3 (range 9))]
(is (dfn/equals (dtt/ensure-tensor a)
(-> (dtt/->tensor (partition 3 (range 9)))
(dtt/transpose [1 0]))))
(let [second-row (second (n-core/rows a))]
(is (dfn/equals (dtt/ensure-tensor second-row)
[1 4 7])))))
(deftest basic-neanderthal-test-row-major
(let [b (n-native/dge 3 3 (range 9) {:layout :row})]
(is (dfn/equals (dtt/ensure-tensor b)
(dtt/->tensor (partition 3 (range 9)))))
(let [second-row (second (n-core/rows b))]
(is (dfn/equals (dtt/ensure-tensor second-row)
[3 4 5])))))
(deftest single-col-row-matrix
(is (dfn/equals (dtt/ensure-tensor (n-native/dge 1 3 (range 3) {:layout :row}))
(dtt/->tensor (range 3))))
(is (dfn/equals (dtt/ensure-tensor (n-native/dge 1 3 (range 3) {:layout :column}))
(dtt/->tensor (range 3))))
(is (dfn/equals (dtt/ensure-tensor (n-native/dge 3 1 (range 3) {:layout :row}))
(dtt/->tensor (range 3))))
(is (dfn/equals (dtt/ensure-tensor (n-native/dge 3 1 (range 3) {:layout :column}))
(dtt/->tensor (range 3)))))
|
|
493912c78c3bfe8c6cabc640a9270cd8f55e80a566507bc3cf8ca19303816083 | basho/riak_test | repl_aae_fullsync_util.erl | %% @doc
This module implements a riak_test to exercise the Active Anti - Entropy Fullsync replication .
It sets up two clusters and starts a single fullsync worker for a single AAE tree .
-module(repl_aae_fullsync_util).
-export([make_clusters/3,
prepare_cluster_data/5]).
-include_lib("eunit/include/eunit.hrl").
-import(rt, [deploy_nodes/3,
join/2,
log_to_nodes/2,
log_to_nodes/3]).
make_clusters(NumNodesWanted, ClusterSize, Conf) ->
NumNodes = rt_config:get(num_nodes, NumNodesWanted),
ClusterASize = rt_config:get(cluster_a_size, ClusterSize),
lager:info("Deploy ~p nodes", [NumNodes]),
Nodes = deploy_nodes(NumNodes, Conf, [riak_kv, riak_repl]),
{ANodes, BNodes} = lists:split(ClusterASize, Nodes),
lager:info("ANodes: ~p", [ANodes]),
lager:info("BNodes: ~p", [BNodes]),
lager:info("Build cluster A"),
repl_util:make_cluster(ANodes),
lager:info("Build cluster B"),
repl_util:make_cluster(BNodes),
{ANodes, BNodes}.
prepare_cluster_data(TestBucket, NumKeysAOnly, _NumKeysBoth, [AFirst|_] = ANodes, [BFirst|_] = BNodes) ->
AllNodes = ANodes ++ BNodes,
log_to_nodes(AllNodes, "Starting AAE Fullsync test"),
%% clusters are not connected, connect them
repl_util:name_cluster(AFirst, "A"),
repl_util:name_cluster(BFirst, "B"),
%% we'll need to wait for cluster names before continuing
rt:wait_until_ring_converged(ANodes),
rt:wait_until_ring_converged(BNodes),
lager:info("waiting for leader to converge on cluster A"),
?assertEqual(ok, repl_util:wait_until_leader_converge(ANodes)),
lager:info("waiting for leader to converge on cluster B"),
?assertEqual(ok, repl_util:wait_until_leader_converge(BNodes)),
get the leader for the first cluster
LeaderA = rpc:call(AFirst, riak_core_cluster_mgr, get_leader, []),
{ok, {_IP, Port}} = rpc:call(BFirst, application, get_env,
[riak_core, cluster_mgr]),
lager:info("connect cluster A:~p to B on port ~p", [LeaderA, Port]),
repl_util:connect_cluster(LeaderA, "127.0.0.1", Port),
?assertEqual(ok, repl_util:wait_for_connection(LeaderA, "B")),
%% make sure we are connected
lager:info("Wait for cluster connection A:~p -> B:~p:~p", [LeaderA, BFirst, Port]),
?assertEqual(ok, repl_util:wait_for_connection(LeaderA, "B")),
%%---------------------------------------------------
TEST : write data , NOT replicated by RT or fullsync
keys : 1 .. NumKeysAOnly
%%---------------------------------------------------
lager:info("Writing ~p keys to A(~p)", [NumKeysAOnly, AFirst]),
?assertEqual([], repl_util:do_write(AFirst, 1, NumKeysAOnly, TestBucket, 2)),
%% check that the keys we wrote initially aren't replicated yet, because
%% we've disabled fullsync_on_connect
lager:info("Check keys written before repl was connected are not present"),
Res2 = rt:systest_read(BFirst, 1, NumKeysAOnly, TestBucket, 1, <<>>, true),
?assertEqual(NumKeysAOnly, length(Res2)),
wait for the AAE trees to be built so that we do n't get a not_built error
rt:wait_until_aae_trees_built(ANodes),
rt:wait_until_aae_trees_built(BNodes),
ok.
| null | https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/repl_aae_fullsync_util.erl | erlang | @doc
clusters are not connected, connect them
we'll need to wait for cluster names before continuing
make sure we are connected
---------------------------------------------------
---------------------------------------------------
check that the keys we wrote initially aren't replicated yet, because
we've disabled fullsync_on_connect | This module implements a riak_test to exercise the Active Anti - Entropy Fullsync replication .
It sets up two clusters and starts a single fullsync worker for a single AAE tree .
-module(repl_aae_fullsync_util).
-export([make_clusters/3,
prepare_cluster_data/5]).
-include_lib("eunit/include/eunit.hrl").
-import(rt, [deploy_nodes/3,
join/2,
log_to_nodes/2,
log_to_nodes/3]).
make_clusters(NumNodesWanted, ClusterSize, Conf) ->
NumNodes = rt_config:get(num_nodes, NumNodesWanted),
ClusterASize = rt_config:get(cluster_a_size, ClusterSize),
lager:info("Deploy ~p nodes", [NumNodes]),
Nodes = deploy_nodes(NumNodes, Conf, [riak_kv, riak_repl]),
{ANodes, BNodes} = lists:split(ClusterASize, Nodes),
lager:info("ANodes: ~p", [ANodes]),
lager:info("BNodes: ~p", [BNodes]),
lager:info("Build cluster A"),
repl_util:make_cluster(ANodes),
lager:info("Build cluster B"),
repl_util:make_cluster(BNodes),
{ANodes, BNodes}.
prepare_cluster_data(TestBucket, NumKeysAOnly, _NumKeysBoth, [AFirst|_] = ANodes, [BFirst|_] = BNodes) ->
AllNodes = ANodes ++ BNodes,
log_to_nodes(AllNodes, "Starting AAE Fullsync test"),
repl_util:name_cluster(AFirst, "A"),
repl_util:name_cluster(BFirst, "B"),
rt:wait_until_ring_converged(ANodes),
rt:wait_until_ring_converged(BNodes),
lager:info("waiting for leader to converge on cluster A"),
?assertEqual(ok, repl_util:wait_until_leader_converge(ANodes)),
lager:info("waiting for leader to converge on cluster B"),
?assertEqual(ok, repl_util:wait_until_leader_converge(BNodes)),
get the leader for the first cluster
LeaderA = rpc:call(AFirst, riak_core_cluster_mgr, get_leader, []),
{ok, {_IP, Port}} = rpc:call(BFirst, application, get_env,
[riak_core, cluster_mgr]),
lager:info("connect cluster A:~p to B on port ~p", [LeaderA, Port]),
repl_util:connect_cluster(LeaderA, "127.0.0.1", Port),
?assertEqual(ok, repl_util:wait_for_connection(LeaderA, "B")),
lager:info("Wait for cluster connection A:~p -> B:~p:~p", [LeaderA, BFirst, Port]),
?assertEqual(ok, repl_util:wait_for_connection(LeaderA, "B")),
TEST : write data , NOT replicated by RT or fullsync
keys : 1 .. NumKeysAOnly
lager:info("Writing ~p keys to A(~p)", [NumKeysAOnly, AFirst]),
?assertEqual([], repl_util:do_write(AFirst, 1, NumKeysAOnly, TestBucket, 2)),
lager:info("Check keys written before repl was connected are not present"),
Res2 = rt:systest_read(BFirst, 1, NumKeysAOnly, TestBucket, 1, <<>>, true),
?assertEqual(NumKeysAOnly, length(Res2)),
wait for the AAE trees to be built so that we do n't get a not_built error
rt:wait_until_aae_trees_built(ANodes),
rt:wait_until_aae_trees_built(BNodes),
ok.
|
d052617d6aac9183562f32b5f1e0d2a95de8693b3a56ba92287b5cb66f6be7ff | mpickering/apply-refact | Default36.hs | yes = Prelude.concat $ intersperse " " xs | null | https://raw.githubusercontent.com/mpickering/apply-refact/a4343ea0f4f9d8c2e16d6b16b9068f321ba4f272/tests/examples/Default36.hs | haskell | yes = Prelude.concat $ intersperse " " xs |
|
e7876f9cb6db0050b0b12c16d7ce6656108f2c574ca92a4166cfb64d0d99714e | evrim/core-server | serialization.lisp | (in-package :core-server.test)
(defmacro defserialization-test (name lisp-element db-element &optional (equal 'equalp))
`(deftest ,name
(and (xml.equal (xml-serialize ,lisp-element) ,db-element)
(,equal (xml-deserialize ,db-element) ,lisp-element))
t))
(defserialization-test serialize-null nil (<db:null))
(defserialization-test serialize-true t (<db:true))
(defserialization-test serialize-symbol 'my-symbol? (<db:symbol "TR.GEN.CORE.SERVER.TEST::MY-SYMBOL?"))
(defserialization-test serialize-character #\A (<db:character "\"A\""))
(defserialization-test serialize-int 100000 (<db:integer "100000"))
(defserialization-test serialize-ratio (/ 1 2) (<db:ratio "1/2"))
(defserialization-test serialize-complex #C(3 4) (<db:complex "#C(3 4)"))
(defserialization-test serialize-float (float (/ 1 2)) (<db:float "0.5"))
(defserialization-test serialize-string "mooo 1 2 3>" (<db:string "\"mooo 1 2 3>\""))
(defserialization-test serialize-cons (cons 1 2)
(<db:cons :consp t
(<db:integer "1")
(<db:integer "2")))
(defserialization-test serialize-list (list 3 4 5 6)
(<db:cons :length 4
(<db:integer "3")
(<db:integer "4")
(<db:integer "5")
(<db:integer "6")))
(defun serialization-hash-table ()
(let ((table (make-hash-table :test #'equal)))
(setf (gethash "test1" table) "test1-value"
(gethash "test2" table) "test2-value")
table))
(defun hash-table-equalp (a b)
(and (equal (hash-table-keys a) (hash-table-keys b))
(equal (hash-table-values a) (hash-table-values b))))
(defserialization-test serialize-hash-table (serialization-hash-table)
(<db:hash-table :test "COMMON-LISP::EQUAL"
:size "16"
(<db:hash-table-entry
(<db:hash-table-key (<db:string "\"test1\""))
(<db:hash-table-value (<db:string "\"test1-value\"")))
(<db:hash-table-entry
(<db:hash-table-key (<db:string "\"test2\""))
(<db:hash-table-value (<db:string "\"test2-value\""))))
hash-table-equalp)
(defstruct (my-structure)
(slot1))
(defun serialization-structure ()
(make-my-structure :slot1 "test"))
(defserialization-test serialize-structure (serialization-structure)
(<db:struct :class "TR.GEN.CORE.SERVER.TEST::MY-STRUCTURE"
(<db:slot :name "TR.GEN.CORE.SERVER.TEST::SLOT1"
(<db:string "\"test\""))))
(defclass my-class ()
((slot1 :initarg :slot1)))
(defun serialization-object ()
(make-instance 'my-class :slot1 "slot1"))
(defun my-object-equalp (a b)
(and (equal (class-of a) (class-of b))
(equal (slot-value a 'slot1) (slot-value b 'slot1))))
(defserialization-test serialize-object (serialization-object)
(<db:instance :class "TR.GEN.CORE.SERVER.TEST::MY-CLASS"
(<db:slot :name "TR.GEN.CORE.SERVER.TEST::SLOT1"
(<db:string "\"slot1\"")))
my-object-equalp)
(defclass+ my-class+ ()
((slot1 :initarg :slot1)
(slot2 :host remote)))
(defserialization-test serialize-class+ (my-class+ :slot1 "slot1")
(<db:instance :class "TR.GEN.CORE.SERVER.TEST::MY-CLASS+"
(<db:slot :name "TR.GEN.CORE.SERVER.TEST::SLOT1"
(<db:string "\"slot1\"")))
my-object-equalp)
;; Generate unique filename for temporary usage
(sb-alien:define-alien-routine "tmpnam" sb-alien:c-string
(dest (* sb-alien:c-string)))
(defparameter *dbpath*
(pathname (format nil "~A/" (tmpnam nil))))
(defvar *db* nil)
(defun test-db ()
(setf *dB* (make-instance 'database :database-directory *dbpath*))
(start *db*)
*db*)
(deftest db-serialize-object
(let ((db (test-db)))
(and (= 123 (database.deserialize db (database.serialize db 123)))))
t)
| null | https://raw.githubusercontent.com/evrim/core-server/200ea8151d2f8d81b593d605b183a9cddae1e82d/t/database/serialization.lisp | lisp | Generate unique filename for temporary usage | (in-package :core-server.test)
(defmacro defserialization-test (name lisp-element db-element &optional (equal 'equalp))
`(deftest ,name
(and (xml.equal (xml-serialize ,lisp-element) ,db-element)
(,equal (xml-deserialize ,db-element) ,lisp-element))
t))
(defserialization-test serialize-null nil (<db:null))
(defserialization-test serialize-true t (<db:true))
(defserialization-test serialize-symbol 'my-symbol? (<db:symbol "TR.GEN.CORE.SERVER.TEST::MY-SYMBOL?"))
(defserialization-test serialize-character #\A (<db:character "\"A\""))
(defserialization-test serialize-int 100000 (<db:integer "100000"))
(defserialization-test serialize-ratio (/ 1 2) (<db:ratio "1/2"))
(defserialization-test serialize-complex #C(3 4) (<db:complex "#C(3 4)"))
(defserialization-test serialize-float (float (/ 1 2)) (<db:float "0.5"))
(defserialization-test serialize-string "mooo 1 2 3>" (<db:string "\"mooo 1 2 3>\""))
(defserialization-test serialize-cons (cons 1 2)
(<db:cons :consp t
(<db:integer "1")
(<db:integer "2")))
(defserialization-test serialize-list (list 3 4 5 6)
(<db:cons :length 4
(<db:integer "3")
(<db:integer "4")
(<db:integer "5")
(<db:integer "6")))
(defun serialization-hash-table ()
(let ((table (make-hash-table :test #'equal)))
(setf (gethash "test1" table) "test1-value"
(gethash "test2" table) "test2-value")
table))
(defun hash-table-equalp (a b)
(and (equal (hash-table-keys a) (hash-table-keys b))
(equal (hash-table-values a) (hash-table-values b))))
(defserialization-test serialize-hash-table (serialization-hash-table)
(<db:hash-table :test "COMMON-LISP::EQUAL"
:size "16"
(<db:hash-table-entry
(<db:hash-table-key (<db:string "\"test1\""))
(<db:hash-table-value (<db:string "\"test1-value\"")))
(<db:hash-table-entry
(<db:hash-table-key (<db:string "\"test2\""))
(<db:hash-table-value (<db:string "\"test2-value\""))))
hash-table-equalp)
(defstruct (my-structure)
(slot1))
(defun serialization-structure ()
(make-my-structure :slot1 "test"))
(defserialization-test serialize-structure (serialization-structure)
(<db:struct :class "TR.GEN.CORE.SERVER.TEST::MY-STRUCTURE"
(<db:slot :name "TR.GEN.CORE.SERVER.TEST::SLOT1"
(<db:string "\"test\""))))
(defclass my-class ()
((slot1 :initarg :slot1)))
(defun serialization-object ()
(make-instance 'my-class :slot1 "slot1"))
(defun my-object-equalp (a b)
(and (equal (class-of a) (class-of b))
(equal (slot-value a 'slot1) (slot-value b 'slot1))))
(defserialization-test serialize-object (serialization-object)
(<db:instance :class "TR.GEN.CORE.SERVER.TEST::MY-CLASS"
(<db:slot :name "TR.GEN.CORE.SERVER.TEST::SLOT1"
(<db:string "\"slot1\"")))
my-object-equalp)
(defclass+ my-class+ ()
((slot1 :initarg :slot1)
(slot2 :host remote)))
(defserialization-test serialize-class+ (my-class+ :slot1 "slot1")
(<db:instance :class "TR.GEN.CORE.SERVER.TEST::MY-CLASS+"
(<db:slot :name "TR.GEN.CORE.SERVER.TEST::SLOT1"
(<db:string "\"slot1\"")))
my-object-equalp)
(sb-alien:define-alien-routine "tmpnam" sb-alien:c-string
(dest (* sb-alien:c-string)))
(defparameter *dbpath*
(pathname (format nil "~A/" (tmpnam nil))))
(defvar *db* nil)
(defun test-db ()
(setf *dB* (make-instance 'database :database-directory *dbpath*))
(start *db*)
*db*)
(deftest db-serialize-object
(let ((db (test-db)))
(and (= 123 (database.deserialize db (database.serialize db 123)))))
t)
|
fc8fa8b0a97425e05fdfa62d88d5b7572ad012d0e47e33f7e5538e6c520eb0a4 | albertoruiz/easyVision | Statistics.hs | module Util.Statistics(
mean, median, quartiles, shDist,
Histogram, histogram, meanAndSigma, credible,
randomPermutation, randomSamples,
MCMC(..), metropolis, metropolis', infoMetro
) where
import Numeric.LinearAlgebra.HMatrix hiding (step)
import Data.List(sortBy, sort)
import System.Random
import qualified Data.Vector as V
import Data.Function(on)
import Text.Printf
import Data.List.Split
-- | pseudorandom permutation of a list
randomPermutation :: Seed -> [a] -> [a]
randomPermutation seed l = map fst $ sortBy (compare `on` snd) randomTuples where
randomTuples = zip l (randomRs (0, 1::Double) (mkStdGen seed))
-- | without replacement
randomSamples :: Seed -> Int -> [a] -> [[a]]
randomSamples seed n dat = map (V.toList . V.backpermute vdat . V.fromList) goodsubsets
where
randomIndices = randomRs (0, length dat -1) (mkStdGen seed)
goodsubsets = filter unique $ chunksOf n randomIndices
vdat = V.fromList dat
unique = g . sort
g [] = True
g [_] = True
g (a:b:cs) | a == b = False
| otherwise = unique (b:cs)
mean :: (Fractional a) => [a] -> a
mean l = sum l / fromIntegral (length l)
median :: (Ord a) => [a] -> a
median l = sort l !! (div (length l) 2)
| minimum , q0.25 , q0.5 , q.075 , maximum
quartiles :: (Ord a) => [a] -> (a,a,a,a,a)
quartiles l = (f 0, f a, f b, f c, f n) where
f = (s!!)
s = sort l
n = length l - 1
n' = fromIntegral n
[a,b,c] = map (round . (*n')) [0.25,0.5,0.75::Double]
| display with name and format the mean , min , , and quartiles of a list of data
shDist :: String -> String -> String -> [Double] -> IO ()
shDist name fmtm fmt xs = printf (name ++ fmtm ++" ("++fmt++", "++fmt++", "++fmt++", "++fmt++", "++fmt++")\n") m xmin a b c xmax
where (xmin,a,b,c,xmax) = quartiles xs
m = mean xs
type Histogram = (V, (V, V))
histogram :: Int -> (ℝ,ℝ) -> Vector Double -> Histogram
histogram n (a,b) xs = (scale s h,(l,r))
where
nxs = (xs - scalar a) * scalar (fromIntegral n / (b-a))
idxs = f $ map floor $ toList nxs
h = accum (konst 0 n) (+) (map (flip (,) 1) idxs)
z = linspace (n+1) (a,b)
l = subVector 0 n z
r = subVector 1 n z
f = filter (>=0) . filter (<n)
s = fromIntegral n / fromIntegral (size xs) / (b-a)
meanAndSigma :: Histogram -> (Double, Double, Double)
meanAndSigma (v,(s1,s2)) = (i, m,sqrt (s-m**2))
where
δ = s2!0-s1!0
i = sumElements v * δ
m = (v <·> ((s1+s2)/2)) * δ
s = (v <·> ((s1+s2)/2)**2) * δ
credible :: Double -> Histogram -> (Double, Double)
credible p (v,(s1,s2)) = (a,b)
where
δ = s2!0-s1!0
a = s1!i
b = s2!j
(i,j,_) = until ok go (0,size v -1, 0)
ok (_,_,x) = x*δ >= (1-p)
go (l,r,x)
| v!l < v!r = (l+1,r,x+v!l)
| otherwise = (l,r-1,x+v!r)
--------------------------------------------------------------------------------
type V = Vector Double
data MCMC = MCMC
{ mcX :: V
, mcL :: ℝ
, mcA :: Bool
}
metropolis :: Seed -> Int -> Int -> ℝ -> V -> Int -> (V -> ℝ) -> ([V],ℝ)
metropolis seed step burn σ x0 tot lprob = infoMetro $ take tot $ metropolis' seed step burn σ x0 lprob
infoMetro :: [MCMC] -> ([V],ℝ)
infoMetro mcs = (map mcX mcs, ar)
where
ar = fromIntegral (length (filter mcA mcs)) / fromIntegral (length mcs)
metropolis' :: Seed -> Int -> Int -> ℝ -> V -> (V -> ℝ) -> [MCMC]
metropolis' seed step burn σ x0 lprob = g $ scanl f mc0 deltas
where
f (MCMC x lp _) (δ,r)
| accept = MCMC x' lp' True
| otherwise = MCMC x lp False
where
x' = x+δ
lp' = lprob x'
ratio = lp' - lp
accept = ratio > 0 || log r < ratio
deltas = zip (infn seed (size x0) σ) (infu seed)
g = drop burn . map head . chunksOf step
mc0 = MCMC x0 (lprob x0) True
infn :: Int -> Int -> Double -> [V]
infn seed n σ = concatMap g seeds
where
seeds = randoms (mkStdGen seed)
g s = toRows $ gaussianSample s 1000 (vector (replicate n 0)) (diagl (replicate n σ))
infu :: Int -> [ℝ]
infu seed = randomRs (0,1) (mkStdGen seed) :: [ℝ]
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/packages/tools/src/Util/Statistics.hs | haskell | | pseudorandom permutation of a list
| without replacement
------------------------------------------------------------------------------ | module Util.Statistics(
mean, median, quartiles, shDist,
Histogram, histogram, meanAndSigma, credible,
randomPermutation, randomSamples,
MCMC(..), metropolis, metropolis', infoMetro
) where
import Numeric.LinearAlgebra.HMatrix hiding (step)
import Data.List(sortBy, sort)
import System.Random
import qualified Data.Vector as V
import Data.Function(on)
import Text.Printf
import Data.List.Split
randomPermutation :: Seed -> [a] -> [a]
randomPermutation seed l = map fst $ sortBy (compare `on` snd) randomTuples where
randomTuples = zip l (randomRs (0, 1::Double) (mkStdGen seed))
randomSamples :: Seed -> Int -> [a] -> [[a]]
randomSamples seed n dat = map (V.toList . V.backpermute vdat . V.fromList) goodsubsets
where
randomIndices = randomRs (0, length dat -1) (mkStdGen seed)
goodsubsets = filter unique $ chunksOf n randomIndices
vdat = V.fromList dat
unique = g . sort
g [] = True
g [_] = True
g (a:b:cs) | a == b = False
| otherwise = unique (b:cs)
mean :: (Fractional a) => [a] -> a
mean l = sum l / fromIntegral (length l)
median :: (Ord a) => [a] -> a
median l = sort l !! (div (length l) 2)
| minimum , q0.25 , q0.5 , q.075 , maximum
quartiles :: (Ord a) => [a] -> (a,a,a,a,a)
quartiles l = (f 0, f a, f b, f c, f n) where
f = (s!!)
s = sort l
n = length l - 1
n' = fromIntegral n
[a,b,c] = map (round . (*n')) [0.25,0.5,0.75::Double]
| display with name and format the mean , min , , and quartiles of a list of data
shDist :: String -> String -> String -> [Double] -> IO ()
shDist name fmtm fmt xs = printf (name ++ fmtm ++" ("++fmt++", "++fmt++", "++fmt++", "++fmt++", "++fmt++")\n") m xmin a b c xmax
where (xmin,a,b,c,xmax) = quartiles xs
m = mean xs
type Histogram = (V, (V, V))
histogram :: Int -> (ℝ,ℝ) -> Vector Double -> Histogram
histogram n (a,b) xs = (scale s h,(l,r))
where
nxs = (xs - scalar a) * scalar (fromIntegral n / (b-a))
idxs = f $ map floor $ toList nxs
h = accum (konst 0 n) (+) (map (flip (,) 1) idxs)
z = linspace (n+1) (a,b)
l = subVector 0 n z
r = subVector 1 n z
f = filter (>=0) . filter (<n)
s = fromIntegral n / fromIntegral (size xs) / (b-a)
meanAndSigma :: Histogram -> (Double, Double, Double)
meanAndSigma (v,(s1,s2)) = (i, m,sqrt (s-m**2))
where
δ = s2!0-s1!0
i = sumElements v * δ
m = (v <·> ((s1+s2)/2)) * δ
s = (v <·> ((s1+s2)/2)**2) * δ
credible :: Double -> Histogram -> (Double, Double)
credible p (v,(s1,s2)) = (a,b)
where
δ = s2!0-s1!0
a = s1!i
b = s2!j
(i,j,_) = until ok go (0,size v -1, 0)
ok (_,_,x) = x*δ >= (1-p)
go (l,r,x)
| v!l < v!r = (l+1,r,x+v!l)
| otherwise = (l,r-1,x+v!r)
type V = Vector Double
data MCMC = MCMC
{ mcX :: V
, mcL :: ℝ
, mcA :: Bool
}
metropolis :: Seed -> Int -> Int -> ℝ -> V -> Int -> (V -> ℝ) -> ([V],ℝ)
metropolis seed step burn σ x0 tot lprob = infoMetro $ take tot $ metropolis' seed step burn σ x0 lprob
infoMetro :: [MCMC] -> ([V],ℝ)
infoMetro mcs = (map mcX mcs, ar)
where
ar = fromIntegral (length (filter mcA mcs)) / fromIntegral (length mcs)
metropolis' :: Seed -> Int -> Int -> ℝ -> V -> (V -> ℝ) -> [MCMC]
metropolis' seed step burn σ x0 lprob = g $ scanl f mc0 deltas
where
f (MCMC x lp _) (δ,r)
| accept = MCMC x' lp' True
| otherwise = MCMC x lp False
where
x' = x+δ
lp' = lprob x'
ratio = lp' - lp
accept = ratio > 0 || log r < ratio
deltas = zip (infn seed (size x0) σ) (infu seed)
g = drop burn . map head . chunksOf step
mc0 = MCMC x0 (lprob x0) True
infn :: Int -> Int -> Double -> [V]
infn seed n σ = concatMap g seeds
where
seeds = randoms (mkStdGen seed)
g s = toRows $ gaussianSample s 1000 (vector (replicate n 0)) (diagl (replicate n σ))
infu :: Int -> [ℝ]
infu seed = randomRs (0,1) (mkStdGen seed) :: [ℝ]
|
1f5586b6a975c518368c4affd981b028bc0d3be24c0d9df0b4174de615f64843 | mjmeintjes/cljs-react-native-tictactoe | macro.clj | (ns reagent-native.macro
(:require [clojure.string :as string]))
(defn snake-case->camel-case [^String input-str]
(string/replace input-str
#"-(\w)"
(fn [[match captured]]
(string/upper-case captured))))
(defn generate-binding [clj-name]
(let [js-name (snake-case->camel-case (string/capitalize (str clj-name)))
attr-symbol (symbol (str ".-" js-name))]
`(def ~clj-name
(if (~attr-symbol js/React)
(reagent.core/adapt-react-class (~attr-symbol js/React))
(keyword (str "mock-" '~clj-name))))))
(defmacro adapt-react-classes [& list]
(let [generated-bindings (map generate-binding list)]
`(do ~@generated-bindings)))
#_(macroexpand-1 '(adapt-react-classes text
view
app-registry))
| null | https://raw.githubusercontent.com/mjmeintjes/cljs-react-native-tictactoe/b41ead9ac3982b139a315b3e60c149342f7c345e/src/reagent_native/macro.clj | clojure | (ns reagent-native.macro
(:require [clojure.string :as string]))
(defn snake-case->camel-case [^String input-str]
(string/replace input-str
#"-(\w)"
(fn [[match captured]]
(string/upper-case captured))))
(defn generate-binding [clj-name]
(let [js-name (snake-case->camel-case (string/capitalize (str clj-name)))
attr-symbol (symbol (str ".-" js-name))]
`(def ~clj-name
(if (~attr-symbol js/React)
(reagent.core/adapt-react-class (~attr-symbol js/React))
(keyword (str "mock-" '~clj-name))))))
(defmacro adapt-react-classes [& list]
(let [generated-bindings (map generate-binding list)]
`(do ~@generated-bindings)))
#_(macroexpand-1 '(adapt-react-classes text
view
app-registry))
|
|
1ad599f98f53090f678a23614cc2db45d629b47aedc9d30e0916a17111be6488 | kimwnasptd/YAAC-Yet-Another-Alan-Compiler | ASTTypes.hs | module ASTTypes where
import Tokens
data Program = Prog Func_Def
deriving (Eq, Show)
data Func_Def = F_Def String FPar_List R_Type L_Def_List Comp_Stmt
deriving (Eq, Show)
-- It doesn't need a custom data type
type Stmt_List = [ Stmt ]
type L_Def_List = [ Local_Def ] -- Local Functions or variables
deriving ( Eq , Show )
data Comp_Stmt = C_Stmt Stmt_List
deriving (Eq, Show)
type FPar_List = [ FPar_Def ]
data FPar_Def = FPar_Def_Ref String Type
| FPar_Def_NR String Type
deriving (Eq, Show)
Parser takes care of us ,
only Token Int and Token Byte can reach this point
data Type = S_Type Data_Type
| Table_Type Data_Type
deriving (Eq, Show)
data R_Type = R_Type_DT Data_Type
| R_Type_Proc
deriving (Eq, Show)
data Local_Def = Loc_Def_Fun Func_Def
| Loc_Def_Var Var_Def
deriving (Eq, Show)
data Var_Def = VDef String Data_Type
| VDef_T String Data_Type Int
deriving (Eq, Show)
data Func_Call = Func_Call String Expr_List
deriving (Eq, Show)
-- It doesn't need a custom data type -> I am sorry.
type Expr_List = [ Expr ]
deriving ( Eq , Show )
data Expr = Expr_Add Expr Expr --
| Expr_Sub Expr Expr --
| Expr_Tms Expr Expr --
| Expr_Div Expr Expr --
| Expr_Mod Expr Expr --
| Expr_Pos Expr
| Expr_Neg Expr
| Expr_Fcall Func_Call
| Expr_Brack Expr --
| Expr_Lval L_Value --
| Expr_Char String
| Expr_Int Int --
deriving (Eq, Show)
data L_Value = LV_Var String --
| LV_Tbl String Expr --
| LV_Lit String --
deriving (Eq, Show)
data Stmt = Stmt_Semi --
| Stmt_Eq L_Value Expr --
| Stmt_Cmp Comp_Stmt
| Stmt_FCall Func_Call
| Stmt_If Cond Stmt
| Stmt_IFE Cond Stmt Stmt
| Stmt_Wh Cond Stmt
| Stmt_Ret
| Stmt_Ret_Expr Expr
deriving (Eq, Show)
data Cond = Cond_True -- done
| Cond_False -- done
| Cond_Br Cond -- done
| Cond_Bang Cond -- done in a cute way!
| Cond_Eq Expr Expr -- done
| Cond_Neq Expr Expr -- done
| Cond_L Expr Expr -- done
| Cond_G Expr Expr -- done
| Cond_LE Expr Expr -- done
| Cond_GE Expr Expr -- done
| Cond_And Cond Cond -- done
| Cond_Or Cond Cond -- done
deriving (Eq, Show)
| null | https://raw.githubusercontent.com/kimwnasptd/YAAC-Yet-Another-Alan-Compiler/73046cb21d29aaeb5ab3f83ae6ff6978d445afc8/Parser/ASTTypes.hs | haskell | It doesn't need a custom data type
Local Functions or variables
It doesn't need a custom data type -> I am sorry.
done
done
done
done in a cute way!
done
done
done
done
done
done
done
done | module ASTTypes where
import Tokens
data Program = Prog Func_Def
deriving (Eq, Show)
data Func_Def = F_Def String FPar_List R_Type L_Def_List Comp_Stmt
deriving (Eq, Show)
type Stmt_List = [ Stmt ]
deriving ( Eq , Show )
data Comp_Stmt = C_Stmt Stmt_List
deriving (Eq, Show)
type FPar_List = [ FPar_Def ]
data FPar_Def = FPar_Def_Ref String Type
| FPar_Def_NR String Type
deriving (Eq, Show)
Parser takes care of us ,
only Token Int and Token Byte can reach this point
data Type = S_Type Data_Type
| Table_Type Data_Type
deriving (Eq, Show)
data R_Type = R_Type_DT Data_Type
| R_Type_Proc
deriving (Eq, Show)
data Local_Def = Loc_Def_Fun Func_Def
| Loc_Def_Var Var_Def
deriving (Eq, Show)
data Var_Def = VDef String Data_Type
| VDef_T String Data_Type Int
deriving (Eq, Show)
data Func_Call = Func_Call String Expr_List
deriving (Eq, Show)
type Expr_List = [ Expr ]
deriving ( Eq , Show )
| Expr_Pos Expr
| Expr_Neg Expr
| Expr_Fcall Func_Call
| Expr_Char String
deriving (Eq, Show)
deriving (Eq, Show)
| Stmt_Cmp Comp_Stmt
| Stmt_FCall Func_Call
| Stmt_If Cond Stmt
| Stmt_IFE Cond Stmt Stmt
| Stmt_Wh Cond Stmt
| Stmt_Ret
| Stmt_Ret_Expr Expr
deriving (Eq, Show)
deriving (Eq, Show)
|
70ed07e5244ac6525be08cd136167304fdd2ad33944578893aed3a0b2f908298 | static-analysis-engineering/codehawk | jCHTemplateUtil.mli | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
(* chutil *)
open CHXmlDocument
(* jchlib *)
open JCHBasicTypesAPI
val get_inherited_fields:
?allfields:bool
-> class_name_int
-> (field_signature_int * class_name_int) list
val write_xmlx_inherited_field:
xml_element_int -> field_signature_int -> class_name_int -> unit
val write_xmlx_inherited_method:
xml_element_int -> method_signature_int -> class_name_int -> unit
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchpre/jCHTemplateUtil.mli | ocaml | chutil
jchlib | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author : ------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Henny Sipma
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
open CHXmlDocument
open JCHBasicTypesAPI
val get_inherited_fields:
?allfields:bool
-> class_name_int
-> (field_signature_int * class_name_int) list
val write_xmlx_inherited_field:
xml_element_int -> field_signature_int -> class_name_int -> unit
val write_xmlx_inherited_method:
xml_element_int -> method_signature_int -> class_name_int -> unit
|
4c81d5b6448eb3e852a8dd6990e04bf72f2ec82449678a6333e4735628ac295c | melange-re/melange | ext_json_noloc.mli | Copyright ( C ) 2017- Authors of ReScript
*
* 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 .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
type t = private
| True
| False
| Null
| Flo of string
| Str of string
| Arr of t array
| Obj of t Map_string.t
val true_ : t
val false_ : t
val null : t
val str : string -> t
val flo : string -> t
val arr : t array -> t
val obj : t Map_string.t -> t
val kvs : (string * t) list -> t
val to_string : t -> string
val to_channel : out_channel -> t -> unit
val to_file : string -> t -> unit
| null | https://raw.githubusercontent.com/melange-re/melange/246e6df78fe3b6cc124cb48e5a37fdffd99379ed/jscomp/ext/ext_json_noloc.mli | ocaml | Copyright ( C ) 2017- Authors of ReScript
*
* 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 .
*
* In addition to the permissions granted to you by the LGPL , you may combine
* or link a " work that uses the Library " with a publicly distributed version
* of this file to produce a combined library or application , then distribute
* that combined work under the terms of your choosing , with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 ( or the corresponding section of a later version of the LGPL
* should you choose to use a later version ) .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program ; if not , write to the Free Software
* Foundation , Inc. , 59 Temple Place - Suite 330 , Boston , MA 02111 - 1307 , USA .
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* In addition to the permissions granted to you by the LGPL, you may combine
* or link a "work that uses the Library" with a publicly distributed version
* of this file to produce a combined library or application, then distribute
* that combined work under the terms of your choosing, with no requirement
* to comply with the obligations normally placed on you by section 4 of the
* LGPL version 3 (or the corresponding section of a later version of the LGPL
* should you choose to use a later version).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *)
type t = private
| True
| False
| Null
| Flo of string
| Str of string
| Arr of t array
| Obj of t Map_string.t
val true_ : t
val false_ : t
val null : t
val str : string -> t
val flo : string -> t
val arr : t array -> t
val obj : t Map_string.t -> t
val kvs : (string * t) list -> t
val to_string : t -> string
val to_channel : out_channel -> t -> unit
val to_file : string -> t -> unit
|
|
2f380d8ef8dc7a57cad155680a999df9dd5e77c17af09e3ec06907aa6ae578c4 | DanielG/ghc-mod | PkgDoc.hs | module GhcMod.Exe.PkgDoc (pkgDoc) where
import GhcMod.Types
import GhcMod.GhcPkg
import GhcMod.Monad
import GhcMod.Output
import Control.Applicative
import Prelude
-- | Obtaining the package name and the doc path of a module.
pkgDoc :: IOish m => String -> GhcModT m String
pkgDoc mdl = do
ghcPkg <- getGhcPkgProgram
readProc <- gmReadProcess
pkgDbStack <- getPackageDbStack
pkg <- liftIO $ trim <$> readProc ghcPkg (toModuleOpts pkgDbStack) ""
if pkg == "" then
return "\n"
else do
htmlpath <- liftIO $ readProc ghcPkg (toDocDirOpts pkg pkgDbStack) ""
let ret = pkg ++ " " ++ drop 14 htmlpath
return ret
where
toModuleOpts dbs = ["find-module", mdl, "--simple-output"]
++ ghcPkgDbStackOpts dbs
toDocDirOpts pkg dbs = ["field", pkg, "haddock-html"]
++ ghcPkgDbStackOpts dbs
trim = takeWhile (`notElem` " \n")
| null | https://raw.githubusercontent.com/DanielG/ghc-mod/391e187a5dfef4421aab2508fa6ff7875cc8259d/GhcMod/Exe/PkgDoc.hs | haskell | | Obtaining the package name and the doc path of a module. | module GhcMod.Exe.PkgDoc (pkgDoc) where
import GhcMod.Types
import GhcMod.GhcPkg
import GhcMod.Monad
import GhcMod.Output
import Control.Applicative
import Prelude
pkgDoc :: IOish m => String -> GhcModT m String
pkgDoc mdl = do
ghcPkg <- getGhcPkgProgram
readProc <- gmReadProcess
pkgDbStack <- getPackageDbStack
pkg <- liftIO $ trim <$> readProc ghcPkg (toModuleOpts pkgDbStack) ""
if pkg == "" then
return "\n"
else do
htmlpath <- liftIO $ readProc ghcPkg (toDocDirOpts pkg pkgDbStack) ""
let ret = pkg ++ " " ++ drop 14 htmlpath
return ret
where
toModuleOpts dbs = ["find-module", mdl, "--simple-output"]
++ ghcPkgDbStackOpts dbs
toDocDirOpts pkg dbs = ["field", pkg, "haddock-html"]
++ ghcPkgDbStackOpts dbs
trim = takeWhile (`notElem` " \n")
|
230b816b812b5928bef3dd032f2ac21dddb54ecad1812cb99f8d86559bc0a426 | pallix/lacij | core.clj | Copyright © 2010 - 2013 Fraunhofer Gesellschaft
Licensed under the EPL V.1.0
(ns ^{:doc "Layout protocol definition"}
lacij.layouts.core)
(defprotocol Layout
(layout-graph [this graph options])
(layout-graph! [this graph options]))
| null | https://raw.githubusercontent.com/pallix/lacij/ee9b7dcda13f25f7460acb5995b7970a7564c11e/src/lacij/layouts/core.clj | clojure | Copyright © 2010 - 2013 Fraunhofer Gesellschaft
Licensed under the EPL V.1.0
(ns ^{:doc "Layout protocol definition"}
lacij.layouts.core)
(defprotocol Layout
(layout-graph [this graph options])
(layout-graph! [this graph options]))
|
|
32abf05d776b059d9c1f18051b9a3e9495a0d955591fd81e41f145d9a46b60a6 | sgbj/MaximaSharp | mutils.lisp | -*- Mode : Lisp ; Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; The data in this file contains enhancments. ;;;;;
;;; ;;;;;
Copyright ( c ) 1984,1987 by , University of Texas ; ; ; ; ;
;;; All rights reserved ;;;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
( c ) Copyright 1980 Massachusetts Institute of Technology ; ; ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(in-package :maxima)
(macsyma-module mutils)
General purpose utilities . This file contains runtime functions
which perform operations on functions or data , but which are
;;; too general for placement in a particular file.
;;;
;;; Every function in this file is known about externally.
;;; This function searches for the key in the left hand side of the input list
;;; of the form [x,y,z...] where each of the list elements is a expression of
a binary operand and 2 elements . For example x=1 , 2 ^ 3 , [ a , b ] etc .
The key checked againts the first operand and and returns the second
;;; operand if the key is found.
;;; If the key is not found it either returns the default value if supplied or
;;; false.
Author 12/1/02
(defmfun $assoc (key ielist &optional default)
(let ((elist (if (listp ielist)
(margs ielist)
(merror
(intl:gettext "assoc: second argument must be a list; found: ~:M")
ielist))))
(if (and (listp elist)
(every #'(lambda (x) (and (listp x) (= 3 (length x)))) elist))
(let ((found (find key elist :test #'alike1 :key #'second)))
(if found (third found) default))
(merror (intl:gettext "assoc: every list element must be an expression with two arguments; found: ~:M") ielist))))
;;; (ASSOL item A-list)
;;;
Like ASSOC , but uses ALIKE1 as the comparison predicate rather
than EQUAL .
;;;
Meta - Synonym : ( ASS # ' ALIKE1 ITEM ALIST )
(defmfun assol (item alist)
(dolist (pair alist)
(if (alike1 item (car pair)) (return pair))))
(defmfun assolike (item alist)
(cdr (assol item alist)))
(defmfun memalike (x l)
(do ((l l (cdr l)))
((null l))
(when (alike1 x (car l)) (return l))))
Return a Maxima gensym .
(defun $gensym (&optional x)
(when (and x
(not (or (integerp x)
(stringp x))))
(merror
(intl:gettext
"gensym: Argument must be an integer or a string. Found: ~M") x))
(when (stringp x) (setq x (maybe-invert-string-case x)))
(if x
(cadr (dollarify (list (gensym x))))
(cadr (dollarify (list (gensym))))))
| null | https://raw.githubusercontent.com/sgbj/MaximaSharp/75067d7e045b9ed50883b5eb09803b4c8f391059/Test/bin/Debug/Maxima-5.30.0/share/maxima/5.30.0/src/mutils.lisp | lisp | Package : Maxima ; Syntax : Common - Lisp ; Base : 10 -*- ; ; ; ;
The data in this file contains enhancments. ;;;;;
;;;;;
; ; ; ;
All rights reserved ;;;;;
; ;
too general for placement in a particular file.
Every function in this file is known about externally.
This function searches for the key in the left hand side of the input list
of the form [x,y,z...] where each of the list elements is a expression of
operand if the key is found.
If the key is not found it either returns the default value if supplied or
false.
(ASSOL item A-list)
|
(in-package :maxima)
(macsyma-module mutils)
General purpose utilities . This file contains runtime functions
which perform operations on functions or data , but which are
a binary operand and 2 elements . For example x=1 , 2 ^ 3 , [ a , b ] etc .
The key checked againts the first operand and and returns the second
Author 12/1/02
(defmfun $assoc (key ielist &optional default)
(let ((elist (if (listp ielist)
(margs ielist)
(merror
(intl:gettext "assoc: second argument must be a list; found: ~:M")
ielist))))
(if (and (listp elist)
(every #'(lambda (x) (and (listp x) (= 3 (length x)))) elist))
(let ((found (find key elist :test #'alike1 :key #'second)))
(if found (third found) default))
(merror (intl:gettext "assoc: every list element must be an expression with two arguments; found: ~:M") ielist))))
Like ASSOC , but uses ALIKE1 as the comparison predicate rather
than EQUAL .
Meta - Synonym : ( ASS # ' ALIKE1 ITEM ALIST )
(defmfun assol (item alist)
(dolist (pair alist)
(if (alike1 item (car pair)) (return pair))))
(defmfun assolike (item alist)
(cdr (assol item alist)))
(defmfun memalike (x l)
(do ((l l (cdr l)))
((null l))
(when (alike1 x (car l)) (return l))))
Return a Maxima gensym .
(defun $gensym (&optional x)
(when (and x
(not (or (integerp x)
(stringp x))))
(merror
(intl:gettext
"gensym: Argument must be an integer or a string. Found: ~M") x))
(when (stringp x) (setq x (maybe-invert-string-case x)))
(if x
(cadr (dollarify (list (gensym x))))
(cadr (dollarify (list (gensym))))))
|
6f05f8b66333c911153f599765c4d5e4f04f6cfea3928ea4ccdd7f81c42a6b6c | grav/seq | nodejs.cljs | (ns ^:figwheel-always seq.nodejs
(:require [cljs.nodejs :as nodejs]
[seq.core :as seq]))
(nodejs/enable-util-print!)
(def midi-access (nodejs/require "webmidi-shim"))
(defonce app-state (atom nil))
(defn -main [& args]
(let [nav (nodejs/require "webmidi-shim")
now (nodejs/require "performance-now")]
(seq/setup-midi! app-state nav.requestMIDIAccess now)
(seq/play-sequences! app-state now 0 0))
#_(-> (midi-access.requestMIDIAccess)
(.then (fn [ma]
(-> (ma.outputs.values)
es6-iterator-seq
first
(.send #js [0x90 48 64] 1000))))))
(set! *main-cli-fn* -main)
| null | https://raw.githubusercontent.com/grav/seq/ca0bccbe8e12b8cbfffdae4c3af85584de27be5a/src-nodejs/seq/nodejs.cljs | clojure | (ns ^:figwheel-always seq.nodejs
(:require [cljs.nodejs :as nodejs]
[seq.core :as seq]))
(nodejs/enable-util-print!)
(def midi-access (nodejs/require "webmidi-shim"))
(defonce app-state (atom nil))
(defn -main [& args]
(let [nav (nodejs/require "webmidi-shim")
now (nodejs/require "performance-now")]
(seq/setup-midi! app-state nav.requestMIDIAccess now)
(seq/play-sequences! app-state now 0 0))
#_(-> (midi-access.requestMIDIAccess)
(.then (fn [ma]
(-> (ma.outputs.values)
es6-iterator-seq
first
(.send #js [0x90 48 64] 1000))))))
(set! *main-cli-fn* -main)
|
|
bf908297fd365d06d3ae94f5326a4f8dbffddb28d502834e4aa49cc85eb7f833 | emqx/emqx | emqx_mgmt_auth.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%--------------------------------------------------------------------
-module(emqx_mgmt_auth).
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/logger.hrl").
%% API
-export([mnesia/1]).
-boot_mnesia({mnesia, [boot]}).
-export([
create/4,
read/1,
update/4,
delete/1,
list/0,
init_bootstrap_file/0
]).
-export([authorize/3]).
%% Internal exports (RPC)
-export([
do_update/4,
do_delete/1,
do_create_app/3,
do_force_create_app/3
]).
-ifdef(TEST).
-export([create/5]).
-endif.
-define(APP, emqx_app).
-record(?APP, {
name = <<>> :: binary() | '_',
api_key = <<>> :: binary() | '_',
api_secret_hash = <<>> :: binary() | '_',
enable = true :: boolean() | '_',
desc = <<>> :: binary() | '_',
expired_at = 0 :: integer() | undefined | infinity | '_',
created_at = 0 :: integer() | '_'
}).
mnesia(boot) ->
ok = mria:create_table(?APP, [
{type, set},
{rlog_shard, ?COMMON_SHARD},
{storage, disc_copies},
{record_name, ?APP},
{attributes, record_info(fields, ?APP)}
]).
-spec init_bootstrap_file() -> ok | {error, _}.
init_bootstrap_file() ->
File = bootstrap_file(),
?SLOG(debug, #{msg => "init_bootstrap_api_keys_from_file", file => File}),
init_bootstrap_file(File).
create(Name, Enable, ExpiredAt, Desc) ->
ApiSecret = generate_api_secret(),
create(Name, ApiSecret, Enable, ExpiredAt, Desc).
create(Name, ApiSecret, Enable, ExpiredAt, Desc) ->
case mnesia:table_info(?APP, size) < 100 of
true -> create_app(Name, ApiSecret, Enable, ExpiredAt, Desc);
false -> {error, "Maximum ApiKey"}
end.
read(Name) ->
case mnesia:dirty_read(?APP, Name) of
[App] -> {ok, to_map(App)};
[] -> {error, not_found}
end.
update(Name, Enable, ExpiredAt, Desc) ->
trans(fun ?MODULE:do_update/4, [Name, Enable, ExpiredAt, Desc]).
do_update(Name, Enable, ExpiredAt, Desc) ->
case mnesia:read(?APP, Name, write) of
[] ->
mnesia:abort(not_found);
[App0 = #?APP{enable = Enable0, desc = Desc0}] ->
App =
App0#?APP{
expired_at = ExpiredAt,
enable = ensure_not_undefined(Enable, Enable0),
desc = ensure_not_undefined(Desc, Desc0)
},
ok = mnesia:write(App),
to_map(App)
end.
delete(Name) ->
trans(fun ?MODULE:do_delete/1, [Name]).
do_delete(Name) ->
case mnesia:read(?APP, Name) of
[] -> mnesia:abort(not_found);
[_App] -> mnesia:delete({?APP, Name})
end.
list() ->
to_map(ets:match_object(?APP, #?APP{_ = '_'})).
authorize(<<"/api/v5/users", _/binary>>, _ApiKey, _ApiSecret) ->
{error, <<"not_allowed">>};
authorize(<<"/api/v5/api_key", _/binary>>, _ApiKey, _ApiSecret) ->
{error, <<"not_allowed">>};
authorize(_Path, ApiKey, ApiSecret) ->
Now = erlang:system_time(second),
case find_by_api_key(ApiKey) of
{ok, true, ExpiredAt, SecretHash} when ExpiredAt >= Now ->
case emqx_dashboard_admin:verify_hash(ApiSecret, SecretHash) of
ok -> ok;
error -> {error, "secret_error"}
end;
{ok, true, _ExpiredAt, _SecretHash} ->
{error, "secret_expired"};
{ok, false, _ExpiredAt, _SecretHash} ->
{error, "secret_disable"};
{error, Reason} ->
{error, Reason}
end.
find_by_api_key(ApiKey) ->
Fun = fun() -> mnesia:match_object(#?APP{api_key = ApiKey, _ = '_'}) end,
case mria:ro_transaction(?COMMON_SHARD, Fun) of
{atomic, [#?APP{api_secret_hash = SecretHash, enable = Enable, expired_at = ExpiredAt}]} ->
{ok, Enable, ExpiredAt, SecretHash};
_ ->
{error, "not_found"}
end.
ensure_not_undefined(undefined, Old) -> Old;
ensure_not_undefined(New, _Old) -> New.
to_map(Apps) when is_list(Apps) ->
[to_map(App) || App <- Apps];
to_map(#?APP{name = N, api_key = K, enable = E, expired_at = ET, created_at = CT, desc = D}) ->
#{
name => N,
api_key => K,
enable => E,
expired_at => ET,
created_at => CT,
desc => D,
expired => is_expired(ET)
}.
is_expired(undefined) -> false;
is_expired(ExpiredTime) -> ExpiredTime < erlang:system_time(second).
create_app(Name, ApiSecret, Enable, ExpiredAt, Desc) ->
App =
#?APP{
name = Name,
enable = Enable,
expired_at = ExpiredAt,
desc = Desc,
created_at = erlang:system_time(second),
api_secret_hash = emqx_dashboard_admin:hash(ApiSecret),
api_key = list_to_binary(emqx_misc:gen_id(16))
},
case create_app(App) of
{ok, Res} ->
{ok, Res#{api_secret => ApiSecret}};
Error ->
Error
end.
create_app(App = #?APP{api_key = ApiKey, name = Name}) ->
trans(fun ?MODULE:do_create_app/3, [App, ApiKey, Name]).
force_create_app(NamePrefix, App = #?APP{api_key = ApiKey}) ->
trans(fun ?MODULE:do_force_create_app/3, [App, ApiKey, NamePrefix]).
do_create_app(App, ApiKey, Name) ->
case mnesia:read(?APP, Name) of
[_] ->
mnesia:abort(name_already_existed);
[] ->
case mnesia:match_object(?APP, #?APP{api_key = ApiKey, _ = '_'}, read) of
[] ->
ok = mnesia:write(App),
to_map(App);
_ ->
mnesia:abort(api_key_already_existed)
end
end.
do_force_create_app(App, ApiKey, NamePrefix) ->
case mnesia:match_object(?APP, #?APP{api_key = ApiKey, _ = '_'}, read) of
[] ->
NewName = generate_unique_name(NamePrefix),
ok = mnesia:write(App#?APP{name = NewName});
[#?APP{name = Name}] ->
ok = mnesia:write(App#?APP{name = Name})
end.
generate_unique_name(NamePrefix) ->
New = list_to_binary(NamePrefix ++ emqx_misc:gen_id(16)),
case mnesia:read(?APP, New) of
[] -> New;
_ -> generate_unique_name(NamePrefix)
end.
trans(Fun, Args) ->
case mria:transaction(?COMMON_SHARD, Fun, Args) of
{atomic, Res} -> {ok, Res};
{aborted, Error} -> {error, Error}
end.
generate_api_secret() ->
Random = crypto:strong_rand_bytes(32),
emqx_base62:encode(Random).
bootstrap_file() ->
case emqx:get_config([api_key, bootstrap_file], <<>>) of
For compatible remove until 5.1.0
<<>> ->
emqx:get_config([dashboard, bootstrap_users_file], <<>>);
File ->
File
end.
init_bootstrap_file(<<>>) ->
ok;
init_bootstrap_file(File) ->
case file:open(File, [read, binary]) of
{ok, Dev} ->
{ok, MP} = re:compile(<<"(\.+):(\.+$)">>, [ungreedy]),
init_bootstrap_file(File, Dev, MP);
{error, Reason0} ->
Reason = emqx_misc:explain_posix(Reason0),
?SLOG(
error,
#{
msg => "failed_to_open_the_bootstrap_file",
file => File,
reason => Reason
}
),
{error, Reason}
end.
init_bootstrap_file(File, Dev, MP) ->
try
add_bootstrap_file(File, Dev, MP, 1)
catch
throw:Error -> {error, Error};
Type:Reason:Stacktrace -> {error, {Type, Reason, Stacktrace}}
after
file:close(Dev)
end.
-define(BOOTSTRAP_TAG, <<"Bootstrapped From File">>).
add_bootstrap_file(File, Dev, MP, Line) ->
case file:read_line(Dev) of
{ok, Bin} ->
case re:run(Bin, MP, [global, {capture, all_but_first, binary}]) of
{match, [[AppKey, ApiSecret]]} ->
App =
#?APP{
enable = true,
expired_at = infinity,
desc = ?BOOTSTRAP_TAG,
created_at = erlang:system_time(second),
api_secret_hash = emqx_dashboard_admin:hash(ApiSecret),
api_key = AppKey
},
case force_create_app("from_bootstrap_file_", App) of
{ok, ok} ->
add_bootstrap_file(File, Dev, MP, Line + 1);
{error, Reason} ->
throw(#{file => File, line => Line, content => Bin, reason => Reason})
end;
_ ->
Reason = "invalid_format",
?SLOG(
error,
#{
msg => "failed_to_load_bootstrap_file",
file => File,
line => Line,
content => Bin,
reason => Reason
}
),
throw(#{file => File, line => Line, content => Bin, reason => Reason})
end;
eof ->
ok;
{error, Reason} ->
throw(#{file => File, line => Line, reason => Reason})
end.
| null | https://raw.githubusercontent.com/emqx/emqx/a26c05f4f6d332364aa4195818ee0d6d95dadbbe/apps/emqx_management/src/emqx_mgmt_auth.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
Internal exports (RPC) | Copyright ( c ) 2020 - 2023 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(emqx_mgmt_auth).
-include_lib("emqx/include/emqx.hrl").
-include_lib("emqx/include/logger.hrl").
-export([mnesia/1]).
-boot_mnesia({mnesia, [boot]}).
-export([
create/4,
read/1,
update/4,
delete/1,
list/0,
init_bootstrap_file/0
]).
-export([authorize/3]).
-export([
do_update/4,
do_delete/1,
do_create_app/3,
do_force_create_app/3
]).
-ifdef(TEST).
-export([create/5]).
-endif.
-define(APP, emqx_app).
-record(?APP, {
name = <<>> :: binary() | '_',
api_key = <<>> :: binary() | '_',
api_secret_hash = <<>> :: binary() | '_',
enable = true :: boolean() | '_',
desc = <<>> :: binary() | '_',
expired_at = 0 :: integer() | undefined | infinity | '_',
created_at = 0 :: integer() | '_'
}).
mnesia(boot) ->
ok = mria:create_table(?APP, [
{type, set},
{rlog_shard, ?COMMON_SHARD},
{storage, disc_copies},
{record_name, ?APP},
{attributes, record_info(fields, ?APP)}
]).
-spec init_bootstrap_file() -> ok | {error, _}.
init_bootstrap_file() ->
File = bootstrap_file(),
?SLOG(debug, #{msg => "init_bootstrap_api_keys_from_file", file => File}),
init_bootstrap_file(File).
create(Name, Enable, ExpiredAt, Desc) ->
ApiSecret = generate_api_secret(),
create(Name, ApiSecret, Enable, ExpiredAt, Desc).
create(Name, ApiSecret, Enable, ExpiredAt, Desc) ->
case mnesia:table_info(?APP, size) < 100 of
true -> create_app(Name, ApiSecret, Enable, ExpiredAt, Desc);
false -> {error, "Maximum ApiKey"}
end.
read(Name) ->
case mnesia:dirty_read(?APP, Name) of
[App] -> {ok, to_map(App)};
[] -> {error, not_found}
end.
update(Name, Enable, ExpiredAt, Desc) ->
trans(fun ?MODULE:do_update/4, [Name, Enable, ExpiredAt, Desc]).
do_update(Name, Enable, ExpiredAt, Desc) ->
case mnesia:read(?APP, Name, write) of
[] ->
mnesia:abort(not_found);
[App0 = #?APP{enable = Enable0, desc = Desc0}] ->
App =
App0#?APP{
expired_at = ExpiredAt,
enable = ensure_not_undefined(Enable, Enable0),
desc = ensure_not_undefined(Desc, Desc0)
},
ok = mnesia:write(App),
to_map(App)
end.
delete(Name) ->
trans(fun ?MODULE:do_delete/1, [Name]).
do_delete(Name) ->
case mnesia:read(?APP, Name) of
[] -> mnesia:abort(not_found);
[_App] -> mnesia:delete({?APP, Name})
end.
list() ->
to_map(ets:match_object(?APP, #?APP{_ = '_'})).
authorize(<<"/api/v5/users", _/binary>>, _ApiKey, _ApiSecret) ->
{error, <<"not_allowed">>};
authorize(<<"/api/v5/api_key", _/binary>>, _ApiKey, _ApiSecret) ->
{error, <<"not_allowed">>};
authorize(_Path, ApiKey, ApiSecret) ->
Now = erlang:system_time(second),
case find_by_api_key(ApiKey) of
{ok, true, ExpiredAt, SecretHash} when ExpiredAt >= Now ->
case emqx_dashboard_admin:verify_hash(ApiSecret, SecretHash) of
ok -> ok;
error -> {error, "secret_error"}
end;
{ok, true, _ExpiredAt, _SecretHash} ->
{error, "secret_expired"};
{ok, false, _ExpiredAt, _SecretHash} ->
{error, "secret_disable"};
{error, Reason} ->
{error, Reason}
end.
find_by_api_key(ApiKey) ->
Fun = fun() -> mnesia:match_object(#?APP{api_key = ApiKey, _ = '_'}) end,
case mria:ro_transaction(?COMMON_SHARD, Fun) of
{atomic, [#?APP{api_secret_hash = SecretHash, enable = Enable, expired_at = ExpiredAt}]} ->
{ok, Enable, ExpiredAt, SecretHash};
_ ->
{error, "not_found"}
end.
ensure_not_undefined(undefined, Old) -> Old;
ensure_not_undefined(New, _Old) -> New.
to_map(Apps) when is_list(Apps) ->
[to_map(App) || App <- Apps];
to_map(#?APP{name = N, api_key = K, enable = E, expired_at = ET, created_at = CT, desc = D}) ->
#{
name => N,
api_key => K,
enable => E,
expired_at => ET,
created_at => CT,
desc => D,
expired => is_expired(ET)
}.
is_expired(undefined) -> false;
is_expired(ExpiredTime) -> ExpiredTime < erlang:system_time(second).
create_app(Name, ApiSecret, Enable, ExpiredAt, Desc) ->
App =
#?APP{
name = Name,
enable = Enable,
expired_at = ExpiredAt,
desc = Desc,
created_at = erlang:system_time(second),
api_secret_hash = emqx_dashboard_admin:hash(ApiSecret),
api_key = list_to_binary(emqx_misc:gen_id(16))
},
case create_app(App) of
{ok, Res} ->
{ok, Res#{api_secret => ApiSecret}};
Error ->
Error
end.
create_app(App = #?APP{api_key = ApiKey, name = Name}) ->
trans(fun ?MODULE:do_create_app/3, [App, ApiKey, Name]).
force_create_app(NamePrefix, App = #?APP{api_key = ApiKey}) ->
trans(fun ?MODULE:do_force_create_app/3, [App, ApiKey, NamePrefix]).
do_create_app(App, ApiKey, Name) ->
case mnesia:read(?APP, Name) of
[_] ->
mnesia:abort(name_already_existed);
[] ->
case mnesia:match_object(?APP, #?APP{api_key = ApiKey, _ = '_'}, read) of
[] ->
ok = mnesia:write(App),
to_map(App);
_ ->
mnesia:abort(api_key_already_existed)
end
end.
do_force_create_app(App, ApiKey, NamePrefix) ->
case mnesia:match_object(?APP, #?APP{api_key = ApiKey, _ = '_'}, read) of
[] ->
NewName = generate_unique_name(NamePrefix),
ok = mnesia:write(App#?APP{name = NewName});
[#?APP{name = Name}] ->
ok = mnesia:write(App#?APP{name = Name})
end.
generate_unique_name(NamePrefix) ->
New = list_to_binary(NamePrefix ++ emqx_misc:gen_id(16)),
case mnesia:read(?APP, New) of
[] -> New;
_ -> generate_unique_name(NamePrefix)
end.
trans(Fun, Args) ->
case mria:transaction(?COMMON_SHARD, Fun, Args) of
{atomic, Res} -> {ok, Res};
{aborted, Error} -> {error, Error}
end.
generate_api_secret() ->
Random = crypto:strong_rand_bytes(32),
emqx_base62:encode(Random).
bootstrap_file() ->
case emqx:get_config([api_key, bootstrap_file], <<>>) of
For compatible remove until 5.1.0
<<>> ->
emqx:get_config([dashboard, bootstrap_users_file], <<>>);
File ->
File
end.
init_bootstrap_file(<<>>) ->
ok;
init_bootstrap_file(File) ->
case file:open(File, [read, binary]) of
{ok, Dev} ->
{ok, MP} = re:compile(<<"(\.+):(\.+$)">>, [ungreedy]),
init_bootstrap_file(File, Dev, MP);
{error, Reason0} ->
Reason = emqx_misc:explain_posix(Reason0),
?SLOG(
error,
#{
msg => "failed_to_open_the_bootstrap_file",
file => File,
reason => Reason
}
),
{error, Reason}
end.
init_bootstrap_file(File, Dev, MP) ->
try
add_bootstrap_file(File, Dev, MP, 1)
catch
throw:Error -> {error, Error};
Type:Reason:Stacktrace -> {error, {Type, Reason, Stacktrace}}
after
file:close(Dev)
end.
-define(BOOTSTRAP_TAG, <<"Bootstrapped From File">>).
add_bootstrap_file(File, Dev, MP, Line) ->
case file:read_line(Dev) of
{ok, Bin} ->
case re:run(Bin, MP, [global, {capture, all_but_first, binary}]) of
{match, [[AppKey, ApiSecret]]} ->
App =
#?APP{
enable = true,
expired_at = infinity,
desc = ?BOOTSTRAP_TAG,
created_at = erlang:system_time(second),
api_secret_hash = emqx_dashboard_admin:hash(ApiSecret),
api_key = AppKey
},
case force_create_app("from_bootstrap_file_", App) of
{ok, ok} ->
add_bootstrap_file(File, Dev, MP, Line + 1);
{error, Reason} ->
throw(#{file => File, line => Line, content => Bin, reason => Reason})
end;
_ ->
Reason = "invalid_format",
?SLOG(
error,
#{
msg => "failed_to_load_bootstrap_file",
file => File,
line => Line,
content => Bin,
reason => Reason
}
),
throw(#{file => File, line => Line, content => Bin, reason => Reason})
end;
eof ->
ok;
{error, Reason} ->
throw(#{file => File, line => Line, reason => Reason})
end.
|
54f1fd4cdac6ba19f155eeee6d8e3575a4961b132bfae515b06692f6fdf665c3 | soegaard/pyffi | tutorial-numpy-fish-market.rkt | #lang racket
;;;
;;; Fish Market
;;;
This example uses a data set from Finland .
;; A number of fish were caught and measurements for each fish were recorded.
;;
One way to use the data set : Consider ` weight ` the dependent variable
;; and try to predict the `weight` from the other data.
;;; Import and initialize Numpy
(require pyffi pyffi/numpy)
(initialize)
(import-numpy)
(finish-initialization)
(declare-special-prefix numpy)
1 . Load the data set
> less fish.csv
Species , Weight , Length1,Length2,Length3,Height ,
;; Bream,242,23.2,25.4,30,11.52,4.02
Bream,290,24,26.3,31.2,12.48,4.3056
;; ...
;; Apart from "Species" all values are floating points.
;; >>> dtypes
;; [('Species', 'U'), ('Weight', 'f8'), ('Length1', 'f8'), ('Length2', 'f8'),
( ' Length3 ' , ' f8 ' ) , ( ' Height ' , ' f8 ' ) , ( ' ' , ' f8 ' ) ]
; `dtype` stands for data type
unicode , 10 characters
#("Weight" "f8") ; floating-point
#("Length1" "f8")
#("Length2" "f8")
#("Length3" "f8")
#("Height" "f8")
#("Width" "f8")))
(define data (numpy.genfromtxt "fish.csv" #:skip_header 1 #:delimiter "," #:dtype dtypes))
2 . Get to know the data set
Print a sample of 10 fish
"Sample of 10 fish"
(define sample (numpy.random.choice data #:size 10))
sample
"Total number of fish"
; (ref (numpy.shape #:a data) 0)
(ref (numpy.shape data) 0)
"Weights in the sample"
(define sample-weights (ref sample "Weight"))
sample-weights
"Lengths in sample"
(define sample-lengths (ref sample "Length1"))
sample-lengths
"Minimal length"
(define sample-min-length (from (numpy.min sample-lengths)))
sample-min-length
"Maximal length"
(define sample-max-length (from (numpy.max sample-lengths)))
sample-max-length
; Could `weight` be estimated using `length1`?
(require plot)
(plot-new-window? #t)
(plot #:title "Sample plot" #:x-label "length1 (cm)" #:y-label "weight (g)"
(points (list->vector (map vector (from sample-lengths) (from sample-weights)))))
; Conclusion for now: to some degree.
3 . Transform data for use with Gradient Descent
(define T numpy.transpose)
(define dot numpy.dot)
turn an 1d array into a column vector
(T (numpy.atleast_2d xs)))
"Weigths as column vector"
(column sample-weights)
(define (prepend-ones Xs)
(define m (ref (numpy.shape Xs) 0))
(numpy.hstack (vector (numpy.ones `#(,m 1))
(column Xs))))
"Lengths with a one-column in front"
(prepend-ones sample-lengths)
4 . Find a model for ` weight ` based on ` length1 ` .
;; We will attempt to find a linear model of the form:
;; weight = w0 + w1 * length1
;; Our job is to find the weights w0 and w1.
;; If we write the model as:
;; weight = w0*1 + w1 * length1
;; We see that the weight is the dot products between the weights and
the length with a prepended 1 .
weight = w . ( 1,length ) where w is the vector ( w0,w1 )
;; The standard regression method is minimal least squares.
;; The sum of the squares of the residual must be minimal.
;; sum_residual_sqares(w) = sum( y - w . xs )
;; where y is the observed values (the weights),
and xs are the independent variables with a 1 in front ( here the length ) .
"Using Numpys least square solver"
(define sample-solution (numpy.linalg.lstsq (prepend-ones sample-lengths) sample-weights #:rcond (void)))
(define sample-coeffs (ref sample-solution 0))
(define sample-residuals (ref sample-solution 1))
(define sample-rank (ref sample-solution 2))
(define sample-singular-values (ref sample-solution 3))
"Sample: solution"
(from sample-coeffs)
"Sample: sum of squared residuals"
sample-residuals
"Sample plot with regression line"
(let ()
(match-define (list w0 w1) (from sample-coeffs))
(define (f x) (+ w0 (* w1 x)))
(plot #:title "Sample with linear model" #:x-label "length1 (cm)" #:y-label "weight (g)"
(list (points (list->vector (map vector (from sample-lengths) (from sample-weights))))
(function f sample-min-length sample-max-length))))
5 . Fine linear model using Gradient Descent
;;
;; The function `sum_residual_squares` can be minimized using the method of Gradient Descent.
srs(w ) = sum_residual_sqares(w ) = sum ( y - w . xs )
;; We already know the result, but this allow us to test the validity of our grafient
;; descent implementation.
;; For a given `w` the gradient of `srs` at `w` is a vector that points in the direction
;; that maximized the growth of `srs`. Thus minus the gradient is a vector that points
;; in the direction that minimizes `srs`.
;; If we repeatedly subtract the gradient (more precisely: a vector with the same
;; direction as the gradient) from our guess, the guess will improve.
;; The idea of gradient descent is simple:
;; w = initial_guess
;; loop:
;; compute gradient
;; w = w - α gradient
;; the coefficient α is called the learning rate.
;; We will use a very simple version of gradient descent and let α be fixed.
The formula for the gradient of ` srs ` can be found at Wikipedia .
def descent(X , y , α = 0.001 , iters = 100 ):
w = np.zeros((X.shape[1 ] , 1 ) )
;; for i in range(iters):
;; gradient = -2.(X.T).dot(y - X.dot(w))
;; w = w - α*gradient
;; return w
(define (gradient-descent xss ys [α 0.001] [iterations 100])
(define X (prepend-ones xss))
(set! ys (column ys))
(define n (ref (numpy.shape ys) 1)) ; n = number of features measured (number of columns)
(define w (numpy.zeros (vector (+ n 1) 1))) ; (n+1)x1
(for ([i (in-range iterations)])
(define predictions (dot X w))
(define observed ys)
(define residuals (sub observed predictions))
(define gradient (mul -2. (dot (T X) residuals)))
(set! w (sub w (mul α gradient))))
w)
"Sample solution found with Gradient Descent"
; these parameters seem to work for most samples
( gradient - descent sample - lengths sample - weights 0.0001 100000 )
| null | https://raw.githubusercontent.com/soegaard/pyffi/84cee7adbd9fcd1206dbe9224915911206498410/pyffi-tutorials/tutorial-numpy-fish-market.rkt | racket |
Fish Market
A number of fish were caught and measurements for each fish were recorded.
and try to predict the `weight` from the other data.
Import and initialize Numpy
Bream,242,23.2,25.4,30,11.52,4.02
...
Apart from "Species" all values are floating points.
>>> dtypes
[('Species', 'U'), ('Weight', 'f8'), ('Length1', 'f8'), ('Length2', 'f8'),
`dtype` stands for data type
floating-point
(ref (numpy.shape #:a data) 0)
Could `weight` be estimated using `length1`?
Conclusion for now: to some degree.
We will attempt to find a linear model of the form:
weight = w0 + w1 * length1
Our job is to find the weights w0 and w1.
If we write the model as:
weight = w0*1 + w1 * length1
We see that the weight is the dot products between the weights and
The standard regression method is minimal least squares.
The sum of the squares of the residual must be minimal.
sum_residual_sqares(w) = sum( y - w . xs )
where y is the observed values (the weights),
The function `sum_residual_squares` can be minimized using the method of Gradient Descent.
We already know the result, but this allow us to test the validity of our grafient
descent implementation.
For a given `w` the gradient of `srs` at `w` is a vector that points in the direction
that maximized the growth of `srs`. Thus minus the gradient is a vector that points
in the direction that minimizes `srs`.
If we repeatedly subtract the gradient (more precisely: a vector with the same
direction as the gradient) from our guess, the guess will improve.
The idea of gradient descent is simple:
w = initial_guess
loop:
compute gradient
w = w - α gradient
the coefficient α is called the learning rate.
We will use a very simple version of gradient descent and let α be fixed.
for i in range(iters):
gradient = -2.(X.T).dot(y - X.dot(w))
w = w - α*gradient
return w
n = number of features measured (number of columns)
(n+1)x1
these parameters seem to work for most samples | #lang racket
This example uses a data set from Finland .
One way to use the data set : Consider ` weight ` the dependent variable
(require pyffi pyffi/numpy)
(initialize)
(import-numpy)
(finish-initialization)
(declare-special-prefix numpy)
1 . Load the data set
> less fish.csv
Species , Weight , Length1,Length2,Length3,Height ,
Bream,290,24,26.3,31.2,12.48,4.3056
( ' Length3 ' , ' f8 ' ) , ( ' Height ' , ' f8 ' ) , ( ' ' , ' f8 ' ) ]
unicode , 10 characters
#("Length1" "f8")
#("Length2" "f8")
#("Length3" "f8")
#("Height" "f8")
#("Width" "f8")))
(define data (numpy.genfromtxt "fish.csv" #:skip_header 1 #:delimiter "," #:dtype dtypes))
2 . Get to know the data set
Print a sample of 10 fish
"Sample of 10 fish"
(define sample (numpy.random.choice data #:size 10))
sample
"Total number of fish"
(ref (numpy.shape data) 0)
"Weights in the sample"
(define sample-weights (ref sample "Weight"))
sample-weights
"Lengths in sample"
(define sample-lengths (ref sample "Length1"))
sample-lengths
"Minimal length"
(define sample-min-length (from (numpy.min sample-lengths)))
sample-min-length
"Maximal length"
(define sample-max-length (from (numpy.max sample-lengths)))
sample-max-length
(require plot)
(plot-new-window? #t)
(plot #:title "Sample plot" #:x-label "length1 (cm)" #:y-label "weight (g)"
(points (list->vector (map vector (from sample-lengths) (from sample-weights)))))
3 . Transform data for use with Gradient Descent
(define T numpy.transpose)
(define dot numpy.dot)
turn an 1d array into a column vector
(T (numpy.atleast_2d xs)))
"Weigths as column vector"
(column sample-weights)
(define (prepend-ones Xs)
(define m (ref (numpy.shape Xs) 0))
(numpy.hstack (vector (numpy.ones `#(,m 1))
(column Xs))))
"Lengths with a one-column in front"
(prepend-ones sample-lengths)
4 . Find a model for ` weight ` based on ` length1 ` .
the length with a prepended 1 .
weight = w . ( 1,length ) where w is the vector ( w0,w1 )
and xs are the independent variables with a 1 in front ( here the length ) .
"Using Numpys least square solver"
(define sample-solution (numpy.linalg.lstsq (prepend-ones sample-lengths) sample-weights #:rcond (void)))
(define sample-coeffs (ref sample-solution 0))
(define sample-residuals (ref sample-solution 1))
(define sample-rank (ref sample-solution 2))
(define sample-singular-values (ref sample-solution 3))
"Sample: solution"
(from sample-coeffs)
"Sample: sum of squared residuals"
sample-residuals
"Sample plot with regression line"
(let ()
(match-define (list w0 w1) (from sample-coeffs))
(define (f x) (+ w0 (* w1 x)))
(plot #:title "Sample with linear model" #:x-label "length1 (cm)" #:y-label "weight (g)"
(list (points (list->vector (map vector (from sample-lengths) (from sample-weights))))
(function f sample-min-length sample-max-length))))
5 . Fine linear model using Gradient Descent
srs(w ) = sum_residual_sqares(w ) = sum ( y - w . xs )
The formula for the gradient of ` srs ` can be found at Wikipedia .
def descent(X , y , α = 0.001 , iters = 100 ):
w = np.zeros((X.shape[1 ] , 1 ) )
(define (gradient-descent xss ys [α 0.001] [iterations 100])
(define X (prepend-ones xss))
(set! ys (column ys))
(for ([i (in-range iterations)])
(define predictions (dot X w))
(define observed ys)
(define residuals (sub observed predictions))
(define gradient (mul -2. (dot (T X) residuals)))
(set! w (sub w (mul α gradient))))
w)
"Sample solution found with Gradient Descent"
( gradient - descent sample - lengths sample - weights 0.0001 100000 )
|
ebd2091fa419e35d805adde96f581bae8b5e2809bd2d6bbd454d2b77c3b0be12 | 05st/artemis | Name.hs | module Name where
data Namespace = Global | Relative Namespace String deriving (Eq, Ord)
data QualifiedName = Qualified Namespace String deriving (Eq, Ord)
instance Show Namespace where
show Global = []
show (Relative parent name) = show parent ++ "::" ++ name
instance Show QualifiedName where
show (Qualified namespace name) = show namespace ++ "::" ++ name
| null | https://raw.githubusercontent.com/05st/artemis/0a5622a07d225ce7c14ef61e9c46ce2a46a42536/src/Name.hs | haskell | module Name where
data Namespace = Global | Relative Namespace String deriving (Eq, Ord)
data QualifiedName = Qualified Namespace String deriving (Eq, Ord)
instance Show Namespace where
show Global = []
show (Relative parent name) = show parent ++ "::" ++ name
instance Show QualifiedName where
show (Qualified namespace name) = show namespace ++ "::" ++ name
|
|
dd4f8cb0d34d2f36c3d27f96d38ac4d75c193dd007749081afb3b1f184d1facd | Ericson2314/lighthouse | Substrate.hs | # OPTIONS_GHC -ffi #
{-# OPTIONS_GHC -fglasgow-exts #-}
module LwConc.Substrate
( SCont
, newSCont
, switch
, TLSKey
, newTLSKey
, getTLS
, setTLS
) where
import GHC.Exts
import GHC.Prim
import GHC.IOBase
import LwConc.PTM
import Data.IORef
import Data.Sequence as Seq
-----------------------------------------------------------------------------
Thread Local State ( TLS )
data TLSKey a = TLSKey Int#
newTLSKey :: a -> IO (TLSKey a)
newTLSKey x = IO $ \s10# ->
case newTLSKey# x s10# of
(#s20#, key #) -> (#s20#, TLSKey key #)
getTLS :: TLSKey a -> PTM a
getTLS (TLSKey key) = unsafeIOToPTM $ IO $ \s -> case getTLS# key s of
(# s', val #) -> (# s', val #)
setTLS :: TLSKey a -> a -> IO ()
setTLS (TLSKey key) x = IO $ \s10# ->
case setTLS# key x s10# of
s20# -> (# s20#, () #)
-----------------------------------------------------------------------------
Stack Continuations ( SCont )
Continuations are one - shot and consist of the TSO along with ( essentially )
-- a boolean flag to indicate whether the SCont is "used up", i.e. already
-- switched to.
data SContStatus = Used | Usable
data SCont = SCont TSO# (IORef SContStatus)
instance Eq SCont where
(SCont _ xref) == (SCont _ yref) = xref == yref
# INLINE newSCont #
newSCont :: IO () -> IO SCont
newSCont x = do ref <- newIORef Usable
IO $ \s -> case newSCont# x s of
(# s', tso #) -> (# s', SCont tso ref #)
# INLINE switch #
switch :: (SCont -> PTM SCont) -> IO ()
switch scheduler = do s1 <- getSCont
s2 <- atomically (scheduler s1)
switchTo s2
where getSCont :: IO SCont
getSCont = do ref <- newIORef Usable
IO $ \s -> case getTSO# s of (# s', tso #) -> (# s', SCont tso ref #)
switchTo :: SCont -> IO ()
switchTo (SCont tso ref) =
do status <- readIORef ref
case status of
Used -> error "Attempted to switch to used SCont!"
Usable -> do writeIORef ref Used
IO $ \s -> case switch# tso s of s' -> (# s', () #)
| null | https://raw.githubusercontent.com/Ericson2314/lighthouse/210078b846ebd6c43b89b5f0f735362a01a9af02/ghc-6.8.2/libraries/base/LwConc/Substrate.hs | haskell | # OPTIONS_GHC -fglasgow-exts #
---------------------------------------------------------------------------
---------------------------------------------------------------------------
a boolean flag to indicate whether the SCont is "used up", i.e. already
switched to. | # OPTIONS_GHC -ffi #
module LwConc.Substrate
( SCont
, newSCont
, switch
, TLSKey
, newTLSKey
, getTLS
, setTLS
) where
import GHC.Exts
import GHC.Prim
import GHC.IOBase
import LwConc.PTM
import Data.IORef
import Data.Sequence as Seq
Thread Local State ( TLS )
data TLSKey a = TLSKey Int#
newTLSKey :: a -> IO (TLSKey a)
newTLSKey x = IO $ \s10# ->
case newTLSKey# x s10# of
(#s20#, key #) -> (#s20#, TLSKey key #)
getTLS :: TLSKey a -> PTM a
getTLS (TLSKey key) = unsafeIOToPTM $ IO $ \s -> case getTLS# key s of
(# s', val #) -> (# s', val #)
setTLS :: TLSKey a -> a -> IO ()
setTLS (TLSKey key) x = IO $ \s10# ->
case setTLS# key x s10# of
s20# -> (# s20#, () #)
Stack Continuations ( SCont )
Continuations are one - shot and consist of the TSO along with ( essentially )
data SContStatus = Used | Usable
data SCont = SCont TSO# (IORef SContStatus)
instance Eq SCont where
(SCont _ xref) == (SCont _ yref) = xref == yref
# INLINE newSCont #
newSCont :: IO () -> IO SCont
newSCont x = do ref <- newIORef Usable
IO $ \s -> case newSCont# x s of
(# s', tso #) -> (# s', SCont tso ref #)
# INLINE switch #
switch :: (SCont -> PTM SCont) -> IO ()
switch scheduler = do s1 <- getSCont
s2 <- atomically (scheduler s1)
switchTo s2
where getSCont :: IO SCont
getSCont = do ref <- newIORef Usable
IO $ \s -> case getTSO# s of (# s', tso #) -> (# s', SCont tso ref #)
switchTo :: SCont -> IO ()
switchTo (SCont tso ref) =
do status <- readIORef ref
case status of
Used -> error "Attempted to switch to used SCont!"
Usable -> do writeIORef ref Used
IO $ \s -> case switch# tso s of s' -> (# s', () #)
|
84f304a52e54fb679ab936e8f2dc14b239275914db4e4e0e0b06062eb4a2ee27 | charlieg/Sparser | rule-population-window.lisp | ;;; -*- Mode:Lisp; Syntax:Common-Lisp; Package:SPARSER
copyright ( c ) 1995 -- all rights reserved
;;;
;;; File: "rule population window"
;;; module: "interface;workbench:def rule:"
Version : December 1995
broken out of [ define - rule ] 4/27 . 6/14 added initialization for
* rdt / reference - category * . 8/28 added dossier hooks . 11/16 extended
the canonical - positioning and warping - off - screen code . 11/17 added result
;; announcement widgets. (12/5) fixed bug it initialization of that.
12/18 added the global for the autodef save routine to the state cleanup
routine . 12/26 tweeked Shutdown - rdt - rule - population - widget - state to reverse
;; possible effects of *slvd/tree-family-restriction*
(in-package :sparser)
(defparameter *rdt/rule-populating-window* nil)
(defclass rdt/rule-population-window (dialog) ())
(defun launch-rdt-rule-populating-window
(&key (position #@(30 57))
(size #@(455 275)))
(warp-announcement-widgets-off-screen)
(setq *rdt/rule-populating-window*
(MAKE-INSTANCE 'rdt/rule-population-window
:WINDOW-TYPE :DOCUMENT ;;-WITH-GROW
:window-title "Populate rule schema"
:VIEW-POSITION position
:VIEW-SIZE size
:VIEW-FONT '("Chicago" 12 :SRCOR :PLAIN)
:VIEW-SUBVIEWS
(list *rdtrpw/ok-button*
*rdtrpw/next-pattern-button*
*rdtrpw/change-schema-button*
*rdtrpw/abort-button*
*rdtrpw/syntax-label*
*rdtrpw/lhs-radio-button*
*rdtrpw/lhs-input*
*rdtrpw/lhs-description*
*rdtrpw/rhs/left/radio-button*
*rdtrpw/rhs/left/input*
*rdtrpw/rhs/left/description*
*rdtrpw/rhs/right/radio-button*
*rdtrpw/rhs/right/input*
*rdtrpw/rhs/right/description*
*rdtrpw/semantics-label*
*rdtrpw/reference-category-button*
*rdtrpw/headline-radio-button*
*rdtrpw/headline-input*
*rdtrpw/headline-description*
*rdtrpw/comp-radio-button*
*rdtrpw/comp-input*
*rdtrpw/comp-description*
*rdtrpw/result-radio-button*
*rdtrpw/result-input*
*rdtrpw/result-description*
*rdt/dossier-label*
*rdt/dossier-namestring*
*rdt/change-dossier-button*
*rdt/result-rule-banner*
*rdt/result-rule-listing*
*rdt/result-saved-banner*
*rdt/result-saved-filename*
*rdt/result-view-file-button*
*rdt/result-ok-button*
)))
(initialize-rdt-rule-population-widget-state))
(defmethod Window-close ((w rdt/rule-population-window))
(close-down-rdt-rule-population-state)
(call-next-method w))
(defun close-down-rdt-rule-population-state ()
(setq *rdt/rule-populating-window* nil
*predefined-partial-rdt-mapping* nil
*slvd/save-routine* nil)
(shutdown-rdt-rule-population-widget-state))
(defun shutdown-rdt-rule-population-widget-state ()
(release-edges-table-from-rdt-input-fields)
(release-inspector-from-rdt-input-fields)
(when *slvd/tree-family-restriction*
(setq *slvd/tree-family-restriction* nil)
(populate-rdt-schema-table-items)))
(defun initialize-rdt-rule-population-widget-state ()
(wire-edges-table-to-rdt-input-fields)
(wire-inspector-to-rdt-input-fields)
( setq * rdt / input - field - for - selected - edge * 6/15/95
* / rhs / right / input * )
(setq *rdt/input-field-for-selected-edge* nil)
(ccl:set-dialog-item-text *rdtrpw/lhs-input* "lhs")
(ccl:set-dialog-item-text *rdtrpw/rhs/left/input* "rhs, left-edge")
(ccl:set-dialog-item-text *rdtrpw/rhs/right/input* "rhs, right-edge")
(ccl:set-dialog-item-text *rdtrpw/headline-input* "slot filled by head")
(ccl:set-dialog-item-text *rdtrpw/comp-input* "slot filled by comp/spec")
(ccl:set-dialog-item-text *rdtrpw/result-input* "category of result")
(ccl:set-dialog-item-text *rdtrpw/lhs-description* "spanning label")
(ccl:set-dialog-item-text *rdtrpw/rhs/left/description* "") ;; the rest are done
(ccl:set-dialog-item-text *rdtrpw/rhs/right/description* "") ;; during the setup
(ccl:set-dialog-item-text *rdtrpw/headline-description* "")
(ccl:set-dialog-item-text *rdtrpw/comp-description* "")
(ccl:set-dialog-item-text *rdtrpw/result-description* "")
(ccl:dialog-item-disable *rdtrpw/ok-button*)
(set-default-button *rdt/rule-populating-window* *rdtrpw/ok-button*)
(ccl:dialog-item-disable *rdtrpw/next-pattern-button*)
(ccl:set-dialog-item-text *rdtrpw/next-pattern-button* "next pattern")
(ccl:dialog-item-enable *rdtrpw/change-schema-button*)
(ccl:dialog-item-enable *rdtrpw/abort-button*)
(if *slvd/reference-category* ;; from higher level driver
(ccl:set-dialog-item-text *rdtrpw/reference-category-button*
(string-downcase
(cat-symbol *slvd/reference-category*)))
(ccl:set-dialog-item-text *rdtrpw/reference-category-button*
"reference category"))
(setq *rdt/reference-category* (or *slvd/reference-category*
nil))
(setq *rdt/lhs-label* nil)
(setq *rdt/rhs-left-label* nil)
(setq *rdt/rhs-right-label* nil)
(setq *rdt/result-category* nil)
(setq *rdt/head-line-category* nil)
(setq *rdt/comp-category* nil)
(setq *rdt/mapping-schema* nil)
(setq *rdt/mapping* (or *predefined-partial-rdt-mapping*
nil))
(setq *rdt/nailed-down-fields* nil)
(initialize-rdt-dossier)
(warp-announcement-widgets-off-screen)
(set-rdt-widgets-to-canonical-positions))
;;;-----------------------------------------
;;; after-initialization widget positioning
;;;-----------------------------------------
(defun set-rdt-widgets-to-canonical-positions ()
called from Initialize - schema - selection - state
(ccl:set-view-position *rdtrpw/ok-button* #@(14 187))
(ccl:set-view-position *rdtrpw/next-pattern-button* #@(106 187))
(ccl:set-view-position *rdtrpw/change-schema-button* #@(295 187))
(ccl:set-view-position *rdtrpw/abort-button* #@(380 215))
(ccl:set-view-position *rdtrpw/syntax-label* #@(84 7))
(ccl:set-view-position *rdtrpw/lhs-radio-button* #@(3 39))
(ccl:set-view-position *rdtrpw/lhs-input* #@(25 39))
(ccl:set-view-position *rdtrpw/lhs-description* #@(25 62))
(ccl:set-view-position *rdtrpw/rhs/left/radio-button* #@(3 84))
(ccl:set-view-position *rdtrpw/rhs/left/input* #@(25 84))
(ccl:set-view-position *rdtrpw/rhs/left/description* #@(25 108))
(ccl:set-view-position *rdtrpw/rhs/right/radio-button* #@(3 129))
(ccl:set-view-position *rdtrpw/rhs/right/input* #@(25 129))
(ccl:set-view-position *rdtrpw/rhs/right/description* #@(25 154))
(ccl:set-view-position *rdtrpw/semantics-label* #@(260 6))
(ccl:set-view-position *rdtrpw/reference-category-button* #@(337 6))
(ccl:set-view-position *rdt/dossier-label* #@(39 224))
(ccl:set-view-position *rdt/dossier-namestring* #@(107 226))
(ccl:set-view-position *rdt/change-dossier-button* #@(8 244))
(setup-rdt-semantic-widgets-in-canonical-positions))
(defun setup-rdt-semantic-widgets-in-canonical-positions ()
(place-result-widgets)
(place-comp-widgets)
(place-headline-widgets))
(defun warp-rdt-semantic-widgets-off-screen ()
(warp-result-widgets-off-screen)
(warp-comp-widgets-off-screen)
(warp-head-widgets-off-screen))
(defun place-result-widgets ()
(ccl:set-view-position *rdtrpw/result-radio-button* #@(228 39))
(ccl:set-view-position *rdtrpw/result-input* #@(252 39))
(ccl:set-view-position *rdtrpw/result-description* #@(252 62)))
(defun warp-result-widgets-off-screen ()
called from drirt / Just - bindings
(ccl:set-view-position *rdtrpw/result-radio-button* #@(528 129))
(ccl:set-view-position *rdtrpw/result-input* #@(552 39))
(ccl:set-view-position *rdtrpw/result-description* #@(552 62)))
(defun place-comp-widgets ()
(ccl:set-view-position *rdtrpw/comp-radio-button* #@(228 84))
(ccl:set-view-position *rdtrpw/comp-input* #@(252 84))
(ccl:set-view-position *rdtrpw/comp-description* #@(252 106)))
(defun warp-comp-widgets-off-screen ()
(ccl:set-view-position *rdtrpw/comp-radio-button* #@(528 84))
(ccl:set-view-position *rdtrpw/comp-input* #@(552 84))
(ccl:set-view-position *rdtrpw/comp-description* #@(552 106)))
(defun warp-comp-widgets-to-head-position ()
(ccl:set-view-position *rdtrpw/comp-radio-button* #@(228 129))
(ccl:set-view-position *rdtrpw/comp-input* #@(252 129))
(ccl:set-view-position *rdtrpw/comp-description* #@(252 154)))
(defun place-headline-widgets ()
(ccl:set-view-position *rdtrpw/headline-radio-button* #@(228 129))
(ccl:set-view-position *rdtrpw/headline-input* #@(252 129))
(ccl:set-view-position *rdtrpw/headline-description* #@(252 154)))
(defun warp-head-widgets-off-screen ()
(ccl:set-view-position *rdtrpw/headline-radio-button* #@(528 129))
(ccl:set-view-position *rdtrpw/headline-input* #@(552 129))
(ccl:set-view-position *rdtrpw/headline-description* #@(552 154)))
(defun warp-head-widgets-to-comp-position ()
(ccl:set-view-position *rdtrpw/headline-radio-button* #@(228 84))
(ccl:set-view-position *rdtrpw/headline-input* #@(252 84))
(ccl:set-view-position *rdtrpw/headline-description* #@(252 106)))
(defun clear-widgets-off-the-rdt-visible-window-area ()
called from Initialize - schema - selection - state
(ccl:set-view-position *rdtrpw/ok-button* #@(14 587))
(ccl:set-view-position *rdtrpw/next-pattern-button* #@(106 587))
(ccl:set-view-position *rdtrpw/change-schema-button* #@(295 587))
(ccl:set-view-position *rdtrpw/abort-button* #@(380 515))
(ccl:set-view-position *rdtrpw/syntax-label* #@(84 507))
(ccl:set-view-position *rdtrpw/lhs-radio-button* #@(3 539))
(ccl:set-view-position *rdtrpw/lhs-input* #@(25 539))
(ccl:set-view-position *rdtrpw/lhs-description* #@(25 562))
(ccl:set-view-position *rdtrpw/rhs/left/radio-button* #@(3 584))
(ccl:set-view-position *rdtrpw/rhs/left/input* #@(25 584))
(ccl:set-view-position *rdtrpw/rhs/left/description* #@(25 508))
(ccl:set-view-position *rdtrpw/rhs/right/radio-button* #@(3 529))
(ccl:set-view-position *rdtrpw/rhs/right/input* #@(25 529))
(ccl:set-view-position *rdtrpw/rhs/right/description* #@(25 554))
(ccl:set-view-position *rdtrpw/semantics-label* #@(260 506))
(ccl:set-view-position *rdtrpw/reference-category-button* #@(337 506))
(ccl:set-view-position *rdt/dossier-label* #@(39 524))
(ccl:set-view-position *rdt/dossier-namestring* #@(107 526))
(ccl:set-view-position *rdt/change-dossier-button* #@(8 544))
(warp-rdt-semantic-widgets-off-screen))
(defun move-the-announcement-widgets-onto-the-rdt-window ()
(ccl:set-view-position *rdt/result-rule-banner* #@(14 10))
(ccl:set-view-position *rdt/result-rule-listing* #@(50 33))
(ccl:set-view-position *rdt/result-saved-banner* #@(7 186))
(ccl:set-view-position *rdt/result-saved-filename* #@(39 201))
(ccl:set-view-position *rdt/result-view-file-button* #@(50 248))
(ccl:set-view-position *rdt/result-ok-button* #@(380 239)))
(defun warp-announcement-widgets-off-screen ()
(ccl:set-view-position *rdt/result-rule-banner* #@(514 10))
(ccl:set-view-position *rdt/result-rule-listing* #@(550 33))
(ccl:set-view-position *rdt/result-saved-banner* #@(507 186))
(ccl:set-view-position *rdt/result-saved-filename* #@(539 201))
(ccl:set-view-position *rdt/result-view-file-button* #@(550 248))
(ccl:set-view-position *rdt/result-ok-button* #@(580 239)))
| null | https://raw.githubusercontent.com/charlieg/Sparser/b9bb7d01d2e40f783f3214fc104062db3d15e608/Sparser/code/s/interface/workbench/def-rule/rule-population-window.lisp | lisp | -*- Mode:Lisp; Syntax:Common-Lisp; Package:SPARSER
File: "rule population window"
module: "interface;workbench:def rule:"
announcement widgets. (12/5) fixed bug it initialization of that.
possible effects of *slvd/tree-family-restriction*
-WITH-GROW
the rest are done
during the setup
from higher level driver
-----------------------------------------
after-initialization widget positioning
----------------------------------------- | copyright ( c ) 1995 -- all rights reserved
Version : December 1995
broken out of [ define - rule ] 4/27 . 6/14 added initialization for
* rdt / reference - category * . 8/28 added dossier hooks . 11/16 extended
the canonical - positioning and warping - off - screen code . 11/17 added result
12/18 added the global for the autodef save routine to the state cleanup
routine . 12/26 tweeked Shutdown - rdt - rule - population - widget - state to reverse
(in-package :sparser)
(defparameter *rdt/rule-populating-window* nil)
(defclass rdt/rule-population-window (dialog) ())
(defun launch-rdt-rule-populating-window
(&key (position #@(30 57))
(size #@(455 275)))
(warp-announcement-widgets-off-screen)
(setq *rdt/rule-populating-window*
(MAKE-INSTANCE 'rdt/rule-population-window
:window-title "Populate rule schema"
:VIEW-POSITION position
:VIEW-SIZE size
:VIEW-FONT '("Chicago" 12 :SRCOR :PLAIN)
:VIEW-SUBVIEWS
(list *rdtrpw/ok-button*
*rdtrpw/next-pattern-button*
*rdtrpw/change-schema-button*
*rdtrpw/abort-button*
*rdtrpw/syntax-label*
*rdtrpw/lhs-radio-button*
*rdtrpw/lhs-input*
*rdtrpw/lhs-description*
*rdtrpw/rhs/left/radio-button*
*rdtrpw/rhs/left/input*
*rdtrpw/rhs/left/description*
*rdtrpw/rhs/right/radio-button*
*rdtrpw/rhs/right/input*
*rdtrpw/rhs/right/description*
*rdtrpw/semantics-label*
*rdtrpw/reference-category-button*
*rdtrpw/headline-radio-button*
*rdtrpw/headline-input*
*rdtrpw/headline-description*
*rdtrpw/comp-radio-button*
*rdtrpw/comp-input*
*rdtrpw/comp-description*
*rdtrpw/result-radio-button*
*rdtrpw/result-input*
*rdtrpw/result-description*
*rdt/dossier-label*
*rdt/dossier-namestring*
*rdt/change-dossier-button*
*rdt/result-rule-banner*
*rdt/result-rule-listing*
*rdt/result-saved-banner*
*rdt/result-saved-filename*
*rdt/result-view-file-button*
*rdt/result-ok-button*
)))
(initialize-rdt-rule-population-widget-state))
(defmethod Window-close ((w rdt/rule-population-window))
(close-down-rdt-rule-population-state)
(call-next-method w))
(defun close-down-rdt-rule-population-state ()
(setq *rdt/rule-populating-window* nil
*predefined-partial-rdt-mapping* nil
*slvd/save-routine* nil)
(shutdown-rdt-rule-population-widget-state))
(defun shutdown-rdt-rule-population-widget-state ()
(release-edges-table-from-rdt-input-fields)
(release-inspector-from-rdt-input-fields)
(when *slvd/tree-family-restriction*
(setq *slvd/tree-family-restriction* nil)
(populate-rdt-schema-table-items)))
(defun initialize-rdt-rule-population-widget-state ()
(wire-edges-table-to-rdt-input-fields)
(wire-inspector-to-rdt-input-fields)
( setq * rdt / input - field - for - selected - edge * 6/15/95
* / rhs / right / input * )
(setq *rdt/input-field-for-selected-edge* nil)
(ccl:set-dialog-item-text *rdtrpw/lhs-input* "lhs")
(ccl:set-dialog-item-text *rdtrpw/rhs/left/input* "rhs, left-edge")
(ccl:set-dialog-item-text *rdtrpw/rhs/right/input* "rhs, right-edge")
(ccl:set-dialog-item-text *rdtrpw/headline-input* "slot filled by head")
(ccl:set-dialog-item-text *rdtrpw/comp-input* "slot filled by comp/spec")
(ccl:set-dialog-item-text *rdtrpw/result-input* "category of result")
(ccl:set-dialog-item-text *rdtrpw/lhs-description* "spanning label")
(ccl:set-dialog-item-text *rdtrpw/headline-description* "")
(ccl:set-dialog-item-text *rdtrpw/comp-description* "")
(ccl:set-dialog-item-text *rdtrpw/result-description* "")
(ccl:dialog-item-disable *rdtrpw/ok-button*)
(set-default-button *rdt/rule-populating-window* *rdtrpw/ok-button*)
(ccl:dialog-item-disable *rdtrpw/next-pattern-button*)
(ccl:set-dialog-item-text *rdtrpw/next-pattern-button* "next pattern")
(ccl:dialog-item-enable *rdtrpw/change-schema-button*)
(ccl:dialog-item-enable *rdtrpw/abort-button*)
(ccl:set-dialog-item-text *rdtrpw/reference-category-button*
(string-downcase
(cat-symbol *slvd/reference-category*)))
(ccl:set-dialog-item-text *rdtrpw/reference-category-button*
"reference category"))
(setq *rdt/reference-category* (or *slvd/reference-category*
nil))
(setq *rdt/lhs-label* nil)
(setq *rdt/rhs-left-label* nil)
(setq *rdt/rhs-right-label* nil)
(setq *rdt/result-category* nil)
(setq *rdt/head-line-category* nil)
(setq *rdt/comp-category* nil)
(setq *rdt/mapping-schema* nil)
(setq *rdt/mapping* (or *predefined-partial-rdt-mapping*
nil))
(setq *rdt/nailed-down-fields* nil)
(initialize-rdt-dossier)
(warp-announcement-widgets-off-screen)
(set-rdt-widgets-to-canonical-positions))
(defun set-rdt-widgets-to-canonical-positions ()
called from Initialize - schema - selection - state
(ccl:set-view-position *rdtrpw/ok-button* #@(14 187))
(ccl:set-view-position *rdtrpw/next-pattern-button* #@(106 187))
(ccl:set-view-position *rdtrpw/change-schema-button* #@(295 187))
(ccl:set-view-position *rdtrpw/abort-button* #@(380 215))
(ccl:set-view-position *rdtrpw/syntax-label* #@(84 7))
(ccl:set-view-position *rdtrpw/lhs-radio-button* #@(3 39))
(ccl:set-view-position *rdtrpw/lhs-input* #@(25 39))
(ccl:set-view-position *rdtrpw/lhs-description* #@(25 62))
(ccl:set-view-position *rdtrpw/rhs/left/radio-button* #@(3 84))
(ccl:set-view-position *rdtrpw/rhs/left/input* #@(25 84))
(ccl:set-view-position *rdtrpw/rhs/left/description* #@(25 108))
(ccl:set-view-position *rdtrpw/rhs/right/radio-button* #@(3 129))
(ccl:set-view-position *rdtrpw/rhs/right/input* #@(25 129))
(ccl:set-view-position *rdtrpw/rhs/right/description* #@(25 154))
(ccl:set-view-position *rdtrpw/semantics-label* #@(260 6))
(ccl:set-view-position *rdtrpw/reference-category-button* #@(337 6))
(ccl:set-view-position *rdt/dossier-label* #@(39 224))
(ccl:set-view-position *rdt/dossier-namestring* #@(107 226))
(ccl:set-view-position *rdt/change-dossier-button* #@(8 244))
(setup-rdt-semantic-widgets-in-canonical-positions))
(defun setup-rdt-semantic-widgets-in-canonical-positions ()
(place-result-widgets)
(place-comp-widgets)
(place-headline-widgets))
(defun warp-rdt-semantic-widgets-off-screen ()
(warp-result-widgets-off-screen)
(warp-comp-widgets-off-screen)
(warp-head-widgets-off-screen))
(defun place-result-widgets ()
(ccl:set-view-position *rdtrpw/result-radio-button* #@(228 39))
(ccl:set-view-position *rdtrpw/result-input* #@(252 39))
(ccl:set-view-position *rdtrpw/result-description* #@(252 62)))
(defun warp-result-widgets-off-screen ()
called from drirt / Just - bindings
(ccl:set-view-position *rdtrpw/result-radio-button* #@(528 129))
(ccl:set-view-position *rdtrpw/result-input* #@(552 39))
(ccl:set-view-position *rdtrpw/result-description* #@(552 62)))
(defun place-comp-widgets ()
(ccl:set-view-position *rdtrpw/comp-radio-button* #@(228 84))
(ccl:set-view-position *rdtrpw/comp-input* #@(252 84))
(ccl:set-view-position *rdtrpw/comp-description* #@(252 106)))
(defun warp-comp-widgets-off-screen ()
(ccl:set-view-position *rdtrpw/comp-radio-button* #@(528 84))
(ccl:set-view-position *rdtrpw/comp-input* #@(552 84))
(ccl:set-view-position *rdtrpw/comp-description* #@(552 106)))
(defun warp-comp-widgets-to-head-position ()
(ccl:set-view-position *rdtrpw/comp-radio-button* #@(228 129))
(ccl:set-view-position *rdtrpw/comp-input* #@(252 129))
(ccl:set-view-position *rdtrpw/comp-description* #@(252 154)))
(defun place-headline-widgets ()
(ccl:set-view-position *rdtrpw/headline-radio-button* #@(228 129))
(ccl:set-view-position *rdtrpw/headline-input* #@(252 129))
(ccl:set-view-position *rdtrpw/headline-description* #@(252 154)))
(defun warp-head-widgets-off-screen ()
(ccl:set-view-position *rdtrpw/headline-radio-button* #@(528 129))
(ccl:set-view-position *rdtrpw/headline-input* #@(552 129))
(ccl:set-view-position *rdtrpw/headline-description* #@(552 154)))
(defun warp-head-widgets-to-comp-position ()
(ccl:set-view-position *rdtrpw/headline-radio-button* #@(228 84))
(ccl:set-view-position *rdtrpw/headline-input* #@(252 84))
(ccl:set-view-position *rdtrpw/headline-description* #@(252 106)))
(defun clear-widgets-off-the-rdt-visible-window-area ()
called from Initialize - schema - selection - state
(ccl:set-view-position *rdtrpw/ok-button* #@(14 587))
(ccl:set-view-position *rdtrpw/next-pattern-button* #@(106 587))
(ccl:set-view-position *rdtrpw/change-schema-button* #@(295 587))
(ccl:set-view-position *rdtrpw/abort-button* #@(380 515))
(ccl:set-view-position *rdtrpw/syntax-label* #@(84 507))
(ccl:set-view-position *rdtrpw/lhs-radio-button* #@(3 539))
(ccl:set-view-position *rdtrpw/lhs-input* #@(25 539))
(ccl:set-view-position *rdtrpw/lhs-description* #@(25 562))
(ccl:set-view-position *rdtrpw/rhs/left/radio-button* #@(3 584))
(ccl:set-view-position *rdtrpw/rhs/left/input* #@(25 584))
(ccl:set-view-position *rdtrpw/rhs/left/description* #@(25 508))
(ccl:set-view-position *rdtrpw/rhs/right/radio-button* #@(3 529))
(ccl:set-view-position *rdtrpw/rhs/right/input* #@(25 529))
(ccl:set-view-position *rdtrpw/rhs/right/description* #@(25 554))
(ccl:set-view-position *rdtrpw/semantics-label* #@(260 506))
(ccl:set-view-position *rdtrpw/reference-category-button* #@(337 506))
(ccl:set-view-position *rdt/dossier-label* #@(39 524))
(ccl:set-view-position *rdt/dossier-namestring* #@(107 526))
(ccl:set-view-position *rdt/change-dossier-button* #@(8 544))
(warp-rdt-semantic-widgets-off-screen))
(defun move-the-announcement-widgets-onto-the-rdt-window ()
(ccl:set-view-position *rdt/result-rule-banner* #@(14 10))
(ccl:set-view-position *rdt/result-rule-listing* #@(50 33))
(ccl:set-view-position *rdt/result-saved-banner* #@(7 186))
(ccl:set-view-position *rdt/result-saved-filename* #@(39 201))
(ccl:set-view-position *rdt/result-view-file-button* #@(50 248))
(ccl:set-view-position *rdt/result-ok-button* #@(380 239)))
(defun warp-announcement-widgets-off-screen ()
(ccl:set-view-position *rdt/result-rule-banner* #@(514 10))
(ccl:set-view-position *rdt/result-rule-listing* #@(550 33))
(ccl:set-view-position *rdt/result-saved-banner* #@(507 186))
(ccl:set-view-position *rdt/result-saved-filename* #@(539 201))
(ccl:set-view-position *rdt/result-view-file-button* #@(550 248))
(ccl:set-view-position *rdt/result-ok-button* #@(580 239)))
|
48eec91d8faf31ff07d5a72841c2c4ed663abc0c0772f71621069473873eb683 | xapi-project/xen-api | lwt_support.ml |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Iteratees
type 'a t = 'a Iteratee(Lwt).t =
| IE_done of 'a
| IE_cont of err option * (stream -> ('a t * stream) Lwt.t)
let ( >>= ) = Lwt.bind
let really_write fd str =
let len = String.length str in
let rec inner written =
Lwt_unix.write fd (Bytes.unsafe_of_string str) written (len - written)
>>= fun n ->
if n < len - written then inner (written + n) else Lwt.return ()
in
inner 0
let lwt_fd_enumerator fd =
let blocksize = 1024 in
let buf = Bytes.create blocksize in
let get_str n =
if n = 0 then
Eof None
else
Chunk (Bytes.sub_string buf 0 n)
in
let rec go = function
| IE_cont (None, x) ->
Lwt_unix.read fd buf 0 blocksize >>= fun n ->
x (get_str n) >>= fun x ->
Lwt.return (fst x) >>= fun x -> go x
| x ->
Lwt.return x
in
go
let lwt_enumerator file iter =
Lwt_unix.openfile file [Lwt_unix.O_RDONLY] 0o777 >>= fun fd ->
lwt_fd_enumerator fd iter
exception Host_not_found of string
let with_fd fd ~callback =
Lwt.finalize
(fun () -> callback fd)
(* The Lwt.catch below prevents errors on double close of the fd. *)
(fun () ->
Lwt.catch (fun () -> Lwt_unix.close fd) (fun _ -> Lwt.return_unit)
)
let with_open_connection_fd addr ~callback =
let s = Lwt_unix.(socket (Unix.domain_of_sockaddr addr) SOCK_STREAM 0) in
with_fd s ~callback:(fun fd ->
Lwt_unix.setsockopt fd Lwt_unix.SO_KEEPALIVE true ;
Lwt_unix.connect fd addr >>= fun () -> callback fd
)
| null | https://raw.githubusercontent.com/xapi-project/xen-api/47fae74032aa6ade0fc12e867c530eaf2a96bf75/ocaml/wsproxy/src/lwt_support.ml | ocaml | The Lwt.catch below prevents errors on double close of the fd. |
* Copyright ( C ) Citrix Systems Inc.
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation ; version 2.1 only . with the special
* exception on linking described in file LICENSE .
*
* This program is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
* Copyright (C) Citrix Systems Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 only. with the special
* exception on linking described in file LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*)
open Iteratees
type 'a t = 'a Iteratee(Lwt).t =
| IE_done of 'a
| IE_cont of err option * (stream -> ('a t * stream) Lwt.t)
let ( >>= ) = Lwt.bind
let really_write fd str =
let len = String.length str in
let rec inner written =
Lwt_unix.write fd (Bytes.unsafe_of_string str) written (len - written)
>>= fun n ->
if n < len - written then inner (written + n) else Lwt.return ()
in
inner 0
let lwt_fd_enumerator fd =
let blocksize = 1024 in
let buf = Bytes.create blocksize in
let get_str n =
if n = 0 then
Eof None
else
Chunk (Bytes.sub_string buf 0 n)
in
let rec go = function
| IE_cont (None, x) ->
Lwt_unix.read fd buf 0 blocksize >>= fun n ->
x (get_str n) >>= fun x ->
Lwt.return (fst x) >>= fun x -> go x
| x ->
Lwt.return x
in
go
let lwt_enumerator file iter =
Lwt_unix.openfile file [Lwt_unix.O_RDONLY] 0o777 >>= fun fd ->
lwt_fd_enumerator fd iter
exception Host_not_found of string
let with_fd fd ~callback =
Lwt.finalize
(fun () -> callback fd)
(fun () ->
Lwt.catch (fun () -> Lwt_unix.close fd) (fun _ -> Lwt.return_unit)
)
let with_open_connection_fd addr ~callback =
let s = Lwt_unix.(socket (Unix.domain_of_sockaddr addr) SOCK_STREAM 0) in
with_fd s ~callback:(fun fd ->
Lwt_unix.setsockopt fd Lwt_unix.SO_KEEPALIVE true ;
Lwt_unix.connect fd addr >>= fun () -> callback fd
)
|
515df8ab27aeb3c5685caa3e427c5c037fe356161b84ad2abd3e8de509b41a3c | siilisolutions/hedge | core.clj | (ns boot-hedge.common.core
(:require
[boot.util]
[clojure.pprint]
[clojure.string :as str]
[cheshire.core :refer [generate-stream]]))
(def SUPPORTED_HANDLERS [:api :timer :queue])
(def AZURE_FUNCTION {:api 'azure-api-function
:timer 'azure-timer-function
:queue 'azure-queue-function})
(def AWS_FUNCTIONS {:api 'lambda-apigw-function
:timer 'lambda-timer-function
:queue 'lambda-queue-function})
(defn print-and-return [s]
(clojure.pprint/pprint s)
s)
(defn now
[]
(java.util.Date.))
(defn date->unixts
[date]
(-> date
(.getTime)
(/ 1000)
(int)))
(defn serialize-json [f d]
(generate-stream d (clojure.java.io/writer f) {:pretty true}))
(defn dashed-alphanumeric [s]
(str/replace s #"[^A-Za-z0-9\-]" "_"))
(defn generate-cloud-name [handler]
; hedge-test.core/hello => hedge-test_core__hello
(str
(dashed-alphanumeric (namespace handler))
"__"
(dashed-alphanumeric (name handler))))
(defn fail-if-false
"Check if `value` is truthy and fail the build if not. `msg` & `more` will be
printed as if passed to `format`."
[value msg & more]
(when (not value)
(do
(boot.util/fail (str msg "\n") more)
(boot.util/exit-error))))
(defn ^:private ->handler
"Helper to create handler variables"
[key handler value]
{key {handler value}})
(defn ^:private handler-config
"Gets handler (given as string) config from hedge.edn, returns a map of type one-handler-config"
[handler edn-config]
(into {}
(map
(fn [key] (when-let [value (get (-> edn-config key) handler)]
(->handler key handler value)))
(keys edn-config))))
(defn one-handler-config
"Returns a one-handler-cfg map"
[handler edn-config]
(let [cfg (handler-config handler edn-config)
type (-> cfg keys first)
function (get (first (vals cfg)) handler)
trigger-handler {:type type
:path handler
:function function}]
trigger-handler))
(defn ^:private item->handler-name
"helper to clarify expression, extracting the handler name during calling map function."
[item]
(first item))
(defn one-handler-configs
"Returns a sequence of one-handler-configs"
[edn-config]
(let [configs (select-keys edn-config SUPPORTED_HANDLERS)]
(->
(for [config-type (keys configs)]
(map
(fn [item] (one-handler-config (item->handler-name item) edn-config))
(get configs config-type)))
flatten)))
(defn ensure-valid-cron
[{timer :timer :as all}]
(doseq [timer (vals timer)]
(let [[minutes hours dom month dow :as splitted] (str/split (:cron timer) #" ")]
(when (not= 5 (count splitted)) (throw (Exception. "Bad amount of parameters in cron expression")))
(when (and (not= "*" dom) (not= "*" dow)) (throw (Exception. "Bad cron expression")))))
TODO : use spec and add checks for L , W and #
all)
| null | https://raw.githubusercontent.com/siilisolutions/hedge/c856b232f3057530921a1e186371647317819f16/boot/src/boot_hedge/common/core.clj | clojure | hedge-test.core/hello => hedge-test_core__hello | (ns boot-hedge.common.core
(:require
[boot.util]
[clojure.pprint]
[clojure.string :as str]
[cheshire.core :refer [generate-stream]]))
(def SUPPORTED_HANDLERS [:api :timer :queue])
(def AZURE_FUNCTION {:api 'azure-api-function
:timer 'azure-timer-function
:queue 'azure-queue-function})
(def AWS_FUNCTIONS {:api 'lambda-apigw-function
:timer 'lambda-timer-function
:queue 'lambda-queue-function})
(defn print-and-return [s]
(clojure.pprint/pprint s)
s)
(defn now
[]
(java.util.Date.))
(defn date->unixts
[date]
(-> date
(.getTime)
(/ 1000)
(int)))
(defn serialize-json [f d]
(generate-stream d (clojure.java.io/writer f) {:pretty true}))
(defn dashed-alphanumeric [s]
(str/replace s #"[^A-Za-z0-9\-]" "_"))
(defn generate-cloud-name [handler]
(str
(dashed-alphanumeric (namespace handler))
"__"
(dashed-alphanumeric (name handler))))
(defn fail-if-false
"Check if `value` is truthy and fail the build if not. `msg` & `more` will be
printed as if passed to `format`."
[value msg & more]
(when (not value)
(do
(boot.util/fail (str msg "\n") more)
(boot.util/exit-error))))
(defn ^:private ->handler
"Helper to create handler variables"
[key handler value]
{key {handler value}})
(defn ^:private handler-config
"Gets handler (given as string) config from hedge.edn, returns a map of type one-handler-config"
[handler edn-config]
(into {}
(map
(fn [key] (when-let [value (get (-> edn-config key) handler)]
(->handler key handler value)))
(keys edn-config))))
(defn one-handler-config
"Returns a one-handler-cfg map"
[handler edn-config]
(let [cfg (handler-config handler edn-config)
type (-> cfg keys first)
function (get (first (vals cfg)) handler)
trigger-handler {:type type
:path handler
:function function}]
trigger-handler))
(defn ^:private item->handler-name
"helper to clarify expression, extracting the handler name during calling map function."
[item]
(first item))
(defn one-handler-configs
"Returns a sequence of one-handler-configs"
[edn-config]
(let [configs (select-keys edn-config SUPPORTED_HANDLERS)]
(->
(for [config-type (keys configs)]
(map
(fn [item] (one-handler-config (item->handler-name item) edn-config))
(get configs config-type)))
flatten)))
(defn ensure-valid-cron
[{timer :timer :as all}]
(doseq [timer (vals timer)]
(let [[minutes hours dom month dow :as splitted] (str/split (:cron timer) #" ")]
(when (not= 5 (count splitted)) (throw (Exception. "Bad amount of parameters in cron expression")))
(when (and (not= "*" dom) (not= "*" dow)) (throw (Exception. "Bad cron expression")))))
TODO : use spec and add checks for L , W and #
all)
|
550b2d367cd30b275eef55fdb26cf1c07771928015342384e47ad1a41c37c8f0 | JHU-PL-Lab/jaylang | config.ml | open Core
type test_group = string list
and t = {
testcases_to_time : test_group;
testcases_not_time : test_group;
repeat : int;
timeout : string;
engine : string; [@default "dbmc"]
test_path : string; [@default "benchmark/cases/ddse"]
working_path : string; [@default "benchmark/_working"]
result_path : string; [@default "benchmark/result"]
}
[@@deriving sexp]
| null | https://raw.githubusercontent.com/JHU-PL-Lab/jaylang/a88468ce8fb7507ec77a88a4cf8146da104328fb/benchmark/config.ml | ocaml | open Core
type test_group = string list
and t = {
testcases_to_time : test_group;
testcases_not_time : test_group;
repeat : int;
timeout : string;
engine : string; [@default "dbmc"]
test_path : string; [@default "benchmark/cases/ddse"]
working_path : string; [@default "benchmark/_working"]
result_path : string; [@default "benchmark/result"]
}
[@@deriving sexp]
|
|
f87cbfa93bf2cd1f1453fe34236f52e523b4f82596a6596f583bd5a673c85d1f | vereis/jarlang | io_lib_format.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2017 . All Rights Reserved .
%%
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
%% you may not use this file except in compliance with the License.
%% You may obtain a copy of the License at
%%
%% -2.0
%%
%% Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an " AS IS " BASIS ,
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
%% See the License for the specific language governing permissions and
%% limitations under the License.
%%
%% %CopyrightEnd%
%%
-module(io_lib_format).
%% Formatting functions of io library.
-export([fwrite/2,fwrite_g/1,indentation/2,scan/2,unscan/1,build/1]).
Format the arguments in after string Format . Just generate
%% an error if there is an error in the arguments.
%%
%% To do the printing command correctly we need to calculate the
%% current indentation for everything before it. This may be very
expensive , especially when it is not needed , so we first determine
%% if, and for how long, we need to calculate the indentations. We do
this by first collecting all the control sequences and
%% corresponding arguments, then counting the print sequences and
%% then building the output. This method has some drawbacks, it does
two passes over the format string and creates more temporary data ,
and it also splits the handling of the control characters into two
%% parts.
-spec fwrite(Format, Data) -> FormatList when
Format :: io:format(),
Data :: [term()],
FormatList :: [char() | io_lib:format_spec()].
fwrite(Format, Args) ->
build(scan(Format, Args)).
%% Build the output text for a pre-parsed format list.
-spec build(FormatList) -> io_lib:chars() when
FormatList :: [char() | io_lib:format_spec()].
build(Cs) ->
Pc = pcount(Cs),
build(Cs, Pc, 0).
Parse all control sequences in the format string .
-spec scan(Format, Data) -> FormatList when
Format :: io:format(),
Data :: [term()],
FormatList :: [char() | io_lib:format_spec()].
scan(Format, Args) when is_atom(Format) ->
scan(atom_to_list(Format), Args);
scan(Format, Args) when is_binary(Format) ->
scan(binary_to_list(Format), Args);
scan(Format, Args) ->
collect(Format, Args).
%% Revert a pre-parsed format list to a plain character list and a
%% list of arguments.
-spec unscan(FormatList) -> {Format, Data} when
FormatList :: [char() | io_lib:format_spec()],
Format :: io:format(),
Data :: [term()].
unscan(Cs) ->
{print(Cs), args(Cs)}.
args([#{args := As} | Cs]) ->
As ++ args(Cs);
args([_C | Cs]) ->
args(Cs);
args([]) ->
[].
print([#{control_char := C, width := F, adjust := Ad, precision := P,
pad_char := Pad, encoding := Encoding, strings := Strings} | Cs]) ->
print(C, F, Ad, P, Pad, Encoding, Strings) ++ print(Cs);
print([C | Cs]) ->
[C | print(Cs)];
print([]) ->
[].
print(C, F, Ad, P, Pad, Encoding, Strings) ->
[$~] ++ print_field_width(F, Ad) ++ print_precision(P) ++
print_pad_char(Pad) ++ print_encoding(Encoding) ++
print_strings(Strings) ++ [C].
print_field_width(none, _Ad) -> "";
print_field_width(F, left) -> integer_to_list(-F);
print_field_width(F, right) -> integer_to_list(F).
print_precision(none) -> "";
print_precision(P) -> [$. | integer_to_list(P)].
print_pad_char($\s) -> ""; % default, no need to make explicit
print_pad_char(Pad) -> [$., Pad].
print_encoding(unicode) -> "t";
print_encoding(latin1) -> "".
print_strings(false) -> "l";
print_strings(true) -> "".
collect([$~|Fmt0], Args0) ->
{C,Fmt1,Args1} = collect_cseq(Fmt0, Args0),
[C|collect(Fmt1, Args1)];
collect([C|Fmt], Args) ->
[C|collect(Fmt, Args)];
collect([], []) -> [].
collect_cseq(Fmt0, Args0) ->
{F,Ad,Fmt1,Args1} = field_width(Fmt0, Args0),
{P,Fmt2,Args2} = precision(Fmt1, Args1),
{Pad,Fmt3,Args3} = pad_char(Fmt2, Args2),
{Encoding,Fmt4,Args4} = encoding(Fmt3, Args3),
{Strings,Fmt5,Args5} = strings(Fmt4, Args4),
{C,As,Fmt6,Args6} = collect_cc(Fmt5, Args5),
FormatSpec = #{control_char => C, args => As, width => F, adjust => Ad,
precision => P, pad_char => Pad, encoding => Encoding,
strings => Strings},
{FormatSpec,Fmt6,Args6}.
encoding([$t|Fmt],Args) ->
true = hd(Fmt) =/= $l,
{unicode,Fmt,Args};
encoding(Fmt,Args) ->
{latin1,Fmt,Args}.
strings([$l|Fmt],Args) ->
true = hd(Fmt) =/= $t,
{false,Fmt,Args};
strings(Fmt,Args) ->
{true,Fmt,Args}.
field_width([$-|Fmt0], Args0) ->
{F,Fmt,Args} = field_value(Fmt0, Args0),
field_width(-F, Fmt, Args);
field_width(Fmt0, Args0) ->
{F,Fmt,Args} = field_value(Fmt0, Args0),
field_width(F, Fmt, Args).
field_width(F, Fmt, Args) when F < 0 ->
{-F,left,Fmt,Args};
field_width(F, Fmt, Args) when F >= 0 ->
{F,right,Fmt,Args}.
precision([$.|Fmt], Args) ->
field_value(Fmt, Args);
precision(Fmt, Args) ->
{none,Fmt,Args}.
field_value([$*|Fmt], [A|Args]) when is_integer(A) ->
{A,Fmt,Args};
field_value([C|Fmt], Args) when is_integer(C), C >= $0, C =< $9 ->
field_value([C|Fmt], Args, 0);
field_value(Fmt, Args) ->
{none,Fmt,Args}.
field_value([C|Fmt], Args, F) when is_integer(C), C >= $0, C =< $9 ->
field_value(Fmt, Args, 10*F + (C - $0));
field_value(Fmt, Args, F) -> %Default case
{F,Fmt,Args}.
pad_char([$.,$*|Fmt], [Pad|Args]) -> {Pad,Fmt,Args};
pad_char([$.,Pad|Fmt], Args) -> {Pad,Fmt,Args};
pad_char(Fmt, Args) -> {$\s,Fmt,Args}.
%% collect_cc([FormatChar], [Argument]) ->
%% {Control,[ControlArg],[FormatChar],[Arg]}.
%% Here we collect the argments for each control character.
%% Be explicit to cause failure early.
collect_cc([$w|Fmt], [A|Args]) -> {$w,[A],Fmt,Args};
collect_cc([$p|Fmt], [A|Args]) -> {$p,[A],Fmt,Args};
collect_cc([$W|Fmt], [A,Depth|Args]) -> {$W,[A,Depth],Fmt,Args};
collect_cc([$P|Fmt], [A,Depth|Args]) -> {$P,[A,Depth],Fmt,Args};
collect_cc([$s|Fmt], [A|Args]) -> {$s,[A],Fmt,Args};
collect_cc([$e|Fmt], [A|Args]) -> {$e,[A],Fmt,Args};
collect_cc([$f|Fmt], [A|Args]) -> {$f,[A],Fmt,Args};
collect_cc([$g|Fmt], [A|Args]) -> {$g,[A],Fmt,Args};
collect_cc([$b|Fmt], [A|Args]) -> {$b,[A],Fmt,Args};
collect_cc([$B|Fmt], [A|Args]) -> {$B,[A],Fmt,Args};
collect_cc([$x|Fmt], [A,Prefix|Args]) -> {$x,[A,Prefix],Fmt,Args};
collect_cc([$X|Fmt], [A,Prefix|Args]) -> {$X,[A,Prefix],Fmt,Args};
collect_cc([$+|Fmt], [A|Args]) -> {$+,[A],Fmt,Args};
collect_cc([$#|Fmt], [A|Args]) -> {$#,[A],Fmt,Args};
collect_cc([$c|Fmt], [A|Args]) -> {$c,[A],Fmt,Args};
collect_cc([$~|Fmt], Args) when is_list(Args) -> {$~,[],Fmt,Args};
collect_cc([$n|Fmt], Args) when is_list(Args) -> {$n,[],Fmt,Args};
collect_cc([$i|Fmt], [A|Args]) -> {$i,[A],Fmt,Args}.
%% pcount([ControlC]) -> Count.
%% Count the number of print requests.
pcount(Cs) -> pcount(Cs, 0).
pcount([#{control_char := $p}|Cs], Acc) -> pcount(Cs, Acc+1);
pcount([#{control_char := $P}|Cs], Acc) -> pcount(Cs, Acc+1);
pcount([_|Cs], Acc) -> pcount(Cs, Acc);
pcount([], Acc) -> Acc.
%% build([Control], Pc, Indentation) -> io_lib:chars().
%% Interpret the control structures. Count the number of print
%% remaining and only calculate indentation when necessary. Must also
%% be smart when calculating indentation for characters in format.
build([#{control_char := C, args := As, width := F, adjust := Ad,
precision := P, pad_char := Pad, encoding := Enc,
strings := Str} | Cs], Pc0, I) ->
S = control(C, As, F, Ad, P, Pad, Enc, Str, I),
Pc1 = decr_pc(C, Pc0),
if
Pc1 > 0 -> [S|build(Cs, Pc1, indentation(S, I))];
true -> [S|build(Cs, Pc1, I)]
end;
build([$\n|Cs], Pc, _I) -> [$\n|build(Cs, Pc, 0)];
build([$\t|Cs], Pc, I) -> [$\t|build(Cs, Pc, ((I + 8) div 8) * 8)];
build([C|Cs], Pc, I) -> [C|build(Cs, Pc, I+1)];
build([], _Pc, _I) -> [].
decr_pc($p, Pc) -> Pc - 1;
decr_pc($P, Pc) -> Pc - 1;
decr_pc(_, Pc) -> Pc.
%% Calculate the indentation of the end of a string given its start
indentation . We assume tabs at 8 cols .
-spec indentation(String, StartIndent) -> integer() when
String :: io_lib:chars(),
StartIndent :: integer().
indentation([$\n|Cs], _I) -> indentation(Cs, 0);
indentation([$\t|Cs], I) -> indentation(Cs, ((I + 8) div 8) * 8);
indentation([C|Cs], I) when is_integer(C) ->
indentation(Cs, I+1);
indentation([C|Cs], I) ->
indentation(Cs, indentation(C, I));
indentation([], I) -> I.
%% control(FormatChar, [Argument], FieldWidth, Adjust, Precision, PadChar,
%% Encoding, Indentation) -> String
%% This is the main dispatch function for the various formatting commands.
%% Field widths and precisions have already been calculated.
control($w, [A], F, Adj, P, Pad, Enc, _Str, _I) ->
term(io_lib:write(A, [{depth,-1}, {encoding, Enc}]), F, Adj, P, Pad);
control($p, [A], F, Adj, P, Pad, Enc, Str, I) ->
print(A, -1, F, Adj, P, Pad, Enc, Str, I);
control($W, [A,Depth], F, Adj, P, Pad, Enc, _Str, _I) when is_integer(Depth) ->
term(io_lib:write(A, [{depth,Depth}, {encoding, Enc}]), F, Adj, P, Pad);
control($P, [A,Depth], F, Adj, P, Pad, Enc, Str, I) when is_integer(Depth) ->
print(A, Depth, F, Adj, P, Pad, Enc, Str, I);
control($s, [A], F, Adj, P, Pad, latin1, _Str, _I) when is_atom(A) ->
L = iolist_to_chars(atom_to_list(A)),
string(L, F, Adj, P, Pad);
control($s, [A], F, Adj, P, Pad, unicode, _Str, _I) when is_atom(A) ->
string(atom_to_list(A), F, Adj, P, Pad);
control($s, [L0], F, Adj, P, Pad, latin1, _Str, _I) ->
L = iolist_to_chars(L0),
string(L, F, Adj, P, Pad);
control($s, [L0], F, Adj, P, Pad, unicode, _Str, _I) ->
L = cdata_to_chars(L0),
uniconv(string(L, F, Adj, P, Pad));
control($e, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_float(A) ->
fwrite_e(A, F, Adj, P, Pad);
control($f, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_float(A) ->
fwrite_f(A, F, Adj, P, Pad);
control($g, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_float(A) ->
fwrite_g(A, F, Adj, P, Pad);
control($b, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
unprefixed_integer(A, F, Adj, base(P), Pad, true);
control($B, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
unprefixed_integer(A, F, Adj, base(P), Pad, false);
control($x, [A,Prefix], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A),
is_atom(Prefix) ->
prefixed_integer(A, F, Adj, base(P), Pad, atom_to_list(Prefix), true);
control($x, [A,Prefix], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
true = io_lib:deep_char_list(Prefix), %Check if Prefix a character list
prefixed_integer(A, F, Adj, base(P), Pad, Prefix, true);
control($X, [A,Prefix], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A),
is_atom(Prefix) ->
prefixed_integer(A, F, Adj, base(P), Pad, atom_to_list(Prefix), false);
control($X, [A,Prefix], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
true = io_lib:deep_char_list(Prefix), %Check if Prefix a character list
prefixed_integer(A, F, Adj, base(P), Pad, Prefix, false);
control($+, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
Base = base(P),
Prefix = [integer_to_list(Base), $#],
prefixed_integer(A, F, Adj, Base, Pad, Prefix, true);
control($#, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
Base = base(P),
Prefix = [integer_to_list(Base), $#],
prefixed_integer(A, F, Adj, Base, Pad, Prefix, false);
control($c, [A], F, Adj, P, Pad, unicode, _Str, _I) when is_integer(A) ->
char(A, F, Adj, P, Pad);
control($c, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
char(A band 255, F, Adj, P, Pad);
control($~, [], F, Adj, P, Pad, _Enc, _Str, _I) -> char($~, F, Adj, P, Pad);
control($n, [], F, Adj, P, Pad, _Enc, _Str, _I) -> newline(F, Adj, P, Pad);
control($i, [_A], _F, _Adj, _P, _Pad, _Enc, _Str, _I) -> [].
-ifdef(UNICODE_AS_BINARIES).
uniconv(C) ->
unicode:characters_to_binary(C,unicode).
-else.
uniconv(C) ->
C.
-endif.
%% Default integer base
base(none) ->
10;
base(B) when is_integer(B) ->
B.
term(TermList , Field , Adjust , Precision , PadChar )
%% Output the characters in a term.
Adjust the characters within the field if length less than padding
%% with PadChar.
term(T, none, _Adj, none, _Pad) -> T;
term(T, none, Adj, P, Pad) -> term(T, P, Adj, P, Pad);
term(T, F, Adj, P0, Pad) ->
L = string:length(T),
P = erlang:min(L, case P0 of none -> F; _ -> min(P0, F) end),
if
L > P ->
adjust(chars($*, P), chars(Pad, F-P), Adj);
F >= P ->
adjust(T, chars(Pad, F-L), Adj)
end.
print(Term , Depth , Field , Adjust , Precision , PadChar , Encoding ,
%% Indentation)
%% Print a term. Field width sets maximum line length, Precision sets
%% initial indentation.
print(T, D, none, Adj, P, Pad, E, Str, I) ->
print(T, D, 80, Adj, P, Pad, E, Str, I);
print(T, D, F, Adj, none, Pad, E, Str, I) ->
print(T, D, F, Adj, I+1, Pad, E, Str, I);
print(T, D, F, right, P, _Pad, Enc, Str, _I) ->
Options = [{column, P},
{line_length, F},
{depth, D},
{encoding, Enc},
{strings, Str}],
io_lib_pretty:print(T, Options).
fwrite_e(Float , Field , Adjust , Precision , PadChar )
fwrite_e(Fl, none, Adj, none, Pad) -> %Default values
fwrite_e(Fl, none, Adj, 6, Pad);
fwrite_e(Fl, none, _Adj, P, _Pad) when P >= 2 ->
float_e(Fl, float_data(Fl), P);
fwrite_e(Fl, F, Adj, none, Pad) ->
fwrite_e(Fl, F, Adj, 6, Pad);
fwrite_e(Fl, F, Adj, P, Pad) when P >= 2 ->
term(float_e(Fl, float_data(Fl), P), F, Adj, F, Pad).
float_e(Fl, Fd, P) when Fl < 0.0 -> %Negative numbers
[$-|float_e(-Fl, Fd, P)];
float_e(_Fl, {Ds,E}, P) ->
case float_man(Ds, 1, P-1) of
{[$0|Fs],true} -> [[$1|Fs]|float_exp(E)];
{Fs,false} -> [Fs|float_exp(E-1)]
end.
float_man([Digit ] , Icount , Dcount ) - > { [ Char],CarryFlag } .
Generate the characters in the mantissa from the digits with Icount
characters before the ' . ' and Dcount decimals . Handle carry and let
%% caller decide what to do at top.
float_man(Ds, 0, Dc) ->
{Cs,C} = float_man(Ds, Dc),
{[$.|Cs],C};
float_man([D|Ds], I, Dc) ->
case float_man(Ds, I-1, Dc) of
{Cs,true} when D =:= $9 -> {[$0|Cs],true};
{Cs,true} -> {[D+1|Cs],false};
{Cs,false} -> {[D|Cs],false}
end;
float_man([], I, Dc) -> %Pad with 0's
{lists:duplicate(I, $0) ++ [$.|lists:duplicate(Dc, $0)],false}.
float_man([D|_], 0) when D >= $5 -> {[],true};
float_man([_|_], 0) -> {[],false};
float_man([D|Ds], Dc) ->
case float_man(Ds, Dc-1) of
{Cs,true} when D =:= $9 -> {[$0|Cs],true};
{Cs,true} -> {[D+1|Cs],false};
{Cs,false} -> {[D|Cs],false}
end;
float_man([], Dc) -> {lists:duplicate(Dc, $0),false}. %Pad with 0's
float_exp(Exponent ) - > [ ] .
%% Generate the exponent of a floating point number. Always include sign.
float_exp(E) when E >= 0 ->
[$e,$+|integer_to_list(E)];
float_exp(E) ->
[$e|integer_to_list(E)].
fwrite_f(FloatData , Field , Adjust , Precision , PadChar )
fwrite_f(Fl, none, Adj, none, Pad) -> %Default values
fwrite_f(Fl, none, Adj, 6, Pad);
fwrite_f(Fl, none, _Adj, P, _Pad) when P >= 1 ->
float_f(Fl, float_data(Fl), P);
fwrite_f(Fl, F, Adj, none, Pad) ->
fwrite_f(Fl, F, Adj, 6, Pad);
fwrite_f(Fl, F, Adj, P, Pad) when P >= 1 ->
term(float_f(Fl, float_data(Fl), P), F, Adj, F, Pad).
float_f(Fl, Fd, P) when Fl < 0.0 ->
[$-|float_f(-Fl, Fd, P)];
float_f(Fl, {Ds,E}, P) when E =< 0 ->
float_f(Fl, {lists:duplicate(-E+1, $0)++Ds,1}, P); %Prepend enough 0's
float_f(_Fl, {Ds,E}, P) ->
case float_man(Ds, E, P) of
{Fs,true} -> "1" ++ Fs; %Handle carry
{Fs,false} -> Fs
end.
%% float_data([FloatChar]) -> {[Digit],Exponent}
float_data(Fl) ->
float_data(float_to_list(Fl), []).
float_data([$e|E], Ds) ->
{lists:reverse(Ds),list_to_integer(E)+1};
float_data([D|Cs], Ds) when D >= $0, D =< $9 ->
float_data(Cs, [D|Ds]);
float_data([_|Cs], Ds) ->
float_data(Cs, Ds).
%% Writes the shortest, correctly rounded string that converts
%% to Float when read back with list_to_float/1.
%%
See also " Printing Floating - Point Numbers Quickly and Accurately "
in Proceedings of the SIGPLAN ' 96 Conference on Programming
Language Design and Implementation .
-spec fwrite_g(float()) -> string().
fwrite_g(0.0) ->
"0.0";
fwrite_g(Float) when is_float(Float) ->
{Frac, Exp} = mantissa_exponent(Float),
{Place, Digits} = fwrite_g_1(Float, Exp, Frac),
R = insert_decimal(Place, [$0 + D || D <- Digits]),
[$- || true <- [Float < 0.0]] ++ R.
-define(BIG_POW, (1 bsl 52)).
-define(MIN_EXP, (-1074)).
mantissa_exponent(F) ->
case <<F:64/float>> of
denormalized
E = log2floor(M),
{M bsl (53 - E), E - 52 - 1075};
<<_S:1, BE:11, M:52>> when BE < 2047 ->
{M + ?BIG_POW, BE - 1075}
end.
fwrite_g_1(Float, Exp, Frac) ->
Round = (Frac band 1) =:= 0,
if
Exp >= 0 ->
BExp = 1 bsl Exp,
if
Frac =:= ?BIG_POW ->
scale(Frac * BExp * 4, 4, BExp * 2, BExp,
Round, Round, Float);
true ->
scale(Frac * BExp * 2, 2, BExp, BExp,
Round, Round, Float)
end;
Exp < ?MIN_EXP ->
BExp = 1 bsl (?MIN_EXP - Exp),
scale(Frac * 2, 1 bsl (1 - Exp), BExp, BExp,
Round, Round, Float);
Exp > ?MIN_EXP, Frac =:= ?BIG_POW ->
scale(Frac * 4, 1 bsl (2 - Exp), 2, 1,
Round, Round, Float);
true ->
scale(Frac * 2, 1 bsl (1 - Exp), 1, 1,
Round, Round, Float)
end.
scale(R, S, MPlus, MMinus, LowOk, HighOk, Float) ->
Est = int_ceil(math:log10(abs(Float)) - 1.0e-10),
Note that the scheme implementation uses a 326 element look - up
%% table for int_pow(10, N) where we do not.
if
Est >= 0 ->
fixup(R, S * int_pow(10, Est), MPlus, MMinus, Est,
LowOk, HighOk);
true ->
Scale = int_pow(10, -Est),
fixup(R * Scale, S, MPlus * Scale, MMinus * Scale, Est,
LowOk, HighOk)
end.
fixup(R, S, MPlus, MMinus, K, LowOk, HighOk) ->
TooLow = if
HighOk -> R + MPlus >= S;
true -> R + MPlus > S
end,
case TooLow of
true ->
{K + 1, generate(R, S, MPlus, MMinus, LowOk, HighOk)};
false ->
{K, generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)}
end.
generate(R0, S, MPlus, MMinus, LowOk, HighOk) ->
D = R0 div S,
R = R0 rem S,
TC1 = if
LowOk -> R =< MMinus;
true -> R < MMinus
end,
TC2 = if
HighOk -> R + MPlus >= S;
true -> R + MPlus > S
end,
case {TC1, TC2} of
{false, false} ->
[D | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)];
{false, true} ->
[D + 1];
{true, false} ->
[D];
{true, true} when R * 2 < S ->
[D];
{true, true} ->
[D + 1]
end.
insert_decimal(0, S) ->
"0." ++ S;
insert_decimal(Place, S) ->
L = length(S),
if
Place < 0;
Place >= L ->
ExpL = integer_to_list(Place - 1),
ExpDot = if L =:= 1 -> 2; true -> 1 end,
ExpCost = length(ExpL) + 1 + ExpDot,
if
Place < 0 ->
if
2 - Place =< ExpCost ->
"0." ++ lists:duplicate(-Place, $0) ++ S;
true ->
insert_exp(ExpL, S)
end;
true ->
if
Place - L + 2 =< ExpCost ->
S ++ lists:duplicate(Place - L, $0) ++ ".0";
true ->
insert_exp(ExpL, S)
end
end;
true ->
{S0, S1} = lists:split(Place, S),
S0 ++ "." ++ S1
end.
insert_exp(ExpL, [C]) ->
[C] ++ ".0e" ++ ExpL;
insert_exp(ExpL, [C | S]) ->
[C] ++ "." ++ S ++ "e" ++ ExpL.
int_ceil(X) when is_float(X) ->
T = trunc(X),
case (X - T) of
Neg when Neg < 0 -> T;
Pos when Pos > 0 -> T + 1;
_ -> T
end.
int_pow(X, 0) when is_integer(X) ->
1;
int_pow(X, N) when is_integer(X), is_integer(N), N > 0 ->
int_pow(X, N, 1).
int_pow(X, N, R) when N < 2 ->
R * X;
int_pow(X, N, R) ->
int_pow(X * X, N bsr 1, case N band 1 of 1 -> R * X; 0 -> R end).
log2floor(Int) when is_integer(Int), Int > 0 ->
log2floor(Int, 0).
log2floor(0, N) ->
N;
log2floor(Int, N) ->
log2floor(Int bsr 1, 1 + N).
fwrite_g(Float , Field , Adjust , Precision , PadChar )
Use the f form if Float is > = 0.1 and < 1.0e4 ,
%% and the prints correctly in the f form, else the e form.
%% Precision always means the # of significant digits.
fwrite_g(Fl, F, Adj, none, Pad) ->
fwrite_g(Fl, F, Adj, 6, Pad);
fwrite_g(Fl, F, Adj, P, Pad) when P >= 1 ->
A = abs(Fl),
E = if A < 1.0e-1 -> -2;
A < 1.0e0 -> -1;
A < 1.0e1 -> 0;
A < 1.0e2 -> 1;
A < 1.0e3 -> 2;
A < 1.0e4 -> 3;
true -> fwrite_f
end,
if P =< 1, E =:= -1;
P-1 > E, E >= -1 ->
fwrite_f(Fl, F, Adj, P-1-E, Pad);
P =< 1 ->
fwrite_e(Fl, F, Adj, 2, Pad);
true ->
fwrite_e(Fl, F, Adj, P, Pad)
end.
%% iolist_to_chars(iolist()) -> deep_char_list()
iolist_to_chars([C|Cs]) when is_integer(C), C >= $\000, C =< $\377 ->
[C | iolist_to_chars(Cs)];
iolist_to_chars([I|Cs]) ->
[iolist_to_chars(I) | iolist_to_chars(Cs)];
iolist_to_chars([]) ->
[];
iolist_to_chars(B) when is_binary(B) ->
binary_to_list(B).
cdata ( ) : : ( ) | cbinary ( )
clist ( ) : : ( ) | cbinary ( ) | clist ( ) ,
%% cbinary() | nil())
%% cbinary() :: unicode:unicode_binary() | unicode:latin1_binary()
%% cdata_to_chars(cdata()) -> io_lib:deep_char_list()
cdata_to_chars([C|Cs]) when is_integer(C), C >= $\000 ->
[C | cdata_to_chars(Cs)];
cdata_to_chars([I|Cs]) ->
[cdata_to_chars(I) | cdata_to_chars(Cs)];
cdata_to_chars([]) ->
[];
cdata_to_chars(B) when is_binary(B) ->
case catch unicode:characters_to_list(B) of
L when is_list(L) -> L;
_ -> binary_to_list(B)
end.
string(String , Field , Adjust , Precision , PadChar )
string(S, none, _Adj, none, _Pad) -> S;
string(S, F, Adj, none, Pad) ->
string_field(S, F, Adj, string:length(S), Pad);
string(S, none, _Adj, P, Pad) ->
string_field(S, P, left, string:length(S), Pad);
string(S, F, Adj, P, Pad) when F >= P ->
N = string:length(S),
if F > P ->
if N > P ->
adjust(flat_trunc(S, P), chars(Pad, F-P), Adj);
N < P ->
adjust([S|chars(Pad, P-N)], chars(Pad, F-P), Adj);
true -> % N == P
adjust(S, chars(Pad, F-P), Adj)
end;
true -> % F == P
string_field(S, F, Adj, N, Pad)
end.
string_field(S, F, _Adj, N, _Pad) when N > F ->
flat_trunc(S, F);
string_field(S, F, Adj, N, Pad) when N < F ->
adjust(S, chars(Pad, F-N), Adj);
string_field(S, _, _, _, _) -> % N == F
S.
unprefixed_integer(Int , Field , Adjust , Base , PadChar , Lowercase )
- > [ ] .
unprefixed_integer(Int, F, Adj, Base, Pad, Lowercase)
when Base >= 2, Base =< 1+$Z-$A+10 ->
if Int < 0 ->
S = cond_lowercase(erlang:integer_to_list(-Int, Base), Lowercase),
term([$-|S], F, Adj, none, Pad);
true ->
S = cond_lowercase(erlang:integer_to_list(Int, Base), Lowercase),
term(S, F, Adj, none, Pad)
end.
prefixed_integer(Int , Field , Adjust , Base , PadChar , Prefix , Lowercase )
- > [ ] .
prefixed_integer(Int, F, Adj, Base, Pad, Prefix, Lowercase)
when Base >= 2, Base =< 1+$Z-$A+10 ->
if Int < 0 ->
S = cond_lowercase(erlang:integer_to_list(-Int, Base), Lowercase),
term([$-,Prefix|S], F, Adj, none, Pad);
true ->
S = cond_lowercase(erlang:integer_to_list(Int, Base), Lowercase),
term([Prefix|S], F, Adj, none, Pad)
end.
char(Char , Field , Adjust , Precision , PadChar ) - > chars ( ) .
char(C, none, _Adj, none, _Pad) -> [C];
char(C, F, _Adj, none, _Pad) -> chars(C, F);
char(C, none, _Adj, P, _Pad) -> chars(C, P);
char(C, F, Adj, P, Pad) when F >= P ->
adjust(chars(C, P), chars(Pad, F - P), Adj).
newline(Field , Adjust , Precision , PadChar ) - > [ ] .
newline(none, _Adj, _P, _Pad) -> "\n";
newline(F, right, _P, _Pad) -> chars($\n, F).
%%
Utilities
%%
adjust(Data, [], _) -> Data;
adjust(Data, Pad, left) -> [Data|Pad];
adjust(Data, Pad, right) -> [Pad|Data].
%% Flatten and truncate a deep list to at most N elements.
flat_trunc(List, N) when is_integer(N), N >= 0 ->
string:slice(List, 0, N).
A deep version of lists : duplicate/2
chars(_C, 0) ->
[];
chars(C, 1) ->
[C];
chars(C, 2) ->
[C,C];
chars(C, 3) ->
[C,C,C];
chars(C, N) when is_integer(N), (N band 1) =:= 0 ->
S = chars(C, N bsr 1),
[S|S];
chars(C, N) when is_integer(N) ->
S = chars(C, N bsr 1),
[C,S|S].
%chars(C, N, Tail) ->
[ chars(C , N)|Tail ] .
%% Lowercase conversion
cond_lowercase(String, true) ->
lowercase(String);
cond_lowercase(String,false) ->
String.
lowercase([H|T]) when is_integer(H), H >= $A, H =< $Z ->
[(H-$A+$a)|lowercase(T)];
lowercase([H|T]) ->
[H|lowercase(T)];
lowercase([]) ->
[].
| null | https://raw.githubusercontent.com/vereis/jarlang/72105b79c1861aa6c4f51c3b50ba695338aafba4/src/erl/lib/stdlib/io_lib_format.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
%CopyrightEnd%
Formatting functions of io library.
an error if there is an error in the arguments.
To do the printing command correctly we need to calculate the
current indentation for everything before it. This may be very
if, and for how long, we need to calculate the indentations. We do
corresponding arguments, then counting the print sequences and
then building the output. This method has some drawbacks, it does
parts.
Build the output text for a pre-parsed format list.
Revert a pre-parsed format list to a plain character list and a
list of arguments.
default, no need to make explicit
Default case
collect_cc([FormatChar], [Argument]) ->
{Control,[ControlArg],[FormatChar],[Arg]}.
Here we collect the argments for each control character.
Be explicit to cause failure early.
pcount([ControlC]) -> Count.
Count the number of print requests.
build([Control], Pc, Indentation) -> io_lib:chars().
Interpret the control structures. Count the number of print
remaining and only calculate indentation when necessary. Must also
be smart when calculating indentation for characters in format.
Calculate the indentation of the end of a string given its start
control(FormatChar, [Argument], FieldWidth, Adjust, Precision, PadChar,
Encoding, Indentation) -> String
This is the main dispatch function for the various formatting commands.
Field widths and precisions have already been calculated.
Check if Prefix a character list
Check if Prefix a character list
Default integer base
Output the characters in a term.
with PadChar.
Indentation)
Print a term. Field width sets maximum line length, Precision sets
initial indentation.
Default values
Negative numbers
caller decide what to do at top.
Pad with 0's
Pad with 0's
Generate the exponent of a floating point number. Always include sign.
Default values
Prepend enough 0's
Handle carry
float_data([FloatChar]) -> {[Digit],Exponent}
Writes the shortest, correctly rounded string that converts
to Float when read back with list_to_float/1.
table for int_pow(10, N) where we do not.
and the prints correctly in the f form, else the e form.
Precision always means the # of significant digits.
iolist_to_chars(iolist()) -> deep_char_list()
cbinary() | nil())
cbinary() :: unicode:unicode_binary() | unicode:latin1_binary()
cdata_to_chars(cdata()) -> io_lib:deep_char_list()
N == P
F == P
N == F
Flatten and truncate a deep list to at most N elements.
chars(C, N, Tail) ->
Lowercase conversion | Copyright Ericsson AB 1996 - 2017 . 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(io_lib_format).
-export([fwrite/2,fwrite_g/1,indentation/2,scan/2,unscan/1,build/1]).
Format the arguments in after string Format . Just generate
expensive , especially when it is not needed , so we first determine
this by first collecting all the control sequences and
two passes over the format string and creates more temporary data ,
and it also splits the handling of the control characters into two
-spec fwrite(Format, Data) -> FormatList when
Format :: io:format(),
Data :: [term()],
FormatList :: [char() | io_lib:format_spec()].
fwrite(Format, Args) ->
build(scan(Format, Args)).
-spec build(FormatList) -> io_lib:chars() when
FormatList :: [char() | io_lib:format_spec()].
build(Cs) ->
Pc = pcount(Cs),
build(Cs, Pc, 0).
Parse all control sequences in the format string .
-spec scan(Format, Data) -> FormatList when
Format :: io:format(),
Data :: [term()],
FormatList :: [char() | io_lib:format_spec()].
scan(Format, Args) when is_atom(Format) ->
scan(atom_to_list(Format), Args);
scan(Format, Args) when is_binary(Format) ->
scan(binary_to_list(Format), Args);
scan(Format, Args) ->
collect(Format, Args).
-spec unscan(FormatList) -> {Format, Data} when
FormatList :: [char() | io_lib:format_spec()],
Format :: io:format(),
Data :: [term()].
unscan(Cs) ->
{print(Cs), args(Cs)}.
args([#{args := As} | Cs]) ->
As ++ args(Cs);
args([_C | Cs]) ->
args(Cs);
args([]) ->
[].
print([#{control_char := C, width := F, adjust := Ad, precision := P,
pad_char := Pad, encoding := Encoding, strings := Strings} | Cs]) ->
print(C, F, Ad, P, Pad, Encoding, Strings) ++ print(Cs);
print([C | Cs]) ->
[C | print(Cs)];
print([]) ->
[].
print(C, F, Ad, P, Pad, Encoding, Strings) ->
[$~] ++ print_field_width(F, Ad) ++ print_precision(P) ++
print_pad_char(Pad) ++ print_encoding(Encoding) ++
print_strings(Strings) ++ [C].
print_field_width(none, _Ad) -> "";
print_field_width(F, left) -> integer_to_list(-F);
print_field_width(F, right) -> integer_to_list(F).
print_precision(none) -> "";
print_precision(P) -> [$. | integer_to_list(P)].
print_pad_char(Pad) -> [$., Pad].
print_encoding(unicode) -> "t";
print_encoding(latin1) -> "".
print_strings(false) -> "l";
print_strings(true) -> "".
collect([$~|Fmt0], Args0) ->
{C,Fmt1,Args1} = collect_cseq(Fmt0, Args0),
[C|collect(Fmt1, Args1)];
collect([C|Fmt], Args) ->
[C|collect(Fmt, Args)];
collect([], []) -> [].
collect_cseq(Fmt0, Args0) ->
{F,Ad,Fmt1,Args1} = field_width(Fmt0, Args0),
{P,Fmt2,Args2} = precision(Fmt1, Args1),
{Pad,Fmt3,Args3} = pad_char(Fmt2, Args2),
{Encoding,Fmt4,Args4} = encoding(Fmt3, Args3),
{Strings,Fmt5,Args5} = strings(Fmt4, Args4),
{C,As,Fmt6,Args6} = collect_cc(Fmt5, Args5),
FormatSpec = #{control_char => C, args => As, width => F, adjust => Ad,
precision => P, pad_char => Pad, encoding => Encoding,
strings => Strings},
{FormatSpec,Fmt6,Args6}.
encoding([$t|Fmt],Args) ->
true = hd(Fmt) =/= $l,
{unicode,Fmt,Args};
encoding(Fmt,Args) ->
{latin1,Fmt,Args}.
strings([$l|Fmt],Args) ->
true = hd(Fmt) =/= $t,
{false,Fmt,Args};
strings(Fmt,Args) ->
{true,Fmt,Args}.
field_width([$-|Fmt0], Args0) ->
{F,Fmt,Args} = field_value(Fmt0, Args0),
field_width(-F, Fmt, Args);
field_width(Fmt0, Args0) ->
{F,Fmt,Args} = field_value(Fmt0, Args0),
field_width(F, Fmt, Args).
field_width(F, Fmt, Args) when F < 0 ->
{-F,left,Fmt,Args};
field_width(F, Fmt, Args) when F >= 0 ->
{F,right,Fmt,Args}.
precision([$.|Fmt], Args) ->
field_value(Fmt, Args);
precision(Fmt, Args) ->
{none,Fmt,Args}.
field_value([$*|Fmt], [A|Args]) when is_integer(A) ->
{A,Fmt,Args};
field_value([C|Fmt], Args) when is_integer(C), C >= $0, C =< $9 ->
field_value([C|Fmt], Args, 0);
field_value(Fmt, Args) ->
{none,Fmt,Args}.
field_value([C|Fmt], Args, F) when is_integer(C), C >= $0, C =< $9 ->
field_value(Fmt, Args, 10*F + (C - $0));
{F,Fmt,Args}.
pad_char([$.,$*|Fmt], [Pad|Args]) -> {Pad,Fmt,Args};
pad_char([$.,Pad|Fmt], Args) -> {Pad,Fmt,Args};
pad_char(Fmt, Args) -> {$\s,Fmt,Args}.
collect_cc([$w|Fmt], [A|Args]) -> {$w,[A],Fmt,Args};
collect_cc([$p|Fmt], [A|Args]) -> {$p,[A],Fmt,Args};
collect_cc([$W|Fmt], [A,Depth|Args]) -> {$W,[A,Depth],Fmt,Args};
collect_cc([$P|Fmt], [A,Depth|Args]) -> {$P,[A,Depth],Fmt,Args};
collect_cc([$s|Fmt], [A|Args]) -> {$s,[A],Fmt,Args};
collect_cc([$e|Fmt], [A|Args]) -> {$e,[A],Fmt,Args};
collect_cc([$f|Fmt], [A|Args]) -> {$f,[A],Fmt,Args};
collect_cc([$g|Fmt], [A|Args]) -> {$g,[A],Fmt,Args};
collect_cc([$b|Fmt], [A|Args]) -> {$b,[A],Fmt,Args};
collect_cc([$B|Fmt], [A|Args]) -> {$B,[A],Fmt,Args};
collect_cc([$x|Fmt], [A,Prefix|Args]) -> {$x,[A,Prefix],Fmt,Args};
collect_cc([$X|Fmt], [A,Prefix|Args]) -> {$X,[A,Prefix],Fmt,Args};
collect_cc([$+|Fmt], [A|Args]) -> {$+,[A],Fmt,Args};
collect_cc([$#|Fmt], [A|Args]) -> {$#,[A],Fmt,Args};
collect_cc([$c|Fmt], [A|Args]) -> {$c,[A],Fmt,Args};
collect_cc([$~|Fmt], Args) when is_list(Args) -> {$~,[],Fmt,Args};
collect_cc([$n|Fmt], Args) when is_list(Args) -> {$n,[],Fmt,Args};
collect_cc([$i|Fmt], [A|Args]) -> {$i,[A],Fmt,Args}.
pcount(Cs) -> pcount(Cs, 0).
pcount([#{control_char := $p}|Cs], Acc) -> pcount(Cs, Acc+1);
pcount([#{control_char := $P}|Cs], Acc) -> pcount(Cs, Acc+1);
pcount([_|Cs], Acc) -> pcount(Cs, Acc);
pcount([], Acc) -> Acc.
build([#{control_char := C, args := As, width := F, adjust := Ad,
precision := P, pad_char := Pad, encoding := Enc,
strings := Str} | Cs], Pc0, I) ->
S = control(C, As, F, Ad, P, Pad, Enc, Str, I),
Pc1 = decr_pc(C, Pc0),
if
Pc1 > 0 -> [S|build(Cs, Pc1, indentation(S, I))];
true -> [S|build(Cs, Pc1, I)]
end;
build([$\n|Cs], Pc, _I) -> [$\n|build(Cs, Pc, 0)];
build([$\t|Cs], Pc, I) -> [$\t|build(Cs, Pc, ((I + 8) div 8) * 8)];
build([C|Cs], Pc, I) -> [C|build(Cs, Pc, I+1)];
build([], _Pc, _I) -> [].
decr_pc($p, Pc) -> Pc - 1;
decr_pc($P, Pc) -> Pc - 1;
decr_pc(_, Pc) -> Pc.
indentation . We assume tabs at 8 cols .
-spec indentation(String, StartIndent) -> integer() when
String :: io_lib:chars(),
StartIndent :: integer().
indentation([$\n|Cs], _I) -> indentation(Cs, 0);
indentation([$\t|Cs], I) -> indentation(Cs, ((I + 8) div 8) * 8);
indentation([C|Cs], I) when is_integer(C) ->
indentation(Cs, I+1);
indentation([C|Cs], I) ->
indentation(Cs, indentation(C, I));
indentation([], I) -> I.
control($w, [A], F, Adj, P, Pad, Enc, _Str, _I) ->
term(io_lib:write(A, [{depth,-1}, {encoding, Enc}]), F, Adj, P, Pad);
control($p, [A], F, Adj, P, Pad, Enc, Str, I) ->
print(A, -1, F, Adj, P, Pad, Enc, Str, I);
control($W, [A,Depth], F, Adj, P, Pad, Enc, _Str, _I) when is_integer(Depth) ->
term(io_lib:write(A, [{depth,Depth}, {encoding, Enc}]), F, Adj, P, Pad);
control($P, [A,Depth], F, Adj, P, Pad, Enc, Str, I) when is_integer(Depth) ->
print(A, Depth, F, Adj, P, Pad, Enc, Str, I);
control($s, [A], F, Adj, P, Pad, latin1, _Str, _I) when is_atom(A) ->
L = iolist_to_chars(atom_to_list(A)),
string(L, F, Adj, P, Pad);
control($s, [A], F, Adj, P, Pad, unicode, _Str, _I) when is_atom(A) ->
string(atom_to_list(A), F, Adj, P, Pad);
control($s, [L0], F, Adj, P, Pad, latin1, _Str, _I) ->
L = iolist_to_chars(L0),
string(L, F, Adj, P, Pad);
control($s, [L0], F, Adj, P, Pad, unicode, _Str, _I) ->
L = cdata_to_chars(L0),
uniconv(string(L, F, Adj, P, Pad));
control($e, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_float(A) ->
fwrite_e(A, F, Adj, P, Pad);
control($f, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_float(A) ->
fwrite_f(A, F, Adj, P, Pad);
control($g, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_float(A) ->
fwrite_g(A, F, Adj, P, Pad);
control($b, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
unprefixed_integer(A, F, Adj, base(P), Pad, true);
control($B, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
unprefixed_integer(A, F, Adj, base(P), Pad, false);
control($x, [A,Prefix], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A),
is_atom(Prefix) ->
prefixed_integer(A, F, Adj, base(P), Pad, atom_to_list(Prefix), true);
control($x, [A,Prefix], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
prefixed_integer(A, F, Adj, base(P), Pad, Prefix, true);
control($X, [A,Prefix], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A),
is_atom(Prefix) ->
prefixed_integer(A, F, Adj, base(P), Pad, atom_to_list(Prefix), false);
control($X, [A,Prefix], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
prefixed_integer(A, F, Adj, base(P), Pad, Prefix, false);
control($+, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
Base = base(P),
Prefix = [integer_to_list(Base), $#],
prefixed_integer(A, F, Adj, Base, Pad, Prefix, true);
control($#, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
Base = base(P),
Prefix = [integer_to_list(Base), $#],
prefixed_integer(A, F, Adj, Base, Pad, Prefix, false);
control($c, [A], F, Adj, P, Pad, unicode, _Str, _I) when is_integer(A) ->
char(A, F, Adj, P, Pad);
control($c, [A], F, Adj, P, Pad, _Enc, _Str, _I) when is_integer(A) ->
char(A band 255, F, Adj, P, Pad);
control($~, [], F, Adj, P, Pad, _Enc, _Str, _I) -> char($~, F, Adj, P, Pad);
control($n, [], F, Adj, P, Pad, _Enc, _Str, _I) -> newline(F, Adj, P, Pad);
control($i, [_A], _F, _Adj, _P, _Pad, _Enc, _Str, _I) -> [].
-ifdef(UNICODE_AS_BINARIES).
uniconv(C) ->
unicode:characters_to_binary(C,unicode).
-else.
uniconv(C) ->
C.
-endif.
base(none) ->
10;
base(B) when is_integer(B) ->
B.
term(TermList , Field , Adjust , Precision , PadChar )
Adjust the characters within the field if length less than padding
term(T, none, _Adj, none, _Pad) -> T;
term(T, none, Adj, P, Pad) -> term(T, P, Adj, P, Pad);
term(T, F, Adj, P0, Pad) ->
L = string:length(T),
P = erlang:min(L, case P0 of none -> F; _ -> min(P0, F) end),
if
L > P ->
adjust(chars($*, P), chars(Pad, F-P), Adj);
F >= P ->
adjust(T, chars(Pad, F-L), Adj)
end.
print(Term , Depth , Field , Adjust , Precision , PadChar , Encoding ,
print(T, D, none, Adj, P, Pad, E, Str, I) ->
print(T, D, 80, Adj, P, Pad, E, Str, I);
print(T, D, F, Adj, none, Pad, E, Str, I) ->
print(T, D, F, Adj, I+1, Pad, E, Str, I);
print(T, D, F, right, P, _Pad, Enc, Str, _I) ->
Options = [{column, P},
{line_length, F},
{depth, D},
{encoding, Enc},
{strings, Str}],
io_lib_pretty:print(T, Options).
fwrite_e(Float , Field , Adjust , Precision , PadChar )
fwrite_e(Fl, none, Adj, 6, Pad);
fwrite_e(Fl, none, _Adj, P, _Pad) when P >= 2 ->
float_e(Fl, float_data(Fl), P);
fwrite_e(Fl, F, Adj, none, Pad) ->
fwrite_e(Fl, F, Adj, 6, Pad);
fwrite_e(Fl, F, Adj, P, Pad) when P >= 2 ->
term(float_e(Fl, float_data(Fl), P), F, Adj, F, Pad).
[$-|float_e(-Fl, Fd, P)];
float_e(_Fl, {Ds,E}, P) ->
case float_man(Ds, 1, P-1) of
{[$0|Fs],true} -> [[$1|Fs]|float_exp(E)];
{Fs,false} -> [Fs|float_exp(E-1)]
end.
float_man([Digit ] , Icount , Dcount ) - > { [ Char],CarryFlag } .
Generate the characters in the mantissa from the digits with Icount
characters before the ' . ' and Dcount decimals . Handle carry and let
float_man(Ds, 0, Dc) ->
{Cs,C} = float_man(Ds, Dc),
{[$.|Cs],C};
float_man([D|Ds], I, Dc) ->
case float_man(Ds, I-1, Dc) of
{Cs,true} when D =:= $9 -> {[$0|Cs],true};
{Cs,true} -> {[D+1|Cs],false};
{Cs,false} -> {[D|Cs],false}
end;
{lists:duplicate(I, $0) ++ [$.|lists:duplicate(Dc, $0)],false}.
float_man([D|_], 0) when D >= $5 -> {[],true};
float_man([_|_], 0) -> {[],false};
float_man([D|Ds], Dc) ->
case float_man(Ds, Dc-1) of
{Cs,true} when D =:= $9 -> {[$0|Cs],true};
{Cs,true} -> {[D+1|Cs],false};
{Cs,false} -> {[D|Cs],false}
end;
float_exp(Exponent ) - > [ ] .
float_exp(E) when E >= 0 ->
[$e,$+|integer_to_list(E)];
float_exp(E) ->
[$e|integer_to_list(E)].
fwrite_f(FloatData , Field , Adjust , Precision , PadChar )
fwrite_f(Fl, none, Adj, 6, Pad);
fwrite_f(Fl, none, _Adj, P, _Pad) when P >= 1 ->
float_f(Fl, float_data(Fl), P);
fwrite_f(Fl, F, Adj, none, Pad) ->
fwrite_f(Fl, F, Adj, 6, Pad);
fwrite_f(Fl, F, Adj, P, Pad) when P >= 1 ->
term(float_f(Fl, float_data(Fl), P), F, Adj, F, Pad).
float_f(Fl, Fd, P) when Fl < 0.0 ->
[$-|float_f(-Fl, Fd, P)];
float_f(Fl, {Ds,E}, P) when E =< 0 ->
float_f(_Fl, {Ds,E}, P) ->
case float_man(Ds, E, P) of
{Fs,false} -> Fs
end.
float_data(Fl) ->
float_data(float_to_list(Fl), []).
float_data([$e|E], Ds) ->
{lists:reverse(Ds),list_to_integer(E)+1};
float_data([D|Cs], Ds) when D >= $0, D =< $9 ->
float_data(Cs, [D|Ds]);
float_data([_|Cs], Ds) ->
float_data(Cs, Ds).
See also " Printing Floating - Point Numbers Quickly and Accurately "
in Proceedings of the SIGPLAN ' 96 Conference on Programming
Language Design and Implementation .
-spec fwrite_g(float()) -> string().
fwrite_g(0.0) ->
"0.0";
fwrite_g(Float) when is_float(Float) ->
{Frac, Exp} = mantissa_exponent(Float),
{Place, Digits} = fwrite_g_1(Float, Exp, Frac),
R = insert_decimal(Place, [$0 + D || D <- Digits]),
[$- || true <- [Float < 0.0]] ++ R.
-define(BIG_POW, (1 bsl 52)).
-define(MIN_EXP, (-1074)).
mantissa_exponent(F) ->
case <<F:64/float>> of
denormalized
E = log2floor(M),
{M bsl (53 - E), E - 52 - 1075};
<<_S:1, BE:11, M:52>> when BE < 2047 ->
{M + ?BIG_POW, BE - 1075}
end.
fwrite_g_1(Float, Exp, Frac) ->
Round = (Frac band 1) =:= 0,
if
Exp >= 0 ->
BExp = 1 bsl Exp,
if
Frac =:= ?BIG_POW ->
scale(Frac * BExp * 4, 4, BExp * 2, BExp,
Round, Round, Float);
true ->
scale(Frac * BExp * 2, 2, BExp, BExp,
Round, Round, Float)
end;
Exp < ?MIN_EXP ->
BExp = 1 bsl (?MIN_EXP - Exp),
scale(Frac * 2, 1 bsl (1 - Exp), BExp, BExp,
Round, Round, Float);
Exp > ?MIN_EXP, Frac =:= ?BIG_POW ->
scale(Frac * 4, 1 bsl (2 - Exp), 2, 1,
Round, Round, Float);
true ->
scale(Frac * 2, 1 bsl (1 - Exp), 1, 1,
Round, Round, Float)
end.
scale(R, S, MPlus, MMinus, LowOk, HighOk, Float) ->
Est = int_ceil(math:log10(abs(Float)) - 1.0e-10),
Note that the scheme implementation uses a 326 element look - up
if
Est >= 0 ->
fixup(R, S * int_pow(10, Est), MPlus, MMinus, Est,
LowOk, HighOk);
true ->
Scale = int_pow(10, -Est),
fixup(R * Scale, S, MPlus * Scale, MMinus * Scale, Est,
LowOk, HighOk)
end.
fixup(R, S, MPlus, MMinus, K, LowOk, HighOk) ->
TooLow = if
HighOk -> R + MPlus >= S;
true -> R + MPlus > S
end,
case TooLow of
true ->
{K + 1, generate(R, S, MPlus, MMinus, LowOk, HighOk)};
false ->
{K, generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)}
end.
generate(R0, S, MPlus, MMinus, LowOk, HighOk) ->
D = R0 div S,
R = R0 rem S,
TC1 = if
LowOk -> R =< MMinus;
true -> R < MMinus
end,
TC2 = if
HighOk -> R + MPlus >= S;
true -> R + MPlus > S
end,
case {TC1, TC2} of
{false, false} ->
[D | generate(R * 10, S, MPlus * 10, MMinus * 10, LowOk, HighOk)];
{false, true} ->
[D + 1];
{true, false} ->
[D];
{true, true} when R * 2 < S ->
[D];
{true, true} ->
[D + 1]
end.
insert_decimal(0, S) ->
"0." ++ S;
insert_decimal(Place, S) ->
L = length(S),
if
Place < 0;
Place >= L ->
ExpL = integer_to_list(Place - 1),
ExpDot = if L =:= 1 -> 2; true -> 1 end,
ExpCost = length(ExpL) + 1 + ExpDot,
if
Place < 0 ->
if
2 - Place =< ExpCost ->
"0." ++ lists:duplicate(-Place, $0) ++ S;
true ->
insert_exp(ExpL, S)
end;
true ->
if
Place - L + 2 =< ExpCost ->
S ++ lists:duplicate(Place - L, $0) ++ ".0";
true ->
insert_exp(ExpL, S)
end
end;
true ->
{S0, S1} = lists:split(Place, S),
S0 ++ "." ++ S1
end.
insert_exp(ExpL, [C]) ->
[C] ++ ".0e" ++ ExpL;
insert_exp(ExpL, [C | S]) ->
[C] ++ "." ++ S ++ "e" ++ ExpL.
int_ceil(X) when is_float(X) ->
T = trunc(X),
case (X - T) of
Neg when Neg < 0 -> T;
Pos when Pos > 0 -> T + 1;
_ -> T
end.
int_pow(X, 0) when is_integer(X) ->
1;
int_pow(X, N) when is_integer(X), is_integer(N), N > 0 ->
int_pow(X, N, 1).
int_pow(X, N, R) when N < 2 ->
R * X;
int_pow(X, N, R) ->
int_pow(X * X, N bsr 1, case N band 1 of 1 -> R * X; 0 -> R end).
log2floor(Int) when is_integer(Int), Int > 0 ->
log2floor(Int, 0).
log2floor(0, N) ->
N;
log2floor(Int, N) ->
log2floor(Int bsr 1, 1 + N).
fwrite_g(Float , Field , Adjust , Precision , PadChar )
Use the f form if Float is > = 0.1 and < 1.0e4 ,
fwrite_g(Fl, F, Adj, none, Pad) ->
fwrite_g(Fl, F, Adj, 6, Pad);
fwrite_g(Fl, F, Adj, P, Pad) when P >= 1 ->
A = abs(Fl),
E = if A < 1.0e-1 -> -2;
A < 1.0e0 -> -1;
A < 1.0e1 -> 0;
A < 1.0e2 -> 1;
A < 1.0e3 -> 2;
A < 1.0e4 -> 3;
true -> fwrite_f
end,
if P =< 1, E =:= -1;
P-1 > E, E >= -1 ->
fwrite_f(Fl, F, Adj, P-1-E, Pad);
P =< 1 ->
fwrite_e(Fl, F, Adj, 2, Pad);
true ->
fwrite_e(Fl, F, Adj, P, Pad)
end.
iolist_to_chars([C|Cs]) when is_integer(C), C >= $\000, C =< $\377 ->
[C | iolist_to_chars(Cs)];
iolist_to_chars([I|Cs]) ->
[iolist_to_chars(I) | iolist_to_chars(Cs)];
iolist_to_chars([]) ->
[];
iolist_to_chars(B) when is_binary(B) ->
binary_to_list(B).
cdata ( ) : : ( ) | cbinary ( )
clist ( ) : : ( ) | cbinary ( ) | clist ( ) ,
cdata_to_chars([C|Cs]) when is_integer(C), C >= $\000 ->
[C | cdata_to_chars(Cs)];
cdata_to_chars([I|Cs]) ->
[cdata_to_chars(I) | cdata_to_chars(Cs)];
cdata_to_chars([]) ->
[];
cdata_to_chars(B) when is_binary(B) ->
case catch unicode:characters_to_list(B) of
L when is_list(L) -> L;
_ -> binary_to_list(B)
end.
string(String , Field , Adjust , Precision , PadChar )
string(S, none, _Adj, none, _Pad) -> S;
string(S, F, Adj, none, Pad) ->
string_field(S, F, Adj, string:length(S), Pad);
string(S, none, _Adj, P, Pad) ->
string_field(S, P, left, string:length(S), Pad);
string(S, F, Adj, P, Pad) when F >= P ->
N = string:length(S),
if F > P ->
if N > P ->
adjust(flat_trunc(S, P), chars(Pad, F-P), Adj);
N < P ->
adjust([S|chars(Pad, P-N)], chars(Pad, F-P), Adj);
adjust(S, chars(Pad, F-P), Adj)
end;
string_field(S, F, Adj, N, Pad)
end.
string_field(S, F, _Adj, N, _Pad) when N > F ->
flat_trunc(S, F);
string_field(S, F, Adj, N, Pad) when N < F ->
adjust(S, chars(Pad, F-N), Adj);
S.
unprefixed_integer(Int , Field , Adjust , Base , PadChar , Lowercase )
- > [ ] .
unprefixed_integer(Int, F, Adj, Base, Pad, Lowercase)
when Base >= 2, Base =< 1+$Z-$A+10 ->
if Int < 0 ->
S = cond_lowercase(erlang:integer_to_list(-Int, Base), Lowercase),
term([$-|S], F, Adj, none, Pad);
true ->
S = cond_lowercase(erlang:integer_to_list(Int, Base), Lowercase),
term(S, F, Adj, none, Pad)
end.
prefixed_integer(Int , Field , Adjust , Base , PadChar , Prefix , Lowercase )
- > [ ] .
prefixed_integer(Int, F, Adj, Base, Pad, Prefix, Lowercase)
when Base >= 2, Base =< 1+$Z-$A+10 ->
if Int < 0 ->
S = cond_lowercase(erlang:integer_to_list(-Int, Base), Lowercase),
term([$-,Prefix|S], F, Adj, none, Pad);
true ->
S = cond_lowercase(erlang:integer_to_list(Int, Base), Lowercase),
term([Prefix|S], F, Adj, none, Pad)
end.
char(Char , Field , Adjust , Precision , PadChar ) - > chars ( ) .
char(C, none, _Adj, none, _Pad) -> [C];
char(C, F, _Adj, none, _Pad) -> chars(C, F);
char(C, none, _Adj, P, _Pad) -> chars(C, P);
char(C, F, Adj, P, Pad) when F >= P ->
adjust(chars(C, P), chars(Pad, F - P), Adj).
newline(Field , Adjust , Precision , PadChar ) - > [ ] .
newline(none, _Adj, _P, _Pad) -> "\n";
newline(F, right, _P, _Pad) -> chars($\n, F).
Utilities
adjust(Data, [], _) -> Data;
adjust(Data, Pad, left) -> [Data|Pad];
adjust(Data, Pad, right) -> [Pad|Data].
flat_trunc(List, N) when is_integer(N), N >= 0 ->
string:slice(List, 0, N).
A deep version of lists : duplicate/2
chars(_C, 0) ->
[];
chars(C, 1) ->
[C];
chars(C, 2) ->
[C,C];
chars(C, 3) ->
[C,C,C];
chars(C, N) when is_integer(N), (N band 1) =:= 0 ->
S = chars(C, N bsr 1),
[S|S];
chars(C, N) when is_integer(N) ->
S = chars(C, N bsr 1),
[C,S|S].
[ chars(C , N)|Tail ] .
cond_lowercase(String, true) ->
lowercase(String);
cond_lowercase(String,false) ->
String.
lowercase([H|T]) when is_integer(H), H >= $A, H =< $Z ->
[(H-$A+$a)|lowercase(T)];
lowercase([H|T]) ->
[H|lowercase(T)];
lowercase([]) ->
[].
|
7571ef7b6a9e3952622c8c30de01d573d7d1597519ae3cb10e8b47cd0ab122e3 | metametadata/clj-fakes | reify_nice_fake.cljc | (ns unit.reify-nice-fake
(:require
[clojure.test :refer [is testing]]
[unit.utils :as u]
[clj-fakes.core :as f]
[clj-fakes.context :as fc]
[unit.fixtures.protocols :as p :refer [AnimalProtocol]]))
(defprotocol LocalProtocol
(bar [this] [this x y])
(baz [this x])
(qux [this x y z]))
(defn is-faked
[method & args]
strings are compared instead of values , because , presumably , ' test - refresh ' plugin incorrectly reloads deftype
; and tests start failing on every change to contex.cljc
(is (= #?(:clj "clj_fakes.context.FakeReturnValue"
:cljs "clj-fakes.context/FakeReturnValue")
(pr-str (type (apply method args)))))
(is (not= (apply method args)
(apply method args))))
(u/deftest+
"methods from same-namespace-protocol can be automatically faked"
(f/with-fakes
(let [foo (f/reify-nice-fake LocalProtocol)]
(is-faked bar foo)
(is-faked bar foo 1 2)
(is-faked baz foo 100)
(is-faked qux foo 1 2 3))))
(u/deftest+
"method from fully-qualified protocol can be automatically faked"
(f/with-fakes
(let [cow (f/reify-nice-fake p/AnimalProtocol)]
(is-faked p/speak cow))))
(u/deftest+
"method from refered protocol can be automatically faked"
(f/with-fakes
(let [cow (f/reify-nice-fake AnimalProtocol)]
(is-faked p/speak cow))))
(u/deftest+
"works in explicit context"
(let [ctx (fc/context)
cow (fc/reify-nice-fake ctx AnimalProtocol)]
(is-faked p/speak cow)))
;
( u/-deftest
" method with arglists can be automatically reified even if one of arglists is faked explicitly "
; (f/with-fakes
( let [ foo ( f / reify - nice - fake
; [bar :optional-fake [f/any "bar"]])]
; (is (= "bar" (bar foo)))
( is - faked bar foo 1 2 ) ) ) )
(u/deftest+
"several protocols can be automatically reified"
(f/with-fakes
(let [cow (f/reify-nice-fake p/AnimalProtocol
p/FileProtocol)]
(is-faked p/speak cow)
(is-faked p/speak cow 1)
(is-faked p/speak cow 1 2)
(is-faked p/eat cow 100 200)
(is-faked p/sleep cow)
(is-faked p/save cow)
(is-faked p/scan cow))))
Java interface
#?(:clj
(u/deftest+
"IFn cannot be automatically reified"
(u/is-exception-thrown
java.lang.AbstractMethodError
"n/a"
#""
(f/with-fakes
(let [foo (f/reify-nice-fake clojure.lang.IFn)]
(foo 1 2 3 4))))))
#?(:clj
(u/deftest+
"java.lang.CharSequence can be explicitly reified alongside automatically reified protocol"
(f/with-fakes
(let [foo (f/reify-nice-fake
java.lang.CharSequence
(charAt :fake [[100] \a])
p/FileProtocol)]
(is (= \a (.charAt foo 100)))
(is-faked p/save foo)
(is-faked p/scan foo)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; Object
#?(:cljs
(u/deftest+
"Object can be reified with a new optional-fake method"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(new-method1 [] :optional-fake)
(new-method2 [x y] :optional-fake [[f/any f/any] #(+ %2 %3)])
(new-method3 [x y z] :optional-fake [f/any "bar"]))]
(is (instance? fc/FakeReturnValue (.new-method1 foo)))
(is (= 5 (.new-method2 foo 2 3)))
(is (= "bar" (.new-method3 foo)))
(is (= "bar" (.new-method3 foo 1)))
(is (= "bar" (.new-method3 foo 1 2)))
(is (= "bar" (.new-method3 foo 1 2 3)))))))
#?(:cljs
(u/deftest+
"Object can be reified with a new fake method"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(new-method1 [] :fake [[] "bla"])
(new-method2 [x y] :fake [[f/any f/any] #(+ %2 %3)])
(new-method3 [x y z] :fake [f/any "bar"]))]
(is (= "bla" (.new-method1 foo)))
(is (= 5 (.new-method2 foo 2 3)))
(is (= "bar" (.new-method3 foo)))
(is (= "bar" (.new-method3 foo 1)))
(is (= "bar" (.new-method3 foo 1 2)))
(is (= "bar" (.new-method3 foo 1 2 3)))))))
#?(:cljs
(u/deftest+
"Object can be reified with a new recorded fake method"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(new-method1 [x] :recorded-fake)
(new-method2 [x y] :recorded-fake [[f/any f/any] #(+ %2 %3)]))]
(is (instance? fc/FakeReturnValue (.new-method1 foo 777)))
(is (= 5 (.new-method2 foo 2 3)))
(is (f/method-was-called "new-method1" foo [777]))
(is (f/method-was-called "new-method2" foo [2 3]))))))
(u/deftest+
"Object/toString cannot be automatically reified"
(f/with-fakes
(let [foo (f/reify-nice-fake Object)]
(is (not (instance? clj_fakes.context.FakeReturnValue (.toString foo)))))))
#?(:cljs
(u/deftest+
"Object/toString can be faked"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(toString [] :recorded-fake [[] "bla"]))]
(is (= "bla" (str foo)))
(is (f/method-was-called "toString" foo []))))))
#?(:clj
(u/deftest+
"Object/toString can be faked"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(toString :recorded-fake [[] "bla"]))]
(is (= "bla" (str foo)))
(is (f/method-was-called "toString" foo []))))))
#?(:clj
(u/deftest+
"java.lang.Object is also supported"
(f/with-fakes
(let [foo (f/reify-nice-fake java.lang.Object
(toString :fake [[] "bla"]))]
(is (= "bla" (str foo)))))))
#?(:clj
(u/deftest+
"Object/toString can be explicitly reified alongside automatically reified protocol"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(toString :recorded-fake [[] "bla"])
p/FileProtocol)]
(is (= "bla" (str foo)))
(is (f/method-was-called "toString" foo []))
(is-faked p/save foo)
(is-faked p/scan foo)))))
#?(:cljs
(u/deftest+
"Object/toString can be explicitly reified alongside automatically reified protocol"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(toString [] :recorded-fake [[] "bla"])
p/FileProtocol)]
(is (= "bla" (str foo)))
(is (f/method-was-called "toString" foo []))
(is-faked p/save foo)
(is-faked p/scan foo)))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;; integration
(u/deftest+
"several protocols can be automatically reified and be partially explicitly faked"
(f/with-fakes
(let [cow (f/reify-nice-fake p/AnimalProtocol
(sleep :recorded-fake [[] "zzz"])
p/FileProtocol
(scan :recorded-fake))]
(is-faked p/speak cow)
(is-faked p/speak cow 1)
(is-faked p/speak cow 2 3)
(is-faked p/eat cow 100 200)
(is (= "zzz" (p/sleep cow)))
FileProtocol
(is-faked p/save cow)
(p/scan cow)
(f/method-was-called p/sleep cow [])
FileProtocol
(f/method-was-called p/scan cow [])))) | null | https://raw.githubusercontent.com/metametadata/clj-fakes/d928ddfd11b150b1cd2df5621265c447bf42395a/test/unit/reify_nice_fake.cljc | clojure | and tests start failing on every change to contex.cljc
(f/with-fakes
[bar :optional-fake [f/any "bar"]])]
(is (= "bar" (bar foo)))
Object
integration | (ns unit.reify-nice-fake
(:require
[clojure.test :refer [is testing]]
[unit.utils :as u]
[clj-fakes.core :as f]
[clj-fakes.context :as fc]
[unit.fixtures.protocols :as p :refer [AnimalProtocol]]))
(defprotocol LocalProtocol
(bar [this] [this x y])
(baz [this x])
(qux [this x y z]))
(defn is-faked
[method & args]
strings are compared instead of values , because , presumably , ' test - refresh ' plugin incorrectly reloads deftype
(is (= #?(:clj "clj_fakes.context.FakeReturnValue"
:cljs "clj-fakes.context/FakeReturnValue")
(pr-str (type (apply method args)))))
(is (not= (apply method args)
(apply method args))))
(u/deftest+
"methods from same-namespace-protocol can be automatically faked"
(f/with-fakes
(let [foo (f/reify-nice-fake LocalProtocol)]
(is-faked bar foo)
(is-faked bar foo 1 2)
(is-faked baz foo 100)
(is-faked qux foo 1 2 3))))
(u/deftest+
"method from fully-qualified protocol can be automatically faked"
(f/with-fakes
(let [cow (f/reify-nice-fake p/AnimalProtocol)]
(is-faked p/speak cow))))
(u/deftest+
"method from refered protocol can be automatically faked"
(f/with-fakes
(let [cow (f/reify-nice-fake AnimalProtocol)]
(is-faked p/speak cow))))
(u/deftest+
"works in explicit context"
(let [ctx (fc/context)
cow (fc/reify-nice-fake ctx AnimalProtocol)]
(is-faked p/speak cow)))
( u/-deftest
" method with arglists can be automatically reified even if one of arglists is faked explicitly "
( let [ foo ( f / reify - nice - fake
( is - faked bar foo 1 2 ) ) ) )
(u/deftest+
"several protocols can be automatically reified"
(f/with-fakes
(let [cow (f/reify-nice-fake p/AnimalProtocol
p/FileProtocol)]
(is-faked p/speak cow)
(is-faked p/speak cow 1)
(is-faked p/speak cow 1 2)
(is-faked p/eat cow 100 200)
(is-faked p/sleep cow)
(is-faked p/save cow)
(is-faked p/scan cow))))
Java interface
#?(:clj
(u/deftest+
"IFn cannot be automatically reified"
(u/is-exception-thrown
java.lang.AbstractMethodError
"n/a"
#""
(f/with-fakes
(let [foo (f/reify-nice-fake clojure.lang.IFn)]
(foo 1 2 3 4))))))
#?(:clj
(u/deftest+
"java.lang.CharSequence can be explicitly reified alongside automatically reified protocol"
(f/with-fakes
(let [foo (f/reify-nice-fake
java.lang.CharSequence
(charAt :fake [[100] \a])
p/FileProtocol)]
(is (= \a (.charAt foo 100)))
(is-faked p/save foo)
(is-faked p/scan foo)))))
#?(:cljs
(u/deftest+
"Object can be reified with a new optional-fake method"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(new-method1 [] :optional-fake)
(new-method2 [x y] :optional-fake [[f/any f/any] #(+ %2 %3)])
(new-method3 [x y z] :optional-fake [f/any "bar"]))]
(is (instance? fc/FakeReturnValue (.new-method1 foo)))
(is (= 5 (.new-method2 foo 2 3)))
(is (= "bar" (.new-method3 foo)))
(is (= "bar" (.new-method3 foo 1)))
(is (= "bar" (.new-method3 foo 1 2)))
(is (= "bar" (.new-method3 foo 1 2 3)))))))
#?(:cljs
(u/deftest+
"Object can be reified with a new fake method"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(new-method1 [] :fake [[] "bla"])
(new-method2 [x y] :fake [[f/any f/any] #(+ %2 %3)])
(new-method3 [x y z] :fake [f/any "bar"]))]
(is (= "bla" (.new-method1 foo)))
(is (= 5 (.new-method2 foo 2 3)))
(is (= "bar" (.new-method3 foo)))
(is (= "bar" (.new-method3 foo 1)))
(is (= "bar" (.new-method3 foo 1 2)))
(is (= "bar" (.new-method3 foo 1 2 3)))))))
#?(:cljs
(u/deftest+
"Object can be reified with a new recorded fake method"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(new-method1 [x] :recorded-fake)
(new-method2 [x y] :recorded-fake [[f/any f/any] #(+ %2 %3)]))]
(is (instance? fc/FakeReturnValue (.new-method1 foo 777)))
(is (= 5 (.new-method2 foo 2 3)))
(is (f/method-was-called "new-method1" foo [777]))
(is (f/method-was-called "new-method2" foo [2 3]))))))
(u/deftest+
"Object/toString cannot be automatically reified"
(f/with-fakes
(let [foo (f/reify-nice-fake Object)]
(is (not (instance? clj_fakes.context.FakeReturnValue (.toString foo)))))))
#?(:cljs
(u/deftest+
"Object/toString can be faked"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(toString [] :recorded-fake [[] "bla"]))]
(is (= "bla" (str foo)))
(is (f/method-was-called "toString" foo []))))))
#?(:clj
(u/deftest+
"Object/toString can be faked"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(toString :recorded-fake [[] "bla"]))]
(is (= "bla" (str foo)))
(is (f/method-was-called "toString" foo []))))))
#?(:clj
(u/deftest+
"java.lang.Object is also supported"
(f/with-fakes
(let [foo (f/reify-nice-fake java.lang.Object
(toString :fake [[] "bla"]))]
(is (= "bla" (str foo)))))))
#?(:clj
(u/deftest+
"Object/toString can be explicitly reified alongside automatically reified protocol"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(toString :recorded-fake [[] "bla"])
p/FileProtocol)]
(is (= "bla" (str foo)))
(is (f/method-was-called "toString" foo []))
(is-faked p/save foo)
(is-faked p/scan foo)))))
#?(:cljs
(u/deftest+
"Object/toString can be explicitly reified alongside automatically reified protocol"
(f/with-fakes
(let [foo (f/reify-nice-fake Object
(toString [] :recorded-fake [[] "bla"])
p/FileProtocol)]
(is (= "bla" (str foo)))
(is (f/method-was-called "toString" foo []))
(is-faked p/save foo)
(is-faked p/scan foo)))))
(u/deftest+
"several protocols can be automatically reified and be partially explicitly faked"
(f/with-fakes
(let [cow (f/reify-nice-fake p/AnimalProtocol
(sleep :recorded-fake [[] "zzz"])
p/FileProtocol
(scan :recorded-fake))]
(is-faked p/speak cow)
(is-faked p/speak cow 1)
(is-faked p/speak cow 2 3)
(is-faked p/eat cow 100 200)
(is (= "zzz" (p/sleep cow)))
FileProtocol
(is-faked p/save cow)
(p/scan cow)
(f/method-was-called p/sleep cow [])
FileProtocol
(f/method-was-called p/scan cow [])))) |
9d453075ffc6090b18b94e06c704fcd664ed8adef49db5e02624ae95d3fcdd5c | karamellpelle/grid | Helpers.hs | grid is a game written in Haskell
Copyright ( C ) 2018
--
-- This file is part of grid.
--
-- grid 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.
--
-- grid 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 grid. If not, see </>.
--
module LevelTools.Helpers where
import MyPrelude
import LevelTools.EditWorld
import Game.Grid.Helpers
findInvalidObject :: EditWorld -> Maybe (RoomIx, Node, String)
findInvalidObject edit =
let ixs = map (\sr -> sroomRoomIx sr) $ scontentRooms $ editSemiContent edit
dotplains = concatMap (\sr -> map (\dot -> (sroomRoomIx sr, dot)) (sroomDotPlain sr)) $ scontentRooms $ editSemiContent edit
in helper ixs dotplains
where
helper :: [RoomIx] -> [(RoomIx, DotPlain)] -> Maybe (RoomIx, Node, String)
helper ixs ((room, dot):rds) =
if dotplainRoom dot `elem` ixs
then helper ixs rds
else Just (room, dotplainNode dot, "no such RoomIx: " ++ show (dotplainRoom dot))
helper ixs [] =
Nothing
editModifyCamera edit f =
editModifyGrid edit $ \grid -> gridModifyCamera grid f
editModifyGrid edit f =
edit { editGrid = f (editGrid edit) }
editModifyLevel edit f =
edit { editLevel = f $ editLevel edit }
editModifyCameraNode edit f =
edit { editCameraNode = f $ editCameraNode edit }
editModifyNode edit f =
edit { editNode = f $ editNode edit }
editModifySemiContent edit f =
edit { editSemiContent = f $ editSemiContent edit }
editModifyDotPlain edit f =
edit { editDotPlain = f $ editDotPlain edit }
editModifyDotBonus edit f =
edit { editDotBonus = f $ editDotBonus edit }
editModifyDotTele edit f =
edit { editDotTele = f $ editDotTele edit }
editModifyDotFinish edit f =
edit { editDotFinish = f $ editDotFinish edit }
editModifyWall edit f =
edit { editWall = f $ editWall edit }
scontentPushDotPlain cnt room dot =
cnt { scontentRooms = helper (scontentRooms cnt) room dot }
where
helper (r:rs) ix dot =
if sroomRoomIx r == ix then let r' = r { sroomDotPlain = sroomDotPlain r ++ [dot] }
in r' : rs
else r : helper rs ix dot
helper [] ix dot =
[makeSemiRoom ix [] [dot] [] [] []]
scontentPushDotBonus cnt room dot =
cnt { scontentRooms = helper (scontentRooms cnt) room dot }
where
helper (r:rs) ix dot =
if sroomRoomIx r == ix then let r' = r { sroomDotBonus = sroomDotBonus r ++ [dot] }
in r' : rs
else r : helper rs ix dot
helper [] ix dot =
[makeSemiRoom ix [] [] [dot] [] []]
scontentPushDotTele cnt room dot =
cnt { scontentRooms = helper (scontentRooms cnt) room dot }
where
helper (r:rs) ix dot =
if sroomRoomIx r == ix then let r' = r { sroomDotTele = sroomDotTele r ++ [dot] }
in r' : rs
else r : helper rs ix dot
helper [] ix dot =
[makeSemiRoom ix [] [] [] [dot] []]
scontentPushDotFinish cnt room dot =
cnt { scontentRooms = helper (scontentRooms cnt) room dot }
where
helper (r:rs) ix dot =
if sroomRoomIx r == ix then let r' = r { sroomDotFinish = sroomDotFinish r ++ [dot] }
in r' : rs
else r : helper rs ix dot
helper [] ix dot =
[makeSemiRoom ix [] [] [] [] [dot]]
scontentPushWall cnt room wall =
cnt { scontentRooms = helper (scontentRooms cnt) room wall }
where
helper (r:rs) ix wall =
if sroomRoomIx r == ix then let r' = r { sroomWall = sroomWall r ++ [wall] }
in r' : rs
else r : helper rs ix wall
helper [] ix wall =
[makeSemiRoom ix [wall] [] [] [] []]
--------------------------------------------------------------------------------
-- editObjects
editChangeObject edit node =
let (edit', mWall, mDotPlain, mDotBonus, mDotTele, mDotFinish) =
modSemiContent edit $ \cnt -> modRoom cnt (scontentRoom cnt) $ \room ->
helper0 room node
in edit'
{
editWall = maybe' (editWall edit) mWall,
editDotPlain = maybe' (editDotPlain edit) mDotPlain,
editDotBonus = maybe' (editDotBonus edit) mDotBonus,
editDotTele = maybe' (editDotTele edit) mDotTele,
editDotFinish = maybe' (editDotFinish edit) mDotFinish
}
where
maybe' a = \maybeA -> case maybeA of
Nothing -> a
Just a' -> a'
modSemiContent edit f =
let (cnt', m0, m1, m2, m3, m4) = f (editSemiContent edit)
in (edit { editSemiContent = cnt' }, m0, m1, m2, m3, m4)
modRoom cnt ix f =
let (rooms', m0, m1, m2, m3, m4) = helper (scontentRooms cnt) ix f
in (cnt { scontentRooms = rooms' }, m0, m1, m2, m3, m4)
where
helper (r:rs) ix f =
if sroomRoomIx r == ix then let (r', m0, m1, m2, m3, m4) = f r
in (r':rs, m0, m1, m2, m3, m4)
else helper rs ix f
helper [] ix f =
([], Nothing, Nothing, Nothing, Nothing, Nothing)
helper0 room node =
case helper (sroomDotPlain room) of
Just (d, ds) -> (room { sroomDotPlain = ds }, Nothing, Just d, Nothing, Nothing, Nothing)
Nothing -> helper1 room node
where
helper (d:ds) =
if dotplainNode d == node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
helper1 room node =
case helper (sroomDotBonus room) of
Just (d, ds) -> (room { sroomDotBonus = ds }, Nothing, Nothing, Just d, Nothing, Nothing)
Nothing -> helper2 room node
where
helper (d:ds) =
if dotbonusNode d == node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
helper2 room node =
case helper (sroomDotTele room) of
Just (d, ds) -> (room { sroomDotTele= ds }, Nothing, Nothing, Nothing, Just d, Nothing)
Nothing -> helper3 room node
where
helper (d:ds) =
if dotteleNode d == node || dotteleNode' d == node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
helper3 room node =
case helper (sroomDotFinish room) of
Just (d, ds) -> (room { sroomDotFinish = ds }, Nothing, Nothing, Nothing, Nothing, Just d)
Nothing -> helper4 room node
where
helper (d:ds) =
if dotfinishNode d == node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
helper4 room node =
case helper (sroomWall room) of
Just (d, ds) -> (room { sroomWall = ds }, Just d, Nothing, Nothing, Nothing, Nothing)
Nothing -> (room, Nothing, Nothing, Nothing, Nothing, Nothing)
where
helper (d:ds) =
if isCol d node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
isCol wall node =
case nodeDiff (wallNode wall) node of
p -> let x = wallX wall
y = wallY wall
n = nodeCross x y
ix = nodeInner p x
iy = nodeInner p y
in nodeInner p n == 0 && 0 <= ix && ix <= nodeInner x x
&& 0 <= iy && iy <= nodeInner y y
editEraseObject edit node =
edit
| null | https://raw.githubusercontent.com/karamellpelle/grid/56729e63ed6404fd6cfd6d11e73fa358f03c386f/designer/source/LevelTools/Helpers.hs | haskell |
This file is part of grid.
grid is free software: you can redistribute it and/or modify
(at your option) any later version.
grid is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
along with grid. If not, see </>.
------------------------------------------------------------------------------
editObjects | grid is a game written in Haskell
Copyright ( C ) 2018
it under the terms of the GNU General Public License as published by
the Free Software Foundation , either version 3 of the License , or
You should have received a copy of the GNU General Public License
module LevelTools.Helpers where
import MyPrelude
import LevelTools.EditWorld
import Game.Grid.Helpers
findInvalidObject :: EditWorld -> Maybe (RoomIx, Node, String)
findInvalidObject edit =
let ixs = map (\sr -> sroomRoomIx sr) $ scontentRooms $ editSemiContent edit
dotplains = concatMap (\sr -> map (\dot -> (sroomRoomIx sr, dot)) (sroomDotPlain sr)) $ scontentRooms $ editSemiContent edit
in helper ixs dotplains
where
helper :: [RoomIx] -> [(RoomIx, DotPlain)] -> Maybe (RoomIx, Node, String)
helper ixs ((room, dot):rds) =
if dotplainRoom dot `elem` ixs
then helper ixs rds
else Just (room, dotplainNode dot, "no such RoomIx: " ++ show (dotplainRoom dot))
helper ixs [] =
Nothing
editModifyCamera edit f =
editModifyGrid edit $ \grid -> gridModifyCamera grid f
editModifyGrid edit f =
edit { editGrid = f (editGrid edit) }
editModifyLevel edit f =
edit { editLevel = f $ editLevel edit }
editModifyCameraNode edit f =
edit { editCameraNode = f $ editCameraNode edit }
editModifyNode edit f =
edit { editNode = f $ editNode edit }
editModifySemiContent edit f =
edit { editSemiContent = f $ editSemiContent edit }
editModifyDotPlain edit f =
edit { editDotPlain = f $ editDotPlain edit }
editModifyDotBonus edit f =
edit { editDotBonus = f $ editDotBonus edit }
editModifyDotTele edit f =
edit { editDotTele = f $ editDotTele edit }
editModifyDotFinish edit f =
edit { editDotFinish = f $ editDotFinish edit }
editModifyWall edit f =
edit { editWall = f $ editWall edit }
scontentPushDotPlain cnt room dot =
cnt { scontentRooms = helper (scontentRooms cnt) room dot }
where
helper (r:rs) ix dot =
if sroomRoomIx r == ix then let r' = r { sroomDotPlain = sroomDotPlain r ++ [dot] }
in r' : rs
else r : helper rs ix dot
helper [] ix dot =
[makeSemiRoom ix [] [dot] [] [] []]
scontentPushDotBonus cnt room dot =
cnt { scontentRooms = helper (scontentRooms cnt) room dot }
where
helper (r:rs) ix dot =
if sroomRoomIx r == ix then let r' = r { sroomDotBonus = sroomDotBonus r ++ [dot] }
in r' : rs
else r : helper rs ix dot
helper [] ix dot =
[makeSemiRoom ix [] [] [dot] [] []]
scontentPushDotTele cnt room dot =
cnt { scontentRooms = helper (scontentRooms cnt) room dot }
where
helper (r:rs) ix dot =
if sroomRoomIx r == ix then let r' = r { sroomDotTele = sroomDotTele r ++ [dot] }
in r' : rs
else r : helper rs ix dot
helper [] ix dot =
[makeSemiRoom ix [] [] [] [dot] []]
scontentPushDotFinish cnt room dot =
cnt { scontentRooms = helper (scontentRooms cnt) room dot }
where
helper (r:rs) ix dot =
if sroomRoomIx r == ix then let r' = r { sroomDotFinish = sroomDotFinish r ++ [dot] }
in r' : rs
else r : helper rs ix dot
helper [] ix dot =
[makeSemiRoom ix [] [] [] [] [dot]]
scontentPushWall cnt room wall =
cnt { scontentRooms = helper (scontentRooms cnt) room wall }
where
helper (r:rs) ix wall =
if sroomRoomIx r == ix then let r' = r { sroomWall = sroomWall r ++ [wall] }
in r' : rs
else r : helper rs ix wall
helper [] ix wall =
[makeSemiRoom ix [wall] [] [] [] []]
editChangeObject edit node =
let (edit', mWall, mDotPlain, mDotBonus, mDotTele, mDotFinish) =
modSemiContent edit $ \cnt -> modRoom cnt (scontentRoom cnt) $ \room ->
helper0 room node
in edit'
{
editWall = maybe' (editWall edit) mWall,
editDotPlain = maybe' (editDotPlain edit) mDotPlain,
editDotBonus = maybe' (editDotBonus edit) mDotBonus,
editDotTele = maybe' (editDotTele edit) mDotTele,
editDotFinish = maybe' (editDotFinish edit) mDotFinish
}
where
maybe' a = \maybeA -> case maybeA of
Nothing -> a
Just a' -> a'
modSemiContent edit f =
let (cnt', m0, m1, m2, m3, m4) = f (editSemiContent edit)
in (edit { editSemiContent = cnt' }, m0, m1, m2, m3, m4)
modRoom cnt ix f =
let (rooms', m0, m1, m2, m3, m4) = helper (scontentRooms cnt) ix f
in (cnt { scontentRooms = rooms' }, m0, m1, m2, m3, m4)
where
helper (r:rs) ix f =
if sroomRoomIx r == ix then let (r', m0, m1, m2, m3, m4) = f r
in (r':rs, m0, m1, m2, m3, m4)
else helper rs ix f
helper [] ix f =
([], Nothing, Nothing, Nothing, Nothing, Nothing)
helper0 room node =
case helper (sroomDotPlain room) of
Just (d, ds) -> (room { sroomDotPlain = ds }, Nothing, Just d, Nothing, Nothing, Nothing)
Nothing -> helper1 room node
where
helper (d:ds) =
if dotplainNode d == node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
helper1 room node =
case helper (sroomDotBonus room) of
Just (d, ds) -> (room { sroomDotBonus = ds }, Nothing, Nothing, Just d, Nothing, Nothing)
Nothing -> helper2 room node
where
helper (d:ds) =
if dotbonusNode d == node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
helper2 room node =
case helper (sroomDotTele room) of
Just (d, ds) -> (room { sroomDotTele= ds }, Nothing, Nothing, Nothing, Just d, Nothing)
Nothing -> helper3 room node
where
helper (d:ds) =
if dotteleNode d == node || dotteleNode' d == node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
helper3 room node =
case helper (sroomDotFinish room) of
Just (d, ds) -> (room { sroomDotFinish = ds }, Nothing, Nothing, Nothing, Nothing, Just d)
Nothing -> helper4 room node
where
helper (d:ds) =
if dotfinishNode d == node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
helper4 room node =
case helper (sroomWall room) of
Just (d, ds) -> (room { sroomWall = ds }, Just d, Nothing, Nothing, Nothing, Nothing)
Nothing -> (room, Nothing, Nothing, Nothing, Nothing, Nothing)
where
helper (d:ds) =
if isCol d node then Just (d, ds)
else case helper ds of
Just (d', ds') -> Just (d', d:ds')
Nothing -> Nothing
helper [] =
Nothing
isCol wall node =
case nodeDiff (wallNode wall) node of
p -> let x = wallX wall
y = wallY wall
n = nodeCross x y
ix = nodeInner p x
iy = nodeInner p y
in nodeInner p n == 0 && 0 <= ix && ix <= nodeInner x x
&& 0 <= iy && iy <= nodeInner y y
editEraseObject edit node =
edit
|
f9b92628d0d7802c8b55f62b253ed9caa924425659412151fba62a00cf7dc541 | nunchaku-inria/nunchaku | Elim_prop_args.mli |
(* This file is free software, part of nunchaku. See file "license" for more details. *)
* { 1 Eliminate function arguments of type " prop " }
Emits some " if / then / else " instead , using a pseudo - prop type
that has exactly two arguments .
Emits some "if/then/else" instead, using a pseudo-prop type
that has exactly two arguments. *)
open Nunchaku_core
type term = Term.t
type ty = term
type problem = (term, ty) Problem.t
type model = (term,ty) Model.t
type res = (term,ty) Problem.Res.t
val name : string
type state
val transform_problem : problem -> problem * state
val decode_model : state -> model -> model
val pipe_with :
?on_decoded:('b -> unit) list ->
decode:(state -> 'a -> 'b) ->
print:bool ->
check:bool ->
(problem, problem, 'a, 'b) Transform.t
val pipe :
print:bool ->
check:bool ->
(problem, problem, res, res) Transform.t
| null | https://raw.githubusercontent.com/nunchaku-inria/nunchaku/16f33db3f5e92beecfb679a13329063b194f753d/src/transformations/Elim_prop_args.mli | ocaml | This file is free software, part of nunchaku. See file "license" for more details. |
* { 1 Eliminate function arguments of type " prop " }
Emits some " if / then / else " instead , using a pseudo - prop type
that has exactly two arguments .
Emits some "if/then/else" instead, using a pseudo-prop type
that has exactly two arguments. *)
open Nunchaku_core
type term = Term.t
type ty = term
type problem = (term, ty) Problem.t
type model = (term,ty) Model.t
type res = (term,ty) Problem.Res.t
val name : string
type state
val transform_problem : problem -> problem * state
val decode_model : state -> model -> model
val pipe_with :
?on_decoded:('b -> unit) list ->
decode:(state -> 'a -> 'b) ->
print:bool ->
check:bool ->
(problem, problem, 'a, 'b) Transform.t
val pipe :
print:bool ->
check:bool ->
(problem, problem, res, res) Transform.t
|
d491c080c916a6f7f1051906f77188f219220e406b04069890095f5c85dc6c73 | ocaml-ppx/ocamlformat | shebang.ml | #!/usr/bin/env ocaml
type t = {a: a; b: b}
let f x = x
| null | https://raw.githubusercontent.com/ocaml-ppx/ocamlformat/3d1c992240f7d30bcb8151285274f44619dae197/test/passing/tests/shebang.ml | ocaml | #!/usr/bin/env ocaml
type t = {a: a; b: b}
let f x = x
|
|
38ae48b9a3976575fa98dc206aee09c08e356c4523dd134e334ce7b8d96f9816 | den1k/vimsical | config.cljc | (ns vimsical.frontend.config
(:require [clojure.spec.alpha :as s]))
(def debug?
#?(:clj false
:cljs (let [dbg? ^boolean goog.DEBUG]
(s/check-asserts dbg?)
dbg?))) | null | https://raw.githubusercontent.com/den1k/vimsical/1e4a1f1297849b1121baf24bdb7a0c6ba3558954/src/frontend/vimsical/frontend/config.cljc | clojure | (ns vimsical.frontend.config
(:require [clojure.spec.alpha :as s]))
(def debug?
#?(:clj false
:cljs (let [dbg? ^boolean goog.DEBUG]
(s/check-asserts dbg?)
dbg?))) |
|
6295ab5ab2537f56124fccd91b494ea4f049ba70d9209013c332a66e02b8c9f2 | 2nishantg/hScraper | Show.hs | module HScraper.Show (
showTree
) where
import HScraper.Types
import HScraper.HTMLparser
import qualified Data.Text as T
-- | takes a 'HTMLtree' and prints it in a neat manner.
--
-- expected output
--
-- @
-- |html
-- |head
-- |body
-- YOLO
-- @
--
showTree:: IO HTMLTree -> IO ()
showTree y= do
x <- y
let x' = (showTree' x $showString "") ""
putStrLn x'
showTree':: HTMLTree -> ShowS -> ShowS
showTree' (NTree (Text t) []) p = p . showString (T.unpack t) . showString "\n"
showTree' (NTree (Element t a) l) p = p . showChar '|' . showString (T.unpack t) . showString "\n" . foldr (\x y -> showTree' x (p . showString "\t") . showString " " . y) (showString " ") l
| null | https://raw.githubusercontent.com/2nishantg/hScraper/d2cb0d8ee4a9729fecc06701b76c03d763e49d44/HScraper/Show.hs | haskell | | takes a 'HTMLtree' and prints it in a neat manner.
expected output
@
|html
|head
|body
YOLO
@
| module HScraper.Show (
showTree
) where
import HScraper.Types
import HScraper.HTMLparser
import qualified Data.Text as T
showTree:: IO HTMLTree -> IO ()
showTree y= do
x <- y
let x' = (showTree' x $showString "") ""
putStrLn x'
showTree':: HTMLTree -> ShowS -> ShowS
showTree' (NTree (Text t) []) p = p . showString (T.unpack t) . showString "\n"
showTree' (NTree (Element t a) l) p = p . showChar '|' . showString (T.unpack t) . showString "\n" . foldr (\x y -> showTree' x (p . showString "\t") . showString " " . y) (showString " ") l
|
a3f4b3632e4890c9897d0ac002e3ca1ebc88fa366d79277cb1b0098b870e50d1 | robashton/cravendb | transaction.clj | (ns cravendb.transaction
(:refer-clojure :exclude [load] )
(:require [cravendb.client :as client]
[cravendb.database :as db]))
(defn mode
"Determines whether a transaction is operating on an embedded or remote endpoint
Returns either :remote or :embedded"
[tx & _] (if (:href tx) :remote :embedded))
(defmulti from-storage
"Retrieves a document by id directly from the underlying storage without checking the transaction cache"
mode)
(defmethod from-storage :remote
[{:keys [href]} id]
(client/get-document href id))
(defmethod from-storage :embedded
[{:keys [instance]} id]
(db/load-document instance id))
(defn store
"Stores any clojure object as a document in the transaction with the specified id"
[tx id data]
(assoc-in tx [:cache id] data))
(defn delete [tx id]
"Deletes a document by id in the current transaction"
(assoc-in tx [:cache id] :deleted))
(defn load
"Loads a document from the current transaction by id
will honour any changes made in previous operations"
[tx id]
(let [cached (get-in tx [:cache id])]
(if (= cached :deleted) nil
(or cached (from-storage tx id)))))
(defn package
"Packages up a transaction's cache into a bulk operation which can be submitted either over HTTP or directly to a database instance"
[cache]
(into ()
(for [[k v] cache]
(if (= v :deleted)
{ :operation :docs-delete :id k }
{ :operation :docs-put :id k :document v }))))
(defmulti commit!
"flushes a transaction as a bulk operation to the underlying storage - this is atomic"
mode)
(defmethod commit! :remote
[{:keys [href] :as tx}]
(client/bulk-operation href (package (:cache tx))))
(defmethod commit! :embedded
[{:keys [instance] :as tx}]
(db/bulk instance (package (:cache tx))))
(defn open
"Starts a transaction ready for working with"
[{:keys [href] :as instance}]
{ :href href :instance instance})
| null | https://raw.githubusercontent.com/robashton/cravendb/461e80c7c028478adb4287922db6ee4d2593a880/src/cravendb/transaction.clj | clojure | (ns cravendb.transaction
(:refer-clojure :exclude [load] )
(:require [cravendb.client :as client]
[cravendb.database :as db]))
(defn mode
"Determines whether a transaction is operating on an embedded or remote endpoint
Returns either :remote or :embedded"
[tx & _] (if (:href tx) :remote :embedded))
(defmulti from-storage
"Retrieves a document by id directly from the underlying storage without checking the transaction cache"
mode)
(defmethod from-storage :remote
[{:keys [href]} id]
(client/get-document href id))
(defmethod from-storage :embedded
[{:keys [instance]} id]
(db/load-document instance id))
(defn store
"Stores any clojure object as a document in the transaction with the specified id"
[tx id data]
(assoc-in tx [:cache id] data))
(defn delete [tx id]
"Deletes a document by id in the current transaction"
(assoc-in tx [:cache id] :deleted))
(defn load
"Loads a document from the current transaction by id
will honour any changes made in previous operations"
[tx id]
(let [cached (get-in tx [:cache id])]
(if (= cached :deleted) nil
(or cached (from-storage tx id)))))
(defn package
"Packages up a transaction's cache into a bulk operation which can be submitted either over HTTP or directly to a database instance"
[cache]
(into ()
(for [[k v] cache]
(if (= v :deleted)
{ :operation :docs-delete :id k }
{ :operation :docs-put :id k :document v }))))
(defmulti commit!
"flushes a transaction as a bulk operation to the underlying storage - this is atomic"
mode)
(defmethod commit! :remote
[{:keys [href] :as tx}]
(client/bulk-operation href (package (:cache tx))))
(defmethod commit! :embedded
[{:keys [instance] :as tx}]
(db/bulk instance (package (:cache tx))))
(defn open
"Starts a transaction ready for working with"
[{:keys [href] :as instance}]
{ :href href :instance instance})
|
|
7d44e1ae637aec0912a58389daa650643c6507ef8f96fe096bd164b57cf367ff | utz82/pstk | treeview.scm | (cond-expand
(chicken-4 (use pstk))
(chicken-5 (import pstk)))
PS - TK example : display a treeview
(tk-start)
(ttk-map-widgets 'all) ; make sure we are using tile widget set
(tk/wm 'title tk "PS-Tk Example: TreeView")
(tk 'configure 'height: 230 'width: 350)
;; create a tree view within scroll bars
(let ((treeview (tk 'create-widget 'treeview 'columns: '("col1" "col2" "col3")))
(hsb (tk 'create-widget 'scrollbar 'orient: 'horizontal))
(vsb (tk 'create-widget 'scrollbar 'orient: 'vertical)))
;; associate scrollbars and treeview
(hsb 'configure 'command: (list treeview 'xview))
(vsb 'configure 'command: (list treeview 'yview))
(treeview 'configure 'xscrollcommand: (list hsb 'set))
(treeview 'configure 'yscrollcommand: (list vsb 'set))
;; set up columns in tree view
(treeview 'column "col1" 'width: 70)
(treeview 'heading "col1" 'text: "Col 1")
(treeview 'column "col2" 'width: 70)
(treeview 'heading "col2" 'text: "Col 2")
(treeview 'column "col3" 'width: 70)
(treeview 'heading "col3" 'text: "Col 3")
;; insert items into tree view
(treeview 'insert "" 'end 'id: "item1" 'text: "item 1" 'values: "a b 1")
(treeview 'insert "" 'end 'id: "subtree1" 'text: "item 2" 'values: "c d 2")
(treeview 'insert "" 'end 'id: "subtree2" 'text: "item 3" 'values: "e f 3")
(treeview 'insert "subtree1" 'end 'text: "item 4" 'values: "g h 4")
(treeview 'insert "subtree1" 'end 'text: "item 5" 'values: "i j 5")
(treeview 'insert "subtree2" 'end 'text: "item 6" 'values: "k l 6")
(treeview 'insert "subtree2" 'end 'text: "item 7" 'values: "m n 7")
(treeview 'insert "subtree2" 'end 'text: "item 8" 'values: "o p 8")
;; place tree view and scroll bar
(tk/grid treeview 'column: 0 'row: 0 'sticky: 'news)
(tk/grid hsb 'column: 0 'row: 1 'sticky: 'we)
(tk/grid vsb 'column: 1 'row: 0 'sticky: 'ns)
; ensure grid fills the frame
(tk/grid 'columnconfigure tk 0 'weight: 1)
(tk/grid 'rowconfigure tk 0 'weight: 1)
;; create a label and button to show selection
(let ((label (tk 'create-widget 'label)))
(tk/grid label 'column: 0 'row: 2 'pady: 5)
(tk/grid (tk 'create-widget 'button
'text: "Show item"
'command: (lambda () (label 'configure 'text: (treeview 'selection))))
'column: 0 'row: 3 'pady: 5))
)
(tk-event-loop)
| null | https://raw.githubusercontent.com/utz82/pstk/27e907097529a3d61bb63e87e4e1cd1ca9abc3af/doc/examples/treeview.scm | scheme | make sure we are using tile widget set
create a tree view within scroll bars
associate scrollbars and treeview
set up columns in tree view
insert items into tree view
place tree view and scroll bar
ensure grid fills the frame
create a label and button to show selection | (cond-expand
(chicken-4 (use pstk))
(chicken-5 (import pstk)))
PS - TK example : display a treeview
(tk-start)
(tk/wm 'title tk "PS-Tk Example: TreeView")
(tk 'configure 'height: 230 'width: 350)
(let ((treeview (tk 'create-widget 'treeview 'columns: '("col1" "col2" "col3")))
(hsb (tk 'create-widget 'scrollbar 'orient: 'horizontal))
(vsb (tk 'create-widget 'scrollbar 'orient: 'vertical)))
(hsb 'configure 'command: (list treeview 'xview))
(vsb 'configure 'command: (list treeview 'yview))
(treeview 'configure 'xscrollcommand: (list hsb 'set))
(treeview 'configure 'yscrollcommand: (list vsb 'set))
(treeview 'column "col1" 'width: 70)
(treeview 'heading "col1" 'text: "Col 1")
(treeview 'column "col2" 'width: 70)
(treeview 'heading "col2" 'text: "Col 2")
(treeview 'column "col3" 'width: 70)
(treeview 'heading "col3" 'text: "Col 3")
(treeview 'insert "" 'end 'id: "item1" 'text: "item 1" 'values: "a b 1")
(treeview 'insert "" 'end 'id: "subtree1" 'text: "item 2" 'values: "c d 2")
(treeview 'insert "" 'end 'id: "subtree2" 'text: "item 3" 'values: "e f 3")
(treeview 'insert "subtree1" 'end 'text: "item 4" 'values: "g h 4")
(treeview 'insert "subtree1" 'end 'text: "item 5" 'values: "i j 5")
(treeview 'insert "subtree2" 'end 'text: "item 6" 'values: "k l 6")
(treeview 'insert "subtree2" 'end 'text: "item 7" 'values: "m n 7")
(treeview 'insert "subtree2" 'end 'text: "item 8" 'values: "o p 8")
(tk/grid treeview 'column: 0 'row: 0 'sticky: 'news)
(tk/grid hsb 'column: 0 'row: 1 'sticky: 'we)
(tk/grid vsb 'column: 1 'row: 0 'sticky: 'ns)
(tk/grid 'columnconfigure tk 0 'weight: 1)
(tk/grid 'rowconfigure tk 0 'weight: 1)
(let ((label (tk 'create-widget 'label)))
(tk/grid label 'column: 0 'row: 2 'pady: 5)
(tk/grid (tk 'create-widget 'button
'text: "Show item"
'command: (lambda () (label 'configure 'text: (treeview 'selection))))
'column: 0 'row: 3 'pady: 5))
)
(tk-event-loop)
|
8ddecf2f51825e020a980e20e9c3bbc19b870b2ac1e1374cd0ee99299c273a92 | patricoferris/ocaml-multicore-monorepo | caqti_driver_lib.ml | Copyright ( C ) 2017 - -2019 < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the OCaml static compilation exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library . If not , see < / > .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see </>.
*)
open Caqti_common_priv
let linear_param_length templ =
let rec loop = function
| Caqti_query.L _ -> ident
| Caqti_query.Q _ -> succ
| Caqti_query.P _ -> succ
| Caqti_query.S frags -> List.fold loop frags in
loop templ 0
let nonlinear_param_length templ =
let rec loop = function
| Caqti_query.L _ -> ident
| Caqti_query.Q _ -> ident
| Caqti_query.P n -> max (n + 1)
| Caqti_query.S frags -> List.fold loop frags in
loop templ 0
let linear_param_order templ =
let a = Array.make (nonlinear_param_length templ) [] in
let rec loop = function
| Caqti_query.L _ -> ident
| Caqti_query.Q s -> fun (j, quotes) -> (j + 1, (j, s) :: quotes)
| Caqti_query.P i -> fun (j, quotes) -> a.(i) <- j :: a.(i); (j + 1, quotes)
| Caqti_query.S frags -> List.fold loop frags in
let _, quotes = loop templ (0, []) in
(Array.to_list a, List.rev quotes)
let linear_query_string templ =
let buf = Buffer.create 64 in
let rec loop = function
| Caqti_query.L s -> Buffer.add_string buf s
| Caqti_query.Q _ | Caqti_query.P _ -> Buffer.add_char buf '?'
| Caqti_query.S frags -> List.iter loop frags in
loop templ;
Buffer.contents buf
| null | https://raw.githubusercontent.com/patricoferris/ocaml-multicore-monorepo/22b441e6727bc303950b3b37c8fbc024c748fe55/duniverse/ocaml-caqti/lib/caqti_driver_lib.ml | ocaml | Copyright ( C ) 2017 - -2019 < >
*
* This library is free software ; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , either version 3 of the License , or ( at your
* option ) any later version , with the OCaml static compilation exception .
*
* This library is distributed in the hope that it will be useful , but WITHOUT
* ANY WARRANTY ; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE . See the GNU Lesser General Public
* License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library . If not , see < / > .
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version, with the OCaml static compilation exception.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library. If not, see </>.
*)
open Caqti_common_priv
let linear_param_length templ =
let rec loop = function
| Caqti_query.L _ -> ident
| Caqti_query.Q _ -> succ
| Caqti_query.P _ -> succ
| Caqti_query.S frags -> List.fold loop frags in
loop templ 0
let nonlinear_param_length templ =
let rec loop = function
| Caqti_query.L _ -> ident
| Caqti_query.Q _ -> ident
| Caqti_query.P n -> max (n + 1)
| Caqti_query.S frags -> List.fold loop frags in
loop templ 0
let linear_param_order templ =
let a = Array.make (nonlinear_param_length templ) [] in
let rec loop = function
| Caqti_query.L _ -> ident
| Caqti_query.Q s -> fun (j, quotes) -> (j + 1, (j, s) :: quotes)
| Caqti_query.P i -> fun (j, quotes) -> a.(i) <- j :: a.(i); (j + 1, quotes)
| Caqti_query.S frags -> List.fold loop frags in
let _, quotes = loop templ (0, []) in
(Array.to_list a, List.rev quotes)
let linear_query_string templ =
let buf = Buffer.create 64 in
let rec loop = function
| Caqti_query.L s -> Buffer.add_string buf s
| Caqti_query.Q _ | Caqti_query.P _ -> Buffer.add_char buf '?'
| Caqti_query.S frags -> List.iter loop frags in
loop templ;
Buffer.contents buf
|
|
1e6d71a8bd58e40d0f993c62f917fd644da73931d69f849b35ddf29f7fd2ea39 | polysemy-research/polysemy-zoo | MonadWriter.hs | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
module Polysemy.ConstraintAbsorber.MonadWriter
( absorbWriter
) where
import qualified Control.Monad.Writer.Class as S
import Polysemy
import Polysemy.ConstraintAbsorber
import Polysemy.Writer
------------------------------------------------------------------------------
-- | Introduce a local 'S.MonadWriter' constraint on 'Sem' --- allowing it to
interop nicely with MTL .
--
@since 0.3.0.0
absorbWriter
:: forall w r a
. ( Monoid w
, Member (Writer w) r
)
=> (S.MonadWriter w (Sem r) => Sem r a)
-- ^ A computation that requires an instance of 'S.MonadWriter' for
-- 'Sem'. This might be something with type @'S.MonadWriter' w m => m a@.
-> Sem r a
absorbWriter =
let swapTuple (x,y) = (y,x)
semTell = tell
semListen :: Member (Writer w) r => Sem r b -> Sem r (b, w)
semListen = fmap swapTuple . listen @w
semPass :: Member (Writer w) r => Sem r (b, w -> w) -> Sem r b
semPass = pass @w . fmap swapTuple
in absorbWithSem @(S.MonadWriter _) @Action
(WriterDict semTell semListen semPass)
(Sub Dict)
# INLINEABLE absorbWriter #
------------------------------------------------------------------------------
-- | A dictionary of the functions we need to supply
-- to make an instance of Writer
data WriterDict w m = WriterDict
{ tell_ :: w -> m ()
, listen_ :: forall a. m a -> m (a, w)
, pass_ :: forall a. m (a, w -> w) -> m a
}
------------------------------------------------------------------------------
-- | Wrapper for a monadic action with phantom
-- type parameter for reflection.
-- Locally defined so that the instance we are going
-- to build with reflection must be coherent, that is
-- there cannot be orphans.
newtype Action m s' a = Action { action :: m a }
deriving (Functor, Applicative, Monad)
------------------------------------------------------------------------------
-- | Given a reifiable mtl Writer dictionary,
-- we can make an instance of @MonadWriter@ for the action
wrapped in @Action@.
instance ( Monad m
, Monoid w
, Reifies s' (WriterDict w m)
) => S.MonadWriter w (Action m s') where
tell w = Action $ tell_ (reflect $ Proxy @s') w
# INLINEABLE tell #
listen x = Action $ listen_ (reflect $ Proxy @s') (action x)
# INLINEABLE listen #
pass x = Action $ pass_ (reflect $ Proxy @s') (action x)
# INLINEABLE pass #
| null | https://raw.githubusercontent.com/polysemy-research/polysemy-zoo/eb0ce40e4d3b9757ede851a3450c05cc42949b49/src/Polysemy/ConstraintAbsorber/MonadWriter.hs | haskell | ----------------------------------------------------------------------------
| Introduce a local 'S.MonadWriter' constraint on 'Sem' --- allowing it to
^ A computation that requires an instance of 'S.MonadWriter' for
'Sem'. This might be something with type @'S.MonadWriter' w m => m a@.
----------------------------------------------------------------------------
| A dictionary of the functions we need to supply
to make an instance of Writer
----------------------------------------------------------------------------
| Wrapper for a monadic action with phantom
type parameter for reflection.
Locally defined so that the instance we are going
to build with reflection must be coherent, that is
there cannot be orphans.
----------------------------------------------------------------------------
| Given a reifiable mtl Writer dictionary,
we can make an instance of @MonadWriter@ for the action | # LANGUAGE FlexibleInstances #
# LANGUAGE GeneralizedNewtypeDeriving #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE UndecidableInstances #
module Polysemy.ConstraintAbsorber.MonadWriter
( absorbWriter
) where
import qualified Control.Monad.Writer.Class as S
import Polysemy
import Polysemy.ConstraintAbsorber
import Polysemy.Writer
interop nicely with MTL .
@since 0.3.0.0
absorbWriter
:: forall w r a
. ( Monoid w
, Member (Writer w) r
)
=> (S.MonadWriter w (Sem r) => Sem r a)
-> Sem r a
absorbWriter =
let swapTuple (x,y) = (y,x)
semTell = tell
semListen :: Member (Writer w) r => Sem r b -> Sem r (b, w)
semListen = fmap swapTuple . listen @w
semPass :: Member (Writer w) r => Sem r (b, w -> w) -> Sem r b
semPass = pass @w . fmap swapTuple
in absorbWithSem @(S.MonadWriter _) @Action
(WriterDict semTell semListen semPass)
(Sub Dict)
# INLINEABLE absorbWriter #
data WriterDict w m = WriterDict
{ tell_ :: w -> m ()
, listen_ :: forall a. m a -> m (a, w)
, pass_ :: forall a. m (a, w -> w) -> m a
}
newtype Action m s' a = Action { action :: m a }
deriving (Functor, Applicative, Monad)
wrapped in @Action@.
instance ( Monad m
, Monoid w
, Reifies s' (WriterDict w m)
) => S.MonadWriter w (Action m s') where
tell w = Action $ tell_ (reflect $ Proxy @s') w
# INLINEABLE tell #
listen x = Action $ listen_ (reflect $ Proxy @s') (action x)
# INLINEABLE listen #
pass x = Action $ pass_ (reflect $ Proxy @s') (action x)
# INLINEABLE pass #
|
e85fcde567f8f82a1df9eb5015780b150f4e086ec47ea65620487e2040bf9ccf | earl-ducaine/cl-garnet | abstract-errors.lisp | ;;; -*- Mode: COMMON-LISP; Package: GARNET-GADGETS -*- ;;
;;-------------------------------------------------------------------;;
Copyright 1993 ; ;
;;-------------------------------------------------------------------;;
;; This code is in the Public Domain. Anyone who can get some use ;;
;; from it is welcome. ;;
;; This code comes with no warranty. ;;
;;-------------------------------------------------------------------;;
$ Id$
;;; Abstract error handler functions
;;
;;
;; These functions provide an abstraction of the error handling
;; facilities which can be bound as appropriate.
(in-package "GARNET-GADGETS")
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(prompting-protected-eval
prompting-protected-read prompting-protected-read-from-string
prompter
protect-errors with-protected-errors
protected-eval
protected-read protected-read-from-string
call-prompter
displayer call-displayer
selector call-selector
*application-long-name* *application-short-name*
)))
(defun prompting-protected-eval (form &key (default-value nil dv?)
(context (format nil
"Evaluating ~S"
form))
(allow-debug (eq *user-type* :programmer))
(local-abort nil)
(abort-val nil))
"This function executes a form in an environment where errors are
caught and handled by a special protected-error gadget. This
gadget prints the error message and allows for several different
restarts: ABORT, DEBUG and CONTINUE, USE-VALUE and STORE-VALUE.
<form> is the form to be evaluated.
<default-value> if supplied, produces a continue restart which returns
that value.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter.
If <allow-debug> is nil (defaul (eq *user-type* :programmer)) then the
debug switch is suppressed.
<context> is a string defining the context of the error. Default
value is `Evaluating <form>'.
"
(let* ((handler-function
(lambda (condition)
(prompting-error-handler context condition :allow-debugger
allow-debug)))
(handled-form `(handler-bind ((error ,handler-function))
,form)))
(when dv?
(setq handled-form
`(restart-case ,handled-form
(continue ()
:report (lambda (s)
(format s "Return value ~S" ,default-value))
,default-value))))
(when local-abort
(setq handled-form
`(restart-case ,handled-form
(abort ()
:report (lambda (s)
(format s "Abort and return value ~S" ,abort-val))
(values ,abort-val :abort)))))
(eval handled-form)))
(defun prompting-protected-read
(&optional (stream *standard-input*)
&key (context (format nil "Reading from ~S" stream))
(read-package *package*)
(read-bindings nil)
(default-value nil)
(allow-debug nil)
(local-abort nil)
(abort-val nil))
"This works rather like protected-eval except it tries to
read from the <stream>.
<stream> is the stream to be read from (if omitted *standard-input*).
<read-package> (default :user) selects the package to read from. This
is because I don't want to make any assumptions about what the binding
of package will be at eval time especially in a multiprocessed lisp,
and I think this is safer. If you want the string to be read in a
different package, you can try using :read-package *package*
<read-bindings> is a list of (var . form)'s as in a let statement.
These bindings are made (with the let) before reading the string to
allow for effects such as binding the readtable.
<default-value> (default nil) this establishes a continue restart
which returns this value. Note that this is slightly different from
protected-eval in that it is always available.
<allow-debug> (default (eq *user-type* :programmer) if true, this
includes a button which allows the debugger to be entered on an error.
Note that the default value is different from protected-eval.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter. (Same as
protected-eval).
"
(let* ((form `(let ((*package* ,read-package))
(let ,read-bindings
(read ,stream))))
(handler-function
(lambda (condition)
(prompting-error-handler context condition
:allow-debugger allow-debug)))
(handled-form
`(handler-bind ((error ,handler-function))
,form)))
(when T
(setq handled-form
`(restart-case ,handled-form
(continue ()
:report (lambda (s)
(format s "Return value ~S" ,default-value))
,default-value))))
(when local-abort
(setq handled-form
`(restart-case ,handled-form
(abort ()
:report (lambda (s)
(format s "Return value ~S" ,abort-val))
(values ,abort-val :abort)))))
(eval handled-form)))
(defun prompting-protected-read-from-string
(string
&key (start 0)
(end (length string))
(context (format nil "Parsing ~A" string))
(read-package *package*)
(read-bindings nil)
(default-value nil)
(allow-debug nil)
(local-abort nil)
(abort-val nil))
"This works rather like protected-eval except it tries to
read from the <stream>.
<string> is the string to be read from (probably the :string of a text
input gadget).
<start> and <end> allow selecting a substring.
<read-package> (default :user) selects the package to read from. This
is because I don't want to make any assumptions about what the binding
of package will be at eval time especially in a multiprocessed lisp,
and I think this is safer. If you want the string to be read in a
different package, you can try using :read-package *package*
<read-bindings> is a list of (var . form)'s as in a let statement.
These bindings are made (with the let) before reading the string to
allow for effects such as binding the readtable.
<default-value> (default nil) this establishes a continue restart
which returns this value. Note that this is slightly different from
protected-eval in that it is always available.
<allow-debug> (default (eq *user-type* :programmer) if true, this
includes a button which allows the debugger to be entered on an error.
Note that the default value is different from protected-eval.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter. (Same as
protected-eval).
"
(let* ((form `(let ((*package* ,read-package))
(let ,read-bindings
(read-from-string ,(subseq string start end)))))
(handler-function
(lambda (condition)
(prompting-error-handler context condition
:allow-debugger allow-debug)))
(handled-form
`(handler-bind ((error ,handler-function))
,form)))
(when T
(setq handled-form
`(restart-case ,handled-form
(continue ()
:report (lambda (s)
(format s "Return value ~S" ,default-value))
,default-value))))
(when local-abort
(setq handled-form
`(restart-case ,handled-form
(abort ()
:report (lambda (s)
(format s "Return value ~S" ,abort-val))
(values ,abort-val :abort)))))
(eval handled-form)))
(defun prompter (prompt &optional (stream *query-io*)
&key (local-abort nil)
(default-value nil dv?)
(abort-val :ABORT)
(satisfy-test #'(lambda (obj) T))
(eval-input? nil)
&allow-other-keys
&aux flag form val test?)
"Prompts user for an input. <Prompt> is printed with ~A as a prompt.
<stream> defaults to *query-io*. If <local-abort> is true a local
abort is set up which will return the values <abort-val> and :ABORT.
If <default-value> is supplied, a CONTINUE restart is set up which
allows the user to select the default value.
If <eval-input?> is true, then the expression is evaluated before it
is returned; if not, the unevaluated expression is returned.
The value supplied by the user is passed to <satisfy-test>. If that
test fails, the user is prompted again."
(loop
(format stream "~A~%==>" prompt)
(multiple-value-setq (form flag)
(apply #'prompting-protected-read stream
:local-abort local-abort :abort-val abort-val
(if dv? (list :default-value default-value) '())))
(unless (eq flag :ABORT)
(if eval-input?
(multiple-value-setq (val flag)
(apply #'prompting-protected-eval form
:local-abort local-abort :abort-val abort-val
(if dv? (list :default-value default-value) '())))
(setq val form)))
(if (eq flag :ABORT)
(if local-abort (return-from prompter (values abort-val :ABORT)))
(progn
(multiple-value-setq (test? flag)
(ignore-errors (funcall satisfy-test val)))
(if test? (return-from prompter (values val :OK))
(if (typep flag 'Condition)
(format stream "~&Error: ~A~%" flag)))))
(format stream "~&Bad Input, try again~%")))
;;; Abstract error handler functions
;;
;;
;; These functions provide an abstraction of the error handling
;; facilities which can be bound as appropriate.
;;
(defun protect-errors (context condition
&key (allow-debugger (eql *user-type* :programmer)))
"Error handler which prompts user for a choice of
:ABORT, :DEBUG, :CONTINE, :USE-VALUE and :STORE-VALUE
restarts.
<context> is used to supply a context for the error.
<allow-debugger> is used to determine whether or not the user can
enter the LISP debugger.
Should be invoked with an expression such as:
(handler-bind
((error \#'(lambda (condition)
(protect-errors context-string condition))))
...)
"
(prompting-error-handler context condition :allow-debugger allow-debugger))
(defmacro with-protected-errors (context &body forms)
"Executes forms in a protected environment where errors are handled
by prompting-error-handler, which creates queries the user with
options to abort or continue, possibly with various recovery
strategies. If *user-type* is :programmer, then allows debugging.
<context> should be a string describing user meaningful context in
which error occured."
`(handler-bind
((error
(lambda (condition)
(protect-errors ,context condition))))
,.forms))
(defun protected-eval (form &rest args
&key (default-value nil dv?) (context (format
nil "Evaluating ~S" form)) (allow-debug
(eq *user-type* :programmer)) (local-abort
nil) (abort-val nil))
"This function executes a form in an environment where errors are
caught and handled by a special protected-error. This
gadget prints the error message and allows for several different
restarts: ABORT, DEBUG and CONTINUE, USE-VALUE and STORE-VALUE.
<form> is the form to be evaluated.
<default-value> if supplied, produces a continue restart which returns
that value.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter.
If <allow-debug> is nil (defaul (eq *user-type* :programmer)) then the
debug switch is suppressed.
<context> is a string defining the context of the error. Default
value is `Evaluating <form>'.
This abtract function allows the type of error handler to be hidden
from the routine which sets it up. In particular, both
promting-protected-eval and protected-eval could be bound to
this symbol."
(declare (ignore default-value dv? context allow-debug local-abort abort-val))
(apply #'prompting-protected-eval args))
(defun protected-read (&optional (stream *standard-input*)
&rest args
&key (context (format nil "Reading from ~S" stream))
(read-package *package*)
(read-bindings nil)
(default-value nil)
(allow-debug nil)
(local-abort nil)
(abort-val nil))
"This works rather like protected-eval except it tries to
read from the <stream>.
<stream> is the stream to be read from (if omitted *standard-input*).
<read-package> (default :user) selects the package to read from. This
is because I don't want to make any assumptions about what the binding
of package will be at eval time especially in a multiprocessed lisp,
and I think this is safer. If you want the string to be read in a
different package, you can try using :read-package *package*
<read-bindings> is a list of (var . form)'s as in a let statement.
These bindings are made (with the let) before reading the string to
allow for effects such as binding the readtable.
<default-value> (default nil) this establishes a continue restart
which returns this value. Note that this is slightly different from
protected-eval in that it is always available.
<allow-debug> (default (eq *user-type* :programmer) if true, this
includes a button which allows the debugger to be entered on an error.
Note that the default value is different from protected-eval.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter. (Same as
protected-eval).
This abtract function allows the type of error handler to be hidden
from the routine which sets it up. In particular, both
promting-protected-eval and protected-eval could be bound to
this symbol."
(declare (ignore context read-package read-bindings
default-value allow-debug local-abort
abort-val))
(apply #'prompting-protected-read stream args))
(defun protected-read-from-string
(string &rest args
&key (start 0)
(context (format nil "Parsing ~S" string))
(end (length string))
(read-package *package*)
(read-bindings nil)
(default-value nil)
(allow-debug nil)
(local-abort nil)
(abort-val nil))
"This works rather like protected-eval except it tries to
read from the <stream>.
<string> is the string to be read from (probably the :string of a text
input gadget).
<start> and <end> allow selecting a substring.
<read-package> (default :user) selects the package to read from. This
is because I don't want to make any assumptions about what the binding
of package will be at eval time especially in a multiprocessed lisp,
and I think this is safer. If you want the string to be read in a
different package, you can try using :read-package *package*
<read-bindings> is a list of (var . form)'s as in a let statement.
These bindings are made (with the let) before reading the string to
allow for effects such as binding the readtable.
<default-value> (default nil) this establishes a continue restart
which returns this value. Note that this is slightly different from
protected-eval in that it is always available.
<allow-debug> (default (eq *user-type* :programmer) if true, this
includes a button which allows the debugger to be entered on an error.
Note that the default value is different from protected-eval.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter. (Same as
protected-eval).
"
(declare (ignore start context end read-package read-bindings
default-value allow-debug local-abort abort-val))
(apply #'prompting-protected-read-from-string string args))
(defun call-prompter (prompt
&rest args
&key (stream *query-io*)
(local-abort nil)
(default-value nil dv?)
(abort-val :ABORT)
(eval-input? nil)
(satisfy-test #'(lambda (obj) T))
&allow-other-keys)
"Prompts user for an input. <Prompt> is printed with ~A as a prompt.
<stream> defaults to *query-io*. If <local-abort> is true a local
abort is set up which will return the values <abort-val> and :ABORT.
If <default-value> is supplied, a CONTINUE restart is set up which
allows the user to select the default value.
If <eval-input?> is true, then the expression is evaluated before it
is returned; if not, the unevaluated expression is returned.
The value supplied by the user is passed to <satisfy-test>. If that
test fails, the user is prompted again.
This is mostly a dummy function for hiding the prompter type from the
implementatoin mechanism."
(declare (ignore local-abort default-value dv? abort-val
eval-input? satisfy-test))
(apply #'prompter prompt stream :allow-other-keys t args))
;;;
;;;----------------------------------------------------------------------
;;; Simple Displays
;;;----------------------------------------------------------------------
(defun displayer (message &key (stream *standard-output*)
(beep t)
&allow-other-keys)
"A generic display function which sends a display to the specified
location. <stream> indicates the stream to which the message is to be
sent in the text based version. <beep> is a logical value indicating
whether or not the device should make some sort of alert signal. This
is meant to be called through call-displayer."
(declare (ignore beep))
(princ message stream))
(defun call-displayer (message &rest keys
&key (stream *standard-output*)
(beep t)
&allow-other-keys)
"A generic display function which sends a display to the specified
location. <stream> indicates the stream to which the message is to be
sent in the text based version. <beep> is a logical value indicating
whether or not the device should make some sort of alert signal. This
is meant to abstract the means of sending the message from the sending
program."
(declare (ignore stream beep))
(apply #'displayer message :allow-other-keys t keys))
(defun selector (message &key (stream *query-io*)
(in-stream stream)
(out-stream stream)
(option-list '(:yes :no))
&allow-other-keys
&aux option)
"This function offers the user a choice of items from a menu of
keywords. The user can either type the keword or select the option by
number. <stream> is the stream (default *query-io*) and <option-list>
is the list of options (default '(:yes no)). <message> is displayed
first on the stream as a prompt."
(declare (type String message) (type Stream stream in-stream out-stream)
(type List option-list)
#-(and)(:returns (type (Member option-list) option)))
(loop
(format out-stream "~&;;;? ~A~%" message)
(format out-stream ";;;? Select an option by name or number.:~%;;;?(")
(dotimes (i (length option-list))
(let ((option (nth i option-list)))
(format out-stream "~D. ~S " i option)))
(format out-stream "::?~%")
(setq option (read in-stream))
(if (find option option-list) (return option))
(if (and (numberp option) (< option (length option-list)))
(return (nth option option-list)))
(format out-stream "Unrecognized selection ~S, try again." option)))
(defun call-selector (message &rest keys
&key (stream *query-io*)
(in-stream stream)
(out-stream stream)
(option-list '(:yes :no))
&allow-other-keys)
"This function offers the user a choice of items from a menu of
keywords. The user can either type the keword or select the option by
number. <stream> is the stream (default *query-io*) and <option-list>
is the list of options (default '(:yes no)). <message> is displayed
first on the stream as a prompt."
(declare (type String message)
(type Stream stream in-stream out-stream)
(type List option-list)
;; (:returns (type (Member option-list) option))
)
(declare (ignore in-stream out-stream option-list))
(apply #'selector message :allow-other-keys t keys))
(defvar *application-long-name* "Common-Lisp"
"Name of application for window titles.")
(defvar *application-short-name* "LISP"
"Name of application for Icon titles.")
| null | https://raw.githubusercontent.com/earl-ducaine/cl-garnet/f0095848513ba69c370ed1dc51ee01f0bb4dd108/src/protected-eval/abstract-errors.lisp | lisp | -*- Mode: COMMON-LISP; Package: GARNET-GADGETS -*- ;;
-------------------------------------------------------------------;;
;
-------------------------------------------------------------------;;
This code is in the Public Domain. Anyone who can get some use ;;
from it is welcome. ;;
This code comes with no warranty. ;;
-------------------------------------------------------------------;;
Abstract error handler functions
These functions provide an abstraction of the error handling
facilities which can be bound as appropriate.
if not, the unevaluated expression is returned.
Abstract error handler functions
These functions provide an abstraction of the error handling
facilities which can be bound as appropriate.
if not, the unevaluated expression is returned.
----------------------------------------------------------------------
Simple Displays
----------------------------------------------------------------------
(:returns (type (Member option-list) option)) |
$ Id$
(in-package "GARNET-GADGETS")
(eval-when (:compile-toplevel :load-toplevel :execute)
(export '(prompting-protected-eval
prompting-protected-read prompting-protected-read-from-string
prompter
protect-errors with-protected-errors
protected-eval
protected-read protected-read-from-string
call-prompter
displayer call-displayer
selector call-selector
*application-long-name* *application-short-name*
)))
(defun prompting-protected-eval (form &key (default-value nil dv?)
(context (format nil
"Evaluating ~S"
form))
(allow-debug (eq *user-type* :programmer))
(local-abort nil)
(abort-val nil))
"This function executes a form in an environment where errors are
caught and handled by a special protected-error gadget. This
gadget prints the error message and allows for several different
restarts: ABORT, DEBUG and CONTINUE, USE-VALUE and STORE-VALUE.
<form> is the form to be evaluated.
<default-value> if supplied, produces a continue restart which returns
that value.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter.
If <allow-debug> is nil (defaul (eq *user-type* :programmer)) then the
debug switch is suppressed.
<context> is a string defining the context of the error. Default
value is `Evaluating <form>'.
"
(let* ((handler-function
(lambda (condition)
(prompting-error-handler context condition :allow-debugger
allow-debug)))
(handled-form `(handler-bind ((error ,handler-function))
,form)))
(when dv?
(setq handled-form
`(restart-case ,handled-form
(continue ()
:report (lambda (s)
(format s "Return value ~S" ,default-value))
,default-value))))
(when local-abort
(setq handled-form
`(restart-case ,handled-form
(abort ()
:report (lambda (s)
(format s "Abort and return value ~S" ,abort-val))
(values ,abort-val :abort)))))
(eval handled-form)))
(defun prompting-protected-read
(&optional (stream *standard-input*)
&key (context (format nil "Reading from ~S" stream))
(read-package *package*)
(read-bindings nil)
(default-value nil)
(allow-debug nil)
(local-abort nil)
(abort-val nil))
"This works rather like protected-eval except it tries to
read from the <stream>.
<stream> is the stream to be read from (if omitted *standard-input*).
<read-package> (default :user) selects the package to read from. This
is because I don't want to make any assumptions about what the binding
of package will be at eval time especially in a multiprocessed lisp,
and I think this is safer. If you want the string to be read in a
different package, you can try using :read-package *package*
<read-bindings> is a list of (var . form)'s as in a let statement.
These bindings are made (with the let) before reading the string to
allow for effects such as binding the readtable.
<default-value> (default nil) this establishes a continue restart
which returns this value. Note that this is slightly different from
protected-eval in that it is always available.
<allow-debug> (default (eq *user-type* :programmer) if true, this
includes a button which allows the debugger to be entered on an error.
Note that the default value is different from protected-eval.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter. (Same as
protected-eval).
"
(let* ((form `(let ((*package* ,read-package))
(let ,read-bindings
(read ,stream))))
(handler-function
(lambda (condition)
(prompting-error-handler context condition
:allow-debugger allow-debug)))
(handled-form
`(handler-bind ((error ,handler-function))
,form)))
(when T
(setq handled-form
`(restart-case ,handled-form
(continue ()
:report (lambda (s)
(format s "Return value ~S" ,default-value))
,default-value))))
(when local-abort
(setq handled-form
`(restart-case ,handled-form
(abort ()
:report (lambda (s)
(format s "Return value ~S" ,abort-val))
(values ,abort-val :abort)))))
(eval handled-form)))
(defun prompting-protected-read-from-string
(string
&key (start 0)
(end (length string))
(context (format nil "Parsing ~A" string))
(read-package *package*)
(read-bindings nil)
(default-value nil)
(allow-debug nil)
(local-abort nil)
(abort-val nil))
"This works rather like protected-eval except it tries to
read from the <stream>.
<string> is the string to be read from (probably the :string of a text
input gadget).
<start> and <end> allow selecting a substring.
<read-package> (default :user) selects the package to read from. This
is because I don't want to make any assumptions about what the binding
of package will be at eval time especially in a multiprocessed lisp,
and I think this is safer. If you want the string to be read in a
different package, you can try using :read-package *package*
<read-bindings> is a list of (var . form)'s as in a let statement.
These bindings are made (with the let) before reading the string to
allow for effects such as binding the readtable.
<default-value> (default nil) this establishes a continue restart
which returns this value. Note that this is slightly different from
protected-eval in that it is always available.
<allow-debug> (default (eq *user-type* :programmer) if true, this
includes a button which allows the debugger to be entered on an error.
Note that the default value is different from protected-eval.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter. (Same as
protected-eval).
"
(let* ((form `(let ((*package* ,read-package))
(let ,read-bindings
(read-from-string ,(subseq string start end)))))
(handler-function
(lambda (condition)
(prompting-error-handler context condition
:allow-debugger allow-debug)))
(handled-form
`(handler-bind ((error ,handler-function))
,form)))
(when T
(setq handled-form
`(restart-case ,handled-form
(continue ()
:report (lambda (s)
(format s "Return value ~S" ,default-value))
,default-value))))
(when local-abort
(setq handled-form
`(restart-case ,handled-form
(abort ()
:report (lambda (s)
(format s "Return value ~S" ,abort-val))
(values ,abort-val :abort)))))
(eval handled-form)))
(defun prompter (prompt &optional (stream *query-io*)
&key (local-abort nil)
(default-value nil dv?)
(abort-val :ABORT)
(satisfy-test #'(lambda (obj) T))
(eval-input? nil)
&allow-other-keys
&aux flag form val test?)
"Prompts user for an input. <Prompt> is printed with ~A as a prompt.
<stream> defaults to *query-io*. If <local-abort> is true a local
abort is set up which will return the values <abort-val> and :ABORT.
If <default-value> is supplied, a CONTINUE restart is set up which
allows the user to select the default value.
If <eval-input?> is true, then the expression is evaluated before it
The value supplied by the user is passed to <satisfy-test>. If that
test fails, the user is prompted again."
(loop
(format stream "~A~%==>" prompt)
(multiple-value-setq (form flag)
(apply #'prompting-protected-read stream
:local-abort local-abort :abort-val abort-val
(if dv? (list :default-value default-value) '())))
(unless (eq flag :ABORT)
(if eval-input?
(multiple-value-setq (val flag)
(apply #'prompting-protected-eval form
:local-abort local-abort :abort-val abort-val
(if dv? (list :default-value default-value) '())))
(setq val form)))
(if (eq flag :ABORT)
(if local-abort (return-from prompter (values abort-val :ABORT)))
(progn
(multiple-value-setq (test? flag)
(ignore-errors (funcall satisfy-test val)))
(if test? (return-from prompter (values val :OK))
(if (typep flag 'Condition)
(format stream "~&Error: ~A~%" flag)))))
(format stream "~&Bad Input, try again~%")))
(defun protect-errors (context condition
&key (allow-debugger (eql *user-type* :programmer)))
"Error handler which prompts user for a choice of
:ABORT, :DEBUG, :CONTINE, :USE-VALUE and :STORE-VALUE
restarts.
<context> is used to supply a context for the error.
<allow-debugger> is used to determine whether or not the user can
enter the LISP debugger.
Should be invoked with an expression such as:
(handler-bind
((error \#'(lambda (condition)
(protect-errors context-string condition))))
...)
"
(prompting-error-handler context condition :allow-debugger allow-debugger))
(defmacro with-protected-errors (context &body forms)
"Executes forms in a protected environment where errors are handled
by prompting-error-handler, which creates queries the user with
options to abort or continue, possibly with various recovery
strategies. If *user-type* is :programmer, then allows debugging.
<context> should be a string describing user meaningful context in
which error occured."
`(handler-bind
((error
(lambda (condition)
(protect-errors ,context condition))))
,.forms))
(defun protected-eval (form &rest args
&key (default-value nil dv?) (context (format
nil "Evaluating ~S" form)) (allow-debug
(eq *user-type* :programmer)) (local-abort
nil) (abort-val nil))
"This function executes a form in an environment where errors are
caught and handled by a special protected-error. This
gadget prints the error message and allows for several different
restarts: ABORT, DEBUG and CONTINUE, USE-VALUE and STORE-VALUE.
<form> is the form to be evaluated.
<default-value> if supplied, produces a continue restart which returns
that value.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter.
If <allow-debug> is nil (defaul (eq *user-type* :programmer)) then the
debug switch is suppressed.
<context> is a string defining the context of the error. Default
value is `Evaluating <form>'.
This abtract function allows the type of error handler to be hidden
from the routine which sets it up. In particular, both
promting-protected-eval and protected-eval could be bound to
this symbol."
(declare (ignore default-value dv? context allow-debug local-abort abort-val))
(apply #'prompting-protected-eval args))
(defun protected-read (&optional (stream *standard-input*)
&rest args
&key (context (format nil "Reading from ~S" stream))
(read-package *package*)
(read-bindings nil)
(default-value nil)
(allow-debug nil)
(local-abort nil)
(abort-val nil))
"This works rather like protected-eval except it tries to
read from the <stream>.
<stream> is the stream to be read from (if omitted *standard-input*).
<read-package> (default :user) selects the package to read from. This
is because I don't want to make any assumptions about what the binding
of package will be at eval time especially in a multiprocessed lisp,
and I think this is safer. If you want the string to be read in a
different package, you can try using :read-package *package*
<read-bindings> is a list of (var . form)'s as in a let statement.
These bindings are made (with the let) before reading the string to
allow for effects such as binding the readtable.
<default-value> (default nil) this establishes a continue restart
which returns this value. Note that this is slightly different from
protected-eval in that it is always available.
<allow-debug> (default (eq *user-type* :programmer) if true, this
includes a button which allows the debugger to be entered on an error.
Note that the default value is different from protected-eval.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter. (Same as
protected-eval).
This abtract function allows the type of error handler to be hidden
from the routine which sets it up. In particular, both
promting-protected-eval and protected-eval could be bound to
this symbol."
(declare (ignore context read-package read-bindings
default-value allow-debug local-abort
abort-val))
(apply #'prompting-protected-read stream args))
(defun protected-read-from-string
(string &rest args
&key (start 0)
(context (format nil "Parsing ~S" string))
(end (length string))
(read-package *package*)
(read-bindings nil)
(default-value nil)
(allow-debug nil)
(local-abort nil)
(abort-val nil))
"This works rather like protected-eval except it tries to
read from the <stream>.
<string> is the string to be read from (probably the :string of a text
input gadget).
<start> and <end> allow selecting a substring.
<read-package> (default :user) selects the package to read from. This
is because I don't want to make any assumptions about what the binding
of package will be at eval time especially in a multiprocessed lisp,
and I think this is safer. If you want the string to be read in a
different package, you can try using :read-package *package*
<read-bindings> is a list of (var . form)'s as in a let statement.
These bindings are made (with the let) before reading the string to
allow for effects such as binding the readtable.
<default-value> (default nil) this establishes a continue restart
which returns this value. Note that this is slightly different from
protected-eval in that it is always available.
<allow-debug> (default (eq *user-type* :programmer) if true, this
includes a button which allows the debugger to be entered on an error.
Note that the default value is different from protected-eval.
If <local-abort> is true (default nil), then a local restart is
established for abort which returns (values <abort-val> :abort)
where <abort-val> is another parameter. (Same as
protected-eval).
"
(declare (ignore start context end read-package read-bindings
default-value allow-debug local-abort abort-val))
(apply #'prompting-protected-read-from-string string args))
(defun call-prompter (prompt
&rest args
&key (stream *query-io*)
(local-abort nil)
(default-value nil dv?)
(abort-val :ABORT)
(eval-input? nil)
(satisfy-test #'(lambda (obj) T))
&allow-other-keys)
"Prompts user for an input. <Prompt> is printed with ~A as a prompt.
<stream> defaults to *query-io*. If <local-abort> is true a local
abort is set up which will return the values <abort-val> and :ABORT.
If <default-value> is supplied, a CONTINUE restart is set up which
allows the user to select the default value.
If <eval-input?> is true, then the expression is evaluated before it
The value supplied by the user is passed to <satisfy-test>. If that
test fails, the user is prompted again.
This is mostly a dummy function for hiding the prompter type from the
implementatoin mechanism."
(declare (ignore local-abort default-value dv? abort-val
eval-input? satisfy-test))
(apply #'prompter prompt stream :allow-other-keys t args))
(defun displayer (message &key (stream *standard-output*)
(beep t)
&allow-other-keys)
"A generic display function which sends a display to the specified
location. <stream> indicates the stream to which the message is to be
sent in the text based version. <beep> is a logical value indicating
whether or not the device should make some sort of alert signal. This
is meant to be called through call-displayer."
(declare (ignore beep))
(princ message stream))
(defun call-displayer (message &rest keys
&key (stream *standard-output*)
(beep t)
&allow-other-keys)
"A generic display function which sends a display to the specified
location. <stream> indicates the stream to which the message is to be
sent in the text based version. <beep> is a logical value indicating
whether or not the device should make some sort of alert signal. This
is meant to abstract the means of sending the message from the sending
program."
(declare (ignore stream beep))
(apply #'displayer message :allow-other-keys t keys))
(defun selector (message &key (stream *query-io*)
(in-stream stream)
(out-stream stream)
(option-list '(:yes :no))
&allow-other-keys
&aux option)
"This function offers the user a choice of items from a menu of
keywords. The user can either type the keword or select the option by
number. <stream> is the stream (default *query-io*) and <option-list>
is the list of options (default '(:yes no)). <message> is displayed
first on the stream as a prompt."
(declare (type String message) (type Stream stream in-stream out-stream)
(type List option-list)
#-(and)(:returns (type (Member option-list) option)))
(loop
(format out-stream "~&;;;? ~A~%" message)
(format out-stream ";;;? Select an option by name or number.:~%;;;?(")
(dotimes (i (length option-list))
(let ((option (nth i option-list)))
(format out-stream "~D. ~S " i option)))
(format out-stream "::?~%")
(setq option (read in-stream))
(if (find option option-list) (return option))
(if (and (numberp option) (< option (length option-list)))
(return (nth option option-list)))
(format out-stream "Unrecognized selection ~S, try again." option)))
(defun call-selector (message &rest keys
&key (stream *query-io*)
(in-stream stream)
(out-stream stream)
(option-list '(:yes :no))
&allow-other-keys)
"This function offers the user a choice of items from a menu of
keywords. The user can either type the keword or select the option by
number. <stream> is the stream (default *query-io*) and <option-list>
is the list of options (default '(:yes no)). <message> is displayed
first on the stream as a prompt."
(declare (type String message)
(type Stream stream in-stream out-stream)
(type List option-list)
)
(declare (ignore in-stream out-stream option-list))
(apply #'selector message :allow-other-keys t keys))
(defvar *application-long-name* "Common-Lisp"
"Name of application for window titles.")
(defvar *application-short-name* "LISP"
"Name of application for Icon titles.")
|
183d949bce1172bc7c60b46a12e2c1bb9f06edb27a7d46ccb005d1dcb918f911 | ropas/sparrow | spec.ml | (***********************************************************************)
(* *)
Copyright ( c ) 2007 - present .
Programming Research Laboratory ( ROPAS ) , Seoul National University .
(* All rights reserved. *)
(* *)
This software is distributed under the term of the BSD license .
(* See the LICENSE file for details. *)
(* *)
(***********************************************************************)
module type S =
sig
module Dom : InstrumentedMem.S
type t = {
locset : Dom.PowA.t;
locset_fs : Dom.PowA.t;
ptrinfo : ItvDom.Table.t;
premem : Dom.t;
(* unsoundness *)
unsound_lib : string BatSet.t;
unsound_update : bool;
unsound_bitwise : bool;
}
val empty : t
end
module Make(Dom: InstrumentedMem.S) =
struct
module Dom = Dom
module PowLoc = Dom.PowA
type t = {
locset : PowLoc.t;
locset_fs : PowLoc.t;
ptrinfo : ItvDom.Table.t;
premem : Dom.t;
(* unsoundness *)
unsound_lib : string BatSet.t;
unsound_update : bool;
unsound_bitwise : bool;
}
let empty = {
locset = Dom.PowA.bot;
locset_fs = Dom.PowA.bot;
ptrinfo = ItvDom.Table.empty;
premem = Dom.bot;
unsound_lib = BatSet.empty;
unsound_update = false;
unsound_bitwise = false;
}
end
| null | https://raw.githubusercontent.com/ropas/sparrow/3ec055b8c87b5c8340ef3ed6cde34f5835865b31/src/sparse/spec.ml | ocaml | *********************************************************************
All rights reserved.
See the LICENSE file for details.
*********************************************************************
unsoundness
unsoundness | Copyright ( c ) 2007 - present .
Programming Research Laboratory ( ROPAS ) , Seoul National University .
This software is distributed under the term of the BSD license .
module type S =
sig
module Dom : InstrumentedMem.S
type t = {
locset : Dom.PowA.t;
locset_fs : Dom.PowA.t;
ptrinfo : ItvDom.Table.t;
premem : Dom.t;
unsound_lib : string BatSet.t;
unsound_update : bool;
unsound_bitwise : bool;
}
val empty : t
end
module Make(Dom: InstrumentedMem.S) =
struct
module Dom = Dom
module PowLoc = Dom.PowA
type t = {
locset : PowLoc.t;
locset_fs : PowLoc.t;
ptrinfo : ItvDom.Table.t;
premem : Dom.t;
unsound_lib : string BatSet.t;
unsound_update : bool;
unsound_bitwise : bool;
}
let empty = {
locset = Dom.PowA.bot;
locset_fs = Dom.PowA.bot;
ptrinfo = ItvDom.Table.empty;
premem = Dom.bot;
unsound_lib = BatSet.empty;
unsound_update = false;
unsound_bitwise = false;
}
end
|
87d8031b81a2a411a2e7e1d7a72471aff314f1b91ced02e5c2c90a2763162b5a | leptonyu/guiguzi | Redis.hs | # LANGUAGE UndecidableInstances #
module Base.Redis where
import Boots
import Boots.Web
import Control.Exception (Exception, throw)
import Data.Maybe
import Data.Word
import Database.Redis
import Salak
instance Default ConnectInfo where
def = defaultConnectInfo
instance FromProp m ConnectInfo where
fromProp = ConnInfo
<$> "host" .?: connectHost
<*> "port" .?: connectPort
<*> "password" .?: connectAuth
<*> "database" .?: connectDatabase
<*> "max-conns" .?: connectMaxConnections
<*> "max-idle" .?: connectMaxIdleTime
<*> return Nothing
<*> return Nothing
instance FromProp m PortID where
fromProp = PortNumber . fromIntegral <$> (fromProp :: Prop m Word16)
-- | Middleware context type.
newtype REDIS = REDIS Connection
data RedisException
= RedisException !String
| RedisNotInitializedException
| RedisAbortedException
deriving Show
instance Exception RedisException
class HasRedis env where
askRedis :: Lens' env REDIS
instance HasRedis REDIS where
askRedis = id
instance HasRedis ext => HasRedis (AppEnv ext) where
askRedis = askExt . askRedis
instance (HasRedis env, HasWeb context env) => HasRedis (Context context) where
askRedis = askWeb . askRedis
instance (HasRedis env, MonadIO m) => MonadRedis (AppT env m) where
liftRedis ra = do
REDIS c <- asks (view askRedis)
liftIO $ runRedis c ra
check :: REDIS -> IO HealthStatus
check (REDIS c) = runRedis c ping >>= go
where
go (Left e) = throw $ RedisException $ show e
go _ = return UP
buildRedis
:: (MonadMask m, MonadIO m, HasSalak env, HasLogger env, HasHealth env)
=> Factory m env REDIS
buildRedis = do
enabled <- fromMaybe True <$> require "redis.enabled"
if enabled
then do
ci <- require "redis"
logInfo "Load redis"
rd <- REDIS <$> produce (liftIO $ connect ci) (liftIO . disconnect)
registerHealth "redis" (check rd)
return rd
else do
logInfo "Disable redis module"
return (throw RedisNotInitializedException)
| null | https://raw.githubusercontent.com/leptonyu/guiguzi/9b3cb22f1b0c5387964c0097ef9a789125d2daee/base/base-redis/src/Base/Redis.hs | haskell | | Middleware context type. | # LANGUAGE UndecidableInstances #
module Base.Redis where
import Boots
import Boots.Web
import Control.Exception (Exception, throw)
import Data.Maybe
import Data.Word
import Database.Redis
import Salak
instance Default ConnectInfo where
def = defaultConnectInfo
instance FromProp m ConnectInfo where
fromProp = ConnInfo
<$> "host" .?: connectHost
<*> "port" .?: connectPort
<*> "password" .?: connectAuth
<*> "database" .?: connectDatabase
<*> "max-conns" .?: connectMaxConnections
<*> "max-idle" .?: connectMaxIdleTime
<*> return Nothing
<*> return Nothing
instance FromProp m PortID where
fromProp = PortNumber . fromIntegral <$> (fromProp :: Prop m Word16)
newtype REDIS = REDIS Connection
data RedisException
= RedisException !String
| RedisNotInitializedException
| RedisAbortedException
deriving Show
instance Exception RedisException
class HasRedis env where
askRedis :: Lens' env REDIS
instance HasRedis REDIS where
askRedis = id
instance HasRedis ext => HasRedis (AppEnv ext) where
askRedis = askExt . askRedis
instance (HasRedis env, HasWeb context env) => HasRedis (Context context) where
askRedis = askWeb . askRedis
instance (HasRedis env, MonadIO m) => MonadRedis (AppT env m) where
liftRedis ra = do
REDIS c <- asks (view askRedis)
liftIO $ runRedis c ra
check :: REDIS -> IO HealthStatus
check (REDIS c) = runRedis c ping >>= go
where
go (Left e) = throw $ RedisException $ show e
go _ = return UP
buildRedis
:: (MonadMask m, MonadIO m, HasSalak env, HasLogger env, HasHealth env)
=> Factory m env REDIS
buildRedis = do
enabled <- fromMaybe True <$> require "redis.enabled"
if enabled
then do
ci <- require "redis"
logInfo "Load redis"
rd <- REDIS <$> produce (liftIO $ connect ci) (liftIO . disconnect)
registerHealth "redis" (check rd)
return rd
else do
logInfo "Disable redis module"
return (throw RedisNotInitializedException)
|
8882e1916e7a0accdd2d8d211ff9bb1ccc601090fc7d8796bee04a2d1a348962 | maximedenes/native-coq | vconv.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
open Names
open Term
open Environ
open Reduction
(**********************************************************************
s conversion functions *)
val use_vm : unit -> bool
val set_use_vm : bool -> unit
val vconv : conv_pb -> types conversion_function
val val_of_constr : env -> constr -> values
| null | https://raw.githubusercontent.com/maximedenes/native-coq/3623a4d9fe95c165f02f7119c0e6564a83a9f4c9/kernel/vconv.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
*********************************************************************
s conversion functions | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Names
open Term
open Environ
open Reduction
val use_vm : unit -> bool
val set_use_vm : bool -> unit
val vconv : conv_pb -> types conversion_function
val val_of_constr : env -> constr -> values
|
0f732894892aedce687ea9ac814f9401c421ec6c91e61852e6446a98ac6f27f1 | codecrafters-io/build-your-own-grep | Parser.hs | module Parser (parse, astToMatcher, AST(..)) where
import qualified Text.Megaparsec as M
import Text.Megaparsec.Char (char, digitChar)
import Data.Void (Void)
import Data.Maybe (fromMaybe, isNothing)
import RegEx (M, posLit, negLit, emptyStrM, digitM, digitInverseM, alphaNumM, alphaNumInverseM, anyCharM, orM, andM, concatM, kleeneStarM, kleenePlusM)
type MParser = M.Parsec Void String
data AST a = PosLit a
| NegLit a
| DigitM
| DigitInverseM
| AlphaNumM
| AlphaNumInverseM
| AnyCharM
| OrM [AST a]
| AndM [AST a]
| ConcatM [AST a]
| KleeneStarM (AST a)
| KleenePlusM (AST a)
| EmptyStrM
deriving (Eq, Show)
astToMatcher :: AST Char -> M Char
astToMatcher (PosLit a) = posLit a
astToMatcher (NegLit a) = negLit a
astToMatcher DigitM = digitM
astToMatcher DigitInverseM = digitInverseM
astToMatcher AlphaNumM = alphaNumM
astToMatcher AlphaNumInverseM = alphaNumInverseM
astToMatcher AnyCharM = anyCharM
astToMatcher (OrM ms) = orM $ fmap astToMatcher ms
astToMatcher (AndM ms) = andM $ fmap astToMatcher ms
astToMatcher (ConcatM ms) = concatM $ fmap astToMatcher ms
astToMatcher (KleeneStarM m) = kleeneStarM $ astToMatcher m
astToMatcher (KleenePlusM m) = kleenePlusM $ astToMatcher m
astToMatcher EmptyStrM = emptyStrM
notChar :: Char -> MParser Char
notChar c = M.satisfy (/=c)
anyNotUsed :: String -> MParser Char
anyNotUsed s = M.satisfy $ not . (`elem` s)
-- | Inverts an AST Char
neg :: AST Char -> AST Char
neg DigitM = DigitInverseM
neg AlphaNumM = AlphaNumInverseM
neg (PosLit c) = NegLit c
neg _ = error "Unsupported input string"
-- The regex parser starts here
--
-- I had to adjust a few rules to support better parsing
pRegEx :: MParser (AST Char)
pRegEx = do
s <- pStartOfString
expression <- pExpression
e <- pEndOfString
return $ ConcatM [s, expression, e]
pStartOfString :: MParser (AST Char)
pStartOfString = do
s <- M.optional $ char '^'
return $ if isNothing s then KleeneStarM AnyCharM else EmptyStrM
pEndOfString :: MParser (AST Char)
pEndOfString = do
s <- M.optional $ char '$'
return $ if isNothing s then KleeneStarM AnyCharM else EmptyStrM
pExpression :: MParser (AST Char)
pExpression = do
subExpression <- pSubExpression
alt <- M.optional pAlternation
return $ case alt of
Nothing -> subExpression
Just ex -> OrM [subExpression, ex]
pSubExpression :: MParser (AST Char)
pSubExpression = do
subExp <- M.some $ M.try pMatch M.<|> M.try pGroup
return $ ConcatM subExp
pAlternation :: MParser (AST Char)
pAlternation = do
_ <- char '|'
pExpression
pGroup :: MParser (AST Char)
pGroup = do
_ <- char '('
i <- pExpression
_ <- char ')'
q <- M.optional $ pQuantifiers i
return $ fromMaybe i q
pMatch :: MParser (AST Char)
pMatch = do
i <- pMatchItem
q <- M.optional $ pQuantifiers i
return $ fromMaybe i q
pMatchItem :: MParser (AST Char)
pMatchItem = M.try pMatchAnyChar M.<|> M.try pMatchCharacterClass M.<|> M.try pMatchCharacter
pMatchAnyChar :: MParser (AST Char)
pMatchAnyChar = do
_ <- char '.'
return AnyCharM
pMatchCharacterClass :: MParser (AST Char)
pMatchCharacterClass = M.try pCharacterGroup M.<|> M.try pCharacterClass
pMatchCharacter :: MParser (AST Char)
pMatchCharacter = do
c <- anyNotUsed "|()$"
return $ PosLit c
pCharacterGroup :: MParser (AST Char)
pCharacterGroup = M.try pPositiveCharacterGroup M.<|> M.try pNegativeCharacterGroup
pPositiveCharacterGroup :: MParser (AST Char)
pPositiveCharacterGroup = do
_ <- char '['
c <- anyNotUsed "^]"
cs <- M.many pCharacterGroupItem
let cs' = PosLit c : cs
_ <- char ']'
return $ OrM cs'
pNegativeCharacterGroup :: MParser (AST Char)
pNegativeCharacterGroup = do
_ <- char '['
_ <- char '^'
ms <- M.some pCharacterGroupItem
_ <- char ']'
return $ AndM $ fmap neg ms
pCharacterGroupItem :: MParser (AST Char)
pCharacterGroupItem = M.try pCharacterClass M.<|> M.try pChar
pCharacterClass :: MParser (AST Char)
pCharacterClass = M.try pCharacterClassAnyWord M.<|> M.try pCharacterClassAnyDecimal
pCharacterClassAnyWord :: MParser (AST a)
pCharacterClassAnyWord = do
_ <- char '\\'
_ <- char 'w'
return AlphaNumM
pCharacterClassAnyDecimal :: MParser (AST Char)
pCharacterClassAnyDecimal = do
_ <- char '\\'
_ <- char 'd'
return DigitM
pChar :: MParser (AST Char)
pChar = do
c <- notChar ']'
return $ PosLit c
pQuantifiers :: AST a -> MParser (AST a)
pQuantifiers x = M.try (zeroOrMoreQuantifier x) M.<|> M.try (oneOrMoreQuantifier x) M.<|> M.try (zeroOrOneQuantifier x)
zeroOrMoreQuantifier :: AST a -> MParser (AST a)
zeroOrMoreQuantifier x = do
_ <- char '*'
return $ KleeneStarM x
oneOrMoreQuantifier :: AST a -> MParser (AST a)
oneOrMoreQuantifier x = do
_ <- char '+'
return $ KleenePlusM x
zeroOrOneQuantifier :: AST a -> MParser (AST a)
zeroOrOneQuantifier x = do
_ <- char '?'
return $ OrM [EmptyStrM, x]
parse :: String -> Maybe (AST Char)
parse = M.parseMaybe pRegEx
| null | https://raw.githubusercontent.com/codecrafters-io/build-your-own-grep/085a70404357c4abf11ff7c039cdf13181349e3c/solutions/haskell/12-alternation/code/src/Parser.hs | haskell | | Inverts an AST Char
The regex parser starts here
I had to adjust a few rules to support better parsing | module Parser (parse, astToMatcher, AST(..)) where
import qualified Text.Megaparsec as M
import Text.Megaparsec.Char (char, digitChar)
import Data.Void (Void)
import Data.Maybe (fromMaybe, isNothing)
import RegEx (M, posLit, negLit, emptyStrM, digitM, digitInverseM, alphaNumM, alphaNumInverseM, anyCharM, orM, andM, concatM, kleeneStarM, kleenePlusM)
type MParser = M.Parsec Void String
data AST a = PosLit a
| NegLit a
| DigitM
| DigitInverseM
| AlphaNumM
| AlphaNumInverseM
| AnyCharM
| OrM [AST a]
| AndM [AST a]
| ConcatM [AST a]
| KleeneStarM (AST a)
| KleenePlusM (AST a)
| EmptyStrM
deriving (Eq, Show)
astToMatcher :: AST Char -> M Char
astToMatcher (PosLit a) = posLit a
astToMatcher (NegLit a) = negLit a
astToMatcher DigitM = digitM
astToMatcher DigitInverseM = digitInverseM
astToMatcher AlphaNumM = alphaNumM
astToMatcher AlphaNumInverseM = alphaNumInverseM
astToMatcher AnyCharM = anyCharM
astToMatcher (OrM ms) = orM $ fmap astToMatcher ms
astToMatcher (AndM ms) = andM $ fmap astToMatcher ms
astToMatcher (ConcatM ms) = concatM $ fmap astToMatcher ms
astToMatcher (KleeneStarM m) = kleeneStarM $ astToMatcher m
astToMatcher (KleenePlusM m) = kleenePlusM $ astToMatcher m
astToMatcher EmptyStrM = emptyStrM
notChar :: Char -> MParser Char
notChar c = M.satisfy (/=c)
anyNotUsed :: String -> MParser Char
anyNotUsed s = M.satisfy $ not . (`elem` s)
neg :: AST Char -> AST Char
neg DigitM = DigitInverseM
neg AlphaNumM = AlphaNumInverseM
neg (PosLit c) = NegLit c
neg _ = error "Unsupported input string"
pRegEx :: MParser (AST Char)
pRegEx = do
s <- pStartOfString
expression <- pExpression
e <- pEndOfString
return $ ConcatM [s, expression, e]
pStartOfString :: MParser (AST Char)
pStartOfString = do
s <- M.optional $ char '^'
return $ if isNothing s then KleeneStarM AnyCharM else EmptyStrM
pEndOfString :: MParser (AST Char)
pEndOfString = do
s <- M.optional $ char '$'
return $ if isNothing s then KleeneStarM AnyCharM else EmptyStrM
pExpression :: MParser (AST Char)
pExpression = do
subExpression <- pSubExpression
alt <- M.optional pAlternation
return $ case alt of
Nothing -> subExpression
Just ex -> OrM [subExpression, ex]
pSubExpression :: MParser (AST Char)
pSubExpression = do
subExp <- M.some $ M.try pMatch M.<|> M.try pGroup
return $ ConcatM subExp
pAlternation :: MParser (AST Char)
pAlternation = do
_ <- char '|'
pExpression
pGroup :: MParser (AST Char)
pGroup = do
_ <- char '('
i <- pExpression
_ <- char ')'
q <- M.optional $ pQuantifiers i
return $ fromMaybe i q
pMatch :: MParser (AST Char)
pMatch = do
i <- pMatchItem
q <- M.optional $ pQuantifiers i
return $ fromMaybe i q
pMatchItem :: MParser (AST Char)
pMatchItem = M.try pMatchAnyChar M.<|> M.try pMatchCharacterClass M.<|> M.try pMatchCharacter
pMatchAnyChar :: MParser (AST Char)
pMatchAnyChar = do
_ <- char '.'
return AnyCharM
pMatchCharacterClass :: MParser (AST Char)
pMatchCharacterClass = M.try pCharacterGroup M.<|> M.try pCharacterClass
pMatchCharacter :: MParser (AST Char)
pMatchCharacter = do
c <- anyNotUsed "|()$"
return $ PosLit c
pCharacterGroup :: MParser (AST Char)
pCharacterGroup = M.try pPositiveCharacterGroup M.<|> M.try pNegativeCharacterGroup
pPositiveCharacterGroup :: MParser (AST Char)
pPositiveCharacterGroup = do
_ <- char '['
c <- anyNotUsed "^]"
cs <- M.many pCharacterGroupItem
let cs' = PosLit c : cs
_ <- char ']'
return $ OrM cs'
pNegativeCharacterGroup :: MParser (AST Char)
pNegativeCharacterGroup = do
_ <- char '['
_ <- char '^'
ms <- M.some pCharacterGroupItem
_ <- char ']'
return $ AndM $ fmap neg ms
pCharacterGroupItem :: MParser (AST Char)
pCharacterGroupItem = M.try pCharacterClass M.<|> M.try pChar
pCharacterClass :: MParser (AST Char)
pCharacterClass = M.try pCharacterClassAnyWord M.<|> M.try pCharacterClassAnyDecimal
pCharacterClassAnyWord :: MParser (AST a)
pCharacterClassAnyWord = do
_ <- char '\\'
_ <- char 'w'
return AlphaNumM
pCharacterClassAnyDecimal :: MParser (AST Char)
pCharacterClassAnyDecimal = do
_ <- char '\\'
_ <- char 'd'
return DigitM
pChar :: MParser (AST Char)
pChar = do
c <- notChar ']'
return $ PosLit c
pQuantifiers :: AST a -> MParser (AST a)
pQuantifiers x = M.try (zeroOrMoreQuantifier x) M.<|> M.try (oneOrMoreQuantifier x) M.<|> M.try (zeroOrOneQuantifier x)
zeroOrMoreQuantifier :: AST a -> MParser (AST a)
zeroOrMoreQuantifier x = do
_ <- char '*'
return $ KleeneStarM x
oneOrMoreQuantifier :: AST a -> MParser (AST a)
oneOrMoreQuantifier x = do
_ <- char '+'
return $ KleenePlusM x
zeroOrOneQuantifier :: AST a -> MParser (AST a)
zeroOrOneQuantifier x = do
_ <- char '?'
return $ OrM [EmptyStrM, x]
parse :: String -> Maybe (AST Char)
parse = M.parseMaybe pRegEx
|
54423bcd124061e6f871aadce626555c6b27c7c6ba6f27ca7d7bb94f3b7108b7 | sellout/haskerwaul | Left.hs | # language UndecidableSuperClasses #
module Haskerwaul.Magma.Invertible.Left
( module Haskerwaul.Magma.Invertible.Left
-- * extended modules
, module Haskerwaul.Magma
) where
import Haskerwaul.Magma
-- |
--
-- = references
--
-- - [nLab](+magma)
class Magma c t a => LeftInvertibleMagma c t a
| null | https://raw.githubusercontent.com/sellout/haskerwaul/cdd4a61c6abe0f757e32058f4832cf616025b45f/src/Haskerwaul/Magma/Invertible/Left.hs | haskell | * extended modules
|
= references
- [nLab](+magma) | # language UndecidableSuperClasses #
module Haskerwaul.Magma.Invertible.Left
( module Haskerwaul.Magma.Invertible.Left
, module Haskerwaul.Magma
) where
import Haskerwaul.Magma
class Magma c t a => LeftInvertibleMagma c t a
|
b1c6739b4498bd5c8dff53f54861132f92c2a46bdb320b46e09c78039e38ce24 | dnadales/sandbox | Manual.hs | {-# LANGUAGE BangPatterns #-}
# LANGUAGE ScopedTypeVariables #
module Manual (
Manual(..)
, toManual
, fromManual
, dontShrink
-- * Combinators
, manualSized
, manualReplicate
-- * Auxiliary
, wrapTreeT
, unwrapTreeT
) where
import Control.Monad
import Control.Monad.Trans.Maybe
import Data.Coerce
import Data.Functor.Identity
import Hedgehog
import Hedgehog.Internal.Gen
import Hedgehog.Internal.Tree
import qualified Hedgehog.Internal.Seed as Seed
-- newtype GenT m a = GenT { unGenT :: Size -> Seed -> TreeT m a }
type Gen = GenT ( Maybe Identity )
newtype Manual a = Manual { unManual :: Size -> Seed -> a }
toManual :: Gen a -> Manual (TreeT (MaybeT Identity) a)
toManual (GenT f) = Manual f
fromManual :: Manual (TreeT (MaybeT Identity) a) -> Gen a
fromManual (Manual f) = GenT f
dontShrink :: Gen a -> Manual (Maybe a)
dontShrink = fmap (fmap nodeValue . coerce) . toManual
instance Functor Manual where
fmap = liftM
instance Applicative Manual where
pure x = Manual $ \_ _ -> x
(<*>) = ap
instance Monad Manual where
return = pure
Manual x >>= f = Manual $ \size seed ->
case Seed.split seed of
(sx, sf) -> unManual (f (x size sx)) size sf
{-------------------------------------------------------------------------------
Combinators
-------------------------------------------------------------------------------}
manualSized :: (Size -> Manual a) -> Manual a
manualSized f = Manual $ \size seed -> unManual (f size) size seed
manualReplicate :: forall a. Int -> Manual a -> Manual [a]
manualReplicate n (Manual f) = Manual $ \size seed ->
let go :: Int -> Seed -> [a]
go 0 _ = []
go !n' s = case Seed.split s of
(s', s'') -> f size s' : go (n' - 1) s''
in go n seed
{-------------------------------------------------------------------------------
Auxiliary
-------------------------------------------------------------------------------}
wrapTreeT :: Maybe (NodeT (MaybeT Identity) a) -> TreeT (MaybeT Identity) a
wrapTreeT = coerce
unwrapTreeT :: TreeT (MaybeT Identity) a -> Maybe (NodeT (MaybeT Identity) a)
unwrapTreeT = coerce
splits :: [a] -> [([a], a, [a])]
splits [] = []
splits (x:xs) = ([],x,xs) : fmap (\(as,b,cs) -> (x:as,b,cs)) (splits xs)
-- | @removes n@ splits a list into chunks of size n and returns all possible
lists where one of these chunks has been removed .
--
-- Examples
--
> removes 1 [ 1 .. 3 ] = = [ [ 2,3],[1,3],[1,2 ] ]
> removes 2 [ 1 .. 4 ] = = [ [ 3,4],[1,2 ] ]
> removes 2 [ 1 .. 5 ] = = [ [ 3,4,5],[1,2,5],[1,2,3,4 ] ]
> removes 3 [ 1 .. 5 ] = = [ [ 4,5],[1,2,3 ] ]
--
-- Note that the last chunk we delete might have fewer elements than @n@.
removes :: forall a. Int -> [a] -> [[a]]
removes k = \xs -> go xs
where
go :: [a] -> [[a]]
go [] = []
go xs = xs2 : map (xs1 ++) (go xs2)
where
(xs1, xs2) = splitAt k xs
| null | https://raw.githubusercontent.com/dnadales/sandbox/401c4f0fac5f8044fb6e2e443bacddce6f135b4b/quickcheck-vs-hedgehog/test/Manual.hs | haskell | # LANGUAGE BangPatterns #
* Combinators
* Auxiliary
newtype GenT m a = GenT { unGenT :: Size -> Seed -> TreeT m a }
------------------------------------------------------------------------------
Combinators
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Auxiliary
------------------------------------------------------------------------------
| @removes n@ splits a list into chunks of size n and returns all possible
Examples
Note that the last chunk we delete might have fewer elements than @n@. | # LANGUAGE ScopedTypeVariables #
module Manual (
Manual(..)
, toManual
, fromManual
, dontShrink
, manualSized
, manualReplicate
, wrapTreeT
, unwrapTreeT
) where
import Control.Monad
import Control.Monad.Trans.Maybe
import Data.Coerce
import Data.Functor.Identity
import Hedgehog
import Hedgehog.Internal.Gen
import Hedgehog.Internal.Tree
import qualified Hedgehog.Internal.Seed as Seed
type Gen = GenT ( Maybe Identity )
newtype Manual a = Manual { unManual :: Size -> Seed -> a }
toManual :: Gen a -> Manual (TreeT (MaybeT Identity) a)
toManual (GenT f) = Manual f
fromManual :: Manual (TreeT (MaybeT Identity) a) -> Gen a
fromManual (Manual f) = GenT f
dontShrink :: Gen a -> Manual (Maybe a)
dontShrink = fmap (fmap nodeValue . coerce) . toManual
instance Functor Manual where
fmap = liftM
instance Applicative Manual where
pure x = Manual $ \_ _ -> x
(<*>) = ap
instance Monad Manual where
return = pure
Manual x >>= f = Manual $ \size seed ->
case Seed.split seed of
(sx, sf) -> unManual (f (x size sx)) size sf
manualSized :: (Size -> Manual a) -> Manual a
manualSized f = Manual $ \size seed -> unManual (f size) size seed
manualReplicate :: forall a. Int -> Manual a -> Manual [a]
manualReplicate n (Manual f) = Manual $ \size seed ->
let go :: Int -> Seed -> [a]
go 0 _ = []
go !n' s = case Seed.split s of
(s', s'') -> f size s' : go (n' - 1) s''
in go n seed
wrapTreeT :: Maybe (NodeT (MaybeT Identity) a) -> TreeT (MaybeT Identity) a
wrapTreeT = coerce
unwrapTreeT :: TreeT (MaybeT Identity) a -> Maybe (NodeT (MaybeT Identity) a)
unwrapTreeT = coerce
splits :: [a] -> [([a], a, [a])]
splits [] = []
splits (x:xs) = ([],x,xs) : fmap (\(as,b,cs) -> (x:as,b,cs)) (splits xs)
lists where one of these chunks has been removed .
> removes 1 [ 1 .. 3 ] = = [ [ 2,3],[1,3],[1,2 ] ]
> removes 2 [ 1 .. 4 ] = = [ [ 3,4],[1,2 ] ]
> removes 2 [ 1 .. 5 ] = = [ [ 3,4,5],[1,2,5],[1,2,3,4 ] ]
> removes 3 [ 1 .. 5 ] = = [ [ 4,5],[1,2,3 ] ]
removes :: forall a. Int -> [a] -> [[a]]
removes k = \xs -> go xs
where
go :: [a] -> [[a]]
go [] = []
go xs = xs2 : map (xs1 ++) (go xs2)
where
(xs1, xs2) = splitAt k xs
|
3c8462e33438285f734906a5a7ca5da500601f11e581cb5019e73b91cc39ed87 | ruricolist/spinneret | ps.lisp | (in-package #:spinneret)
(defparameter *props*
'("acceptCharset" "accessKey" "allowTransparency" "bgColor" "cellPadding"
"cellSpacing" "className" "className" "colSpan" "style" "defaultChecked"
"defaultSelected" "defaultValue" "htmlFor" "frameBorder" "hSpace" "htmlFor"
"longDesc" "maxLength" "marginWidth" "marginHeight" "noResize" "noShade"
"readOnly" "rowSpan" "tabIndex" "vAlign" "vSpace"))
(defparameter *ie-attr-props*
'(("for" . "htmlfor")
("class" . "classname")))
(define-ps-symbol-macro *html* (@ window spinneret))
(define-ps-symbol-macro *html-charset* (lisp *html-charset*))
(define-ps-symbol-macro *html-lang* (lisp *html-lang*))
(defpsmacro ch (&rest args)
`(chain ,@args))
(defpsmacro with-html (&rest html-forms)
(with-ps-gensyms (node d)
`(let ((,node (or *html*
(setf *html* (ch document (create-document-fragment)))))
(,d document))
(symbol-macrolet ((*html* ,node)
(document ,d))
,@(with-standard-io-syntax
(parse-html html-forms nil)))
(unless (@ ,node parent-node)
(prog1 ,node
(setf *html* nil))))))
(defpsmacro with-tag ((name &rest attributes) &body body)
`(progn
(setf *html*
(ch *html*
(append-child
(ch document (create-element ,(string-downcase name))))))
,@(loop for (attr val . nil) on attributes by #'cddr
collect (make-attr-setter (string-downcase attr) val))
,@(when body
(loop for form in body
if (and (consp form) (eql (car form) 'with-tag))
collect form
else collect `(ch *html* (append-child
(ch document
(create-text-node
(stringify ,form)))))))
(setf *html* (@ *html* parent-node))
nil))
(defun make-attr-setter (attr val)
;; Compatibility hacks from Laconic.js 0.2.2.
(let ((attr (or (find
(or (cdr (assoc attr *ie-attr-props* :test #'string-equal))
attr)
*props* :test #'string-equal)
attr))
(sval `(stringify ,val)))
(cond
((event? attr)
;; Set events as properties, ensuring a href.
`(setf (@ *html* ,attr) ,sval
(@ *html* href)
(or (@ *html* href) "#")))
Style requires special handling for IE .
((string-equal attr "style")
`(if (@ *html* style set-attribute)
(ch *html* style (set-attribute 'css-text ,sval))
(ch *html* (set-attribute ,attr ,sval))))
((rassoc attr *ie-attr-props* :test #'string-equal)
Other special cases for IE .
`(setf (@ *html* ,attr) ,sval))
((data-attr? attr)
`(setf (@ *html* dataset ,(data-attr-prop attr)) ,sval))
((string-equal attr "attrs")
(with-ps-gensyms (attrs attr)
`(let ((,attrs ,val))
(for-in (,attr ,attrs)
(ch *html*
(set-attribute ,attr
(stringify (@ ,attrs ,attr))))))))
(t `(ch *html* (set-attribute ,attr ,sval))))))
(defun event? (attr)
(starts-with-subseq "on" (string attr)))
(defun data-attr? (attr)
(starts-with-subseq "data-" (string attr)))
(defun data-attr-prop (attr)
(subseq (string-downcase attr) 5))
(defpsmacro comment (text safe?)
(declare (ignore safe?))
`(stringify
,(concat-constant-strings
(list "<!-- " text " -->"))))
(defpsmacro cdata (text safe?)
(declare (ignore safe?))
`(stringify
,(concat-constant-strings
(list cdata-start text cdata-end))))
(defpsmacro format-text (formatter &rest args)
(let ((control-string
(if (listp formatter)
(second formatter)
formatter)))
(prog1 control-string
(when args
(cerror
"Discard arguments and print \"~A\" literally."
"Parenscript doesn't have FORMAT."
control-string)))))
(defpsmacro join-tokens (&rest classes)
`(stringify
,@(concat-constant-strings
(intersperse " "
(remove-duplicates (remove nil classes)
:test #'equal)))))
(defun intersperse (new-elt list)
(cons (car list)
(mapcan
(lambda (elt)
(list new-elt elt))
(cdr list))))
| null | https://raw.githubusercontent.com/ruricolist/spinneret/aea70bb8fae5b463b3852ad761a2bdab793cfaf1/ps.lisp | lisp | Compatibility hacks from Laconic.js 0.2.2.
Set events as properties, ensuring a href. | (in-package #:spinneret)
(defparameter *props*
'("acceptCharset" "accessKey" "allowTransparency" "bgColor" "cellPadding"
"cellSpacing" "className" "className" "colSpan" "style" "defaultChecked"
"defaultSelected" "defaultValue" "htmlFor" "frameBorder" "hSpace" "htmlFor"
"longDesc" "maxLength" "marginWidth" "marginHeight" "noResize" "noShade"
"readOnly" "rowSpan" "tabIndex" "vAlign" "vSpace"))
(defparameter *ie-attr-props*
'(("for" . "htmlfor")
("class" . "classname")))
(define-ps-symbol-macro *html* (@ window spinneret))
(define-ps-symbol-macro *html-charset* (lisp *html-charset*))
(define-ps-symbol-macro *html-lang* (lisp *html-lang*))
(defpsmacro ch (&rest args)
`(chain ,@args))
(defpsmacro with-html (&rest html-forms)
(with-ps-gensyms (node d)
`(let ((,node (or *html*
(setf *html* (ch document (create-document-fragment)))))
(,d document))
(symbol-macrolet ((*html* ,node)
(document ,d))
,@(with-standard-io-syntax
(parse-html html-forms nil)))
(unless (@ ,node parent-node)
(prog1 ,node
(setf *html* nil))))))
(defpsmacro with-tag ((name &rest attributes) &body body)
`(progn
(setf *html*
(ch *html*
(append-child
(ch document (create-element ,(string-downcase name))))))
,@(loop for (attr val . nil) on attributes by #'cddr
collect (make-attr-setter (string-downcase attr) val))
,@(when body
(loop for form in body
if (and (consp form) (eql (car form) 'with-tag))
collect form
else collect `(ch *html* (append-child
(ch document
(create-text-node
(stringify ,form)))))))
(setf *html* (@ *html* parent-node))
nil))
(defun make-attr-setter (attr val)
(let ((attr (or (find
(or (cdr (assoc attr *ie-attr-props* :test #'string-equal))
attr)
*props* :test #'string-equal)
attr))
(sval `(stringify ,val)))
(cond
((event? attr)
`(setf (@ *html* ,attr) ,sval
(@ *html* href)
(or (@ *html* href) "#")))
Style requires special handling for IE .
((string-equal attr "style")
`(if (@ *html* style set-attribute)
(ch *html* style (set-attribute 'css-text ,sval))
(ch *html* (set-attribute ,attr ,sval))))
((rassoc attr *ie-attr-props* :test #'string-equal)
Other special cases for IE .
`(setf (@ *html* ,attr) ,sval))
((data-attr? attr)
`(setf (@ *html* dataset ,(data-attr-prop attr)) ,sval))
((string-equal attr "attrs")
(with-ps-gensyms (attrs attr)
`(let ((,attrs ,val))
(for-in (,attr ,attrs)
(ch *html*
(set-attribute ,attr
(stringify (@ ,attrs ,attr))))))))
(t `(ch *html* (set-attribute ,attr ,sval))))))
(defun event? (attr)
(starts-with-subseq "on" (string attr)))
(defun data-attr? (attr)
(starts-with-subseq "data-" (string attr)))
(defun data-attr-prop (attr)
(subseq (string-downcase attr) 5))
(defpsmacro comment (text safe?)
(declare (ignore safe?))
`(stringify
,(concat-constant-strings
(list "<!-- " text " -->"))))
(defpsmacro cdata (text safe?)
(declare (ignore safe?))
`(stringify
,(concat-constant-strings
(list cdata-start text cdata-end))))
(defpsmacro format-text (formatter &rest args)
(let ((control-string
(if (listp formatter)
(second formatter)
formatter)))
(prog1 control-string
(when args
(cerror
"Discard arguments and print \"~A\" literally."
"Parenscript doesn't have FORMAT."
control-string)))))
(defpsmacro join-tokens (&rest classes)
`(stringify
,@(concat-constant-strings
(intersperse " "
(remove-duplicates (remove nil classes)
:test #'equal)))))
(defun intersperse (new-elt list)
(cons (car list)
(mapcan
(lambda (elt)
(list new-elt elt))
(cdr list))))
|
68e3bb569f278f8fa4d5fe97cd0acefe4ae9dae64bd52432b4bc90897fb362ff | mlabs-haskell/plutus-simple-model | Eval.hs | module Cardano.Simple.Eval (
evalScript,
utxoForTransaction,
txBalance,
evaluateScriptsInTx,
toAlonzoCostModels,
) where
import Prelude
import Data.Array qualified as Array
import Data.Either (lefts, rights)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import GHC.Records (HasField (getField))
import Cardano.Ledger.Alonzo.Data qualified as Ledger
import Cardano.Ledger.Alonzo.Tx qualified as Ledger
import Cardano.Ledger.BaseTypes qualified as Ledger
import Cardano.Ledger.Core qualified as Ledger
import Cardano.Ledger.Language qualified as Ledger
import Cardano.Ledger.Shelley.UTxO qualified as Ledger
import Cardano.Ledger.Slot (EpochSize (..))
import Cardano.Slotting.EpochInfo.Impl (fixedEpochInfo)
import Cardano.Slotting.Time (SystemStart (..), slotLengthFromMillisec)
import Cardano.Ledger.Alonzo.Tools (evaluateTransactionExecutionUnits)
import Cardano.Ledger.Alonzo.TxInfo (ExtendedUTxO, TranslationError)
import Cardano.Ledger.Shelley.API (CLI, evaluateTransactionBalance)
import Cardano.Ledger.Shelley.TxBody (ShelleyEraTxBody)
import Cardano.Ledger.Alonzo.Language qualified as Alonzo
import Cardano.Ledger.Alonzo.Scripts qualified as Alonzo
import Cardano.Simple.Cardano.Class (
IsCardanoTx,
getTxBody,
toCardanoTx,
toUtxo,
)
import Cardano.Simple.Cardano.Common (ToCardanoError)
import Cardano.Simple.Ledger.TimeSlot (SlotConfig, scSlotLength, scSlotZeroTime)
import Cardano.Simple.Ledger.Tx (
Tx (txCollateral, txInputs, txReferenceInputs, txScripts),
TxIn (TxIn),
)
import Cardano.Simple.TxExtra (Extra)
import PlutusLedgerApi.Common qualified as Plutus
import PlutusLedgerApi.V1.Time (getPOSIXTime)
import PlutusLedgerApi.V2 (TxOut, TxOutRef)
evalScript ::
(HasField "_protocolVersion" (Ledger.PParams era) Ledger.ProtVer) =>
Ledger.Language ->
Ledger.PParams era ->
Ledger.CostModel ->
Plutus.SerialisedScript ->
[Ledger.Data era] ->
Maybe Plutus.EvaluationError
evalScript lang pparams cm script args =
either Just (const Nothing) . snd $
Plutus.evaluateScriptCounting
(toPlutusLang lang)
(Alonzo.transProtocolVersion pparams._protocolVersion)
Plutus.Verbose
(Alonzo.getEvaluationContext cm)
script
(Ledger.getPlutusData <$> args)
where
toPlutusLang Ledger.PlutusV1 = Plutus.PlutusV1
toPlutusLang Ledger.PlutusV2 = Plutus.PlutusV2
utxoForTransaction ::
forall era.
IsCardanoTx era =>
Map TxOutRef TxOut ->
Ledger.Network ->
Tx ->
Either ToCardanoError (Ledger.UTxO era)
utxoForTransaction utxos network tx =
case inOutList of
Nothing -> Left "lookup failure"
Just list -> toUtxo @era (txScripts tx) network list
where
inOutList :: Maybe [(TxIn, TxOut)]
inOutList =
sequence
[ (txin,) <$> out
| txin@(TxIn outRef _) <-
Set.toList $
txInputs tx
<> txCollateral tx
<> txReferenceInputs tx
, let out = Map.lookup outRef utxos
]
txBalance ::
forall era.
( IsCardanoTx era
, CLI era
, ShelleyEraTxBody era
) =>
Map TxOutRef TxOut ->
Ledger.PParams era ->
Ledger.Network ->
Tx ->
Extra ->
Either ToCardanoError (Ledger.Value era)
txBalance utxos pparams network tx extra = do
utxo <- utxoForTransaction @era utxos network tx
ltx <- toCardanoTx @era network pparams extra tx
pure $
evaluateTransactionBalance @era
pparams
utxo
(const True)
TODO this is sort of wrong
-- if psm starts supporting staking
-- this would need to be fixed
(getTxBody @era ltx)
evaluateScriptsInTx ::
forall era.
( HasField "_protocolVersion" (Ledger.PParams era) Ledger.ProtVer
, HasField "_maxTxExUnits" (Ledger.PParams era) Alonzo.ExUnits
, HasField "_costmdls" (Ledger.PParams era) Alonzo.CostModels
, Ledger.AlonzoEraTx era
, Ledger.Script era ~ Alonzo.AlonzoScript era
, ExtendedUTxO era
, IsCardanoTx era
) =>
Map TxOutRef TxOut ->
Ledger.PParams era ->
Ledger.Network ->
Tx ->
Extra ->
SlotConfig ->
Either
(Either ToCardanoError (TranslationError (Ledger.Crypto era)))
Alonzo.ExUnits
evaluateScriptsInTx utxos pparams network tx extra slotCfg = do
ltx <- leftMap Left $ toCardanoTx @era network pparams extra tx
utxo <- leftMap Left $ utxoForTransaction @era utxos network tx
res <-
leftMap Right $
evaluateTransactionExecutionUnits @era
pparams
ltx
utxo
( fixedEpochInfo
(EpochSize 1)
(slotLengthFromMillisec $ scSlotLength slotCfg)
)
( SystemStart $
posixSecondsToUTCTime $
fromInteger $
(`div` 1000) $
getPOSIXTime $
scSlotZeroTime slotCfg
)
(toAlonzoCostModels $ getField @"_costmdls" pparams)
let res' = (\(k, v) -> fmap (k,) v) <$> Map.toList res
errs = lefts res'
cost = foldMap snd . rights $ res'
in if null errs
then pure cost
else Left . Left $ show errs
toAlonzoCostModels ::
Alonzo.CostModels ->
Array.Array Alonzo.Language Alonzo.CostModel
toAlonzoCostModels (Alonzo.CostModels costmodels) =
Array.array (minBound, maxBound) $ Map.toList costmodels
leftMap :: (a -> b) -> Either a c -> Either b c
leftMap f = either (Left . f) Right
| null | https://raw.githubusercontent.com/mlabs-haskell/plutus-simple-model/a390bbf51bd9a0ad8a27517d1e02be5fd6d3394e/cardano-simple/src/Cardano/Simple/Eval.hs | haskell | if psm starts supporting staking
this would need to be fixed | module Cardano.Simple.Eval (
evalScript,
utxoForTransaction,
txBalance,
evaluateScriptsInTx,
toAlonzoCostModels,
) where
import Prelude
import Data.Array qualified as Array
import Data.Either (lefts, rights)
import Data.Map.Strict (Map)
import Data.Map.Strict qualified as Map
import Data.Set qualified as Set
import Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import GHC.Records (HasField (getField))
import Cardano.Ledger.Alonzo.Data qualified as Ledger
import Cardano.Ledger.Alonzo.Tx qualified as Ledger
import Cardano.Ledger.BaseTypes qualified as Ledger
import Cardano.Ledger.Core qualified as Ledger
import Cardano.Ledger.Language qualified as Ledger
import Cardano.Ledger.Shelley.UTxO qualified as Ledger
import Cardano.Ledger.Slot (EpochSize (..))
import Cardano.Slotting.EpochInfo.Impl (fixedEpochInfo)
import Cardano.Slotting.Time (SystemStart (..), slotLengthFromMillisec)
import Cardano.Ledger.Alonzo.Tools (evaluateTransactionExecutionUnits)
import Cardano.Ledger.Alonzo.TxInfo (ExtendedUTxO, TranslationError)
import Cardano.Ledger.Shelley.API (CLI, evaluateTransactionBalance)
import Cardano.Ledger.Shelley.TxBody (ShelleyEraTxBody)
import Cardano.Ledger.Alonzo.Language qualified as Alonzo
import Cardano.Ledger.Alonzo.Scripts qualified as Alonzo
import Cardano.Simple.Cardano.Class (
IsCardanoTx,
getTxBody,
toCardanoTx,
toUtxo,
)
import Cardano.Simple.Cardano.Common (ToCardanoError)
import Cardano.Simple.Ledger.TimeSlot (SlotConfig, scSlotLength, scSlotZeroTime)
import Cardano.Simple.Ledger.Tx (
Tx (txCollateral, txInputs, txReferenceInputs, txScripts),
TxIn (TxIn),
)
import Cardano.Simple.TxExtra (Extra)
import PlutusLedgerApi.Common qualified as Plutus
import PlutusLedgerApi.V1.Time (getPOSIXTime)
import PlutusLedgerApi.V2 (TxOut, TxOutRef)
evalScript ::
(HasField "_protocolVersion" (Ledger.PParams era) Ledger.ProtVer) =>
Ledger.Language ->
Ledger.PParams era ->
Ledger.CostModel ->
Plutus.SerialisedScript ->
[Ledger.Data era] ->
Maybe Plutus.EvaluationError
evalScript lang pparams cm script args =
either Just (const Nothing) . snd $
Plutus.evaluateScriptCounting
(toPlutusLang lang)
(Alonzo.transProtocolVersion pparams._protocolVersion)
Plutus.Verbose
(Alonzo.getEvaluationContext cm)
script
(Ledger.getPlutusData <$> args)
where
toPlutusLang Ledger.PlutusV1 = Plutus.PlutusV1
toPlutusLang Ledger.PlutusV2 = Plutus.PlutusV2
utxoForTransaction ::
forall era.
IsCardanoTx era =>
Map TxOutRef TxOut ->
Ledger.Network ->
Tx ->
Either ToCardanoError (Ledger.UTxO era)
utxoForTransaction utxos network tx =
case inOutList of
Nothing -> Left "lookup failure"
Just list -> toUtxo @era (txScripts tx) network list
where
inOutList :: Maybe [(TxIn, TxOut)]
inOutList =
sequence
[ (txin,) <$> out
| txin@(TxIn outRef _) <-
Set.toList $
txInputs tx
<> txCollateral tx
<> txReferenceInputs tx
, let out = Map.lookup outRef utxos
]
txBalance ::
forall era.
( IsCardanoTx era
, CLI era
, ShelleyEraTxBody era
) =>
Map TxOutRef TxOut ->
Ledger.PParams era ->
Ledger.Network ->
Tx ->
Extra ->
Either ToCardanoError (Ledger.Value era)
txBalance utxos pparams network tx extra = do
utxo <- utxoForTransaction @era utxos network tx
ltx <- toCardanoTx @era network pparams extra tx
pure $
evaluateTransactionBalance @era
pparams
utxo
(const True)
TODO this is sort of wrong
(getTxBody @era ltx)
evaluateScriptsInTx ::
forall era.
( HasField "_protocolVersion" (Ledger.PParams era) Ledger.ProtVer
, HasField "_maxTxExUnits" (Ledger.PParams era) Alonzo.ExUnits
, HasField "_costmdls" (Ledger.PParams era) Alonzo.CostModels
, Ledger.AlonzoEraTx era
, Ledger.Script era ~ Alonzo.AlonzoScript era
, ExtendedUTxO era
, IsCardanoTx era
) =>
Map TxOutRef TxOut ->
Ledger.PParams era ->
Ledger.Network ->
Tx ->
Extra ->
SlotConfig ->
Either
(Either ToCardanoError (TranslationError (Ledger.Crypto era)))
Alonzo.ExUnits
evaluateScriptsInTx utxos pparams network tx extra slotCfg = do
ltx <- leftMap Left $ toCardanoTx @era network pparams extra tx
utxo <- leftMap Left $ utxoForTransaction @era utxos network tx
res <-
leftMap Right $
evaluateTransactionExecutionUnits @era
pparams
ltx
utxo
( fixedEpochInfo
(EpochSize 1)
(slotLengthFromMillisec $ scSlotLength slotCfg)
)
( SystemStart $
posixSecondsToUTCTime $
fromInteger $
(`div` 1000) $
getPOSIXTime $
scSlotZeroTime slotCfg
)
(toAlonzoCostModels $ getField @"_costmdls" pparams)
let res' = (\(k, v) -> fmap (k,) v) <$> Map.toList res
errs = lefts res'
cost = foldMap snd . rights $ res'
in if null errs
then pure cost
else Left . Left $ show errs
toAlonzoCostModels ::
Alonzo.CostModels ->
Array.Array Alonzo.Language Alonzo.CostModel
toAlonzoCostModels (Alonzo.CostModels costmodels) =
Array.array (minBound, maxBound) $ Map.toList costmodels
leftMap :: (a -> b) -> Either a c -> Either b c
leftMap f = either (Left . f) Right
|
25241f2445d8616d06a17a2489f857cf67772cf7aa8b49c135993650bdee12cf | iij/lmq | lmq_event_SUITE.erl | -module(lmq_event_SUITE).
-include_lib("common_test/include/ct.hrl").
-include("lmq.hrl").
-include("lmq_test.hrl").
-export([init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2,
all/0]).
-export([emit_new_message/1, handle_new_message/1, handle_local_queue_created/1,
handle_remote_queue_created/1]).
all() ->
[emit_new_message, handle_new_message, handle_local_queue_created,
handle_remote_queue_created].
init_per_suite(Config) ->
Priv = ?config(priv_dir, Config),
application:start(mnesia),
application:set_env(mnesia, dir, Priv),
lmq:start(),
Config.
end_per_suite(_Config) ->
lmq:stop(),
mnesia:delete_schema([node()]).
init_per_testcase(_, Config) ->
lmq_event:add_handler(lmq_test_handler, self()),
[{qname, lmq_event_test} | Config].
end_per_testcase(_, Config) ->
Name = ?config(qname, Config),
lmq_queue_mgr:delete(Name).
emit_new_message(Config) ->
Name = ?config(qname, Config),
Q = lmq_queue_mgr:get(Name, [create]),
lmq_queue:push(Q, 1),
?EVENT_OR_FAIL({local, {new_message, Name}}).
handle_new_message(Config) ->
Name = ?config(qname, Config),
send_remote_event({new_message, Name}),
timer:sleep(50),
not_found = lmq_queue_mgr:get(Name),
Q = lmq_queue_mgr:get(Name, [create]),
Parent = self(),
spawn(fun() -> Parent ! {Q, lmq_queue:pull(Q)} end),
timer:sleep(50),
lmq_lib:enqueue(Name, 1),
send_remote_event({new_message, Name}),
receive {Q, M} when M#message.content =:= 1 -> ok
after 50 -> ct:fail(no_response)
end.
handle_local_queue_created(_Config) ->
lmq_queue_mgr:get('lmq/mpull/a', [create]),
lmq_queue_mgr:get('lmq/mpull/b', [create]),
{ok, Pid} = lmq_mpull:start(),
Parent = self(), Ref = make_ref(),
spawn(fun() -> Parent ! {Ref, lmq_mpull:pull(Pid, <<"lmq/mpull/.*">>, 100)} end),
timer:sleep(10),
Q3 = lmq_queue_mgr:get('lmq/mpull/c', [create]),
lmq_queue:push(Q3, <<"push after pull">>),
receive {Ref, [{queue, 'lmq/mpull/c'}, _, _, _,
{content, <<"push after pull">>}]} -> ok
after 50 -> ct:fail(no_response)
end.
handle_remote_queue_created(_Config) ->
%% start the queue if not exists
not_found = lmq_queue_mgr:get('lmq/remote/a'),
lmq_lib:create('lmq/remote/a', [{retry, 100}]),
send_remote_event({queue_created, 'lmq/remote/a'}),
timer:sleep(10),
Q1 = lmq_queue_mgr:get('lmq/remote/a'),
100 = proplists:get_value(retry, lmq_queue:get_properties(Q1)),
%% update the queue if exists
Q2 = lmq_queue_mgr:get('lmq/remote/b', [create]),
2 = proplists:get_value(retry, lmq_queue:get_properties(Q2)),
lmq_lib:create('lmq/remote/b', [{retry, 100}]),
send_remote_event({queue_created, 'lmq/remote/b'}),
timer:sleep(10),
100 = proplists:get_value(retry, lmq_queue:get_properties(Q2)),
%% ensure mpull also works
lmq_lib:create('lmq/remote/c'),
lmq_lib:enqueue('lmq/remote/c', 1),
{ok, Pid} = lmq_mpull:start(),
Parent = self(), Ref = make_ref(),
spawn(fun() -> Parent ! {Ref, lmq_mpull:pull(Pid, <<"lmq/remote/.*">>, 100)} end),
not_found = lmq_queue_mgr:get('lmq/remote/c'),
send_remote_event({queue_created, 'lmq/remote/c'}),
receive {Ref, [{queue, 'lmq/remote/c'}, _, _, _, {content, 1}]} -> ok
after 50 -> ct:fail(no_response)
end.
send_remote_event(Event) ->
gen_event:notify(?LMQ_EVENT, {remote, Event}).
| null | https://raw.githubusercontent.com/iij/lmq/3f01c555af973a07a3f2b22ff95a2bc1c7930bc2/test/lmq_event_SUITE.erl | erlang | start the queue if not exists
update the queue if exists
ensure mpull also works | -module(lmq_event_SUITE).
-include_lib("common_test/include/ct.hrl").
-include("lmq.hrl").
-include("lmq_test.hrl").
-export([init_per_suite/1, end_per_suite/1,
init_per_testcase/2, end_per_testcase/2,
all/0]).
-export([emit_new_message/1, handle_new_message/1, handle_local_queue_created/1,
handle_remote_queue_created/1]).
all() ->
[emit_new_message, handle_new_message, handle_local_queue_created,
handle_remote_queue_created].
init_per_suite(Config) ->
Priv = ?config(priv_dir, Config),
application:start(mnesia),
application:set_env(mnesia, dir, Priv),
lmq:start(),
Config.
end_per_suite(_Config) ->
lmq:stop(),
mnesia:delete_schema([node()]).
init_per_testcase(_, Config) ->
lmq_event:add_handler(lmq_test_handler, self()),
[{qname, lmq_event_test} | Config].
end_per_testcase(_, Config) ->
Name = ?config(qname, Config),
lmq_queue_mgr:delete(Name).
emit_new_message(Config) ->
Name = ?config(qname, Config),
Q = lmq_queue_mgr:get(Name, [create]),
lmq_queue:push(Q, 1),
?EVENT_OR_FAIL({local, {new_message, Name}}).
handle_new_message(Config) ->
Name = ?config(qname, Config),
send_remote_event({new_message, Name}),
timer:sleep(50),
not_found = lmq_queue_mgr:get(Name),
Q = lmq_queue_mgr:get(Name, [create]),
Parent = self(),
spawn(fun() -> Parent ! {Q, lmq_queue:pull(Q)} end),
timer:sleep(50),
lmq_lib:enqueue(Name, 1),
send_remote_event({new_message, Name}),
receive {Q, M} when M#message.content =:= 1 -> ok
after 50 -> ct:fail(no_response)
end.
handle_local_queue_created(_Config) ->
lmq_queue_mgr:get('lmq/mpull/a', [create]),
lmq_queue_mgr:get('lmq/mpull/b', [create]),
{ok, Pid} = lmq_mpull:start(),
Parent = self(), Ref = make_ref(),
spawn(fun() -> Parent ! {Ref, lmq_mpull:pull(Pid, <<"lmq/mpull/.*">>, 100)} end),
timer:sleep(10),
Q3 = lmq_queue_mgr:get('lmq/mpull/c', [create]),
lmq_queue:push(Q3, <<"push after pull">>),
receive {Ref, [{queue, 'lmq/mpull/c'}, _, _, _,
{content, <<"push after pull">>}]} -> ok
after 50 -> ct:fail(no_response)
end.
handle_remote_queue_created(_Config) ->
not_found = lmq_queue_mgr:get('lmq/remote/a'),
lmq_lib:create('lmq/remote/a', [{retry, 100}]),
send_remote_event({queue_created, 'lmq/remote/a'}),
timer:sleep(10),
Q1 = lmq_queue_mgr:get('lmq/remote/a'),
100 = proplists:get_value(retry, lmq_queue:get_properties(Q1)),
Q2 = lmq_queue_mgr:get('lmq/remote/b', [create]),
2 = proplists:get_value(retry, lmq_queue:get_properties(Q2)),
lmq_lib:create('lmq/remote/b', [{retry, 100}]),
send_remote_event({queue_created, 'lmq/remote/b'}),
timer:sleep(10),
100 = proplists:get_value(retry, lmq_queue:get_properties(Q2)),
lmq_lib:create('lmq/remote/c'),
lmq_lib:enqueue('lmq/remote/c', 1),
{ok, Pid} = lmq_mpull:start(),
Parent = self(), Ref = make_ref(),
spawn(fun() -> Parent ! {Ref, lmq_mpull:pull(Pid, <<"lmq/remote/.*">>, 100)} end),
not_found = lmq_queue_mgr:get('lmq/remote/c'),
send_remote_event({queue_created, 'lmq/remote/c'}),
receive {Ref, [{queue, 'lmq/remote/c'}, _, _, _, {content, 1}]} -> ok
after 50 -> ct:fail(no_response)
end.
send_remote_event(Event) ->
gen_event:notify(?LMQ_EVENT, {remote, Event}).
|
2e1a02988bce59c6940a83627168db20a86f1b34817abcf0f3d606b88a611119 | xclerc/ocamljava | mapReduce.ml |
* This file is part of library .
* Copyright ( C ) 2007 - 2015 .
*
* library is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation ; either version 3 of the License , or
* ( at your option ) any later version .
*
* library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program . If not , see < / > .
* This file is part of OCaml-Java library.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* OCaml-Java library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see </>.
*)
module type Computation = sig
type input
type key
type value
type output
val compare_keys : key -> key -> int
val map : input -> (key * value) list
val combine : key -> value -> value -> value
val reduce : key -> value -> output -> output
end
module type S = sig
type input
type output
val compute : ThreadPoolExecutor.t -> input Stream.t -> output -> output
end
module Make (C : Computation) = struct
type input = C.input
type output = C.output
module KeyMap = Map.Make (struct type t = C.key let compare = C.compare_keys end)
let compute pool inputs =
let n = max 1 (Int32.to_int (ThreadPoolExecutor.get_maximum_pool_size pool)) in
let service = ExecutorCompletionService.make pool in
let init = Stream.npeek n inputs in
let futures =
List.map
(fun x -> ExecutorCompletionService.submit service C.map x)
init in
let running = ref (List.length futures) in
for _i = 1 to !running do
Stream.junk inputs;
done;
let map = ref KeyMap.empty in
while !running > 0 do
let finished = ExecutorCompletionService.take service in
let kv_list : (C.key * C.value) list = Future.get finished in
List.iter
(fun (k, v) ->
try
let old = KeyMap.find k !map in
map := KeyMap.add k (C.combine k old v) !map
with Not_found ->
map := KeyMap.add k v !map)
kv_list;
match Stream.peek inputs with
| Some i ->
Stream.junk inputs;
ignore (ExecutorCompletionService.submit service C.map i)
| None -> decr running
done;
KeyMap.fold C.reduce !map
end
| null | https://raw.githubusercontent.com/xclerc/ocamljava/8330bfdfd01d0c348f2ba2f0f23d8f5a8f6015b1/library/concurrent/src/mapreduce/mapReduce.ml | ocaml |
* This file is part of library .
* Copyright ( C ) 2007 - 2015 .
*
* library is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation ; either version 3 of the License , or
* ( at your option ) any later version .
*
* library is distributed in the hope that it will be useful ,
* but WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the
* GNU Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program . If not , see < / > .
* This file is part of OCaml-Java library.
* Copyright (C) 2007-2015 Xavier Clerc.
*
* OCaml-Java library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* OCaml-Java library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see </>.
*)
module type Computation = sig
type input
type key
type value
type output
val compare_keys : key -> key -> int
val map : input -> (key * value) list
val combine : key -> value -> value -> value
val reduce : key -> value -> output -> output
end
module type S = sig
type input
type output
val compute : ThreadPoolExecutor.t -> input Stream.t -> output -> output
end
module Make (C : Computation) = struct
type input = C.input
type output = C.output
module KeyMap = Map.Make (struct type t = C.key let compare = C.compare_keys end)
let compute pool inputs =
let n = max 1 (Int32.to_int (ThreadPoolExecutor.get_maximum_pool_size pool)) in
let service = ExecutorCompletionService.make pool in
let init = Stream.npeek n inputs in
let futures =
List.map
(fun x -> ExecutorCompletionService.submit service C.map x)
init in
let running = ref (List.length futures) in
for _i = 1 to !running do
Stream.junk inputs;
done;
let map = ref KeyMap.empty in
while !running > 0 do
let finished = ExecutorCompletionService.take service in
let kv_list : (C.key * C.value) list = Future.get finished in
List.iter
(fun (k, v) ->
try
let old = KeyMap.find k !map in
map := KeyMap.add k (C.combine k old v) !map
with Not_found ->
map := KeyMap.add k v !map)
kv_list;
match Stream.peek inputs with
| Some i ->
Stream.junk inputs;
ignore (ExecutorCompletionService.submit service C.map i)
| None -> decr running
done;
KeyMap.fold C.reduce !map
end
|
|
7268a42cf0bd0383dcce6c6cf4011fb5207859213f701c4d2f700f83aa55c8f1 | JAremko/spacetools | spacedoc-cli-project.clj | (defproject spacetools/spacedoc-cli "0.1.0-SNAPSHOT"
:description "CLI tools for Spacemacs documentation."
:plugins [[lein-environ "1.1.0"]]
:dependencies [[funcool/cats "2.3.6"]
[medley "1.3.0"]
[nio2 "0.2.3"]
[orchestra "2020.07.12-1"]
[org.clojure/clojure "1.10.2-alpha2"]
[org.clojure/core.match "1.0.0"]
[org.clojure/tools.cli "1.0.194"]]
:main spacetools.spacedoc-cli.run
:uberjar-name "spacedoc.jar"
:global-vars {*warn-on-reflection* true *assert* true}
:profiles
{:dev {:jvm-opts ["-Xss8m"]
:dependencies [[com.google.jimfs/jimfs "1.1"]
[org.clojure/test.check
"0.10.0"]]}
:test {:env {:gentest-multiplier "1"}}
:uberjar
{:aot :all
:jvm-opts
["-Dclojure.compiler.elide-meta=[:doc :file :line :added]"
"-Dclojure.compiler.direct-linking=true"
"-Xmn1G"]
:global-vars {*warn-on-reflection* false
*assert* false}}})
| null | https://raw.githubusercontent.com/JAremko/spacetools/2343810353da275bacb21cf49df43286df4bf9be/environments/development/project-files/systems/spacedoc-cli-project.clj | clojure | (defproject spacetools/spacedoc-cli "0.1.0-SNAPSHOT"
:description "CLI tools for Spacemacs documentation."
:plugins [[lein-environ "1.1.0"]]
:dependencies [[funcool/cats "2.3.6"]
[medley "1.3.0"]
[nio2 "0.2.3"]
[orchestra "2020.07.12-1"]
[org.clojure/clojure "1.10.2-alpha2"]
[org.clojure/core.match "1.0.0"]
[org.clojure/tools.cli "1.0.194"]]
:main spacetools.spacedoc-cli.run
:uberjar-name "spacedoc.jar"
:global-vars {*warn-on-reflection* true *assert* true}
:profiles
{:dev {:jvm-opts ["-Xss8m"]
:dependencies [[com.google.jimfs/jimfs "1.1"]
[org.clojure/test.check
"0.10.0"]]}
:test {:env {:gentest-multiplier "1"}}
:uberjar
{:aot :all
:jvm-opts
["-Dclojure.compiler.elide-meta=[:doc :file :line :added]"
"-Dclojure.compiler.direct-linking=true"
"-Xmn1G"]
:global-vars {*warn-on-reflection* false
*assert* false}}})
|
|
1c4011aa9788ad87d44ec543c0db9832a0fc73dc2a2ad3c9e0594603ed3d38a6 | haskell/attoparsec | Alternative.hs | {-# LANGUAGE OverloadedStrings #-}
-- This benchmark reveals a huge performance regression that showed up
under GHC 7.8.1 ( ) .
--
With GHC 7.6.3 and older , this program runs in 0.04 seconds . Under
GHC 7.8.1 with ( < | > ) inlined , time jumps to 12 seconds !
import Control.Applicative
import Data.Text (Text)
import qualified Data.Attoparsec.Text as A
import qualified Data.Text as T
testParser :: Text -> Either String Int
testParser f = fmap length -- avoid printing out the entire matched list
. A.parseOnly (many ((() <$ A.string "b") <|> (() <$ A.anyChar)))
$ f
main :: IO ()
main = print . testParser $ T.replicate 50000 "a"
| null | https://raw.githubusercontent.com/haskell/attoparsec/85510bdf2c0a42daaf2ab5ef126d5d94a648993a/benchmarks/Alternative.hs | haskell | # LANGUAGE OverloadedStrings #
This benchmark reveals a huge performance regression that showed up
avoid printing out the entire matched list |
under GHC 7.8.1 ( ) .
With GHC 7.6.3 and older , this program runs in 0.04 seconds . Under
GHC 7.8.1 with ( < | > ) inlined , time jumps to 12 seconds !
import Control.Applicative
import Data.Text (Text)
import qualified Data.Attoparsec.Text as A
import qualified Data.Text as T
testParser :: Text -> Either String Int
. A.parseOnly (many ((() <$ A.string "b") <|> (() <$ A.anyChar)))
$ f
main :: IO ()
main = print . testParser $ T.replicate 50000 "a"
|
6afba779659fa5124911f4c6af5bbc76e3eb61781682f169e7ccfc1235c46fc2 | odj/Ouch | Methods.hs | ------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Module : Ouch . Test . Methods
-- Maintainer :
-- Stability : Unstable
-- Portability :
Copyright ( c ) 2010 Orion
This file is part of Ouch , a chemical informatics toolkit
written entirely in Haskell .
Ouch 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 .
Ouch 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 Ouch . If not , see < / > .
--------------------------------------------------------------------------------
------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Module : Ouch.Test.Methods
-- Maintainer : Orion Jankowski
-- Stability : Unstable
-- Portability :
Copyright (c) 2010 Orion D. Jankowski
This file is part of Ouch, a chemical informatics toolkit
written entirely in Haskell.
Ouch 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.
Ouch 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 Ouch. If not, see </>.
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------}
module Ouch.Test.Methods
(
TestData(..)
, performTests
, makeTestFromString
, testArray
, testAtomCount
, testTest
, testFail
, testMolForm
, testForm
, testRoundTrip
) where
{-# LANGUAGE RecordWildCards, CPP #-}
import Ouch.Structure.Molecule
import Ouch.Structure.Atom
import Ouch.Structure.Bond
import Ouch.Structure.Marker
import Ouch.Property.Composition
import Ouch.Property.Builder
import Ouch.Enumerate.Method
import Ouch.Input.Smiles
import Ouch.Data.Atom
import Ouch.Enumerate.Formula
import Data.List as List
import Data.Either
import Data.Maybe
import Data.Char as Char
import System.IO
import System.Environment
import Data.Time.Clock
-- Data structure to hold test/result pairs and descriptions. All 'functions' should
-- evaluate as (String -> Either String String)
data TestData = TestData { function :: (String -> Either String String)
, description :: String
, input :: String
, outcome :: String
}
parseAtTab :: String -> [String]
parseAtTab s = case dropWhile Char.isSpace s of
"" -> []
s' -> w : parseAtTab s''
where (w, s'') = break (=='\t') s'
makeTestFromString :: String -> TestData
makeTestFromString "" = TestData {function=testTest, description="Empty test", input="", outcome=""}
makeTestFromString s = TestData {function=func, description=l3, input=l2, outcome=l4}
where (l1:l2:l3:l4:_) = parseAtTab s
func | l1 == "testTest" = testTest
| l1 == "testFail" = testFail
| l1 == "testMolForm" = testMolForm
| l1 == "testMolWt" = testMolWt
| l1 == "testAtomCount" = testAtomCount
| l1 == "testHeavyCount" = testHeavyCount
| l1 == "testEnum" = testEnum
| l1 == "testForm" = testForm
| l1 == "testRoundTrip" = testRoundTrip
| otherwise = testTest
performTests :: [TestData] -> (String, String)
performTests [] = ("", "")
performTests td = (summary, errorLog)
where summary = "++++++++++++++++++++++\nPerforming "
++ show (length td)
++ " tests.\n----------------------\n"
++ "\tPassed: " ++ show ((length td) - (length $ lines errorLog)) ++ "\n"
++ "\tFailed: " ++ show ((length $ lines errorLog))
errorLog = detail td results
results = List.map (\a -> (function a) (input a)) td
detail [] _ = ""
detail _ [] = ""
detail (t:ts) (r:rs) = case r of
Left s -> description t ++ ":\t" ++ "FAILED\t-with error string:\t"
++ s ++ "\n" ++ detail ts rs
Right s -> if s == (outcome t)
then detail ts rs
else description t ++ ":\t" ++ "FAILED\t-with output: "
++ s ++ " || should get: " ++ (outcome t)
++ "\n" ++ detail ts rs
testArray :: [(String, [TestData])] -> IO ()
testArray [] = return ()
testArray (x:xs) = do
let (summary, errorLog) = performTests $ snd x
time1 <- getCurrentTime
putStrLn $ "\n\nTest file: " ++ fst x
putStrLn $ performTests (snd x) `seq` summary
time2 <- getCurrentTime
putStrLn $ "\t" ++ (show $ diffUTCTime time2 time1)
++ " seconds."
appendFile "errorLog.txt" $ "\n\n\nTest file: " ++ (fst x) ++ "\n"
++ "=====================================\n"
++ errorLog
testArray xs
-- Simple test function
testTest :: String -> Either String String
testTest s = Right s
-- Simple test fail function
testFail :: String -> Either String String
testFail s = Left s
-- Little utility function, unsafe for general use.
right p = case p of Right r -> r
-- Test smiles to formula
testMolForm :: String -> Either String String
testMolForm s = Right $ show $ (right $ value molecularFormula) $ readSmi s
testMolWt :: String -> Either String String
testMolWt s = Right $ show $ (right $ value molecularWeight) $ readSmi s
testAtomCount :: String -> Either String String
testAtomCount s = Right $ show $ (right $ value atomCount) $ readSmi s
testHeavyCount :: String -> Either String String
testHeavyCount s = Right $ show $ (right $ value heavyAtomCount) $ readSmi s
testEnum :: String -> Either String String
testEnum s = Right $ show $ length $ [mol] >#> method
>#> method
>#> method
>#> method
>#> method
where mol = makeScaffoldFromSmiles s
scaffoldList = map makeScaffoldFromSmiles ["Cl", "OC(=O)C", "C(=O)C", "C1CCCCC1"]
bondList = replicate 6 Single
list = zip bondList scaffoldList
method = Just $ AddMethod Nothing Nothing (\_ _ -> True) list
testForm :: String -> Either String String
testForm s = Right $ show $ List.length $ expand (read s :: Formula)
testRoundTrip :: String -> Either String String
testRoundTrip s = let
mol1 = read s :: Molecule
smi1 = show mol1
mol2 = read smi1 :: Molecule
smi2 = show mol2
in Right $ show $ (smi1 == smi2)
| null | https://raw.githubusercontent.com/odj/Ouch/ed20599214cf77b0cb81cc7cefb4cd9c35bc7cf7/Ouch/Test/Methods.hs | haskell | ----------------------------------------------------------------------------
------------------------------------------------------------------------------
Module : Ouch . Test . Methods
Maintainer :
Stability : Unstable
Portability :
------------------------------------------------------------------------------
----------------------------------------------------------------------------
------------------------------------------------------------------------------
Module : Ouch.Test.Methods
Maintainer : Orion Jankowski
Stability : Unstable
Portability :
------------------------------------------------------------------------------
-----------------------------------------------------------------------------}
# LANGUAGE RecordWildCards, CPP #
Data structure to hold test/result pairs and descriptions. All 'functions' should
evaluate as (String -> Either String String)
Simple test function
Simple test fail function
Little utility function, unsafe for general use.
Test smiles to formula |
Copyright ( c ) 2010 Orion
This file is part of Ouch , a chemical informatics toolkit
written entirely in Haskell .
Ouch 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 .
Ouch 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 Ouch . If not , see < / > .
Copyright (c) 2010 Orion D. Jankowski
This file is part of Ouch, a chemical informatics toolkit
written entirely in Haskell.
Ouch 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.
Ouch 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 Ouch. If not, see </>.
module Ouch.Test.Methods
(
TestData(..)
, performTests
, makeTestFromString
, testArray
, testAtomCount
, testTest
, testFail
, testMolForm
, testForm
, testRoundTrip
) where
import Ouch.Structure.Molecule
import Ouch.Structure.Atom
import Ouch.Structure.Bond
import Ouch.Structure.Marker
import Ouch.Property.Composition
import Ouch.Property.Builder
import Ouch.Enumerate.Method
import Ouch.Input.Smiles
import Ouch.Data.Atom
import Ouch.Enumerate.Formula
import Data.List as List
import Data.Either
import Data.Maybe
import Data.Char as Char
import System.IO
import System.Environment
import Data.Time.Clock
data TestData = TestData { function :: (String -> Either String String)
, description :: String
, input :: String
, outcome :: String
}
parseAtTab :: String -> [String]
parseAtTab s = case dropWhile Char.isSpace s of
"" -> []
s' -> w : parseAtTab s''
where (w, s'') = break (=='\t') s'
makeTestFromString :: String -> TestData
makeTestFromString "" = TestData {function=testTest, description="Empty test", input="", outcome=""}
makeTestFromString s = TestData {function=func, description=l3, input=l2, outcome=l4}
where (l1:l2:l3:l4:_) = parseAtTab s
func | l1 == "testTest" = testTest
| l1 == "testFail" = testFail
| l1 == "testMolForm" = testMolForm
| l1 == "testMolWt" = testMolWt
| l1 == "testAtomCount" = testAtomCount
| l1 == "testHeavyCount" = testHeavyCount
| l1 == "testEnum" = testEnum
| l1 == "testForm" = testForm
| l1 == "testRoundTrip" = testRoundTrip
| otherwise = testTest
performTests :: [TestData] -> (String, String)
performTests [] = ("", "")
performTests td = (summary, errorLog)
where summary = "++++++++++++++++++++++\nPerforming "
++ show (length td)
++ " tests.\n----------------------\n"
++ "\tPassed: " ++ show ((length td) - (length $ lines errorLog)) ++ "\n"
++ "\tFailed: " ++ show ((length $ lines errorLog))
errorLog = detail td results
results = List.map (\a -> (function a) (input a)) td
detail [] _ = ""
detail _ [] = ""
detail (t:ts) (r:rs) = case r of
Left s -> description t ++ ":\t" ++ "FAILED\t-with error string:\t"
++ s ++ "\n" ++ detail ts rs
Right s -> if s == (outcome t)
then detail ts rs
else description t ++ ":\t" ++ "FAILED\t-with output: "
++ s ++ " || should get: " ++ (outcome t)
++ "\n" ++ detail ts rs
testArray :: [(String, [TestData])] -> IO ()
testArray [] = return ()
testArray (x:xs) = do
let (summary, errorLog) = performTests $ snd x
time1 <- getCurrentTime
putStrLn $ "\n\nTest file: " ++ fst x
putStrLn $ performTests (snd x) `seq` summary
time2 <- getCurrentTime
putStrLn $ "\t" ++ (show $ diffUTCTime time2 time1)
++ " seconds."
appendFile "errorLog.txt" $ "\n\n\nTest file: " ++ (fst x) ++ "\n"
++ "=====================================\n"
++ errorLog
testArray xs
testTest :: String -> Either String String
testTest s = Right s
testFail :: String -> Either String String
testFail s = Left s
right p = case p of Right r -> r
testMolForm :: String -> Either String String
testMolForm s = Right $ show $ (right $ value molecularFormula) $ readSmi s
testMolWt :: String -> Either String String
testMolWt s = Right $ show $ (right $ value molecularWeight) $ readSmi s
testAtomCount :: String -> Either String String
testAtomCount s = Right $ show $ (right $ value atomCount) $ readSmi s
testHeavyCount :: String -> Either String String
testHeavyCount s = Right $ show $ (right $ value heavyAtomCount) $ readSmi s
testEnum :: String -> Either String String
testEnum s = Right $ show $ length $ [mol] >#> method
>#> method
>#> method
>#> method
>#> method
where mol = makeScaffoldFromSmiles s
scaffoldList = map makeScaffoldFromSmiles ["Cl", "OC(=O)C", "C(=O)C", "C1CCCCC1"]
bondList = replicate 6 Single
list = zip bondList scaffoldList
method = Just $ AddMethod Nothing Nothing (\_ _ -> True) list
testForm :: String -> Either String String
testForm s = Right $ show $ List.length $ expand (read s :: Formula)
testRoundTrip :: String -> Either String String
testRoundTrip s = let
mol1 = read s :: Molecule
smi1 = show mol1
mol2 = read smi1 :: Molecule
smi2 = show mol2
in Right $ show $ (smi1 == smi2)
|
e795f8c7075d58e73b82f33c987f506305768f86d9cca125c5bba5ae367cc36c | vbmithr/ocaml-bitstamp-api | bitstamp.mli | module Credentials : sig
type t = private {
id: string; key: string; secret: string;
}
val make : id:string -> key:string -> secret:string -> t
module Signature : sig
val make : t -> string * string
end
end
module type HTTP_CLIENT = sig
include Cohttp.S.IO
val get : string -> (string * string) list ->
(string -> [< `Error of string | `Ok of 'a ]) -> 'a t
val post : Credentials.t -> string -> (string * string) list ->
(string -> [< `Error of string | `Ok of 'a ]) -> 'a t
end
module API(H: HTTP_CLIENT) : sig
* { 1 Public API }
module Ticker :
sig
type t = private {
high : float;
last : float;
timestamp : float;
bid : float;
volume : float;
vwap : float;
low : float;
ask : float;
} [@@deriving show]
val ticker : unit -> t H.t
end
module Order_book :
sig
type order = private { price : float; amount : float; } [@@deriving show]
type t = private {
timestamp : float;
bids : order list;
asks : order list;
} [@@deriving show]
val orders : ?group:bool -> unit -> t H.t
end
module Transaction :
sig
type t = private {
date : float;
tid : int;
price : float;
amount : float;
} [@@deriving show]
val transactions : ?offset:int -> ?limit:int -> ?sort:string -> unit -> t list H.t
end
module Eur_usd :
sig
type t = private {
sell : float;
buy : float;
} [@@deriving show]
val conversion_rate : unit -> t H.t
end
* { 1 Private API }
module Balance :
sig
type t = private {
usd_balance : float;
btc_balance : float;
usd_reserved : float;
btc_reserved : float;
usd_available : float;
btc_available : float;
fee : float;
} [@@deriving show]
val balance : Credentials.t -> t H.t
end
module User_transaction :
sig
val type_of_string : string -> [> `Deposit | `Trade | `Withdrawal ]
type t = private {
datetime : float;
id : int;
type_ : [ `Deposit | `Trade | `Withdrawal ];
usd : float;
btc : float;
fee : float;
order_id : int;
} [@@deriving show]
val transactions : ?offset:int -> ?limit:int -> ?sort:string -> Credentials.t -> t list H.t
end
module Order :
sig
val type_of_string : string -> [> `Buy | `Sell ]
type t = private {
id : int;
datetime : float;
type_ : [ `Buy | `Sell ];
price : float;
amount : float;
} [@@deriving show]
val open_orders : Credentials.t -> t list H.t
val buy : Credentials.t -> price:float -> amount:float -> t H.t
val sell : Credentials.t -> price:float -> amount:float -> t H.t
val cancel : Credentials.t -> int -> unit H.t
end
module Withdraw :
sig
type t = private {
id : int;
datetime : float;
type_ : [ `Bitcoin | `Sepa | `Wire ];
amount : float;
status : [ `Cancelled | `Failed | `Finished | `In_process | `Open ];
data : string;
} [@@deriving show]
val requests : Credentials.t -> t list H.t
val btc : Credentials.t -> amount:float -> address:string -> int H.t
val ripple : Credentials.t -> amount:float -> address:string -> currency:string -> unit H.t
end
module Deposit :
sig
type t = private {
amount : float;
address : string;
confirmations : int;
} [@@deriving show]
val unconfirmeds : Credentials.t -> t list H.t
val btc_address : Credentials.t -> string H.t
val ripple_address : Credentials.t -> string H.t
end
end
| null | https://raw.githubusercontent.com/vbmithr/ocaml-bitstamp-api/22d503236e7ec725dbdd0e0fdd0116970882b567/lib/bitstamp.mli | ocaml | module Credentials : sig
type t = private {
id: string; key: string; secret: string;
}
val make : id:string -> key:string -> secret:string -> t
module Signature : sig
val make : t -> string * string
end
end
module type HTTP_CLIENT = sig
include Cohttp.S.IO
val get : string -> (string * string) list ->
(string -> [< `Error of string | `Ok of 'a ]) -> 'a t
val post : Credentials.t -> string -> (string * string) list ->
(string -> [< `Error of string | `Ok of 'a ]) -> 'a t
end
module API(H: HTTP_CLIENT) : sig
* { 1 Public API }
module Ticker :
sig
type t = private {
high : float;
last : float;
timestamp : float;
bid : float;
volume : float;
vwap : float;
low : float;
ask : float;
} [@@deriving show]
val ticker : unit -> t H.t
end
module Order_book :
sig
type order = private { price : float; amount : float; } [@@deriving show]
type t = private {
timestamp : float;
bids : order list;
asks : order list;
} [@@deriving show]
val orders : ?group:bool -> unit -> t H.t
end
module Transaction :
sig
type t = private {
date : float;
tid : int;
price : float;
amount : float;
} [@@deriving show]
val transactions : ?offset:int -> ?limit:int -> ?sort:string -> unit -> t list H.t
end
module Eur_usd :
sig
type t = private {
sell : float;
buy : float;
} [@@deriving show]
val conversion_rate : unit -> t H.t
end
* { 1 Private API }
module Balance :
sig
type t = private {
usd_balance : float;
btc_balance : float;
usd_reserved : float;
btc_reserved : float;
usd_available : float;
btc_available : float;
fee : float;
} [@@deriving show]
val balance : Credentials.t -> t H.t
end
module User_transaction :
sig
val type_of_string : string -> [> `Deposit | `Trade | `Withdrawal ]
type t = private {
datetime : float;
id : int;
type_ : [ `Deposit | `Trade | `Withdrawal ];
usd : float;
btc : float;
fee : float;
order_id : int;
} [@@deriving show]
val transactions : ?offset:int -> ?limit:int -> ?sort:string -> Credentials.t -> t list H.t
end
module Order :
sig
val type_of_string : string -> [> `Buy | `Sell ]
type t = private {
id : int;
datetime : float;
type_ : [ `Buy | `Sell ];
price : float;
amount : float;
} [@@deriving show]
val open_orders : Credentials.t -> t list H.t
val buy : Credentials.t -> price:float -> amount:float -> t H.t
val sell : Credentials.t -> price:float -> amount:float -> t H.t
val cancel : Credentials.t -> int -> unit H.t
end
module Withdraw :
sig
type t = private {
id : int;
datetime : float;
type_ : [ `Bitcoin | `Sepa | `Wire ];
amount : float;
status : [ `Cancelled | `Failed | `Finished | `In_process | `Open ];
data : string;
} [@@deriving show]
val requests : Credentials.t -> t list H.t
val btc : Credentials.t -> amount:float -> address:string -> int H.t
val ripple : Credentials.t -> amount:float -> address:string -> currency:string -> unit H.t
end
module Deposit :
sig
type t = private {
amount : float;
address : string;
confirmations : int;
} [@@deriving show]
val unconfirmeds : Credentials.t -> t list H.t
val btc_address : Credentials.t -> string H.t
val ripple_address : Credentials.t -> string H.t
end
end
|
|
c9fad4461bf5e6fc4daee2a7a18ae57115ed9473f0d3225d609cda5813c72648 | rems-project/cerberus | colour.ml | Part of the escape ANSI 's " Select Graphic Rendition " parameters
type ansi_style =
| Black
| Red
| Green
| Yellow
| Blue
| Magenta
| Cyan
| White
| Bold
| Underline
| Blinking
| Inverted
(* TODO: the complete list *)
type ansi_format = ansi_style list
let int_fg = function
| Black -> 30
| Red -> 31
| Green -> 32
| Yellow -> 33
| Blue -> 34
| Magenta -> 35
| Cyan -> 36
| White -> 37
| Bold -> 1
| Underline -> 4
| Blinking -> 5
| Inverted -> 7
(* TODO: yuck!!!! *)
let do_colour =
ref (Unix.isatty Unix.stdout)
let without_colour f x =
let col = ! do_colour in
do_colour := false;
let r = f x in
do_colour := col;
r
let do_colour_stderr =
ref (Unix.isatty Unix.stderr)
let ansi_format ?(err=false) f str =
if !do_colour && (if err then !do_colour_stderr else true) then
let g f = String.concat ";" (List.map (fun z -> string_of_int (int_fg z)) f) ^ "m" in
"\x1b[" ^ g f ^ str ^ "\x1b[0m"
else
str
(* NOTE: this takes a continuation otherwise the call to 'with_colour' won't work *)
let pp_ansi_format ?(err=false) f mk_doc =
let module P = PPrint in
let (^^) = P.(^^) in
let doc = without_colour mk_doc () in
if !do_colour && (if err then !do_colour_stderr else true) then
let g f = String.concat ";" (List.map (fun z -> string_of_int (int_fg z)) f) ^ "m" in
P.fancystring ("\x1b[" ^ g f) 0 ^^ doc ^^ P.fancystring "\x1b[0m" 0
else
doc
| null | https://raw.githubusercontent.com/rems-project/cerberus/dbfab2643ce6cedb54d2a52cbcb3673e03bfd161/util/colour.ml | ocaml | TODO: the complete list
TODO: yuck!!!!
NOTE: this takes a continuation otherwise the call to 'with_colour' won't work | Part of the escape ANSI 's " Select Graphic Rendition " parameters
type ansi_style =
| Black
| Red
| Green
| Yellow
| Blue
| Magenta
| Cyan
| White
| Bold
| Underline
| Blinking
| Inverted
type ansi_format = ansi_style list
let int_fg = function
| Black -> 30
| Red -> 31
| Green -> 32
| Yellow -> 33
| Blue -> 34
| Magenta -> 35
| Cyan -> 36
| White -> 37
| Bold -> 1
| Underline -> 4
| Blinking -> 5
| Inverted -> 7
let do_colour =
ref (Unix.isatty Unix.stdout)
let without_colour f x =
let col = ! do_colour in
do_colour := false;
let r = f x in
do_colour := col;
r
let do_colour_stderr =
ref (Unix.isatty Unix.stderr)
let ansi_format ?(err=false) f str =
if !do_colour && (if err then !do_colour_stderr else true) then
let g f = String.concat ";" (List.map (fun z -> string_of_int (int_fg z)) f) ^ "m" in
"\x1b[" ^ g f ^ str ^ "\x1b[0m"
else
str
let pp_ansi_format ?(err=false) f mk_doc =
let module P = PPrint in
let (^^) = P.(^^) in
let doc = without_colour mk_doc () in
if !do_colour && (if err then !do_colour_stderr else true) then
let g f = String.concat ";" (List.map (fun z -> string_of_int (int_fg z)) f) ^ "m" in
P.fancystring ("\x1b[" ^ g f) 0 ^^ doc ^^ P.fancystring "\x1b[0m" 0
else
doc
|
ae0be728f128a056f714b987fde35ff1b3f346be09683d9aed418a305748d4f9 | EFanZh/EOPL-Exercises | exercise-3.22.rkt | #lang eopl
Exercise 3.22 [ ★ ★ ★ ] The concrete syntax of this section uses different syntax for a built - in operation , such as
;; difference, from a procedure call. Modify the concrete syntax so that the user of this language need not know which
;; operations are built-in and which are defined procedures. This exercise may range from very easy to hard, depending
;; on the parsing technology being used.
;; Environments.
(define empty-env-record? null?)
(define environment?
(lambda (x)
(or (empty-env-record? x)
(and (pair? x)
(symbol? (car (car x)))
(expval? (cadr (car x)))
(environment? (cdr x))))))
(define empty-env?
(lambda (x)
(empty-env-record? x)))
(define extended-env-record->sym
(lambda (r)
(car (car r))))
(define extended-env-record->val
(lambda (r)
(cadr (car r))))
(define extended-env-record->old-env
(lambda (r)
(cdr r)))
(define apply-env
(lambda (env search-sym)
(if (empty-env? env)
(eopl:error 'apply-env "No binding for ~s" search-sym)
(let ([sym (extended-env-record->sym env)]
[val (extended-env-record->val env)]
[old-env (extended-env-record->old-env env)])
(if (eqv? search-sym sym)
val
(apply-env old-env search-sym))))))
(define extended-env-record
(lambda (sym val old-env)
(cons (list sym val) old-env)))
(define extend-env
(lambda (sym val old-env)
(extended-env-record sym val old-env)))
(define empty-env-record
(lambda ()
'()))
(define empty-env
(lambda ()
(empty-env-record)))
(define init-env
(lambda ()
(extend-env 'zero?
(proc-val (built-in-procedure 'zero?))
(extend-env '-
(proc-val (built-in-procedure '-))
(empty-env)))))
;; Data structures.
(define the-lexical-spec
'([whitespace (whitespace) skip]
[comment ("%" (arbno (not #\newline))) skip]
[identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol]
[identifier ("-") symbol]
[identifier ("-"
(arbno (or letter digit "_" "-" "?"))
(or letter "_" "-" "?")
(arbno (or letter digit "_" "-" "?"))) symbol]
[number (digit (arbno digit)) number]
[number ("-" digit (arbno digit)) number]))
(define the-grammar
'([program (expression) a-program]
[expression (number) const-exp]
[expression ("if" expression "then" expression "else" expression) if-exp]
[expression (identifier) var-exp]
[expression ("let" identifier "=" expression "in" expression) let-exp]
[expression ("proc" "(" (separated-list identifier ",") ")" expression) proc-exp]
[expression ("(" expression (arbno expression) ")") call-exp]))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define-datatype proc proc?
[procedure [vars (list-of symbol?)]
[body expression?]
[env environment?]]
[built-in-procedure [name symbol?]])
(define-datatype expval expval?
[num-val [value number?]]
[bool-val [boolean boolean?]]
[proc-val [proc proc?]])
(define expval-extractor-error
(lambda (variant value)
(eopl:error 'expval-extractors "Looking for a ~s, found ~s"
variant value)))
(define expval->num
(lambda (v)
(cases expval v
[num-val (num) num]
[else (expval-extractor-error 'num v)])))
(define expval->bool
(lambda (v)
(cases expval v
[bool-val (bool) bool]
[else (expval-extractor-error 'bool v)])))
(define expval->proc
(lambda (v)
(cases expval v
[proc-val (proc) proc]
[else (expval-extractor-error 'proc v)])))
;; Helpers.
(define apply-procedure
(lambda (proc1 vals)
(cases proc proc1
[procedure (vars body saved-env) (value-of body
(let loop ([env saved-env]
[vars vars]
[vals vals])
(if (null? vars)
(if (null? vals)
env
(eopl:error 'apply-procedure "Too many arguments."))
(if (null? vals)
(eopl:error 'apply-procedure "Not enough arguments.")
(loop (extend-env (car vars) (car vals) env)
(cdr vars)
(cdr vals))))))]
[built-in-procedure (name) (cond [(eqv? name '-) (num-val (- (expval->num (car vals))
(expval->num (cadr vals))))]
[(eqv? name 'zero?) (bool-val (zero? (expval->num (car vals))))]
[else (eopl:error 'apply-procedure "Unknown built-in procedure.")])])))
;; Interpreter.
(define value-of
(lambda (exp env)
(cases expression exp
[const-exp (num) (num-val num)]
[var-exp (var) (apply-env env var)]
[if-exp (exp1 exp2 exp3) (let ([val1 (value-of exp1 env)])
(if (expval->bool val1)
(value-of exp2 env)
(value-of exp3 env)))]
[let-exp (var exp1 body) (let ([val1 (value-of exp1 env)])
(value-of body (extend-env var val1 env)))]
[proc-exp (vars body) (proc-val (procedure vars body env))]
[call-exp (rator rands) (let ([proc (expval->proc (value-of rator env))]
[args (map (lambda (rand)
(value-of rand env))
rands)])
(apply-procedure proc args))])))
;; Interfaces.
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(value-of exp1 (init-env))))))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define run
(lambda (string)
(value-of-program (scan&parse string))))
(provide num-val bool-val proc-val run)
| null | https://raw.githubusercontent.com/EFanZh/EOPL-Exercises/11667f1e84a1a3e300c2182630b56db3e3d9246a/solutions/exercise-3.22.rkt | racket | difference, from a procedure call. Modify the concrete syntax so that the user of this language need not know which
operations are built-in and which are defined procedures. This exercise may range from very easy to hard, depending
on the parsing technology being used.
Environments.
Data structures.
Helpers.
Interpreter.
Interfaces. | #lang eopl
Exercise 3.22 [ ★ ★ ★ ] The concrete syntax of this section uses different syntax for a built - in operation , such as
(define empty-env-record? null?)
(define environment?
(lambda (x)
(or (empty-env-record? x)
(and (pair? x)
(symbol? (car (car x)))
(expval? (cadr (car x)))
(environment? (cdr x))))))
(define empty-env?
(lambda (x)
(empty-env-record? x)))
(define extended-env-record->sym
(lambda (r)
(car (car r))))
(define extended-env-record->val
(lambda (r)
(cadr (car r))))
(define extended-env-record->old-env
(lambda (r)
(cdr r)))
(define apply-env
(lambda (env search-sym)
(if (empty-env? env)
(eopl:error 'apply-env "No binding for ~s" search-sym)
(let ([sym (extended-env-record->sym env)]
[val (extended-env-record->val env)]
[old-env (extended-env-record->old-env env)])
(if (eqv? search-sym sym)
val
(apply-env old-env search-sym))))))
(define extended-env-record
(lambda (sym val old-env)
(cons (list sym val) old-env)))
(define extend-env
(lambda (sym val old-env)
(extended-env-record sym val old-env)))
(define empty-env-record
(lambda ()
'()))
(define empty-env
(lambda ()
(empty-env-record)))
(define init-env
(lambda ()
(extend-env 'zero?
(proc-val (built-in-procedure 'zero?))
(extend-env '-
(proc-val (built-in-procedure '-))
(empty-env)))))
(define the-lexical-spec
'([whitespace (whitespace) skip]
[comment ("%" (arbno (not #\newline))) skip]
[identifier (letter (arbno (or letter digit "_" "-" "?"))) symbol]
[identifier ("-") symbol]
[identifier ("-"
(arbno (or letter digit "_" "-" "?"))
(or letter "_" "-" "?")
(arbno (or letter digit "_" "-" "?"))) symbol]
[number (digit (arbno digit)) number]
[number ("-" digit (arbno digit)) number]))
(define the-grammar
'([program (expression) a-program]
[expression (number) const-exp]
[expression ("if" expression "then" expression "else" expression) if-exp]
[expression (identifier) var-exp]
[expression ("let" identifier "=" expression "in" expression) let-exp]
[expression ("proc" "(" (separated-list identifier ",") ")" expression) proc-exp]
[expression ("(" expression (arbno expression) ")") call-exp]))
(sllgen:make-define-datatypes the-lexical-spec the-grammar)
(define-datatype proc proc?
[procedure [vars (list-of symbol?)]
[body expression?]
[env environment?]]
[built-in-procedure [name symbol?]])
(define-datatype expval expval?
[num-val [value number?]]
[bool-val [boolean boolean?]]
[proc-val [proc proc?]])
(define expval-extractor-error
(lambda (variant value)
(eopl:error 'expval-extractors "Looking for a ~s, found ~s"
variant value)))
(define expval->num
(lambda (v)
(cases expval v
[num-val (num) num]
[else (expval-extractor-error 'num v)])))
(define expval->bool
(lambda (v)
(cases expval v
[bool-val (bool) bool]
[else (expval-extractor-error 'bool v)])))
(define expval->proc
(lambda (v)
(cases expval v
[proc-val (proc) proc]
[else (expval-extractor-error 'proc v)])))
(define apply-procedure
(lambda (proc1 vals)
(cases proc proc1
[procedure (vars body saved-env) (value-of body
(let loop ([env saved-env]
[vars vars]
[vals vals])
(if (null? vars)
(if (null? vals)
env
(eopl:error 'apply-procedure "Too many arguments."))
(if (null? vals)
(eopl:error 'apply-procedure "Not enough arguments.")
(loop (extend-env (car vars) (car vals) env)
(cdr vars)
(cdr vals))))))]
[built-in-procedure (name) (cond [(eqv? name '-) (num-val (- (expval->num (car vals))
(expval->num (cadr vals))))]
[(eqv? name 'zero?) (bool-val (zero? (expval->num (car vals))))]
[else (eopl:error 'apply-procedure "Unknown built-in procedure.")])])))
(define value-of
(lambda (exp env)
(cases expression exp
[const-exp (num) (num-val num)]
[var-exp (var) (apply-env env var)]
[if-exp (exp1 exp2 exp3) (let ([val1 (value-of exp1 env)])
(if (expval->bool val1)
(value-of exp2 env)
(value-of exp3 env)))]
[let-exp (var exp1 body) (let ([val1 (value-of exp1 env)])
(value-of body (extend-env var val1 env)))]
[proc-exp (vars body) (proc-val (procedure vars body env))]
[call-exp (rator rands) (let ([proc (expval->proc (value-of rator env))]
[args (map (lambda (rand)
(value-of rand env))
rands)])
(apply-procedure proc args))])))
(define value-of-program
(lambda (pgm)
(cases program pgm
(a-program (exp1)
(value-of exp1 (init-env))))))
(define scan&parse
(sllgen:make-string-parser the-lexical-spec the-grammar))
(define run
(lambda (string)
(value-of-program (scan&parse string))))
(provide num-val bool-val proc-val run)
|
bf39b07f8f88d1fe70380fc2ac51a99b483b2de9340c03d678e0d96a4c7bbe97 | soarlab/FPTaylor | interval2.mli | (* ========================================================================== *)
(* A simple OCaml interval library *)
(* *)
(* *)
Author :
(* *)
(* *)
This file is distributed under the terms of the MIT license
(* ========================================================================== *)
* A simple OCaml interval library .
This interval library needs the OCaml [ Num ] module .
It is assumed that all floating - point operations are IEEE 754
compatible and the rounding mode is to nearest .
It is also assumed that OCaml functions [ exp ] , [ log ] compute results with
less than 1 ulp error .
Intervals computed with this library are optimal floating - point
intervals for basic arithmetic operations .
{ ! Interval1 } provides faster interval functions which are only
slightly less optimal .
This interval library needs the OCaml [Num] module.
It is assumed that all floating-point operations are IEEE 754
compatible and the rounding mode is to nearest.
It is also assumed that OCaml functions [exp], [log] compute results with
less than 1 ulp error.
Intervals computed with this library are optimal floating-point
intervals for basic arithmetic operations.
{!Interval1} provides faster interval functions which are only
slightly less optimal.
*)
(** The interval type *)
type interval = {
low : float;
high : float;
}
(** The empty interval *)
val empty_interval : interval
(** The entire interval representing (-infinity, infinity) *)
val entire_interval : interval
(** [[0., 0.]] *)
val zero_interval : interval
* [ [ 1 . , 1 . ] ]
val one_interval : interval
* { 6 Interval operations }
(** Creates an interval from given endpoints *)
val make_interval : float -> float -> interval
(** Tests if an interval is empty *)
val is_empty : interval -> bool
(** Tests if an interval is the entire interval *)
val is_entire : interval -> bool
(** Tests if an interval is valid. A valid interval is either empty
or [[a, b]] with [a <= b], [a < infinity], [-infinity < b]. *)
val is_valid : interval -> bool
(** Computes a midpoint of an interval. This function returns finite
values for all valid non-empty intervals. *)
val mid_i : interval -> float
(** Interval negation {b (optimal)} *)
val neg_i : interval -> interval
(** Interval absolute value {b (optimal)} *)
val abs_i : interval -> interval
(** Interval maximum {b (optimal)} *)
val max_ii : interval -> interval -> interval
(** Interval minimum {b (optimal)} *)
val min_ii : interval -> interval -> interval
(** Interval addition {b (optimal)} *)
val add_ii : interval -> interval -> interval
(** Addition of an interval and a number {b (optimal)} *)
val add_id : interval -> float -> interval
(** Addition of a number and an interval {b (optimal)} *)
val add_di : float -> interval -> interval
(** Interval subtraction {b (optimal)} *)
val sub_ii : interval -> interval -> interval
(** Subtraction of an interval and a number {b (optimal)} *)
val sub_id : interval -> float -> interval
(** Subtraction of a number and an interval {b (optimal)} *)
val sub_di : float -> interval -> interval
(** Interval multiplication {b (optimal)} *)
val mul_ii : interval -> interval -> interval
(** Multiplication of an interval and a number {b (optimal)} *)
val mul_id : interval -> float -> interval
(** Multiplication of a number and an interval {b (optimal)} *)
val mul_di : float -> interval -> interval
(** Interval division {b (optimal)} *)
val div_ii : interval -> interval -> interval
(** Division of an interval by a number {b (optimal)} *)
val div_id : interval -> float -> interval
(** Division of a number by an interval {b (optimal)} *)
val div_di : float -> interval -> interval
(** Interval reciprocal {b (optimal)} *)
val inv_i : interval -> interval
(** Interval square root {b (optimal)} *)
val sqrt_i : interval -> interval
(** Interval square {b (optimal)} *)
val sqr_i : interval -> interval
(** Interval integer power. This function returns an optimal interval
but this behavior may change in the future. *)
val pown_i : interval -> int -> interval
* Interval exponential function . It is assumed that the standard
function [ exp : float->float ] has less than 1 ulp error .
function [exp:float->float] has less than 1 ulp error. *)
val exp_i : interval -> interval
* Interval natural logarithm . It is assumed that the standard
function [ log : float->float ] has less than 1 ulp error .
function [log:float->float] has less than 1 ulp error. *)
val log_i : interval -> interval
(** Interval sine (not implemented yet) *)
val sin_i : interval -> interval
(** Interval cosine (not implemented yet) *)
val cos_i : interval -> interval
* { 6 Floating - point operations with directed rounding }
(** Computes a successor of a floating-point number {b (optimal)} *)
val fsucc : float -> float
(** Computes a predecessor of a floating-point number {b (optimal)} *)
val fpred : float -> float
* Returns a lower bound of the sum of two floating - point numbers { b
( optimal ) }
(optimal)} *)
val fadd_low : float -> float -> float
* Returns an upper bound of the sum of two floating - point numbers { b
( optimal ) }
(optimal)} *)
val fadd_high : float -> float -> float
* Returns a lower bound of the difference of two floating - point
numbers { b ( optimal ) }
numbers {b (optimal)} *)
val fsub_low : float -> float -> float
* Returns an upper bound of the difference of two floating - point
numbers { b ( optimal ) }
numbers {b (optimal)} *)
val fsub_high : float -> float -> float
* Returns a lower bound of the product of two floating - point numbers
{ b ( optimal ) }
{b (optimal)} *)
val fmul_low : float -> float -> float
* Returns an upper bound of the product of two floating - point
numbers { b ( optimal ) }
numbers {b (optimal)} *)
val fmul_high : float -> float -> float
* Returns a lower bound of the ratio of two floating - point numbers
{ b ( optimal ) }
{b (optimal)} *)
val fdiv_low : float -> float -> float
* Returns an upper bound of the ratio of two floating - point numbers
{ b ( optimal ) }
{b (optimal)} *)
val fdiv_high : float -> float -> float
(** Returns a lower bound of [x^2] {b (optimal)} *)
val fsqr_low : float -> float
(** Returns an upper bound of [x^2] {b (optimal)} *)
val fsqr_high : float -> float
(** Returns a lower bound of [sqrt x] {b (optimal)} *)
val fsqrt_low : float -> float
(** Returns an upper bound of [sqrt x] {b (optimal)} *)
val fsqrt_high : float -> float
(** Returns a lower bound of [exp x] *)
val fexp_low : float -> float
(** Returns an upper bound of [exp x] *)
val fexp_high : float -> float
(** Returns a lower bound of [log x] *)
val flog_low : float -> float
(** Returns an upper bound of [log x] *)
val flog_high : float -> float
(*
(** Return a lower bound of [cos x] *)
val fcos_low : float -> float
(** Returns an upper bound of [cos x] *)
val fcos_high : float -> float
(** Returns a lower bound of [sin x] *)
val fsin_low : float -> float
(** Returns an upper bound of [sin x] *)
val fsin_high : float -> float
*)
(** Returns a lower bound of [x^n] *)
val fpown_low : float -> int -> float
(** Returns an upper bound of [x^n] *)
val fpown_high : float -> int -> float
| null | https://raw.githubusercontent.com/soarlab/FPTaylor/efbbc83970fe3c9f4cb33fafbbe1050dd18749cd/simple_interval/interval2.mli | ocaml | ==========================================================================
A simple OCaml interval library
==========================================================================
* The interval type
* The empty interval
* The entire interval representing (-infinity, infinity)
* [[0., 0.]]
* Creates an interval from given endpoints
* Tests if an interval is empty
* Tests if an interval is the entire interval
* Tests if an interval is valid. A valid interval is either empty
or [[a, b]] with [a <= b], [a < infinity], [-infinity < b].
* Computes a midpoint of an interval. This function returns finite
values for all valid non-empty intervals.
* Interval negation {b (optimal)}
* Interval absolute value {b (optimal)}
* Interval maximum {b (optimal)}
* Interval minimum {b (optimal)}
* Interval addition {b (optimal)}
* Addition of an interval and a number {b (optimal)}
* Addition of a number and an interval {b (optimal)}
* Interval subtraction {b (optimal)}
* Subtraction of an interval and a number {b (optimal)}
* Subtraction of a number and an interval {b (optimal)}
* Interval multiplication {b (optimal)}
* Multiplication of an interval and a number {b (optimal)}
* Multiplication of a number and an interval {b (optimal)}
* Interval division {b (optimal)}
* Division of an interval by a number {b (optimal)}
* Division of a number by an interval {b (optimal)}
* Interval reciprocal {b (optimal)}
* Interval square root {b (optimal)}
* Interval square {b (optimal)}
* Interval integer power. This function returns an optimal interval
but this behavior may change in the future.
* Interval sine (not implemented yet)
* Interval cosine (not implemented yet)
* Computes a successor of a floating-point number {b (optimal)}
* Computes a predecessor of a floating-point number {b (optimal)}
* Returns a lower bound of [x^2] {b (optimal)}
* Returns an upper bound of [x^2] {b (optimal)}
* Returns a lower bound of [sqrt x] {b (optimal)}
* Returns an upper bound of [sqrt x] {b (optimal)}
* Returns a lower bound of [exp x]
* Returns an upper bound of [exp x]
* Returns a lower bound of [log x]
* Returns an upper bound of [log x]
(** Return a lower bound of [cos x]
* Returns an upper bound of [cos x]
* Returns a lower bound of [sin x]
* Returns an upper bound of [sin x]
* Returns a lower bound of [x^n]
* Returns an upper bound of [x^n] | Author :
This file is distributed under the terms of the MIT license
* A simple OCaml interval library .
This interval library needs the OCaml [ Num ] module .
It is assumed that all floating - point operations are IEEE 754
compatible and the rounding mode is to nearest .
It is also assumed that OCaml functions [ exp ] , [ log ] compute results with
less than 1 ulp error .
Intervals computed with this library are optimal floating - point
intervals for basic arithmetic operations .
{ ! Interval1 } provides faster interval functions which are only
slightly less optimal .
This interval library needs the OCaml [Num] module.
It is assumed that all floating-point operations are IEEE 754
compatible and the rounding mode is to nearest.
It is also assumed that OCaml functions [exp], [log] compute results with
less than 1 ulp error.
Intervals computed with this library are optimal floating-point
intervals for basic arithmetic operations.
{!Interval1} provides faster interval functions which are only
slightly less optimal.
*)
type interval = {
low : float;
high : float;
}
val empty_interval : interval
val entire_interval : interval
val zero_interval : interval
* [ [ 1 . , 1 . ] ]
val one_interval : interval
* { 6 Interval operations }
val make_interval : float -> float -> interval
val is_empty : interval -> bool
val is_entire : interval -> bool
val is_valid : interval -> bool
val mid_i : interval -> float
val neg_i : interval -> interval
val abs_i : interval -> interval
val max_ii : interval -> interval -> interval
val min_ii : interval -> interval -> interval
val add_ii : interval -> interval -> interval
val add_id : interval -> float -> interval
val add_di : float -> interval -> interval
val sub_ii : interval -> interval -> interval
val sub_id : interval -> float -> interval
val sub_di : float -> interval -> interval
val mul_ii : interval -> interval -> interval
val mul_id : interval -> float -> interval
val mul_di : float -> interval -> interval
val div_ii : interval -> interval -> interval
val div_id : interval -> float -> interval
val div_di : float -> interval -> interval
val inv_i : interval -> interval
val sqrt_i : interval -> interval
val sqr_i : interval -> interval
val pown_i : interval -> int -> interval
* Interval exponential function . It is assumed that the standard
function [ exp : float->float ] has less than 1 ulp error .
function [exp:float->float] has less than 1 ulp error. *)
val exp_i : interval -> interval
* Interval natural logarithm . It is assumed that the standard
function [ log : float->float ] has less than 1 ulp error .
function [log:float->float] has less than 1 ulp error. *)
val log_i : interval -> interval
val sin_i : interval -> interval
val cos_i : interval -> interval
* { 6 Floating - point operations with directed rounding }
val fsucc : float -> float
val fpred : float -> float
* Returns a lower bound of the sum of two floating - point numbers { b
( optimal ) }
(optimal)} *)
val fadd_low : float -> float -> float
* Returns an upper bound of the sum of two floating - point numbers { b
( optimal ) }
(optimal)} *)
val fadd_high : float -> float -> float
* Returns a lower bound of the difference of two floating - point
numbers { b ( optimal ) }
numbers {b (optimal)} *)
val fsub_low : float -> float -> float
* Returns an upper bound of the difference of two floating - point
numbers { b ( optimal ) }
numbers {b (optimal)} *)
val fsub_high : float -> float -> float
* Returns a lower bound of the product of two floating - point numbers
{ b ( optimal ) }
{b (optimal)} *)
val fmul_low : float -> float -> float
* Returns an upper bound of the product of two floating - point
numbers { b ( optimal ) }
numbers {b (optimal)} *)
val fmul_high : float -> float -> float
* Returns a lower bound of the ratio of two floating - point numbers
{ b ( optimal ) }
{b (optimal)} *)
val fdiv_low : float -> float -> float
* Returns an upper bound of the ratio of two floating - point numbers
{ b ( optimal ) }
{b (optimal)} *)
val fdiv_high : float -> float -> float
val fsqr_low : float -> float
val fsqr_high : float -> float
val fsqrt_low : float -> float
val fsqrt_high : float -> float
val fexp_low : float -> float
val fexp_high : float -> float
val flog_low : float -> float
val flog_high : float -> float
val fcos_low : float -> float
val fcos_high : float -> float
val fsin_low : float -> float
val fsin_high : float -> float
*)
val fpown_low : float -> int -> float
val fpown_high : float -> int -> float
|
af180c876e91cc91d6d37d2e661f6b41ff3d014b96a4dd7fb76ebcd3fed5350d | ryukinix/discrete-mathematics | data-type-definitions.hs | {-- Data Type Definitions --}
data Colour = Red | Orange | Yellow
| Green | Blue | Violet
deriving Show
-- A custom user-defined type for enumerates colors
data Animal a b = Cat a | Dog b | Rat
deriving Show
data BreedOfCat = Siamese | Persian | Moggie
deriving (Show, Eq)
-- Deriving is like inherits properties from other type classes.
The Monad Maybe wrapping a value
-- data Maybe a = Nothing | Just a
-- When using it? Example:
phoneMessage :: Maybe Integer -> String
phoneMessage Nothing = "Telephone number not found"
phoneMessage (Just x) = "The number is " ++ show x
-- If a function has a possibility of variability in our type result/input
We can use Maybe Monad to handling that .
| null | https://raw.githubusercontent.com/ryukinix/discrete-mathematics/1f779e05822c094af33745e2dd3c9a35c6dfb388/src/01-introduction-to-haskell/data-type-definitions.hs | haskell | - Data Type Definitions -
A custom user-defined type for enumerates colors
Deriving is like inherits properties from other type classes.
data Maybe a = Nothing | Just a
When using it? Example:
If a function has a possibility of variability in our type result/input |
data Colour = Red | Orange | Yellow
| Green | Blue | Violet
deriving Show
data Animal a b = Cat a | Dog b | Rat
deriving Show
data BreedOfCat = Siamese | Persian | Moggie
deriving (Show, Eq)
The Monad Maybe wrapping a value
phoneMessage :: Maybe Integer -> String
phoneMessage Nothing = "Telephone number not found"
phoneMessage (Just x) = "The number is " ++ show x
We can use Maybe Monad to handling that .
|
68f77a7b483c488810dbf5381bba9556c41ff44451cfbdab2d810b11e3509b03 | fons/cl-twitter | twitter-blocks.lisp | (in-package :twitter)
;;
;; Block Methods
;;
;; Block resources
;; blocks/create
;; blocks/destroy
;; blocks/exists
;; blocks/blocking
;; blocks/blocking/ids
(define-element cursor-id ((ids (identity)))
"a cursor element "
(next-cursor-str "" nil)
(previous-cursor-str "" nil)
(next-cursor "" nil)
(ids "" nil)
(previous-cursor "" nil))
(defun limit-length (lst)
(if (> (length lst) 5)
(format nil "~{~a~^,~},..." (subseq lst 0 5))
(format nil "~{~a~^,~}" lst)))
(defmethod print-object ((ref cursor-id) stream)
(format stream "#<TWITTER-CURSOR-ID '~A:~A'>" (length (cursor-id-ids ref)) (limit-length (cursor-id-ids ref))))
(defun cursor-id (ref)
(format t "~A: ~A ~A~%" (cursor-id-previous-cursor ref) (cursor-id-next-cursor ref) (length (cursor-id-ids ref))))
;;Destroys a friendship to the blocked user if it exists. Returns the blocked user in the requested format when successful.
(define-command blocks/create (:post :twitter-user)
(twitter-app-uri "blocks/create.json")
"Blocks the user specified in the ID parameter as the authenticating user. "
:user_id "The ID of the user for whom to return results for. Helpful for disambiguating when a valid user ID is also a valid screen name."
:screen_name "The screen name of the user for whom to return results for. Helpful for disambiguating when a valid screen name is also a user ID."
:include_entities "When set to either true, t or 1, each tweet will include a node called entities"
:skip_status "When set to either true, t or 1 statuses will not be included in the returned user objects.")
(define-twitter-method blocks-create (() &key (screen-name) (user-id nil) (include-entities t) (skip-status nil)) :blocks/create )
(define-command blocks/list (:get :cursor-user)
(twitter-app-uri "blocks/list.json")
"Returns a collection of user objects that the authenticating user is blocking."
:cursor "semi-optional:Causes the list of blocked users to be broken into pages of no more than 5000 IDs at a time"
:skip_status "Optional :When set to either true, t or 1 statuses will not be included in the returned user objects."
:include_entities "Optional: When set to either true, t or 1, each tweet will include a node called entities")
(define-twitter-method blocks-list (() &key (cursor nil) (include-entities t) (skip-status nil)) :blocks/list )
(define-command blocks/ids (:get :cursor-id)
(twitter-app-uri "blocks/ids.json")
"Returns an array of numeric user ids the authenticating user is blocking"
:cursor "semi-optional:Causes the list of blocked users to be broken into pages of no more than 5000 IDs at a time"
:stringify_ids "Optional:Many programming environments will not consume our ids due to their size.")
(define-twitter-method blocks-ids (() &key (cursor nil) (stringify-ids nil)) :blocks/ids )
(define-command blocks/destroy (:post :twitter-user)
(twitter-app-uri "blocks/destroy.json")
"Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful."
:user_id "Optional: The ID of the user for whom to return results for. Helpful for disambiguating when a valid user ID is also a valid screen name."
:screen_name "Optional: The screen name of the user for whom to return results for. Helpful for disambiguating when a valid screen name is also a user ID."
:skip_status "Optional: When set to either true, t or 1 statuses will not be included in the returned user objects"
:include_entities "Optional: When set to either true, t or 1, each tweet will include a node called entities")
(define-twitter-method blocks-destroy (() &key (user-id nil) (screen-name nil) (skip-status nil) (include-entities nil)) :blocks/destroy )
;;--------------------- end of blocks resources -----------------------------------------------
;; TODO : helper methods
| null | https://raw.githubusercontent.com/fons/cl-twitter/6a72291f8c60bd07efd2a8605f18a3eb7570cc4a/api/twitter-blocks.lisp | lisp |
Block Methods
Block resources
blocks/create
blocks/destroy
blocks/exists
blocks/blocking
blocks/blocking/ids
Destroys a friendship to the blocked user if it exists. Returns the blocked user in the requested format when successful.
--------------------- end of blocks resources -----------------------------------------------
TODO : helper methods | (in-package :twitter)
(define-element cursor-id ((ids (identity)))
"a cursor element "
(next-cursor-str "" nil)
(previous-cursor-str "" nil)
(next-cursor "" nil)
(ids "" nil)
(previous-cursor "" nil))
(defun limit-length (lst)
(if (> (length lst) 5)
(format nil "~{~a~^,~},..." (subseq lst 0 5))
(format nil "~{~a~^,~}" lst)))
(defmethod print-object ((ref cursor-id) stream)
(format stream "#<TWITTER-CURSOR-ID '~A:~A'>" (length (cursor-id-ids ref)) (limit-length (cursor-id-ids ref))))
(defun cursor-id (ref)
(format t "~A: ~A ~A~%" (cursor-id-previous-cursor ref) (cursor-id-next-cursor ref) (length (cursor-id-ids ref))))
(define-command blocks/create (:post :twitter-user)
(twitter-app-uri "blocks/create.json")
"Blocks the user specified in the ID parameter as the authenticating user. "
:user_id "The ID of the user for whom to return results for. Helpful for disambiguating when a valid user ID is also a valid screen name."
:screen_name "The screen name of the user for whom to return results for. Helpful for disambiguating when a valid screen name is also a user ID."
:include_entities "When set to either true, t or 1, each tweet will include a node called entities"
:skip_status "When set to either true, t or 1 statuses will not be included in the returned user objects.")
(define-twitter-method blocks-create (() &key (screen-name) (user-id nil) (include-entities t) (skip-status nil)) :blocks/create )
(define-command blocks/list (:get :cursor-user)
(twitter-app-uri "blocks/list.json")
"Returns a collection of user objects that the authenticating user is blocking."
:cursor "semi-optional:Causes the list of blocked users to be broken into pages of no more than 5000 IDs at a time"
:skip_status "Optional :When set to either true, t or 1 statuses will not be included in the returned user objects."
:include_entities "Optional: When set to either true, t or 1, each tweet will include a node called entities")
(define-twitter-method blocks-list (() &key (cursor nil) (include-entities t) (skip-status nil)) :blocks/list )
(define-command blocks/ids (:get :cursor-id)
(twitter-app-uri "blocks/ids.json")
"Returns an array of numeric user ids the authenticating user is blocking"
:cursor "semi-optional:Causes the list of blocked users to be broken into pages of no more than 5000 IDs at a time"
:stringify_ids "Optional:Many programming environments will not consume our ids due to their size.")
(define-twitter-method blocks-ids (() &key (cursor nil) (stringify-ids nil)) :blocks/ids )
(define-command blocks/destroy (:post :twitter-user)
(twitter-app-uri "blocks/destroy.json")
"Un-blocks the user specified in the ID parameter as the authenticating user. Returns the un-blocked user in the requested format when successful."
:user_id "Optional: The ID of the user for whom to return results for. Helpful for disambiguating when a valid user ID is also a valid screen name."
:screen_name "Optional: The screen name of the user for whom to return results for. Helpful for disambiguating when a valid screen name is also a user ID."
:skip_status "Optional: When set to either true, t or 1 statuses will not be included in the returned user objects"
:include_entities "Optional: When set to either true, t or 1, each tweet will include a node called entities")
(define-twitter-method blocks-destroy (() &key (user-id nil) (screen-name nil) (skip-status nil) (include-entities nil)) :blocks/destroy )
|
8ca83a5e158fbf878884b5d350ec8349121d3ce18c9477f9cb7888dc96502035 | sru-systems/protobuf-simple | SInt64Msg.hs | -- Generated by protobuf-simple. DO NOT EDIT!
module Types.SInt64Msg where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype SInt64Msg = SInt64Msg
{ value :: PB.Int64
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default SInt64Msg where
defaultVal = SInt64Msg
{ value = PB.defaultVal
}
instance PB.Mergeable SInt64Msg where
merge a b = SInt64Msg
{ value = PB.merge (value a) (value b)
}
instance PB.Required SInt64Msg where
reqTags _ = PB.fromList [PB.WireTag 1 PB.VarInt]
instance PB.WireMessage SInt64Msg where
fieldToValue (PB.WireTag 1 PB.VarInt) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getSInt64
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putSInt64 (PB.WireTag 1 PB.VarInt) (value self)
| null | https://raw.githubusercontent.com/sru-systems/protobuf-simple/ee0f26b6a8588ed9f105bc9ee72c38943133ed4d/test/Types/SInt64Msg.hs | haskell | Generated by protobuf-simple. DO NOT EDIT! | module Types.SInt64Msg where
import Control.Applicative ((<$>))
import Prelude ()
import qualified Data.ProtoBufInt as PB
newtype SInt64Msg = SInt64Msg
{ value :: PB.Int64
} deriving (PB.Show, PB.Eq, PB.Ord)
instance PB.Default SInt64Msg where
defaultVal = SInt64Msg
{ value = PB.defaultVal
}
instance PB.Mergeable SInt64Msg where
merge a b = SInt64Msg
{ value = PB.merge (value a) (value b)
}
instance PB.Required SInt64Msg where
reqTags _ = PB.fromList [PB.WireTag 1 PB.VarInt]
instance PB.WireMessage SInt64Msg where
fieldToValue (PB.WireTag 1 PB.VarInt) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getSInt64
fieldToValue tag self = PB.getUnknown tag self
messageToFields self = do
PB.putSInt64 (PB.WireTag 1 PB.VarInt) (value self)
|
03bf6ced3795f1b3c8ab0b717d804b679a19d708a4238fa2ddd65c05c57be316 | sdiehl/dive-into-ghc | Main.hs | # LANGUAGE ScopedTypeVariables #
module Main where
import GHC
import GHC.Paths (libdir)
import DynFlags
import Outputable
import HscTypes
import CorePrep
import CoreToStg
import Control.Monad.Trans
showGhc :: (Outputable a) => a -> String
showGhc = showPpr unsafeGlobalDynFlags
banner :: MonadIO m => String -> m ()
banner msg = liftIO $ putStrLn (
(replicate (fromIntegral n) '=')
++
msg
++
(replicate (fromIntegral n) '=')
)
where
n = (76 - length msg) `div` 2
main :: IO ()
main = runGhc (Just libdir) $ do
env <- getSession
dflags <- getSessionDynFlags
setSessionDynFlags $ dflags { hscTarget = HscInterpreted }
target <- guessTarget "Example.hs" Nothing
setTargets [target]
load LoadAllTargets
modSum <- getModSummary $ mkModuleName "Example"
pmod <- parseModule modSum -- ModuleSummary
TypecheckedSource
dmod <- desugarModule tmod -- DesugaredModule
CoreModule
stg <- liftIO $ coreToStg dflags (mg_module core) (mg_binds core)
liftIO $ banner "Parsed Source"
liftIO $ putStrLn $ showGhc ( parsedSource pmod )
liftIO $ banner "Renamed Module"
liftIO $ putStrLn $ showGhc ( tm_renamed_source tmod )
liftIO $ banner "Typechecked Module"
liftIO $ putStrLn $ showGhc ( tm_typechecked_source tmod )
liftIO $ banner "Typed Toplevel Definitions"
liftIO $ putStrLn $ showGhc ( modInfoTyThings (moduleInfo tmod) )
liftIO $ banner "Typed Toplevel Exports"
liftIO $ putStrLn $ showGhc ( modInfoExports (moduleInfo tmod) )
liftIO $ banner "Core Module"
liftIO $ putStrLn $ showGhc ( mg_binds core )
liftIO $ banner "STG"
liftIO $ putStrLn $ showGhc stg
| null | https://raw.githubusercontent.com/sdiehl/dive-into-ghc/c9a5d71530864675f54808a5b5302e2bca4d1250/02-parser/Main.hs | haskell | ModuleSummary
DesugaredModule | # LANGUAGE ScopedTypeVariables #
module Main where
import GHC
import GHC.Paths (libdir)
import DynFlags
import Outputable
import HscTypes
import CorePrep
import CoreToStg
import Control.Monad.Trans
showGhc :: (Outputable a) => a -> String
showGhc = showPpr unsafeGlobalDynFlags
banner :: MonadIO m => String -> m ()
banner msg = liftIO $ putStrLn (
(replicate (fromIntegral n) '=')
++
msg
++
(replicate (fromIntegral n) '=')
)
where
n = (76 - length msg) `div` 2
main :: IO ()
main = runGhc (Just libdir) $ do
env <- getSession
dflags <- getSessionDynFlags
setSessionDynFlags $ dflags { hscTarget = HscInterpreted }
target <- guessTarget "Example.hs" Nothing
setTargets [target]
load LoadAllTargets
modSum <- getModSummary $ mkModuleName "Example"
TypecheckedSource
CoreModule
stg <- liftIO $ coreToStg dflags (mg_module core) (mg_binds core)
liftIO $ banner "Parsed Source"
liftIO $ putStrLn $ showGhc ( parsedSource pmod )
liftIO $ banner "Renamed Module"
liftIO $ putStrLn $ showGhc ( tm_renamed_source tmod )
liftIO $ banner "Typechecked Module"
liftIO $ putStrLn $ showGhc ( tm_typechecked_source tmod )
liftIO $ banner "Typed Toplevel Definitions"
liftIO $ putStrLn $ showGhc ( modInfoTyThings (moduleInfo tmod) )
liftIO $ banner "Typed Toplevel Exports"
liftIO $ putStrLn $ showGhc ( modInfoExports (moduleInfo tmod) )
liftIO $ banner "Core Module"
liftIO $ putStrLn $ showGhc ( mg_binds core )
liftIO $ banner "STG"
liftIO $ putStrLn $ showGhc stg
|
87f4246e94f8140b01d11bdb995c25d99dea4f878b85a78474ecea27a00b6039 | masatoi/cl-random-forest | mnist.lisp | -*- coding : utf-8 ; mode : lisp -*-
set dynamic - space - size > = 2500
(defpackage :cl-random-forest/example/classification/mnist
(:use #:cl
#:cl-random-forest)
(:import-from #:cl-random-forest/src/utils
#:read-data))
(in-package :cl-random-forest/example/classification/mnist)
;;; Load Dataset ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
MNIST data
;; /~cjlin/libsvmtools/datasets/multiclass.html#mnist
(defparameter dir (asdf:system-relative-pathname :cl-random-forest "dataset/"))
(defparameter mnist-dim 784)
(defparameter mnist-n-class 10)
(defvar mnist-datamatrix)
(defvar mnist-target)
(defvar mnist-datamatrix-test)
(defvar mnist-target-test)
(defun get-mnist-dataset ()
(ensure-directories-exist dir)
(let ((base-url "/~cjlin/libsvmtools/datasets/multiclass"))
(flet ((download-file (filename)
(uiop:run-program
(format nil "cd ~A ; [ -e ~A ] || wget ~A/~A" dir filename base-url filename)))
(expand-file (filename)
(uiop:run-program (format nil "cd ~A ; [ -e ~A ] || bunzip2 ~A"
dir (subseq filename 0 (- (length filename) 4)) filename))))
(format t "Downloading mnist.scale.bz2~%")
(download-file "mnist.scale.bz2")
(format t "Expanding mnist.scale.bz2~%")
(expand-file "mnist.scale.bz2")
(format t "Downloading mnist.scale.t.bz2~%")
(download-file "mnist.scale.t.bz2")
(format t "Expanding mnist.scale.t.bz2~%")
(expand-file "mnist.scale.t.bz2"))))
(defun read-mnist-dataset ()
(format t "Reading training data~%")
(multiple-value-bind (datamat target)
(read-data (merge-pathnames "mnist.scale" dir) mnist-dim)
(setf mnist-datamatrix datamat
mnist-target target))
(format t "Reading test data~%")
(multiple-value-bind (datamat target)
(read-data (merge-pathnames "mnist.scale.t" dir) mnist-dim)
(setf mnist-datamatrix-test datamat
mnist-target-test target))
Add 1 to labels because the labels of this dataset begin from 0
(loop for i from 0 below (length mnist-target) do
(incf (aref mnist-target i)))
(loop for i from 0 below (length mnist-target-test) do
(incf (aref mnist-target-test i))))
(get-mnist-dataset)
(read-mnist-dataset)
;;; Make Decision Tree ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defparameter mnist-dtree
(make-dtree mnist-n-class mnist-datamatrix mnist-target
:max-depth 15 :n-trial 28 :min-region-samples 5))
;; Prediction
= > 5 ( correct )
;; Testing with training data
(test-dtree mnist-dtree mnist-datamatrix mnist-target)
Accuracy : 90.37333 % , Correct : 54224 , Total : 60000
;; Testing with test data
(test-dtree mnist-dtree mnist-datamatrix-test mnist-target-test)
Accuracy : 81.52 % , Correct : 8152 , Total : 10000
Make Random Forest ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
;;; Enable/Disable parallelizaion
(setf lparallel:*kernel* (lparallel:make-kernel 4))
(setf lparallel:*kernel* nil)
6.079 seconds ( 1 core ) , 2.116 seconds ( 4 core )
(defparameter mnist-forest
(make-forest mnist-n-class mnist-datamatrix mnist-target
:n-tree 500 :bagging-ratio 0.1 :max-depth 10 :n-trial 10 :min-region-samples 5))
;; Prediction
= > 5 ( correct )
;; Testing with test data
4.786 seconds , Accuracy : 93.38 %
(test-forest mnist-forest mnist-datamatrix-test mnist-target-test)
42.717 seconds ( 1 core ) , 13.24 seconds ( 4 core )
(defparameter mnist-forest-tall
(make-forest mnist-n-class mnist-datamatrix mnist-target
:n-tree 100 :bagging-ratio 1.0 :max-depth 15 :n-trial 28 :min-region-samples 5))
2.023 seconds , Accuracy : 96.62 %
(test-forest mnist-forest-tall mnist-datamatrix-test mnist-target-test)
Global Refinement of Random Forest ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
Generate sparse data from Random Forest
6.255 seconds ( 1 core ) , 1.809 seconds ( 4 core )
(defparameter mnist-refine-dataset
(make-refine-dataset mnist-forest mnist-datamatrix))
0.995 seconds ( 1 core ) , 0.322 seconds ( 4 core )
(defparameter mnist-refine-test
(make-refine-dataset mnist-forest mnist-datamatrix-test))
(defparameter mnist-refine-learner (make-refine-learner mnist-forest))
4.347 seconds ( 1 core ) , 2.281 seconds ( 4 core ) , Accuracy : 98.259 %
(train-refine-learner-process mnist-refine-learner mnist-refine-dataset mnist-target
mnist-refine-test mnist-target-test)
(test-refine-learner mnist-refine-learner mnist-refine-test mnist-target-test)
5.859 seconds ( 1 core ) , 4.090 seconds ( 4 core ) , Accuracy : 98.29 %
(loop repeat 5 do
(train-refine-learner mnist-refine-learner mnist-refine-dataset mnist-target)
(test-refine-learner mnist-refine-learner mnist-refine-test mnist-target-test))
;; Make a prediction
(predict-refine-learner mnist-forest mnist-refine-learner mnist-datamatrix-test 0)
Global Pruning of Random Forest ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
= > 98008
0.328 seconds
= > 93228
;; Re-learning refine learner
(defparameter mnist-refine-dataset (make-refine-dataset mnist-forest mnist-datamatrix))
(defparameter mnist-refine-test (make-refine-dataset mnist-forest mnist-datamatrix-test))
(defparameter mnist-refine-learner (make-refine-learner mnist-forest))
(time
(loop repeat 10 do
(train-refine-learner mnist-refine-learner mnist-refine-dataset mnist-target)
(test-refine-learner mnist-refine-learner mnist-refine-test mnist-target-test)))
Accuracy : Accuracy : 98.27 %
(loop repeat 10 do
(sb-ext:gc :full t)
(room)
(format t "~%Making mnist-refine-dataset~%")
(defparameter mnist-refine-dataset (make-refine-dataset mnist-forest mnist-datamatrix))
(format t "Making mnist-refine-test~%")
(defparameter mnist-refine-test (make-refine-dataset mnist-forest mnist-datamatrix-test))
(format t "Re-learning~%")
(defparameter mnist-refine-learner (make-refine-learner mnist-forest))
(train-refine-learner-process mnist-refine-learner mnist-refine-dataset mnist-target
mnist-refine-test mnist-target-test)
(test-refine-learner mnist-refine-learner mnist-refine-test mnist-target-test)
(format t "Pruning. leaf-size: ~A" (length (collect-leaf-parent mnist-forest)))
(pruning! mnist-forest mnist-refine-learner 0.5)
(format t " -> ~A ~%" (length (collect-leaf-parent mnist-forest))))
;;; n-fold cross-validation
(defparameter n-fold 5)
(cross-validation-forest-with-refine-learner
n-fold mnist-n-class mnist-datamatrix mnist-target
:n-tree 100 :bagging-ratio 0.1 :max-depth 10 :n-trial 28 :gamma 10 :min-region-samples 5)
| null | https://raw.githubusercontent.com/masatoi/cl-random-forest/71c8da62bdd5656866b966e0ea85fee1c82c47fb/example/classification/mnist.lisp | lisp | mode : lisp -*-
Load Dataset ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
/~cjlin/libsvmtools/datasets/multiclass.html#mnist
Make Decision Tree ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Prediction
Testing with training data
Testing with test data
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
Enable/Disable parallelizaion
Prediction
Testing with test data
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
Make a prediction
; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ; ;
Re-learning refine learner
n-fold cross-validation |
set dynamic - space - size > = 2500
(defpackage :cl-random-forest/example/classification/mnist
(:use #:cl
#:cl-random-forest)
(:import-from #:cl-random-forest/src/utils
#:read-data))
(in-package :cl-random-forest/example/classification/mnist)
MNIST data
(defparameter dir (asdf:system-relative-pathname :cl-random-forest "dataset/"))
(defparameter mnist-dim 784)
(defparameter mnist-n-class 10)
(defvar mnist-datamatrix)
(defvar mnist-target)
(defvar mnist-datamatrix-test)
(defvar mnist-target-test)
(defun get-mnist-dataset ()
(ensure-directories-exist dir)
(let ((base-url "/~cjlin/libsvmtools/datasets/multiclass"))
(flet ((download-file (filename)
(uiop:run-program
(format nil "cd ~A ; [ -e ~A ] || wget ~A/~A" dir filename base-url filename)))
(expand-file (filename)
(uiop:run-program (format nil "cd ~A ; [ -e ~A ] || bunzip2 ~A"
dir (subseq filename 0 (- (length filename) 4)) filename))))
(format t "Downloading mnist.scale.bz2~%")
(download-file "mnist.scale.bz2")
(format t "Expanding mnist.scale.bz2~%")
(expand-file "mnist.scale.bz2")
(format t "Downloading mnist.scale.t.bz2~%")
(download-file "mnist.scale.t.bz2")
(format t "Expanding mnist.scale.t.bz2~%")
(expand-file "mnist.scale.t.bz2"))))
(defun read-mnist-dataset ()
(format t "Reading training data~%")
(multiple-value-bind (datamat target)
(read-data (merge-pathnames "mnist.scale" dir) mnist-dim)
(setf mnist-datamatrix datamat
mnist-target target))
(format t "Reading test data~%")
(multiple-value-bind (datamat target)
(read-data (merge-pathnames "mnist.scale.t" dir) mnist-dim)
(setf mnist-datamatrix-test datamat
mnist-target-test target))
Add 1 to labels because the labels of this dataset begin from 0
(loop for i from 0 below (length mnist-target) do
(incf (aref mnist-target i)))
(loop for i from 0 below (length mnist-target-test) do
(incf (aref mnist-target-test i))))
(get-mnist-dataset)
(read-mnist-dataset)
(defparameter mnist-dtree
(make-dtree mnist-n-class mnist-datamatrix mnist-target
:max-depth 15 :n-trial 28 :min-region-samples 5))
= > 5 ( correct )
(test-dtree mnist-dtree mnist-datamatrix mnist-target)
Accuracy : 90.37333 % , Correct : 54224 , Total : 60000
(test-dtree mnist-dtree mnist-datamatrix-test mnist-target-test)
Accuracy : 81.52 % , Correct : 8152 , Total : 10000
(setf lparallel:*kernel* (lparallel:make-kernel 4))
(setf lparallel:*kernel* nil)
6.079 seconds ( 1 core ) , 2.116 seconds ( 4 core )
(defparameter mnist-forest
(make-forest mnist-n-class mnist-datamatrix mnist-target
:n-tree 500 :bagging-ratio 0.1 :max-depth 10 :n-trial 10 :min-region-samples 5))
= > 5 ( correct )
4.786 seconds , Accuracy : 93.38 %
(test-forest mnist-forest mnist-datamatrix-test mnist-target-test)
42.717 seconds ( 1 core ) , 13.24 seconds ( 4 core )
(defparameter mnist-forest-tall
(make-forest mnist-n-class mnist-datamatrix mnist-target
:n-tree 100 :bagging-ratio 1.0 :max-depth 15 :n-trial 28 :min-region-samples 5))
2.023 seconds , Accuracy : 96.62 %
(test-forest mnist-forest-tall mnist-datamatrix-test mnist-target-test)
Generate sparse data from Random Forest
6.255 seconds ( 1 core ) , 1.809 seconds ( 4 core )
(defparameter mnist-refine-dataset
(make-refine-dataset mnist-forest mnist-datamatrix))
0.995 seconds ( 1 core ) , 0.322 seconds ( 4 core )
(defparameter mnist-refine-test
(make-refine-dataset mnist-forest mnist-datamatrix-test))
(defparameter mnist-refine-learner (make-refine-learner mnist-forest))
4.347 seconds ( 1 core ) , 2.281 seconds ( 4 core ) , Accuracy : 98.259 %
(train-refine-learner-process mnist-refine-learner mnist-refine-dataset mnist-target
mnist-refine-test mnist-target-test)
(test-refine-learner mnist-refine-learner mnist-refine-test mnist-target-test)
5.859 seconds ( 1 core ) , 4.090 seconds ( 4 core ) , Accuracy : 98.29 %
(loop repeat 5 do
(train-refine-learner mnist-refine-learner mnist-refine-dataset mnist-target)
(test-refine-learner mnist-refine-learner mnist-refine-test mnist-target-test))
(predict-refine-learner mnist-forest mnist-refine-learner mnist-datamatrix-test 0)
= > 98008
0.328 seconds
= > 93228
(defparameter mnist-refine-dataset (make-refine-dataset mnist-forest mnist-datamatrix))
(defparameter mnist-refine-test (make-refine-dataset mnist-forest mnist-datamatrix-test))
(defparameter mnist-refine-learner (make-refine-learner mnist-forest))
(time
(loop repeat 10 do
(train-refine-learner mnist-refine-learner mnist-refine-dataset mnist-target)
(test-refine-learner mnist-refine-learner mnist-refine-test mnist-target-test)))
Accuracy : Accuracy : 98.27 %
(loop repeat 10 do
(sb-ext:gc :full t)
(room)
(format t "~%Making mnist-refine-dataset~%")
(defparameter mnist-refine-dataset (make-refine-dataset mnist-forest mnist-datamatrix))
(format t "Making mnist-refine-test~%")
(defparameter mnist-refine-test (make-refine-dataset mnist-forest mnist-datamatrix-test))
(format t "Re-learning~%")
(defparameter mnist-refine-learner (make-refine-learner mnist-forest))
(train-refine-learner-process mnist-refine-learner mnist-refine-dataset mnist-target
mnist-refine-test mnist-target-test)
(test-refine-learner mnist-refine-learner mnist-refine-test mnist-target-test)
(format t "Pruning. leaf-size: ~A" (length (collect-leaf-parent mnist-forest)))
(pruning! mnist-forest mnist-refine-learner 0.5)
(format t " -> ~A ~%" (length (collect-leaf-parent mnist-forest))))
(defparameter n-fold 5)
(cross-validation-forest-with-refine-learner
n-fold mnist-n-class mnist-datamatrix mnist-target
:n-tree 100 :bagging-ratio 0.1 :max-depth 10 :n-trial 28 :gamma 10 :min-region-samples 5)
|
3553c639fa816b9105a9c363100ec5bb1934d8b023b7421a15ec327b308ce4e5 | racket/rackunit | tl.rkt | #lang racket/base
(require rackunit)
;; test to make sure that the various check functions
;; return what they are promised to at the top-level
;; make drdr notice when a check prints something.
(current-output-port (current-error-port))
(check-equal? (check + 1 2) (void))
(check-equal? (check-eq? 1 1) (void))
(check-equal? (check-not-eq? #f #t) (void))
(check-equal? (check-eqv? (expt 2 100) (expt 2 100)) (void))
(check-equal? (check-not-eqv? (expt 2 100) 1) (void))
(check-equal? (check-equal? (list 1 2) (list 1 2)) (void))
(check-equal? (check-not-equal? (list 1 2) (list 2 1)) (void))
(check-equal? (check-pred not #f) (void))
(check-equal? (check-= 1.1 1.2 0.5) (void))
(check-equal? (check-true #t) (void))
(check-equal? (check-false #f) (void))
(check-equal? (check-not-false 3) (void))
(check-equal? (check-exn #rx"car" (λ () (car 1))) (void))
(check-equal? (check-not-exn (λ () 1)) (void))
(check-equal? (check-regexp-match #rx"a*b" "aaaaaaab") (void))
| null | https://raw.githubusercontent.com/racket/rackunit/f94364891f201f90c055adb1521e5f038ce75411/rackunit-test/tests/rackunit/tl.rkt | racket | test to make sure that the various check functions
return what they are promised to at the top-level
make drdr notice when a check prints something. | #lang racket/base
(require rackunit)
(current-output-port (current-error-port))
(check-equal? (check + 1 2) (void))
(check-equal? (check-eq? 1 1) (void))
(check-equal? (check-not-eq? #f #t) (void))
(check-equal? (check-eqv? (expt 2 100) (expt 2 100)) (void))
(check-equal? (check-not-eqv? (expt 2 100) 1) (void))
(check-equal? (check-equal? (list 1 2) (list 1 2)) (void))
(check-equal? (check-not-equal? (list 1 2) (list 2 1)) (void))
(check-equal? (check-pred not #f) (void))
(check-equal? (check-= 1.1 1.2 0.5) (void))
(check-equal? (check-true #t) (void))
(check-equal? (check-false #f) (void))
(check-equal? (check-not-false 3) (void))
(check-equal? (check-exn #rx"car" (λ () (car 1))) (void))
(check-equal? (check-not-exn (λ () 1)) (void))
(check-equal? (check-regexp-match #rx"a*b" "aaaaaaab") (void))
|
033988f980b8e3db8987c5155890d8743b6f221bd2cc4ddf7cda50186b7acc8f | BillHallahan/G2 | FloodConsts.hs | -- Tries to eliminate a symbolic variable by replacing it with a constant.
module G2.QuasiQuotes.FloodConsts ( floodConstantsChecking
, floodConstants
, floodConstant) where
import G2.Execution.PrimitiveEval
import G2.Language
import qualified G2.Language.ExprEnv as E
import qualified G2.Language.PathConds as PC
-- | Tries to eliminate a symbolic variable by replacing them with constants.
Returns Maybe a State , if the variables are replacable , and do n't make the
-- path constraints obviously false
floodConstantsChecking :: [(Name, Expr)] -> State t -> Maybe (State t)
floodConstantsChecking ne s =
case floodConstants ne s of
Just s' ->
if all (pathCondMaybeSatisfiable (type_env s') (known_values s'))
(PC.toList $ path_conds s')
then Just s'
else Nothing
Nothing -> Nothing
-- | Tries to eliminate a symbolic variable by replacing them with constants.
Returns Maybe a State , if the variables are replacable
floodConstants :: [(Name, Expr)] -> State t -> Maybe (State t)
floodConstants ne s = foldr (\(n, e) s' -> floodConstant n e =<< s') (Just s) ne
floodConstant :: Name -> Expr -> State t -> Maybe (State t)
floodConstant n e s
| E.isSymbolic n (expr_env s) =
case E.lookup n (expr_env s) of
Just e' ->
let
i = Id n $ typeOf e'
r_pc = replaceASTs (Var i) e (path_conds s)
in
Just (s { expr_env = E.insert n e (expr_env s)
, path_conds = r_pc })
_ -> Nothing
| otherwise =
case E.lookup n (expr_env s) of
Just e'
| Data d:es <- unApp e
, Data d':es' <- unApp e'
, dcName d == dcName d' -> floodConstantList s (zip es es')
_ -> Nothing
floodConstantList :: State t -> [(Expr, Expr)] -> Maybe (State t)
floodConstantList s ((e1, e2):xs)
| Var (Id n _) <- e2 =
(\s' -> floodConstantList s' xs) =<< floodConstant n e1 s
| e1 == e2 = floodConstantList s xs
floodConstantList s [] = Just s
floodConstantList _ _ = Nothing
Attempts to determine if a PathCond is satisfiable . A return value of False
means the PathCond is definitely unsatisfiable . A return value of True means
the PathCond may or may not be satisfiable .
pathCondMaybeSatisfiable :: TypeEnv -> KnownValues -> PathCond -> Bool
pathCondMaybeSatisfiable _ _ (AltCond l1 (Lit l2) b) = (l1 == l2) == b
pathCondMaybeSatisfiable _ _ (AltCond _ _ _) = True
pathCondMaybeSatisfiable tenv kv (ExtCond e b) =
let
r = evalPrims tenv kv e
tr = mkBool kv True
fal = mkBool kv False
in
if (r == tr && not b) || (r == fal && b) then False else True
| null | https://raw.githubusercontent.com/BillHallahan/G2/43e7a9f1e8f5131d91e28b54ce669e5e6782412b/src/G2/QuasiQuotes/FloodConsts.hs | haskell | Tries to eliminate a symbolic variable by replacing it with a constant.
| Tries to eliminate a symbolic variable by replacing them with constants.
path constraints obviously false
| Tries to eliminate a symbolic variable by replacing them with constants. |
module G2.QuasiQuotes.FloodConsts ( floodConstantsChecking
, floodConstants
, floodConstant) where
import G2.Execution.PrimitiveEval
import G2.Language
import qualified G2.Language.ExprEnv as E
import qualified G2.Language.PathConds as PC
Returns Maybe a State , if the variables are replacable , and do n't make the
floodConstantsChecking :: [(Name, Expr)] -> State t -> Maybe (State t)
floodConstantsChecking ne s =
case floodConstants ne s of
Just s' ->
if all (pathCondMaybeSatisfiable (type_env s') (known_values s'))
(PC.toList $ path_conds s')
then Just s'
else Nothing
Nothing -> Nothing
Returns Maybe a State , if the variables are replacable
floodConstants :: [(Name, Expr)] -> State t -> Maybe (State t)
floodConstants ne s = foldr (\(n, e) s' -> floodConstant n e =<< s') (Just s) ne
floodConstant :: Name -> Expr -> State t -> Maybe (State t)
floodConstant n e s
| E.isSymbolic n (expr_env s) =
case E.lookup n (expr_env s) of
Just e' ->
let
i = Id n $ typeOf e'
r_pc = replaceASTs (Var i) e (path_conds s)
in
Just (s { expr_env = E.insert n e (expr_env s)
, path_conds = r_pc })
_ -> Nothing
| otherwise =
case E.lookup n (expr_env s) of
Just e'
| Data d:es <- unApp e
, Data d':es' <- unApp e'
, dcName d == dcName d' -> floodConstantList s (zip es es')
_ -> Nothing
floodConstantList :: State t -> [(Expr, Expr)] -> Maybe (State t)
floodConstantList s ((e1, e2):xs)
| Var (Id n _) <- e2 =
(\s' -> floodConstantList s' xs) =<< floodConstant n e1 s
| e1 == e2 = floodConstantList s xs
floodConstantList s [] = Just s
floodConstantList _ _ = Nothing
Attempts to determine if a PathCond is satisfiable . A return value of False
means the PathCond is definitely unsatisfiable . A return value of True means
the PathCond may or may not be satisfiable .
pathCondMaybeSatisfiable :: TypeEnv -> KnownValues -> PathCond -> Bool
pathCondMaybeSatisfiable _ _ (AltCond l1 (Lit l2) b) = (l1 == l2) == b
pathCondMaybeSatisfiable _ _ (AltCond _ _ _) = True
pathCondMaybeSatisfiable tenv kv (ExtCond e b) =
let
r = evalPrims tenv kv e
tr = mkBool kv True
fal = mkBool kv False
in
if (r == tr && not b) || (r == fal && b) then False else True
|
5532467af8118fa57fd70b8151d78d4e63e6c9a0715bcd26a3b9d0da037b69dd | futurice/haskell-mega-repo | Error.hs | {-# LANGUAGE OverloadedStrings #-}
-- |
Copyright : ( c ) 2015 Futurice Oy
-- License : BSD3
Maintainer : < >
module PlanMill.Types.Error (
PlanMillError(..),
PlanMillErrorResponse(..),
) where
import PlanMill.Internal.Prelude
-- | TODO: it should be an 'Int'
type Code = String
data PlanMillError
= DecodeError String String -- ^ Invalid response
| ErrorResponse String PlanMillErrorResponse -- ^ Error response
deriving (Show, Typeable)
instance Exception PlanMillError
data PlanMillErrorResponse = PlanMillErrorResponse Code String
deriving (Show, Typeable)
instance FromJSON PlanMillErrorResponse where
parseJSON = withObject "Error" $ \obj ->
PlanMillErrorResponse
<$> obj .: "code"
<*> obj .: "message"
| null | https://raw.githubusercontent.com/futurice/haskell-mega-repo/2647723f12f5435e2edc373f6738386a9668f603/planmill-client/src/PlanMill/Types/Error.hs | haskell | # LANGUAGE OverloadedStrings #
|
License : BSD3
| TODO: it should be an 'Int'
^ Invalid response
^ Error response | Copyright : ( c ) 2015 Futurice Oy
Maintainer : < >
module PlanMill.Types.Error (
PlanMillError(..),
PlanMillErrorResponse(..),
) where
import PlanMill.Internal.Prelude
type Code = String
data PlanMillError
deriving (Show, Typeable)
instance Exception PlanMillError
data PlanMillErrorResponse = PlanMillErrorResponse Code String
deriving (Show, Typeable)
instance FromJSON PlanMillErrorResponse where
parseJSON = withObject "Error" $ \obj ->
PlanMillErrorResponse
<$> obj .: "code"
<*> obj .: "message"
|
0f29962bd2b9f3b9fe09add529b78a5d195ec49a84ff6108d5eebe80cd8728fb | racket/drracket | syncheck-drracket-button.rkt | #lang racket/base
(require racket/class
string-constants/string-constant
images/compile-time
(for-syntax racket/base images/icons/tool images/icons/style))
(provide syncheck-drracket-button
syncheck-bitmap
syncheck-small-bitmap
syncheck:button-callback)
(define-local-member-name syncheck:button-callback)
(define syncheck-bitmap
(compiled-bitmap (check-syntax-icon #:height (toolbar-icon-height))))
(define syncheck-small-bitmap
(compiled-bitmap (small-check-syntax-icon #:height (toolbar-icon-height))))
(define syncheck-drracket-button
(list
(string-constant check-syntax)
syncheck-bitmap
(λ (drs-frame) (send drs-frame syncheck:button-callback))))
| null | https://raw.githubusercontent.com/racket/drracket/2d7c2cded99e630a69f05fb135d1bf7543096a23/drracket/drracket/syncheck-drracket-button.rkt | racket | #lang racket/base
(require racket/class
string-constants/string-constant
images/compile-time
(for-syntax racket/base images/icons/tool images/icons/style))
(provide syncheck-drracket-button
syncheck-bitmap
syncheck-small-bitmap
syncheck:button-callback)
(define-local-member-name syncheck:button-callback)
(define syncheck-bitmap
(compiled-bitmap (check-syntax-icon #:height (toolbar-icon-height))))
(define syncheck-small-bitmap
(compiled-bitmap (small-check-syntax-icon #:height (toolbar-icon-height))))
(define syncheck-drracket-button
(list
(string-constant check-syntax)
syncheck-bitmap
(λ (drs-frame) (send drs-frame syncheck:button-callback))))
|
|
efb8e971bae7debd3c6b0def4803d889a8e27f48b05617641568648db947b644 | JoseFilipeFerreira/haskHell3D | Utils.hs | |
Module : Utils
Description : Module containing all Utils for haskHell 3D
Module : Utils
Description : Module containing all Utils for haskHell 3D
-}
module Utils where
import Constantes
import Data_structures
import Graphics.Gloss.Geometry.Line
import Graphics.Gloss.Data.Color
import Graphics.Gloss.Data.Vector
import Data.Maybe
-- | Calculate the area that is visible to the player
viewBox :: [Coor]
viewBox = [pn1, pn2, pf2, pf1, pn1]
where
pn1 = (nearPlane, nearPlane * tan (grauToRad $ -viewAngle/2))
pn2 = (nearPlane, nearPlane * tan (grauToRad $ viewAngle/2))
pf1 = (farPlane , farPlane * tan (grauToRad $ -viewAngle/2))
pf2 = (farPlane , farPlane * tan (grauToRad $ viewAngle/2))
-- | Calculate the point a given vector intersects a given Wall. Returns Nothing if it doesn't intercept.
wallIntercept :: Vector -> Wall -> Maybe Coor
wallIntercept v w = intersectSegSeg (0,0) v (p1W w) (p2W w)
-- | Calculate the point a given vector intersects a given Enemy. Returns Nothing if it doesn't intercept.
enemyIntercept :: Vector -> Enemy -> Bool
enemyIntercept v e = isJust $ intersectSegSeg (0,0) v (p1E e) (p2E e)
-- | Calculate the distance to a given Wall
distWall:: Wall -> Float
distWall = minimum . (map (distCoor (0,0))) . (flip getWallPoints precisionWallDist)
-- | Calculate the distance to a given Enemy
distEnemy:: Enemy -> Float
distEnemy = minimum . (map (distCoor (0,0))) . (flip getEnemyPoints precisionEnemyDist)
-- | Checks if a wall is visible from the perspective of the player
isWallVisible:: Mapa -> Wall -> Bool
isWallVisible walls w = any (id) $ map (isPointVisible filteredWalls) wallPoints
where
wallPoints = getWallPoints w precisionWallHidden
filteredWalls = filter (/=w) walls
-- | Check if a wall is Fully visible
isWallFullyVisible:: Mapa -> [Enemy] -> Wall -> Bool
isWallFullyVisible walls en w = (all (id) $ map (isPointVisible filteredWalls) wallPoints)
&& (all (id) $ map (isPointVisibleEnemy en) wallPoints)
where
wallPoints = getWallPoints w precisionWallHidden
filteredWalls = filter (/=w) walls
-- | Checks if a enemy is visible from the perspective of the player
isEnemyVisible:: Mapa -> Enemy -> Bool
isEnemyVisible walls e = any (id) $ map (isPointVisible walls) $ getEnemyPoints e precisionWallHidden
-- | Check if enemy is completely visible
isEnemyFullyVisible:: Mapa -> Enemy -> Bool
isEnemyFullyVisible walls e = all (id) $ map (isPointVisible walls) $ getEnemyPoints e precisionWallHidden
-- | Checks if a point is visible
isPointVisible:: [Wall] -> Coor -> Bool
isPointVisible w p = not $ any isJust $ map (wallIntercept p) w
-- | Checks if a given point is covered by any enemy
isPointVisibleEnemy:: [Enemy] -> Coor -> Bool
isPointVisibleEnemy e p = not $ any (id) $ map (enemyIntercept p) e
-- | Get N points along a given Wall
getWallPoints:: Wall -> Float -> [Coor]
getWallPoints w nP = getLinePoints (p1W w) (p2W w) nP
-- | Get N points along a given Enemy
getEnemyPoints:: Enemy -> Float -> [Coor]
getEnemyPoints e nP = getLinePoints (p1E e) (p2E e) nP
| Get N points between two coordinates
getLinePoints:: Coor -> Coor -> Float -> [Coor]
getLinePoints p1 p2 nP = map (calcVec p1 vec step) [0.. nPd]
where
nPd = nP * (distCoor p1 p2)
step = (distCoor p1 p2) / nPd
vec = unitVetor p1 p2
calcVec :: Coor -> Coor -> Float -> Float -> Coor
calcVec (x, y) (vx, vy) f n = (x + vx * f * n, y + vy * f * n)
unitVetor:: Coor -> Coor -> Vector
unitVetor (x1, y1) (x2, y2) = normalizeV (x2 - x1, y2 - y1)
| Check if a point is outside the viewBox
pointOutside::Coor -> Bool
pointOutside (x, y) = x >= farPlane
|| x <= nearPlane
|| (y <= decl1 * x + offset1)
|| (y >= decl2 * x + offset2)
where
decl1 = decl (viewBox!!3) (viewBox!!0)
decl2 = decl (viewBox!!1) (viewBox!!2)
offset1 = offset (viewBox!!3) decl1
offset2 = offset (viewBox!!1) decl2
decl:: Coor -> Coor -> Float
decl (x1, y1) (x2, y2) = (y2 - y1) / (x2 - x1)
offset:: Coor -> Float -> Float
offset (x, y) m = y - m * x
| Calculate the distance between two points
distCoor:: Coor -> Coor -> Float
distCoor (x0, y0) (x1, y1) = sqrt((x1 - x0)^2 + (y1 - y0)^2)
-- | Sum a list of Vectors
sumVec:: [Vector] -> Vector
sumVec [] = (0,0)
sumVec ((x,y):t) = (x + tx, y + ty)
where
(tx, ty) = sumVec t
-- | Rotates a given point by the given degrees
rotatePoint:: Float -> Coor -> Coor
rotatePoint angDegre (x,y) = ((x * cos ang - y * sin ang), (y * cos ang + x * sin ang))
where
ang = grauToRad angDegre
-- | Move a given point by a given vector
movePoint:: Vector -> Coor -> Coor
movePoint (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
-- | Convert Angular vector(?) to cartesian vector (?)
vetAngToCoor:: (Float, Float) -> Vector
vetAngToCoor (a,n) = (x, y)
where
x = n * cos (grauToRad a)
y = - n * sin (grauToRad a)
-- | Convert degrees to rad
grauToRad:: Float -> Float
grauToRad x = x * pi / 180
-- | get a contrasting colour
contrastColor:: Color -> Color
contrastColor c | c == black = white
| otherwise = black
| null | https://raw.githubusercontent.com/JoseFilipeFerreira/haskHell3D/de47a9462b81c5c9e7e1a527de4893450c8ac21e/src/Utils.hs | haskell | | Calculate the area that is visible to the player
| Calculate the point a given vector intersects a given Wall. Returns Nothing if it doesn't intercept.
| Calculate the point a given vector intersects a given Enemy. Returns Nothing if it doesn't intercept.
| Calculate the distance to a given Wall
| Calculate the distance to a given Enemy
| Checks if a wall is visible from the perspective of the player
| Check if a wall is Fully visible
| Checks if a enemy is visible from the perspective of the player
| Check if enemy is completely visible
| Checks if a point is visible
| Checks if a given point is covered by any enemy
| Get N points along a given Wall
| Get N points along a given Enemy
| Sum a list of Vectors
| Rotates a given point by the given degrees
| Move a given point by a given vector
| Convert Angular vector(?) to cartesian vector (?)
| Convert degrees to rad
| get a contrasting colour | |
Module : Utils
Description : Module containing all Utils for haskHell 3D
Module : Utils
Description : Module containing all Utils for haskHell 3D
-}
module Utils where
import Constantes
import Data_structures
import Graphics.Gloss.Geometry.Line
import Graphics.Gloss.Data.Color
import Graphics.Gloss.Data.Vector
import Data.Maybe
viewBox :: [Coor]
viewBox = [pn1, pn2, pf2, pf1, pn1]
where
pn1 = (nearPlane, nearPlane * tan (grauToRad $ -viewAngle/2))
pn2 = (nearPlane, nearPlane * tan (grauToRad $ viewAngle/2))
pf1 = (farPlane , farPlane * tan (grauToRad $ -viewAngle/2))
pf2 = (farPlane , farPlane * tan (grauToRad $ viewAngle/2))
wallIntercept :: Vector -> Wall -> Maybe Coor
wallIntercept v w = intersectSegSeg (0,0) v (p1W w) (p2W w)
enemyIntercept :: Vector -> Enemy -> Bool
enemyIntercept v e = isJust $ intersectSegSeg (0,0) v (p1E e) (p2E e)
distWall:: Wall -> Float
distWall = minimum . (map (distCoor (0,0))) . (flip getWallPoints precisionWallDist)
distEnemy:: Enemy -> Float
distEnemy = minimum . (map (distCoor (0,0))) . (flip getEnemyPoints precisionEnemyDist)
isWallVisible:: Mapa -> Wall -> Bool
isWallVisible walls w = any (id) $ map (isPointVisible filteredWalls) wallPoints
where
wallPoints = getWallPoints w precisionWallHidden
filteredWalls = filter (/=w) walls
isWallFullyVisible:: Mapa -> [Enemy] -> Wall -> Bool
isWallFullyVisible walls en w = (all (id) $ map (isPointVisible filteredWalls) wallPoints)
&& (all (id) $ map (isPointVisibleEnemy en) wallPoints)
where
wallPoints = getWallPoints w precisionWallHidden
filteredWalls = filter (/=w) walls
isEnemyVisible:: Mapa -> Enemy -> Bool
isEnemyVisible walls e = any (id) $ map (isPointVisible walls) $ getEnemyPoints e precisionWallHidden
isEnemyFullyVisible:: Mapa -> Enemy -> Bool
isEnemyFullyVisible walls e = all (id) $ map (isPointVisible walls) $ getEnemyPoints e precisionWallHidden
isPointVisible:: [Wall] -> Coor -> Bool
isPointVisible w p = not $ any isJust $ map (wallIntercept p) w
isPointVisibleEnemy:: [Enemy] -> Coor -> Bool
isPointVisibleEnemy e p = not $ any (id) $ map (enemyIntercept p) e
getWallPoints:: Wall -> Float -> [Coor]
getWallPoints w nP = getLinePoints (p1W w) (p2W w) nP
getEnemyPoints:: Enemy -> Float -> [Coor]
getEnemyPoints e nP = getLinePoints (p1E e) (p2E e) nP
| Get N points between two coordinates
getLinePoints:: Coor -> Coor -> Float -> [Coor]
getLinePoints p1 p2 nP = map (calcVec p1 vec step) [0.. nPd]
where
nPd = nP * (distCoor p1 p2)
step = (distCoor p1 p2) / nPd
vec = unitVetor p1 p2
calcVec :: Coor -> Coor -> Float -> Float -> Coor
calcVec (x, y) (vx, vy) f n = (x + vx * f * n, y + vy * f * n)
unitVetor:: Coor -> Coor -> Vector
unitVetor (x1, y1) (x2, y2) = normalizeV (x2 - x1, y2 - y1)
| Check if a point is outside the viewBox
pointOutside::Coor -> Bool
pointOutside (x, y) = x >= farPlane
|| x <= nearPlane
|| (y <= decl1 * x + offset1)
|| (y >= decl2 * x + offset2)
where
decl1 = decl (viewBox!!3) (viewBox!!0)
decl2 = decl (viewBox!!1) (viewBox!!2)
offset1 = offset (viewBox!!3) decl1
offset2 = offset (viewBox!!1) decl2
decl:: Coor -> Coor -> Float
decl (x1, y1) (x2, y2) = (y2 - y1) / (x2 - x1)
offset:: Coor -> Float -> Float
offset (x, y) m = y - m * x
| Calculate the distance between two points
distCoor:: Coor -> Coor -> Float
distCoor (x0, y0) (x1, y1) = sqrt((x1 - x0)^2 + (y1 - y0)^2)
sumVec:: [Vector] -> Vector
sumVec [] = (0,0)
sumVec ((x,y):t) = (x + tx, y + ty)
where
(tx, ty) = sumVec t
rotatePoint:: Float -> Coor -> Coor
rotatePoint angDegre (x,y) = ((x * cos ang - y * sin ang), (y * cos ang + x * sin ang))
where
ang = grauToRad angDegre
movePoint:: Vector -> Coor -> Coor
movePoint (x1, y1) (x2, y2) = (x1 + x2, y1 + y2)
vetAngToCoor:: (Float, Float) -> Vector
vetAngToCoor (a,n) = (x, y)
where
x = n * cos (grauToRad a)
y = - n * sin (grauToRad a)
grauToRad:: Float -> Float
grauToRad x = x * pi / 180
contrastColor:: Color -> Color
contrastColor c | c == black = white
| otherwise = black
|
13de28944be0da2c8bff78c161fc668282bdd78bf3b09f01198ca001ec029914 | promesante/hn-clj-pedestal-re-frame | core.clj | (ns hn-clj-pedestal-re-frame.core)
| null | https://raw.githubusercontent.com/promesante/hn-clj-pedestal-re-frame/76b62dbbcc1c803c8e233809796eda75893cf7c9/src/clj/hn_clj_pedestal_re_frame/core.clj | clojure | (ns hn-clj-pedestal-re-frame.core)
|
|
1231f67a429c0fe3aad1ac6cd773d4953b3609f501f3587ee163ef9194864fb9 | MaskRay/99-problems-ocaml | 11.ml | type 'a elem = One of 'a | Many of int * 'a
let ($) f g x = f (g x)
let rec encode =
let rec go c acc = function
| [] -> []
| [a] -> (c+1,a)::acc
| a :: (b :: _ as xs) -> if a = b then go (c+1) acc xs else go 0 ((c+1,a)::acc) xs
in List.rev $ go 0 []
let encode_modified =
List.map (function
| (1,x) -> One x
| (c,x) -> Many (c,x)) $ encode
| null | https://raw.githubusercontent.com/MaskRay/99-problems-ocaml/652604f13ba7a73eee06d359b4db549b49ec9bb3/11-20/11.ml | ocaml | type 'a elem = One of 'a | Many of int * 'a
let ($) f g x = f (g x)
let rec encode =
let rec go c acc = function
| [] -> []
| [a] -> (c+1,a)::acc
| a :: (b :: _ as xs) -> if a = b then go (c+1) acc xs else go 0 ((c+1,a)::acc) xs
in List.rev $ go 0 []
let encode_modified =
List.map (function
| (1,x) -> One x
| (c,x) -> Many (c,x)) $ encode
|
|
50cdc1b2732ce2ecf99e40c043a151fb4acc862e78243cacd61c5321bc2881ac | parapluu/Concuerror | depend_4_screen.erl | -module(depend_4_screen).
-export([depend_4_screen/0]).
-export([scenarios/0]).
scenarios() -> [{?MODULE, inf, dpor}].
depend_4_screen() ->
ets:new(table, [public, named_table]),
ets:insert(table, {x, 0}),
ets:insert(table, {y, 0}),
ets:insert(table, {z, 0}),
P = self(),
P1 = spawn(fun() -> ets:insert(table, {z, 1}), get_and_send( P) end),
P2 = spawn(fun() -> ets:insert(table, {x, 1}), get_and_send(P1) end),
P3 = spawn(fun() -> ets:insert(table, {y, 1}), get_and_send(P2) end),
P4 = spawn(fun() ->
[{x, X}] = ets:lookup(table, x),
Val =
case X of
1 ->
[{y, Y}] = ets:lookup(table, y),
case Y of
1 -> [{x,1},{y,1}|ets:lookup(table, z)];
_ -> [{x,1},{y,0}]
end;
_ -> [{x, X}]
end,
ets:insert(table, {p4, Val}),
get_and_send(P3)
end),
P5 = spawn(fun() ->
[{y, Y}] = ets:lookup(table, y),
Val =
case Y of
1 -> [{y,1}|ets:lookup(table, z)];
_ -> [{y,0}]
end,
ets:insert(table, {p5, Val}),
get_and_send(P4)
end),
P6 = spawn(fun() -> ets:insert(table, {x, 2}), get_and_send(P5) end),
P6 ! ok,
receive
ok ->
A = ets:lookup(table, x),
B = ets:lookup(table, p5),
C = ets:lookup(table, p4),
throw({A,B,C})
end.
get_and_send(P) ->
receive
ok -> P ! ok
end.
| null | https://raw.githubusercontent.com/parapluu/Concuerror/152a5ccee0b6e97d8c3329c2167166435329d261/tests/suites/dpor_tests/src/depend_4_screen.erl | erlang | -module(depend_4_screen).
-export([depend_4_screen/0]).
-export([scenarios/0]).
scenarios() -> [{?MODULE, inf, dpor}].
depend_4_screen() ->
ets:new(table, [public, named_table]),
ets:insert(table, {x, 0}),
ets:insert(table, {y, 0}),
ets:insert(table, {z, 0}),
P = self(),
P1 = spawn(fun() -> ets:insert(table, {z, 1}), get_and_send( P) end),
P2 = spawn(fun() -> ets:insert(table, {x, 1}), get_and_send(P1) end),
P3 = spawn(fun() -> ets:insert(table, {y, 1}), get_and_send(P2) end),
P4 = spawn(fun() ->
[{x, X}] = ets:lookup(table, x),
Val =
case X of
1 ->
[{y, Y}] = ets:lookup(table, y),
case Y of
1 -> [{x,1},{y,1}|ets:lookup(table, z)];
_ -> [{x,1},{y,0}]
end;
_ -> [{x, X}]
end,
ets:insert(table, {p4, Val}),
get_and_send(P3)
end),
P5 = spawn(fun() ->
[{y, Y}] = ets:lookup(table, y),
Val =
case Y of
1 -> [{y,1}|ets:lookup(table, z)];
_ -> [{y,0}]
end,
ets:insert(table, {p5, Val}),
get_and_send(P4)
end),
P6 = spawn(fun() -> ets:insert(table, {x, 2}), get_and_send(P5) end),
P6 ! ok,
receive
ok ->
A = ets:lookup(table, x),
B = ets:lookup(table, p5),
C = ets:lookup(table, p4),
throw({A,B,C})
end.
get_and_send(P) ->
receive
ok -> P ! ok
end.
|
|
c96ecf4eadcee83e3b8d3e8b939131f84c268558d78ef38861a5bb8cabd8b761 | startalkIM/ejabberd | ejabberd_hooks.erl | %%%----------------------------------------------------------------------
File : ejabberd_hooks.erl
Author : < >
%%% Purpose : Manage hooks
Created : 8 Aug 2004 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
%%% License, or (at your option) any later version.
%%%
%%% This program is distributed in the hope that it will be useful,
%%% but WITHOUT ANY WARRANTY; without even the implied warranty of
%%% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
%%%
%%%----------------------------------------------------------------------
-module(ejabberd_hooks).
-author('').
-behaviour(gen_server).
%% External exports
-export([start_link/0,
add/3,
add/4,
add/5,
add_dist/5,
add_dist/6,
delete/3,
delete/4,
delete/5,
delete_dist/5,
delete_dist/6,
run/2,
run/3,
run_fold/3,
run_fold/4,
get_handlers/2]).
-export([delete_all_hooks/0]).
%% gen_server callbacks
-export([init/1,
handle_call/3,
handle_cast/2,
code_change/3,
handle_info/2,
terminate/2]).
-include("logger.hrl").
-record(state, {}).
-type local_hook() :: { Seq :: integer(), Module :: atom(), Function :: atom()}.
-type distributed_hook() :: { Seq :: integer(), Node :: atom(), Module :: atom(), Function :: atom()}.
%%%----------------------------------------------------------------------
%%% API
%%%----------------------------------------------------------------------
start_link() ->
gen_server:start_link({local, ejabberd_hooks}, ejabberd_hooks, [], []).
-spec add(atom(), fun(), number()) -> ok.
@doc See add/4 .
add(Hook, Function, Seq) when is_function(Function) ->
add(Hook, global, undefined, Function, Seq).
-spec add(atom(), HostOrModule :: binary() | atom(), fun() | atom() , number()) -> ok.
add(Hook, Host, Function, Seq) when is_function(Function) ->
add(Hook, Host, undefined, Function, Seq);
%% @doc Add a module and function to this hook.
%% The integer sequence is used to sort the calls: low number is called before high number.
add(Hook, Module, Function, Seq) ->
add(Hook, global, Module, Function, Seq).
-spec add(atom(), binary() | global, atom(), atom() | fun(), number()) -> ok.
add(Hook, Host, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {add, Hook, Host, Module, Function, Seq}).
-spec add_dist(atom(), atom(), atom(), atom() | fun(), number()) -> ok.
add_dist(Hook, Node, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {add, Hook, global, Node, Module, Function, Seq}).
-spec add_dist(atom(), binary() | global, atom(), atom(), atom() | fun(), number()) -> ok.
add_dist(Hook, Host, Node, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {add, Hook, Host, Node, Module, Function, Seq}).
-spec delete(atom(), fun(), number()) -> ok.
%% @doc See del/4.
delete(Hook, Function, Seq) when is_function(Function) ->
delete(Hook, global, undefined, Function, Seq).
-spec delete(atom(), binary() | atom(), atom() | fun(), number()) -> ok.
delete(Hook, Host, Function, Seq) when is_function(Function) ->
delete(Hook, Host, undefined, Function, Seq);
%% @doc Delete a module and function from this hook.
%% It is important to indicate exactly the same information than when the call was added.
delete(Hook, Module, Function, Seq) ->
delete(Hook, global, Module, Function, Seq).
-spec delete(atom(), binary() | global, atom(), atom() | fun(), number()) -> ok.
delete(Hook, Host, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {delete, Hook, Host, Module, Function, Seq}).
-spec delete_dist(atom(), atom(), atom(), atom() | fun(), number()) -> ok.
delete_dist(Hook, Node, Module, Function, Seq) ->
delete_dist(Hook, global, Node, Module, Function, Seq).
-spec delete_dist(atom(), binary() | global, atom(), atom(), atom() | fun(), number()) -> ok.
delete_dist(Hook, Host, Node, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {delete, Hook, Host, Node, Module, Function, Seq}).
-spec delete_all_hooks() -> true.
%% @doc Primarily for testing / instrumentation
delete_all_hooks() ->
gen_server:call(ejabberd_hooks, {delete_all}).
-spec get_handlers(atom(), binary() | global) -> [local_hook() | distributed_hook()].
%% @doc Returns currently set handler for hook name
get_handlers(Hookname, Host) ->
gen_server:call(ejabberd_hooks, {get_handlers, Hookname, Host}).
-spec run(atom(), list()) -> ok.
%% @doc Run the calls of this hook in order, don't care about function results.
%% If a call returns stop, no more calls are performed.
run(Hook, Args) ->
run(Hook, global, Args).
-spec run(atom(), binary() | global, list()) -> ok.
run(Hook, Host, Args) ->
case ets:lookup(hooks, {Hook, Host}) of
[{_, Ls}] ->
run1(Ls, Hook, Args);
[] ->
ok
end.
-spec run_fold(atom(), any(), list()) -> any().
%% @doc Run the calls of this hook in order.
%% The arguments passed to the function are: [Val | Args].
The result of a call is used as for the next call .
%% If a call returns 'stop', no more calls are performed and 'stopped' is returned.
If a call returns { stop , NewVal } , no more calls are performed and NewVal is returned .
run_fold(Hook, Val, Args) ->
run_fold(Hook, global, Val, Args).
-spec run_fold(atom(), binary() | global, any(), list()) -> any().
run_fold(Hook, Host, Val, Args) ->
case ets:lookup(hooks, {Hook, Host}) of
[{_, Ls}] ->
run_fold1(Ls, Hook, Val, Args);
[] ->
Val
end.
%%%----------------------------------------------------------------------
%%% Callback functions from gen_server
%%%----------------------------------------------------------------------
%%----------------------------------------------------------------------
%% Func: init/1
%% Returns: {ok, State} |
{ ok , State , Timeout } |
%% ignore |
%% {stop, Reason}
%%----------------------------------------------------------------------
init([]) ->
ets:new(hooks, [named_table]),
{ok, #state{}}.
%%----------------------------------------------------------------------
Func : handle_call/3
%% Returns: {reply, Reply, State} |
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, Reply, State} | (terminate/2 is called)
%% {stop, Reason, State} (terminate/2 is called)
%%----------------------------------------------------------------------
handle_call({add, Hook, Host, Module, Function, Seq}, _From, State) ->
HookFormat = {Seq, Module, Function},
Reply = handle_add(Hook, Host, HookFormat),
{reply, Reply, State};
handle_call({add, Hook, Host, Node, Module, Function, Seq}, _From, State) ->
HookFormat = {Seq, Node, Module, Function},
Reply = handle_add(Hook, Host, HookFormat),
{reply, Reply, State};
handle_call({delete, Hook, Host, Module, Function, Seq}, _From, State) ->
HookFormat = {Seq, Module, Function},
Reply = handle_delete(Hook, Host, HookFormat),
{reply, Reply, State};
handle_call({delete, Hook, Host, Node, Module, Function, Seq}, _From, State) ->
HookFormat = {Seq, Node, Module, Function},
Reply = handle_delete(Hook, Host, HookFormat),
{reply, Reply, State};
handle_call({get_handlers, Hook, Host}, _From, State) ->
Reply = case ets:lookup(hooks, {Hook, Host}) of
[{_, Handlers}] -> Handlers;
[] -> []
end,
{reply, Reply, State};
handle_call({delete_all}, _From, State) ->
Reply = ets:delete_all_objects(hooks),
{reply, Reply, State};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
-spec handle_add(atom(), atom(), local_hook() | distributed_hook()) -> ok.
%% in-memory storage operation: Handle adding hook in ETS table
handle_add(Hook, Host, El) ->
case ets:lookup(hooks, {Hook, Host}) of
[{_, Ls}] ->
case lists:member(El, Ls) of
true ->
ok;
false ->
NewLs = lists:merge(Ls, [El]),
ets:insert(hooks, {{Hook, Host}, NewLs}),
ok
end;
[] ->
NewLs = [El],
ets:insert(hooks, {{Hook, Host}, NewLs}),
ok
end.
-spec handle_delete(atom(), atom(), local_hook() | distributed_hook()) -> ok.
%% in-memory storage operation: Handle deleting hook from ETS table
handle_delete(Hook, Host, El) ->
case ets:lookup(hooks, {Hook, Host}) of
[{_, Ls}] ->
NewLs = lists:delete(El, Ls),
ets:insert(hooks, {{Hook, Host}, NewLs}),
ok;
[] ->
ok
end.
%%----------------------------------------------------------------------
%% Func: handle_cast/2
Returns : { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State} (terminate/2 is called)
%%----------------------------------------------------------------------
handle_cast(_Msg, State) ->
{noreply, State}.
%%----------------------------------------------------------------------
%% Func: handle_info/2
Returns : { noreply , State } |
{ noreply , State , Timeout } |
%% {stop, Reason, State} (terminate/2 is called)
%%----------------------------------------------------------------------
handle_info(_Info, State) ->
{noreply, State}.
%%----------------------------------------------------------------------
%% Func: terminate/2
%% Purpose: Shutdown the server
%% Returns: any (ignored by gen_server)
%%----------------------------------------------------------------------
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%%%----------------------------------------------------------------------
Internal functions
%%%----------------------------------------------------------------------
-spec run1([local_hook()|distributed_hook()], atom(), list()) -> ok.
run1([], _Hook, _Args) ->
ok;
%% Run distributed hook on target node.
%% It is not attempted again in case of failure. Next hook will be executed
run1([{_Seq, Node, Module, Function} | Ls], Hook, Args) ->
%% MR: Should we have a safe rpc, like we have a safe apply or is bad_rpc enough ?
case ejabberd_cluster:call(Node, Module, Function, Args) of
timeout ->
?ERROR_MSG("Timeout on RPC to ~p~nrunning hook: ~p",
[Node, {Hook, Args}]),
run1(Ls, Hook, Args);
{badrpc, Reason} ->
?ERROR_MSG("Bad RPC error to ~p: ~p~nrunning hook: ~p",
[Node, Reason, {Hook, Args}]),
run1(Ls, Hook, Args);
stop ->
?INFO_MSG("~nThe process ~p in node ~p ran a hook in node ~p.~n"
"Stop.", [self(), node(), Node]), % debug code
ok;
Res ->
?INFO_MSG("~nThe process ~p in node ~p ran a hook in node ~p.~n"
"The response is:~n~s", [self(), node(), Node, Res]), % debug code
run1(Ls, Hook, Args)
end;
run1([{_Seq, Module, Function} | Ls], Hook, Args) ->
Res = safe_apply(Module, Function, Args),
case Res of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nrunning hook: ~p", [Reason, {Hook, Args}]),
run1(Ls, Hook, Args);
stop ->
ok;
_ ->
run1(Ls, Hook, Args)
end.
run_fold1([], _Hook, Val, _Args) ->
Val;
run_fold1([{_Seq, Node, Module, Function} | Ls], Hook, Val, Args) ->
case ejabberd_cluster:call(Node, Module, Function, [Val | Args]) of
{badrpc, Reason} ->
?ERROR_MSG("Bad RPC error to ~p: ~p~nrunning hook: ~p",
[Node, Reason, {Hook, Args}]),
run_fold1(Ls, Hook, Val, Args);
timeout ->
?ERROR_MSG("Timeout on RPC to ~p~nrunning hook: ~p",
[Node, {Hook, Args}]),
run_fold1(Ls, Hook, Val, Args);
stop ->
stopped;
{stop, NewVal} ->
?INFO_MSG("~nThe process ~p in node ~p ran a hook in node ~p.~n"
"Stop, and the NewVal is:~n~p", [self(), node(), Node, NewVal]), % debug code
NewVal;
NewVal ->
?INFO_MSG("~nThe process ~p in node ~p ran a hook in node ~p.~n"
"The NewVal is:~n~p", [self(), node(), Node, NewVal]), % debug code
run_fold1(Ls, Hook, NewVal, Args)
end;
run_fold1([{_Seq, Module, Function} | Ls], Hook, Val, Args) ->
Res = safe_apply(Module, Function, [Val | Args]),
case Res of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nrunning hook: ~p", [Reason, {Hook, Args}]),
run_fold1(Ls, Hook, Val, Args);
stop ->
stopped;
{stop, NewVal} ->
NewVal;
NewVal ->
run_fold1(Ls, Hook, NewVal, Args)
end.
safe_apply(Module, Function, Args) ->
if is_function(Function) ->
catch apply(Function, Args);
true ->
catch apply(Module, Function, Args)
end.
| null | https://raw.githubusercontent.com/startalkIM/ejabberd/718d86cd2f5681099fad14dab5f2541ddc612c8b/src/ejabberd_hooks.erl | erlang | ----------------------------------------------------------------------
Purpose : Manage hooks
This program is free software; you can redistribute it and/or
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
----------------------------------------------------------------------
External exports
gen_server callbacks
----------------------------------------------------------------------
API
----------------------------------------------------------------------
@doc Add a module and function to this hook.
The integer sequence is used to sort the calls: low number is called before high number.
@doc See del/4.
@doc Delete a module and function from this hook.
It is important to indicate exactly the same information than when the call was added.
@doc Primarily for testing / instrumentation
@doc Returns currently set handler for hook name
@doc Run the calls of this hook in order, don't care about function results.
If a call returns stop, no more calls are performed.
@doc Run the calls of this hook in order.
The arguments passed to the function are: [Val | Args].
If a call returns 'stop', no more calls are performed and 'stopped' is returned.
----------------------------------------------------------------------
Callback functions from gen_server
----------------------------------------------------------------------
----------------------------------------------------------------------
Func: init/1
Returns: {ok, State} |
ignore |
{stop, Reason}
----------------------------------------------------------------------
----------------------------------------------------------------------
Returns: {reply, Reply, State} |
{stop, Reason, Reply, State} | (terminate/2 is called)
{stop, Reason, State} (terminate/2 is called)
----------------------------------------------------------------------
in-memory storage operation: Handle adding hook in ETS table
in-memory storage operation: Handle deleting hook from ETS table
----------------------------------------------------------------------
Func: handle_cast/2
{stop, Reason, State} (terminate/2 is called)
----------------------------------------------------------------------
----------------------------------------------------------------------
Func: handle_info/2
{stop, Reason, State} (terminate/2 is called)
----------------------------------------------------------------------
----------------------------------------------------------------------
Func: terminate/2
Purpose: Shutdown the server
Returns: any (ignored by gen_server)
----------------------------------------------------------------------
----------------------------------------------------------------------
----------------------------------------------------------------------
Run distributed hook on target node.
It is not attempted again in case of failure. Next hook will be executed
MR: Should we have a safe rpc, like we have a safe apply or is bad_rpc enough ?
debug code
debug code
debug code
debug code | File : ejabberd_hooks.erl
Author : < >
Created : 8 Aug 2004 by < >
ejabberd , Copyright ( C ) 2002 - 2016 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License along
with this program ; if not , write to the Free Software Foundation , Inc. ,
51 Franklin Street , Fifth Floor , Boston , USA .
-module(ejabberd_hooks).
-author('').
-behaviour(gen_server).
-export([start_link/0,
add/3,
add/4,
add/5,
add_dist/5,
add_dist/6,
delete/3,
delete/4,
delete/5,
delete_dist/5,
delete_dist/6,
run/2,
run/3,
run_fold/3,
run_fold/4,
get_handlers/2]).
-export([delete_all_hooks/0]).
-export([init/1,
handle_call/3,
handle_cast/2,
code_change/3,
handle_info/2,
terminate/2]).
-include("logger.hrl").
-record(state, {}).
-type local_hook() :: { Seq :: integer(), Module :: atom(), Function :: atom()}.
-type distributed_hook() :: { Seq :: integer(), Node :: atom(), Module :: atom(), Function :: atom()}.
start_link() ->
gen_server:start_link({local, ejabberd_hooks}, ejabberd_hooks, [], []).
-spec add(atom(), fun(), number()) -> ok.
@doc See add/4 .
add(Hook, Function, Seq) when is_function(Function) ->
add(Hook, global, undefined, Function, Seq).
-spec add(atom(), HostOrModule :: binary() | atom(), fun() | atom() , number()) -> ok.
add(Hook, Host, Function, Seq) when is_function(Function) ->
add(Hook, Host, undefined, Function, Seq);
add(Hook, Module, Function, Seq) ->
add(Hook, global, Module, Function, Seq).
-spec add(atom(), binary() | global, atom(), atom() | fun(), number()) -> ok.
add(Hook, Host, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {add, Hook, Host, Module, Function, Seq}).
-spec add_dist(atom(), atom(), atom(), atom() | fun(), number()) -> ok.
add_dist(Hook, Node, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {add, Hook, global, Node, Module, Function, Seq}).
-spec add_dist(atom(), binary() | global, atom(), atom(), atom() | fun(), number()) -> ok.
add_dist(Hook, Host, Node, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {add, Hook, Host, Node, Module, Function, Seq}).
-spec delete(atom(), fun(), number()) -> ok.
delete(Hook, Function, Seq) when is_function(Function) ->
delete(Hook, global, undefined, Function, Seq).
-spec delete(atom(), binary() | atom(), atom() | fun(), number()) -> ok.
delete(Hook, Host, Function, Seq) when is_function(Function) ->
delete(Hook, Host, undefined, Function, Seq);
delete(Hook, Module, Function, Seq) ->
delete(Hook, global, Module, Function, Seq).
-spec delete(atom(), binary() | global, atom(), atom() | fun(), number()) -> ok.
delete(Hook, Host, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {delete, Hook, Host, Module, Function, Seq}).
-spec delete_dist(atom(), atom(), atom(), atom() | fun(), number()) -> ok.
delete_dist(Hook, Node, Module, Function, Seq) ->
delete_dist(Hook, global, Node, Module, Function, Seq).
-spec delete_dist(atom(), binary() | global, atom(), atom(), atom() | fun(), number()) -> ok.
delete_dist(Hook, Host, Node, Module, Function, Seq) ->
gen_server:call(ejabberd_hooks, {delete, Hook, Host, Node, Module, Function, Seq}).
-spec delete_all_hooks() -> true.
delete_all_hooks() ->
gen_server:call(ejabberd_hooks, {delete_all}).
-spec get_handlers(atom(), binary() | global) -> [local_hook() | distributed_hook()].
get_handlers(Hookname, Host) ->
gen_server:call(ejabberd_hooks, {get_handlers, Hookname, Host}).
-spec run(atom(), list()) -> ok.
run(Hook, Args) ->
run(Hook, global, Args).
-spec run(atom(), binary() | global, list()) -> ok.
run(Hook, Host, Args) ->
case ets:lookup(hooks, {Hook, Host}) of
[{_, Ls}] ->
run1(Ls, Hook, Args);
[] ->
ok
end.
-spec run_fold(atom(), any(), list()) -> any().
The result of a call is used as for the next call .
If a call returns { stop , NewVal } , no more calls are performed and NewVal is returned .
run_fold(Hook, Val, Args) ->
run_fold(Hook, global, Val, Args).
-spec run_fold(atom(), binary() | global, any(), list()) -> any().
run_fold(Hook, Host, Val, Args) ->
case ets:lookup(hooks, {Hook, Host}) of
[{_, Ls}] ->
run_fold1(Ls, Hook, Val, Args);
[] ->
Val
end.
{ ok , State , Timeout } |
init([]) ->
ets:new(hooks, [named_table]),
{ok, #state{}}.
Func : handle_call/3
{ reply , Reply , State , Timeout } |
{ noreply , State } |
{ noreply , State , Timeout } |
handle_call({add, Hook, Host, Module, Function, Seq}, _From, State) ->
HookFormat = {Seq, Module, Function},
Reply = handle_add(Hook, Host, HookFormat),
{reply, Reply, State};
handle_call({add, Hook, Host, Node, Module, Function, Seq}, _From, State) ->
HookFormat = {Seq, Node, Module, Function},
Reply = handle_add(Hook, Host, HookFormat),
{reply, Reply, State};
handle_call({delete, Hook, Host, Module, Function, Seq}, _From, State) ->
HookFormat = {Seq, Module, Function},
Reply = handle_delete(Hook, Host, HookFormat),
{reply, Reply, State};
handle_call({delete, Hook, Host, Node, Module, Function, Seq}, _From, State) ->
HookFormat = {Seq, Node, Module, Function},
Reply = handle_delete(Hook, Host, HookFormat),
{reply, Reply, State};
handle_call({get_handlers, Hook, Host}, _From, State) ->
Reply = case ets:lookup(hooks, {Hook, Host}) of
[{_, Handlers}] -> Handlers;
[] -> []
end,
{reply, Reply, State};
handle_call({delete_all}, _From, State) ->
Reply = ets:delete_all_objects(hooks),
{reply, Reply, State};
handle_call(_Request, _From, State) ->
Reply = ok,
{reply, Reply, State}.
-spec handle_add(atom(), atom(), local_hook() | distributed_hook()) -> ok.
handle_add(Hook, Host, El) ->
case ets:lookup(hooks, {Hook, Host}) of
[{_, Ls}] ->
case lists:member(El, Ls) of
true ->
ok;
false ->
NewLs = lists:merge(Ls, [El]),
ets:insert(hooks, {{Hook, Host}, NewLs}),
ok
end;
[] ->
NewLs = [El],
ets:insert(hooks, {{Hook, Host}, NewLs}),
ok
end.
-spec handle_delete(atom(), atom(), local_hook() | distributed_hook()) -> ok.
handle_delete(Hook, Host, El) ->
case ets:lookup(hooks, {Hook, Host}) of
[{_, Ls}] ->
NewLs = lists:delete(El, Ls),
ets:insert(hooks, {{Hook, Host}, NewLs}),
ok;
[] ->
ok
end.
Returns : { noreply , State } |
{ noreply , State , Timeout } |
handle_cast(_Msg, State) ->
{noreply, State}.
Returns : { noreply , State } |
{ noreply , State , Timeout } |
handle_info(_Info, State) ->
{noreply, State}.
terminate(_Reason, _State) ->
ok.
code_change(_OldVsn, State, _Extra) ->
{ok, State}.
Internal functions
-spec run1([local_hook()|distributed_hook()], atom(), list()) -> ok.
run1([], _Hook, _Args) ->
ok;
run1([{_Seq, Node, Module, Function} | Ls], Hook, Args) ->
case ejabberd_cluster:call(Node, Module, Function, Args) of
timeout ->
?ERROR_MSG("Timeout on RPC to ~p~nrunning hook: ~p",
[Node, {Hook, Args}]),
run1(Ls, Hook, Args);
{badrpc, Reason} ->
?ERROR_MSG("Bad RPC error to ~p: ~p~nrunning hook: ~p",
[Node, Reason, {Hook, Args}]),
run1(Ls, Hook, Args);
stop ->
?INFO_MSG("~nThe process ~p in node ~p ran a hook in node ~p.~n"
ok;
Res ->
?INFO_MSG("~nThe process ~p in node ~p ran a hook in node ~p.~n"
run1(Ls, Hook, Args)
end;
run1([{_Seq, Module, Function} | Ls], Hook, Args) ->
Res = safe_apply(Module, Function, Args),
case Res of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nrunning hook: ~p", [Reason, {Hook, Args}]),
run1(Ls, Hook, Args);
stop ->
ok;
_ ->
run1(Ls, Hook, Args)
end.
run_fold1([], _Hook, Val, _Args) ->
Val;
run_fold1([{_Seq, Node, Module, Function} | Ls], Hook, Val, Args) ->
case ejabberd_cluster:call(Node, Module, Function, [Val | Args]) of
{badrpc, Reason} ->
?ERROR_MSG("Bad RPC error to ~p: ~p~nrunning hook: ~p",
[Node, Reason, {Hook, Args}]),
run_fold1(Ls, Hook, Val, Args);
timeout ->
?ERROR_MSG("Timeout on RPC to ~p~nrunning hook: ~p",
[Node, {Hook, Args}]),
run_fold1(Ls, Hook, Val, Args);
stop ->
stopped;
{stop, NewVal} ->
?INFO_MSG("~nThe process ~p in node ~p ran a hook in node ~p.~n"
NewVal;
NewVal ->
?INFO_MSG("~nThe process ~p in node ~p ran a hook in node ~p.~n"
run_fold1(Ls, Hook, NewVal, Args)
end;
run_fold1([{_Seq, Module, Function} | Ls], Hook, Val, Args) ->
Res = safe_apply(Module, Function, [Val | Args]),
case Res of
{'EXIT', Reason} ->
?ERROR_MSG("~p~nrunning hook: ~p", [Reason, {Hook, Args}]),
run_fold1(Ls, Hook, Val, Args);
stop ->
stopped;
{stop, NewVal} ->
NewVal;
NewVal ->
run_fold1(Ls, Hook, NewVal, Args)
end.
safe_apply(Module, Function, Args) ->
if is_function(Function) ->
catch apply(Function, Args);
true ->
catch apply(Module, Function, Args)
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.